code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
import { LOAD_SEARCH_RESULT_SUCCESS, CLEAR_SEARCH_RESULTS, } from 'actions/search'; import { createActionHandlers } from 'utils/reducer/actions-handlers'; const actionHandlers = {}; export function loadSearchResultSuccess(state, searchResultsList) { return searchResultsList.reduce((acc, result) => { return { ...acc, [result.id]: result, }; }, {}); } export function clearSearchResult() { return {}; } actionHandlers[LOAD_SEARCH_RESULT_SUCCESS] = loadSearchResultSuccess; actionHandlers[CLEAR_SEARCH_RESULTS] = clearSearchResult; export default createActionHandlers(actionHandlers);
InseeFr/Pogues
src/reducers/search-result-by-id.js
JavaScript
mit
619
/** specified=*(N): you have had a specifier added to you (internal). 0 = no, new ones have to score higher than old specifier=[_]: you are capable of being used in situation where we need to know what to do with you (external). bare noun: has no specifier added, but if it *were* to be used as an NP then the value of specifier would be *mass plural noun: has no specifier added, but if it *were* to be used as an NP then the value of specifier would be *count det+NP: we record values for both specified (a number) and specifier (a property). **/ specifier(X, SPEC) :- specifier@X -- SPEC. specified(X) :- X <> [specifier(*(_))]. unspecified(X) :- -specifier@X. casemarked(X, case@X). subjcase(X) :- case@X -- *subj. objcase(X) :- case@X -- *obj. standardcase(X, CASE) :- case@X -- *CASE. standardcase(X) :- X <> [standardcase(_)]. sing(X) :- number@X -- sing. plural(X) :- number@X -- plural. first(X) :- person@X -- 1. firstSing(X) :- X <> [sing, first]. second(X) :- person@X -- 2. third(X) :- person@X -- 3. thirdSing(X) :- X <> [sing, third]. thirdPlural(X) :- X <> [plural, third]. notThirdSing(X) :- when((nonvar(person@X), nonvar(number@X)), \+ thirdSing(X)). masculine(X) :- gender@X -- masculine. feminine(X) :- gender@X -- feminine.
AllanRamsay/dgParser
agree.pl
Perl
mit
1,345
import { autoinject } from 'aurelia-framework'; import { Customers } from './customers'; import { Router } from 'aurelia-router'; @autoinject() export class List { heading = 'Customer management'; customerList = []; customers: Customers; router: Router; constructor(customers: Customers, router: Router) { this.customers = customers; this.router = router; } gotoCustomer(customer: any) { this.router.navigateToRoute('edit', {id: customer.id}); } new() { this.router.navigateToRoute('create'); } activate() { return this.customers.getAll() .then(customerList => this.customerList = customerList); } }
doktordirk/aurelia-authentication-loopback-sample
client-ts/src/modules/customer/list.ts
TypeScript
mit
657
# Chokidar CLI [![Build Status](https://travis-ci.org/kimmobrunfeldt/chokidar-cli.svg?branch=master)](https://travis-ci.org/kimmobrunfeldt/chokidar-cli) Fast cross-platform command line utility to watch file system changes. The underlying watch library is [Chokidar](https://github.com/paulmillr/chokidar), which is one of the best watch utilities for Node. Chokidar is battle-tested: > It is used in > [brunch](http://brunch.io), > [gulp](https://github.com/gulpjs/gulp/), > [karma](http://karma-runner.github.io), > [PM2](https://github.com/Unitech/PM2), > [browserify](http://browserify.org/), > [webpack](http://webpack.github.io/), > [BrowserSync](http://www.browsersync.io/), > [socketstream](http://www.socketstream.org), > [derby](http://derbyjs.com/), > and [many others](https://www.npmjs.org/browse/depended/chokidar/). > It has proven itself in production environments. ## Install If you need it only with NPM scripts: ```bash npm install chokidar-cli ``` Or globally ```bash npm install -g chokidar-cli ``` ## Usage By default `chokidar` streams changes for all patterns to stdout: ```bash $ chokidar '**/.js' '**/*.less' change:test/dir/a.js change:test/dir/a.less add:test/b.js unlink:test/b.js ``` Each change is represented with format `event:relativepath`. Possible events: `add`, `unlink`, `addDir`, `unlinkDir`, `change`. **Output only relative paths on each change** ```bash $ chokidar '**/.js' '**/*.less' | cut -d ':' -f 2- test/dir/a.js test/dir/a.less test/b.js test/b.js ``` **Run *npm run build-js* whenever any .js file changes in the current work directory tree** ```chokidar '**/*.js' -c 'npm run build-js'``` **Watching in network directories must use polling** ```chokidar '**/*.less' -c 'npm run build-less' --polling``` **Pass the path and event details in to your custom command ```chokidar '**/*.less' -c 'if [ "{event}" = "change" ]; then npm run build-less -- {path}; fi;'``` **Detailed help** ``` Usage: chokidar <pattern> [<pattern>...] [options] <pattern>: Glob pattern to specify files to be watched. Multiple patterns can be watched by separating patterns with spaces. To prevent shell globbing, write pattern inside quotes. Guide to globs: https://github.com/isaacs/node-glob#glob-primer Options: -c, --command Command to run after each change. Needs to be surrounded with quotes when command contains spaces. Instances of `{path}` or `{event}` within the command will be replaced by the corresponding values from the chokidar event. -d, --debounce Debounce timeout in ms for executing command [default: 400] -t, --throttle Throttle timeout in ms for executing command [default: 0] -s, --follow-symlinks When not set, only the symlinks themselves will be watched for changes instead of following the link references and bubbling events through the links path [boolean] [default: false] -i, --ignore Pattern for files which should be ignored. Needs to be surrounded with quotes to prevent shell globbing. The whole relative or absolute path is tested, not just filename. Supports glob patters or regexes using format: /yourmatch/i --initial When set, command is initially run once [boolean] [default: false] -p, --polling Whether to use fs.watchFile(backed by polling) instead of fs.watch. This might lead to high CPU utilization. It is typically necessary to set this to true to successfully watch files over a network, and it may be necessary to successfully watch files in other non- standard situations [boolean] [default: false] --poll-interval Interval of file system polling. Effective when -- polling is set [default: 100] --poll-interval-binary Interval of file system polling for binary files. Effective when --polling is set [default: 300] --verbose When set, output is more verbose and human readable. [boolean] [default: false] --silent When set, internal messages of chokidar-cli won't be written. [boolean] [default: false] -h, --help Show help [boolean] -v, --version Show version number [boolean] Examples: chokidar "**/*.js" -c "npm run build-js" build when any .js file changes chokidar "**/*.js" "**/*.less" output changes of .js and .less files ``` ## License MIT
yaal-fr/ysvgmaps
node_modules/chokidar-cli/README.md
Markdown
mit
5,251
The MIT License (MIT) Copyright (c) 2014 Christophe Van Neste 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.
beukueb/myflq
LICENSE.md
Markdown
mit
1,086
/** * Created by huangxinghui on 2016/1/20. */ var $ = require('jquery') var Widget = require('../../widget') var plugin = require('../../plugin') var TreeNode = require('./treenode') var Tree = Widget.extend({ options: { 'labelField': null, 'labelFunction': null, 'childrenField': 'children', 'autoOpen': true }, events: { 'click li': '_onSelect', 'click i': '_onExpand' }, _create: function() { this.$element.addClass('tree') var that = this var $ul = $('<ul></ul>') this._loadFromDataSource() this.nodes.forEach(function(node) { that._createNode(node) $ul.append(node.element) }) this.$element.append($ul) }, _onSelect: function(e) { var $li = $(e.currentTarget), node = $li.data('node') e.preventDefault() if (!$li.hasClass('active')) { this._setSelectedNode(node) this._trigger('itemClick', node.data) } }, _onExpand: function(e) { var $li = $(e.currentTarget).closest('li'), node = $li.data('node') e.preventDefault() if (node.isOpen) { this.collapseNode(node) } else { this.expandNode(node) } }, _setSelectedNode: function(node) { var $active = this.$element.find('.active') $active.removeClass('active') var $li = node.element $li.addClass('active') this._trigger('change', node.data) }, _createNode: function(node) { if (node.isBranch()) { this._createFolder(node) } else { this._createLeaf(node) } }, _createLeaf: function(node) { var html = ['<li><a href="#"><span>'] html.push(this._createIndentationHtml(node.getLevel())) html.push(this.itemToLabel(node.data)) html.push('</span></a></li>') var $li = $(html.join('')) $li.data('node', node) node.element = $li return $li }, _createFolder: function(node) { var that = this var html = [] if (node.isOpen) { html.push('<li class="open"><a href="#"><span>') html.push(this._createIndentationHtml(node.getLevel() - 1)) html.push('<i class="glyphicon glyphicon-minus-sign js-folder"></i>') } else { html.push('<li><a href="#"><span>') html.push(this._createIndentationHtml(node.getLevel() - 1)) html.push('<i class="glyphicon glyphicon-plus-sign js-folder"></i>') } html.push(this.itemToLabel(node.data)) html.push('</span></a></li>') var $li = $(html.join('')) var $ul = $('<ul class="children-list"></ul>') node.children.forEach(function(childNode) { that._createNode(childNode) $ul.append(childNode.element) }) $li.append($ul) $li.data('node', node) node.element = $li return $li }, _createLabel: function(node) { var html = ['<span>'] var level = node.getLevel() if (node.isBranch()) { html.push(this._createIndentationHtml(level - 1)) html.push('<i class="glyphicon ', node.isOpen ? 'glyphicon-minus-sign' : 'glyphicon-plus-sign', ' js-folder"></i>') } else { html.push(this._createIndentationHtml(level)) } html.push(this.itemToLabel(node.data)) html.push('</span>') return html.join('') }, _createIndentationHtml: function(count) { var html = [] for (var i = 0; i < count; i++) { html.push('<i class="glyphicon tree-indentation"></i>') } return html.join('') }, _loadFromDataSource: function() { var node, children, nodes = [], that = this if (this.options.dataSource) { this.options.dataSource.forEach(function(item) { node = new TreeNode(item) children = item[that.options.childrenField] if (children) { node.isOpen = that.options.autoOpen that._loadFromArray(children, node) } nodes.push(node) }) } this.nodes = nodes }, _loadFromArray: function(array, parentNode) { var node, children, that = this array.forEach(function(item) { node = new TreeNode(item) parentNode.addChild(node) children = item[that.childrenField] if (children) { node.isOpen = that.autoOpen that._loadFromArray(children, node) } }) }, expandNode: function(node) { if (!node.isBranch()) { return } var $li = node.element var $disclosureIcon = $li.children('a').find('.js-folder') if (!node.isOpen) { node.isOpen = true $li.addClass('open') $disclosureIcon.removeClass('glyphicon-plus-sign').addClass('glyphicon-minus-sign') this._trigger('itemOpen') } }, collapseNode: function(node) { if (!node.isBranch()) { return } var $li = node.element var $disclosureIcon = $li.children('a').find('.js-folder') if (node.isOpen) { node.isOpen = false $li.removeClass('open') $disclosureIcon.removeClass('glyphicon-minus-sign').addClass('glyphicon-plus-sign') this._trigger('itemClose') } }, expandAll: function() { var that = this this.nodes.forEach(function(node) { that.expandNode(node) }) }, collapseAll: function() { var that = this this.nodes.forEach(function(node) { that.collapseNode(node) }) }, append: function(item, parentNode) { var $ul, $li, $prev, node = new TreeNode(item) if (parentNode.isBranch()) { parentNode.addChild(node) $ul = parentNode.element.children('ul') this._createNode(node) $li = node.element $ul.append($li) } else { parentNode.addChild(node) $li = parentNode.element $prev = $li.prev() $ul = $li.parent() parentNode.element = null $li.remove() $li = this._createFolder(parentNode) if ($prev.length) { $prev.after($li) } else { $ul.append($li) } } this.expandNode(parentNode) this._setSelectedNode(node) }, remove: function(node) { var parentNode = node.parent node.element.remove() node.destroy() this._setSelectedNode(parentNode) }, update: function(node) { var $li = node.element $li.children('a').html(this._createLabel(node)) }, getSelectedNode: function() { var $li = this.$element.find('.active') return $li.data('node') }, getSelectedItem: function() { var node = this.getSelectedNode() return node.data }, itemToLabel: function(data) { if (!data) { return '' } if (this.options.labelFunction != null) { return this.options.labelFunction(data) } else if (this.options.labelField != null) { return data[this.options.labelField] } else { return data } } }) plugin('tree', Tree)
huang-x-h/Bean.js
src/components/tree/index.js
JavaScript
mit
6,725
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Advent of Code 2015 from http://adventofcode.com/2015/day/5 Author: James Walker Copyrighted 2017 under the MIT license: http://www.opensource.org/licenses/mit-license.php Execution: python advent_of_code_2015_day_05.py --- Day 5: Doesn't He Have Intern-Elves For This? --- Santa needs help figuring out which strings in his text file are naughty or nice. A nice string is one with all of the following properties: It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou. It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd). It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements. For example: ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings. aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap. jchzalrnumimnmhp is naughty because it has no double letter. haegwjzuvuyypxyu is naughty because it contains the string xy. dvszwmarrgswjxmb is naughty because it contains only one vowel. How many strings are nice? Answer: 258 --- Day 5: Part Two --- Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or nice. None of the old rules apply, as they are all clearly ridiculous. Now, a nice string is one with all of the following properties: It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps). It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or even aaa. For example: qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and a letter that repeats with exactly one letter between them (zxz). xxyxx is nice because it has a pair that appears twice and a letter that repeats with one between, even though the letters used by each rule overlap. uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a single letter between them. ieodomkazucvgmuy is naughty because it has a repeating letter with one between (odo), but no pair that appears twice. How many strings are nice under these new rules? Answer: 53 """ import collections import os import re import sys TestCase = collections.namedtuple('TestCase', 'input expected1 expected2') class Advent_Of_Code_2015_Solver_Day05(object): """Advent of Code 2015 Day 5: Doesn't He Have Intern-Elves For This?""" def __init__(self, file_name=None): self._file_name = file_name self._puzzle_input = None self._solved_output = ( "The text file had {0} nice strings using the original rules\n" "and it had {1} nice strings using the new rules." ) self.__regex_vowels = re.compile('[aeiou]') self.__regex_double_char = re.compile('(\w)\\1+') self.__regex_naughty = re.compile('ab|cd|pq|xy') self.__regex_double_pair = re.compile('(\w{2})\w*\\1') self.__regex_triplet = re.compile('(\w)\w\\1') def _load_puzzle_file(self): filePath = "{dir}/{f}".format(dir=os.getcwd(), f=self._file_name) try: with open(filePath, mode='r') as puzzle_file: self._puzzle_input = puzzle_file.readlines() except IOError as err: errorMsg = ( "ERROR: Failed to read the puzzle input from file '{file}'\n" "{error}" ) print(errorMsg.format(file=self._file_name, error=err)) exit(1) def __is_nice_string_using_old_rules(self, string): return (self.__regex_naughty.search(string) is None and len(self.__regex_vowels.findall(string)) > 2 and self.__regex_double_char.search(string)) def __is_nice_string_using_new_rules(self, string): return (self.__regex_double_pair.search(string) and self.__regex_triplet.search(string)) def _solve_puzzle_parts(self): old_nice_count = 0 new_nice_count = 0 for string in self._puzzle_input: if not string: continue if self.__is_nice_string_using_old_rules(string): old_nice_count += 1 if self.__is_nice_string_using_new_rules(string): new_nice_count += 1 return (old_nice_count, new_nice_count) def get_puzzle_solution(self, alt_input=None): if alt_input is None: self._load_puzzle_file() else: self._puzzle_input = alt_input old_nice_count, new_nice_count = self._solve_puzzle_parts() return self._solved_output.format(old_nice_count, new_nice_count) def _run_test_case(self, test_case): correct_output = self._solved_output.format( test_case.expected1, test_case.expected2 ) test_output = self.get_puzzle_solution(test_case.input) if correct_output == test_output: print("Test passed for input '{0}'".format(test_case.input)) else: print("Test failed for input '{0}'".format(test_case.input)) print(test_output) def run_test_cases(self): print("No Puzzle Input for {puzzle}".format(puzzle=self.__doc__)) print("Running Test Cases...") self._run_test_case(TestCase(['ugknbfddgicrmopn'], 1, 0)) self._run_test_case(TestCase(['aaa'], 1, 0)) self._run_test_case(TestCase(['jchzalrnumimnmhp'], 0, 0)) self._run_test_case(TestCase(['haegwjzuvuyypxyu'], 0, 0)) self._run_test_case(TestCase(['dvszwmarrgswjxmb'], 0, 0)) self._run_test_case(TestCase(['xyxy'], 0, 1)) self._run_test_case(TestCase(['aabcdefgaa'], 0, 0)) self._run_test_case(TestCase(['qjhvhtzxzqqjkmpb'], 0, 1)) self._run_test_case(TestCase(['xxyxx'], 0, 1)) self._run_test_case(TestCase(['uurcxstgmygtbstg'], 0, 0)) self._run_test_case(TestCase(['ieodomkazucvgmuy'], 0, 0)) self._run_test_case(TestCase(['aaccacc'], 1, 1)) if __name__ == '__main__': try: day05_solver = Advent_Of_Code_2015_Solver_Day05(sys.argv[1]) print(day05_solver.__doc__) print(day05_solver.get_puzzle_solution()) except IndexError: Advent_Of_Code_2015_Solver_Day05().run_test_cases()
JDSWalker/AdventOfCode
2015/Day05/advent_of_code_2015_day_05.py
Python
mit
6,750
#!/bin/sh _now=$(date +"%m_%d_%Y_%H_%M_%S") PATH=$PATH:/usr/local/bin export PATH cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/huffingtonpost.py -o feeds/huffingtonpost-$_now.json wait cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/iamwire.py -o feeds/iamwire-$_now.json wait cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/vccircle.py -o feeds/vccircle-$_now.json wait cd $HOME/Code/newspost/crawlers/crawlers && $HOME/Installs/envs/newspost/bin/scrapy runspider spiders/moneycontrol.py -o feeds/moneycontrol-$_now.json
Newsrecommender/newsrecommender
ArticleRecommendationProject/Crawlers/crawlers/scripts/scrape_list_3.sh
Shell
mit
689
# Image Widget ?> GitPitch widgets greatly enhance traditional markdown rendering capabilities for slide decks. The image widget extends traditional markdown image syntax with support for positioning, sizing, transformations, and filters. ### Widget Paths All paths to image files specified within [PITCHME.md](/conventions/pitchme-md.md) markdown must be relative to the *root directory* of your local working directory or Git repository. ### Widget Syntax The following markdown snippet demonstrates image widget syntax: ```markdown ![properties...](path/to/image.file) ``` ?> The `properties...` list expects a comma-separated list of property `key=value` pairs. ### Image Properties The image widget supports the following image specific properties: [Image Widget Properties](../_snippets/image-widget-properties.md ':include') ### Grid Native Props The *Image Widget* is a [grid native widget](/grid-layouts/native-widgets.md) meaning it also directly supports [grid layouts](/grid-layouts/) properties: [Grid Widget Properties](../_snippets/grid-widget-properties.md ':include') ### Sample Slide The following slide demonstrates an image rendered using image widget syntax. The markdown snippet used to create this slide takes advantage of numerous *grid native properties* to position, size, and transform the image on the slide: ![Sample slide demonstrating the image widget](../_images/gitpitch-images-widget.png) > This sample slide uses additional grid layouts blocks to set a custom [slide background color](/grid-layouts/backgrounds.md) and to render text alongside the sample image. For details of the current image size limits policy see the [next guide](/images/size-limits-policy.md).
gitpitch/gitpitch
docs/images/widget.md
Markdown
mit
1,722
/** * Test program. * * Copyright (c) 2015 Alex Jin ([email protected]) */ #include "test/test.h" #include <iostream> namespace { void help() { std::cout << "Usage: testalgo -a" << std::endl; std::cout << " testalgo <test-case-name>" << std::endl; std::cout << std::endl; std::cout << "Options:" << std::endl; std::cout << " -a Run all test cases" << std::endl; std::cout << std::endl; std::cout << "Test Case Names:" << std::endl; const auto names = test_manager_t::instance().get_names(); for (auto it = names.begin(); it != names.end(); ++it) { std::cout << " " << *it << std::endl; } std::cout << std::endl; } } // unnamed namespace int main(int argc, char* argv[]) { if (argc != 2) { help(); exit(1); } bool result = false; std::string arg1 = argv[1]; if (arg1 == "-a") { result = test_manager_t::instance().run(); } else { result = test_manager_t::instance().run(arg1); } return result ? 0 : 2; }
toalexjin/algo
test/main.cpp
C++
mit
974
function solve(args) { function biSearch(array, searchedNumber, start, end) { for (var i = start; i <= end; i += 1) { if (+array[i] === searchedNumber) { return i; } } return -1; } var data = args[0].split('\n'), numberN = +data.shift(), numberX = +data.pop(); var firstIndex = 0; var lastIndex = data.length - 1; var resultIndex = 0; var middle = 0; for (var j = firstIndex; j < lastIndex; j += 1) { middle = (lastIndex / 2) | 0; if (+data[middle] === numberX) { resultIndex = middle; break; } if (+data[middle] < numberX) { firstIndex = middle; resultIndex = biSearch(data, numberX, firstIndex, lastIndex); } if (+data[middle] > numberX) { lastIndex = middle; resultIndex = biSearch(data, numberX, firstIndex, lastIndex); } } if (resultIndex >= 0 && resultIndex < data.length) { console.log(resultIndex); } else { console.log('-1'); } }
jorosoft/Telerik-Academy
Homeworks/JS Fundamentals/07. Arrays/07. Binary search/binary-search.js
JavaScript
mit
1,110
#!/usr/bin/env node var pluginlist = [ ]; var exec = require('child_process').exec; function puts(error, stdout, stderr) { console.log(stdout); } pluginlist.forEach(function(plug) { exec("cordova plugin add " + plug, puts); });
ozsay/ionic-brackets
templates/plugins_hook.js
JavaScript
mit
240
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.lang3.text; import java.util.Map; public abstract class StrLookup<V> { public static StrLookup<?> noneLookup() { return null; } public static StrLookup<String> systemPropertiesLookup() { return null; } public static <V> StrLookup<V> mapLookup(final Map<String, V> map) { return null; } public abstract String lookup(String key); }
github/codeql
java/ql/test/stubs/apache-commons-lang3-3.7/org/apache/commons/lang3/text/StrLookup.java
Java
mit
1,213
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DynThings.Data.Models { using System; using System.Collections.Generic; public partial class UserNotification { public long ID { get; set; } public string UserID { get; set; } public Nullable<long> IsRead { get; set; } public string Txt { get; set; } public Nullable<long> NotificationTypeID { get; set; } public Nullable<long> RefID { get; set; } public Nullable<System.DateTime> AlertTimeStamp { get; set; } public Nullable<bool> IsEmailSent { get; set; } public virtual AspNetUser AspNetUser { get; set; } } }
cmoussalli/DynThings
DynThings.Data.Models/UserNotification.cs
C#
mit
1,008
const path = require('path'); require('dotenv').config(); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const { AureliaPlugin } = require('aurelia-webpack-plugin'); const { optimize: { CommonsChunkPlugin }, ProvidePlugin } = require('webpack') const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader'); var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const UglifyJSPlugin = require('uglifyjs-webpack-plugin') var BrowserSyncPlugin = require('browser-sync-webpack-plugin'); // config helpers: const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [] const when = (condition, config, negativeConfig) => condition ? ensureArray(config) : ensureArray(negativeConfig) // primary config: const title = 'TechRadar'; const outDir = path.resolve(__dirname, 'dist'); const srcDir = path.resolve(__dirname, 'src'); const nodeModulesDir = path.resolve(__dirname, 'node_modules'); const baseUrl = '/'; const cssRules = [ { loader: 'css-loader' }, { loader: 'postcss-loader', options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })] } } ] module.exports = ({ production, server, extractCss, coverage } = {}) => ({ resolve: { extensions: ['.ts', '.js'], modules: [srcDir, 'node_modules'], alias: { 'aurelia-binding$': path.resolve(__dirname, 'node_modules/aurelia-binding/dist/amd/aurelia-binding.js') } }, entry: { app: ['./src/main'] }, output: { path: outDir, publicPath: baseUrl, filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js', sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map', chunkFilename: production ? '[chunkhash].chunk.js' : '[hash].chunk.js', }, devServer: { contentBase: baseUrl, }, module: { rules: [ // CSS required in JS/TS files should use the style-loader that auto-injects it into the website // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates { test: /\.css$/i, issuer: [{ not: [{ test: /\.html$/i }] }], use: extractCss ? ExtractTextPlugin.extract({ fallback: 'style-loader', use: cssRules, }) : ['style-loader', ...cssRules], }, { test: /\.css$/i, issuer: [{ test: /\.html$/i }], // CSS required in templates cannot be extracted safely // because Aurelia would try to require it again in runtime use: cssRules, }, { test: /\.html$/i, loader: 'html-loader' }, { test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir }, { test: /\.json$/i, loader: 'json-loader' }, // use Bluebird as the global Promise implementation: { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' }, // exposes jQuery globally as $ and as jQuery: { test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' }, // embed small images and fonts as Data Urls and larger ones as files: { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } }, { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } }, { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } }, // load these fonts normally, as files: { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' }, ...when(coverage, { test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader', include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i], enforce: 'post', options: { esModules: true }, }) ] }, plugins: [ new BrowserSyncPlugin({ // browse to http://localhost:3000/ during development, // ./public directory is being served host: 'localhost', port: 3000, server: { baseDir: ['dist'] } }), new AureliaPlugin(), new ProvidePlugin({ 'Promise': 'bluebird', '$': 'jquery', 'jQuery': 'jquery', 'window.jQuery': 'jquery', }), new TsConfigPathsPlugin(), new CheckerPlugin(), new HtmlWebpackPlugin({ template: 'index.ejs', minify: production ? { removeComments: true, collapseWhitespace: true } : undefined, metadata: { // available in index.ejs // title, server, baseUrl }, }), // new UglifyJSPlugin(), new CopyWebpackPlugin([ { from: 'static/favicon.ico', to: 'favicon.ico' } ,{ from: './../tr-host/projects', to: 'projects' } ,{ from: 'img', to: 'img' } ]), ...when(extractCss, new ExtractTextPlugin({ filename: production ? '[contenthash].css' : '[id].css', allChunks: true, })), ...when(production, new CommonsChunkPlugin({ name: ['vendor'] })), ...when(production, new CopyWebpackPlugin([ { from: 'static/favicon.ico', to: 'favicon.ico' } ])) // , // new BundleAnalyzerPlugin({ // // Can be `server`, `static` or `disabled`. // // In `server` mode analyzer will start HTTP server to show bundle report. // // In `static` mode single HTML file with bundle report will be generated. // // In `disabled` mode you can use this plugin to just generate Webpack Stats JSON file by setting `generateStatsFile` to `true`. // analyzerMode: 'static', // // Host that will be used in `server` mode to start HTTP server. // analyzerHost: '127.0.0.1', // // Port that will be used in `server` mode to start HTTP server. // analyzerPort: 8888, // // Path to bundle report file that will be generated in `static` mode. // // Relative to bundles output directory. // reportFilename: 'report.html', // // Module sizes to show in report by default. // // Should be one of `stat`, `parsed` or `gzip`. // // See "Definitions" section for more information. // defaultSizes: 'parsed', // // Automatically open report in default browser // openAnalyzer: false, // // If `true`, Webpack Stats JSON file will be generated in bundles output directory // generateStatsFile: false, // // Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`. // // Relative to bundles output directory. // statsFilename: 'stats.json', // // Options for `stats.toJson()` method. // // For example you can exclude sources of your modules from stats file with `source: false` option. // // See more options here: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21 // statsOptions: null, // // Log level. Can be 'info', 'warn', 'error' or 'silent'. // logLevel: 'info' // }) ], })
Make-IT-TR/TechRadar
tr-app/webpack.config.js
JavaScript
mit
7,154
--- title: The Coliseum author: rami layout: lifestream categories: [Lifestream] tags: [oakland, california, usa, instagram] image: the-coliseum.jpg --- {% include image.html url="/assets/images/content/lifestream/the-coliseum.jpg" description="The Coliseum Oakland Athletics" %}
rtaibah/jekyll-blog
_posts/lifestream/2012-10-12-the-coliseum-oakland-athletics-taken-with.md
Markdown
mit
283
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Enjoying The New</title> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600"> <link rel="stylesheet" href="/style.css"> <link rel="stylesheet" href="/custom.css"> <link rel="shortcut icon" href="https://micro.blog/joeduvall4/favicon.png" type="image/x-icon" /> <link rel="alternate" type="application/rss+xml" title="Joe Duvall" href="http://micro.blog.joe.duvall.me/feed.xml" /> <link rel="alternate" type="application/json" title="Joe Duvall" href="http://micro.blog.joe.duvall.me/feed.json" /> <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" /> <link rel="me" href="https://micro.blog/joeduvall4" /> <link rel="authorization_endpoint" href="https://indieauth.com/auth" /> <link rel="token_endpoint" href="https://tokens.indieauth.com/token" /> <link rel="micropub" href="https://micro.blog/micropub" /> <link rel="webmention" href="https://micro.blog/webmention" /> <link rel="subscribe" href="https://micro.blog/users/follow" /> </head> <body> <div class="container"> <header class="masthead"> <h1 class="masthead-title--small"> <a href="/">Joe Duvall</a> </h1> </header> <div class="content post h-entry"> <div class="post-date"> <time class="dt-published" datetime="2018-04-25 15:05:59 -0700">25 Apr 2018</time> </div> <div class="e-content"> <p>Enjoying the new Gmail redesign! It’s mostly solid, with a few rough edges, but it’s not labeled beta. Amusing that the original Gmail carried a “beta” tag for 5 years, but this redesign does not!</p> </div> </div> </div> </body> </html>
joeduvall4/joeduvall4.github.io
_site/2018/04/25/enjoying-the-new.html
HTML
mit
1,769
<!-- Begin Footer --> <footer id="footer" class="footer"> <div class="row"> <div class="pull-left col-md-6 col-xs-6"> <div class="g-plusone" data-size="medium" data-annotation="inline" data-width="300" data-href="{{ site.url }}"></div> </div> <div class="logo logo-footer logo-gray pull-right"></div> </div> <div class="row"> {% for block in site.footerBlocks %} {% assign colWidth = 12 | divided_by: forloop.length %} <div class="col-md-{{ colWidth }} col-xs-6"> <h5>{{ block.title }}</h5> <ul> {% for linkElement in block.links %} <li><a href="{% if linkElement.permalink != null %} {{ linkElement.permalink | prepend: site.baseurl }} {% else %} {{ linkElement.link }} {% endif %}" {% if linkElement.link != null %}target="_blank"{% endif %}>{{ linkElement.text }}</a></li> {% endfor %} </ul> </div> {% endfor %} </div> <div class="row"> <div class="col-md-6 col-xs-12"> <ul class="social-links"> {% for social in site.socialLinks %} <li> <a href="{% if social.permalink != null %} {{ social.permalink | prepend: site.baseurl }} {% else %} {{ social.link }} {% endif %}" target="_blank"> <svg class="icon icon-{{ social.icon }}" viewBox="0 0 30 32"> <use xlink:href="{{ site.baseurl }}/img/sprites/sprites.svg#icon-{{ social.icon }}"></use> </svg> </a> </li> {% endfor %} </ul> </div> </div> <div class="row"> <!-- Please don't delete this line--> <div class="col-md-6"> <p class="copyright"> &copy; 2014 Based on <a href="https://github.com/gdg-x/zeppelin" target="_blank">Project Zeppelin</a>. Designed and created by <a href="https://github.com/ozasadnyy" target="_blank">Oleh Zasadnyy</a> &middot; <a href="https://gdg.org.ua" target="_blank">GDG Lviv</a> </p> </div> </div> </footer> <!-- End Footer -->
gdg-x/zeppelin
_includes/footer.html
HTML
mit
1,836
# rustual-boy-www A basic landing page/blog for [Rustual Boy](https://github.com/emu-rs/rustual-boy). ## running locally 1. Update/install dependencies by running: `npm install` from the repo directory (safe to only do this once per pull) 2. Run the site: `node app` The site will be available on [localhost:3000](http://localhost:3000). To use another port, you can specify a just-in-time environment variable like so: `httpPort=[port] node app`. ## running in deployment Start the site: `sudo httpPort=80 useHttps=true pm2 start app.js` Note that `pm2` is used to spawn the app in a separate process so that the ssh terminal isn't blocked while it's running. To monitor the process, use `sudo pm2 list`. It can be restarted using `sudo pm2 restart app`, and if absolutely necessary, all node processes can be killed using `sudo pm2 kill`. ## blog The blog is built with [poet](http://jsantell.github.io/poet/), which means a couple things: - Posts are stored as .md files in the `posts/` directory. We've configured poet to watch the posts dir, but its watcher isn't recursive by default, so we can't use subdirectories. Therefore, all posts follow a simple naming convention: `category-number-postname.md`. This way they can stay cleanly organized within this single folder. - Post slugs are generated using the title of the post, so these can't be changed without also invalidating the post url. - Post dates use the nonintuitive American format (M-D-Y) ## demo reel Just in case I lose them later, here's the encoding settings used for the demo reel video: ``` ffmpeg.exe -i reel.mkv -c:v libvpx -qmin 0 -qmax 50 -crf 5 -b:v 1M -an -r 25 reel.webm ffmpeg.exe -i reel.mkv -c:v libx264 -pix_fmt yuv420p -profile:v baseline -b:v 600k -pass 1 -level 3 -movflags +faststart -an -r 25 -f mp4 /dev/null && \ ffmpeg.exe -i reel.mkv -c:v libx264 -pix_fmt yuv420p -profile:v baseline -b:v 600k -pass 2 -level 3 -movflags +faststart -an -r 25 reel.mp4 ``` ## license MIT (see [LICENSE](LICENSE))
yupferris/rustual-boy-www
README.md
Markdown
mit
2,004
#!/bin/env/python # coding: utf-8 import logging import os import time import uuid from logging import Formatter from logging.handlers import RotatingFileHandler from multiprocessing import Queue from time import strftime import dill from .commands import * from .processing import MultiprocessingLogger class TaskProgress(object): """ Holds both data and graphics-related information for a task's progress bar. The logger will iterate over TaskProgress objects to draw progress bars on screen. """ def __init__(self, total, prefix='', suffix='', decimals=0, bar_length=60, keep_alive=False, display_time=False): """ Creates a new progress bar using the given information. :param total: The total number of iteration for this progress bar. :param prefix: [Optional] The text that should be displayed at the left side of the progress bar. Note that progress bars will always stay left-aligned at the shortest possible. :param suffix: [Optional] The text that should be displayed at the very right side of the progress bar. :param decimals: [Optional] The number of decimals to display for the percentage. :param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character. :param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever once completed or if it should vanish. :param display_time: [Optional] Specify whether the duration since the progress has begun should be displayed. Running time will be displayed between parenthesis, whereas it will be displayed between brackets when the progress has completed. """ super(TaskProgress, self).__init__() self.progress = 0 # Minimum number of seconds at maximum completion before a progress bar is removed from display # The progress bar may vanish at a further time as the redraw rate depends upon chrono AND method calls self.timeout_chrono = None self.begin_time = None self.end_time = None self.elapsed_time_at_end = None # Graphics related information self.keep_alive = keep_alive self.display_time = display_time self.total = total self.prefix = prefix self.suffix = suffix self.decimals = decimals self.bar_length = bar_length def set_progress(self, progress): """ Defines the current progress for this progress bar in iteration units (not percent). :param progress: Current progress in iteration units regarding its total (not percent). :return: True if the progress has changed. If the given progress is higher than the total or lower than 0 then it will be ignored. """ _progress = progress if _progress > self.total: _progress = self.total elif _progress < 0: _progress = 0 # Stop task chrono if needed if _progress == self.total and self.display_time: self.end_time = time.time() * 1000 # If the task has completed instantly then define its begin_time too if not self.begin_time: self.begin_time = self.end_time has_changed = self.progress != _progress if has_changed: self.progress = _progress return has_changed class FancyLogger(object): """ Defines a multiprocess logger object. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. Logger uses one file handler and then uses standard output (stdout) to draw on screen. """ queue = None "Handles all messages and progress to be sent to the logger process." default_message_number = 20 "Default value for the logger configuration." default_exception_number = 5 "Default value for the logger configuration." default_permanent_progressbar_slots = 0 "Default value for the logger configuration." default_redraw_frequency_millis = 500 "Default value for the logger configuration." default_level = logging.INFO "Default value for the logger configuration." default_task_millis_to_removal = 500 "Default value for the logger configuration." default_console_format_strftime = '%d %B %Y %H:%M:%S' "Default value for the logger configuration." default_console_format = '{T} [{L}]' "Default value for the logger configuration." default_file_handlers = [] "Default value for the logger configuration. Filled in constructor." def __init__(self, message_number=default_message_number, exception_number=default_exception_number, permanent_progressbar_slots=default_permanent_progressbar_slots, redraw_frequency_millis=default_redraw_frequency_millis, console_level=default_level, task_millis_to_removal=default_task_millis_to_removal, console_format_strftime=default_console_format_strftime, console_format=default_console_format, file_handlers=None, application_name=None): """ Initializes a new logger and starts its process immediately using given configuration. :param message_number: [Optional] Number of simultaneously displayed messages below progress bars. :param exception_number: [Optional] Number of simultaneously displayed exceptions below messages. :param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times, so the message logger will not move anymore if the bar number is equal or lower than this parameter. :param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be more because the redraw rate depends upon time AND method calls. :param console_level: [Optional] The logging level (from standard logging module). :param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before a progress bar is removed from display. The progress bar may vanish at a further time as the redraw rate depends upon time AND method calls. :param console_format_strftime: [Optional] Specify the time format for console log lines using python strftime format. Defaults to format: '29 november 2016 21:52:12'. :param console_format: [Optional] Specify the format of the console log lines. There are two variables available: {T} for timestamp, {L} for level. Will then add some tabulations in order to align text beginning for all levels. Defaults to format: '{T} [{L}]' Which will produce: '29 november 2016 21:52:12 [INFO] my log text' '29 november 2016 21:52:13 [WARNING] my log text' '29 november 2016 21:52:14 [DEBUG] my log text' :param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its own regular formatter and level. Console logging is distinct from file logging. Console logging uses custom stdout formatting, while file logging uses regular python logging rules. All handlers are permitted except StreamHandler if used with stdout or stderr which are reserved by this library for custom console output. :param application_name: [Optional] Used only if 'file_handlers' parameter is ignored. Specifies the application name to use to format the default file logger using format: application_%Y-%m-%d_%H-%M-%S.log """ super(FancyLogger, self).__init__() # Define default file handlers if not file_handlers: if not application_name: app_name = 'application' else: app_name = application_name handler = RotatingFileHandler(filename=os.path.join(os.getcwd(), '{}_{}.log' .format(app_name, strftime('%Y-%m-%d_%H-%M-%S'))), encoding='utf8', maxBytes=5242880, # 5 MB backupCount=10, delay=True) handler.setLevel(logging.INFO) handler.setFormatter(fmt=Formatter(fmt='%(asctime)s [%(levelname)s]\t%(message)s', datefmt=self.default_console_format_strftime)) self.default_file_handlers.append(handler) file_handlers = self.default_file_handlers if not self.queue: self.queue = Queue() self.process = MultiprocessingLogger(queue=self.queue, console_level=console_level, message_number=message_number, exception_number=exception_number, permanent_progressbar_slots=permanent_progressbar_slots, redraw_frequency_millis=redraw_frequency_millis, task_millis_to_removal=task_millis_to_removal, console_format_strftime=console_format_strftime, console_format=console_format, file_handlers=file_handlers) self.process.start() def flush(self): """ Flushes the remaining messages and progress bars state by forcing redraw. Can be useful if you want to be sure that a message or progress has been updated in display at a given moment in code, like when you are exiting an application or doing some kind of synchronized operations. """ self.queue.put(dill.dumps(FlushCommand())) def terminate(self): """ Tells the logger process to exit immediately. If you do not call 'flush' method before, you may lose some messages of progresses that have not been displayed yet. This method blocks until logger process has stopped. """ self.queue.put(dill.dumps(ExitCommand())) if self.process: self.process.join() def set_configuration(self, message_number=default_message_number, exception_number=default_exception_number, permanent_progressbar_slots=default_permanent_progressbar_slots, redraw_frequency_millis=default_redraw_frequency_millis, console_level=default_level, task_millis_to_removal=default_task_millis_to_removal, console_format_strftime=default_console_format_strftime, console_format=default_console_format, file_handlers=default_file_handlers): """ Defines the current configuration of the logger. Can be used at any moment during runtime to modify the logger behavior. :param message_number: [Optional] Number of simultaneously displayed messages below progress bars. :param exception_number: [Optional] Number of simultaneously displayed exceptions below messages. :param permanent_progressbar_slots: [Optional] The amount of vertical space (bar slots) to keep at all times, so the message logger will not move anymore if the bar number is equal or lower than this parameter. :param redraw_frequency_millis: [Optional] Minimum time lapse in milliseconds between two redraws. It may be more because the redraw rate depends upon time AND method calls. :param console_level: [Optional] The logging level (from standard logging module). :param task_millis_to_removal: [Optional] Minimum time lapse in milliseconds at maximum completion before a progress bar is removed from display. The progress bar may vanish at a further time as the redraw rate depends upon time AND method calls. :param console_format_strftime: [Optional] Specify the time format for console log lines using python strftime format. Defaults to format: '29 november 2016 21:52:12'. :param console_format: [Optional] Specify the format of the console log lines. There are two variables available: {T} for timestamp, {L} for level. Will then add some tabulations in order to align text beginning for all levels. Defaults to format: '{T} [{L}]' Which will produce: '29 november 2016 21:52:12 [INFO] my log text' '29 november 2016 21:52:13 [WARNING] my log text' '29 november 2016 21:52:14 [DEBUG] my log text' :param file_handlers: [Optional] Specify the file handlers to use. Each file handler will use its own regular formatter and level. Console logging is distinct from file logging. Console logging uses custom stdout formatting, while file logging uses regular python logging rules. All handlers are permitted except StreamHandler if used with stdout or stderr which are reserved by this library for custom console output. """ self.queue.put(dill.dumps(SetConfigurationCommand(task_millis_to_removal=task_millis_to_removal, console_level=console_level, permanent_progressbar_slots=permanent_progressbar_slots, message_number=message_number, exception_number=exception_number, redraw_frequency_millis=redraw_frequency_millis, console_format_strftime=console_format_strftime, console_format=console_format, file_handlers=file_handlers))) def set_level(self, level, console_only=False): """ Defines the logging level (from standard logging module) for log messages. :param level: Level of logging for the file logger. :param console_only: [Optional] If True then the file logger will not be affected. """ self.queue.put(dill.dumps(SetLevelCommand(level=level, console_only=console_only))) def set_task_object(self, task_id, task_progress_object): """ Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing. :param task_progress_object: TaskProgress object holding the progress bar information. """ self.set_task(task_id=task_id, total=task_progress_object.total, prefix=task_progress_object.prefix, suffix=task_progress_object.suffix, decimals=task_progress_object.decimals, bar_length=task_progress_object.bar_length, keep_alive=task_progress_object.keep_alive, display_time=task_progress_object.display_time) def set_task(self, task_id, total, prefix, suffix='', decimals=0, bar_length=60, keep_alive=False, display_time=False): """ Defines a new progress bar with the given information. :param task_id: Unique identifier for this progress bar. Will erase if already existing. :param total: The total number of iteration for this progress bar. :param prefix: The text that should be displayed at the left side of the progress bar. Note that progress bars will always stay left-aligned at the shortest possible. :param suffix: [Optional] The text that should be displayed at the very right side of the progress bar. :param decimals: [Optional] The number of decimals to display for the percentage. :param bar_length: [Optional] The graphical bar size displayed on screen. Unit is character. :param keep_alive: [Optional] Specify whether the progress bar should stay displayed forever once completed or if it should vanish. :param display_time: [Optional] Specify whether the duration since the progress has begun should be displayed. Running time will be displayed between parenthesis, whereas it will be displayed between brackets when the progress has completed. """ self.queue.put(dill.dumps(NewTaskCommand(task_id=task_id, task=TaskProgress(total, prefix, suffix, decimals, bar_length, keep_alive, display_time)))) def update(self, task_id, progress): """ Defines the current progress for this progress bar id in iteration units (not percent). If the given id does not exist or the given progress is identical to the current, then does nothing. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param task_id: Unique identifier for this progress bar. Will erase if already existing. :param progress: Current progress in iteration units regarding its total (not percent). """ self.queue.put(dill.dumps(UpdateProgressCommand(task_id=task_id, progress=progress))) def debug(self, text): """ Posts a debug message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console. """ self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.DEBUG))) def info(self, text): """ Posts an info message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console. """ self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.INFO))) def warning(self, text): """ Posts a warning message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console. """ self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.WARNING))) def error(self, text): """ Posts an error message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console. """ self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.ERROR))) def critical(self, text): """ Posts a critical message adding a timestamp and logging level to it for both file and console handlers. Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress at the very time they are being logged but their timestamp will be captured at the right time. Logger will redraw at a given time period AND when new messages or progress are logged. If you still want to force redraw immediately (may produce flickering) then call 'flush' method. :param text: The text to log into file and console. """ self.queue.put(dill.dumps(LogMessageCommand(text=text, level=logging.CRITICAL))) def throw(self, stacktrace, process_title=None): """ Sends an exception to the logger so it can display it as a special message. Prevents console refresh cycles from hiding exceptions that could be thrown by processes. :param stacktrace: Stacktrace string as returned by 'traceback.format_exc()' in an 'except' block. :param process_title: [Optional] Define the current process title to display into the logger for this exception. """ self.queue.put(dill.dumps(StacktraceCommand(pid=os.getpid(), stacktrace=stacktrace, process_title=process_title))) # -------------------------------------------------------------------- # Iterator implementation def progress(self, enumerable, task_progress_object=None): """ Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger. :param enumerable: Collection to iterate over. :param task_progress_object: [Optional] TaskProgress object holding the progress bar information. :return: The logger instance. """ self.list = enumerable self.list_length = len(enumerable) self.task_id = uuid.uuid4() self.index = 0 if task_progress_object: # Force total attribute task_progress_object.total = self.list_length else: task_progress_object = TaskProgress(total=self.list_length, display_time=True, prefix='Progress') # Create a task progress self.set_task_object(task_id=self.task_id, task_progress_object=task_progress_object) return self def __iter__(self): """ Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger. :return: The logger instance. """ return self def __next__(self): """ Enables the object to be used as an iterator. Each iteration will produce a progress update in the logger. :return: The current object of the iterator. """ if self.index >= self.list_length: raise StopIteration else: self.index += 1 self.update(task_id=self.task_id, progress=self.index) return self.list[self.index - 1] # ---------------------------------------------------------------------
peepall/FancyLogger
FancyLogger/__init__.py
Python
mit
27,844
<html><body> <h4>Windows 10 x64 (18362.329)</h4><br> <h2>_DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT</h2> <font face="arial"> +0x000 Size : Uint4B<br> +0x004 Action : Uint4B<br> +0x008 Flags : Uint4B<br> +0x00c OperationStatus : Uint4B<br> +0x010 ExtendedError : Uint4B<br> +0x014 TargetDetailedError : Uint4B<br> +0x018 ReservedStatus : Uint4B<br> +0x01c OutputBlockOffset : Uint4B<br> +0x020 OutputBlockLength : Uint4B<br> </font></body></html>
epikcraw/ggool
public/Windows 10 x64 (18362.329)/_DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT.html
HTML
mit
521
package com.rebuy.consul; import com.ecwid.consul.v1.ConsulClient; import com.ecwid.consul.v1.QueryParams; import com.ecwid.consul.v1.Response; import com.ecwid.consul.v1.agent.model.NewService; import com.ecwid.consul.v1.catalog.model.CatalogService; import com.rebuy.consul.exceptions.NoServiceFoundException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ConsulServiceTest { private ConsulClient clientMock; private ConsulService service; private NewService serviceMock; @Before public void before() { clientMock = mock(ConsulClient.class); serviceMock = mock(NewService.class); when(serviceMock.getId()).thenReturn("42"); service = new ConsulService(clientMock, serviceMock); } @Test public void register_should_invoke_client() { when(clientMock.agentServiceRegister(Mockito.any())).thenReturn(null); service.register(); Mockito.verify(clientMock).agentServiceRegister(serviceMock); } @Test public void unregister_should_invoke_client() { service.unregister(); Mockito.verify(clientMock).agentServiceSetMaintenance("42", true); } @Test(expected = NoServiceFoundException.class) public void findService_should_throw_exception_if_no_services_are_found() { Response<List<CatalogService>> response = new Response<>(new ArrayList<>(), 1L, true, 1L); when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response); service.getRandomService("service"); Mockito.verify(clientMock).getCatalogService("service", Mockito.any(QueryParams.class)); } @Test public void findService_should_invoke_client() { List<CatalogService> services = new ArrayList<>(); services.add(mock(CatalogService.class)); Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L); when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response); service.getRandomService("service"); Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class)); } @Test public void findService_should_return_one_service() { List<CatalogService> services = new ArrayList<>(); CatalogService service1 = mock(CatalogService.class); when(service1.getAddress()).thenReturn("192.168.0.1"); services.add(service1); CatalogService service2 = mock(CatalogService.class); when(service2.getAddress()).thenReturn("192.168.0.2"); services.add(service2); CatalogService service3 = mock(CatalogService.class); when(service3.getAddress()).thenReturn("192.168.0.3"); services.add(service3); Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L); when(clientMock.getCatalogService(Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response); Service catalogService = service.getRandomService("service"); boolean foundMatch = false; for (CatalogService service : services) { if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) { foundMatch = true; } } assertTrue(foundMatch); Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.any(QueryParams.class)); } @Test public void findService_should_return_one_service_with_tag() { List<CatalogService> services = new ArrayList<>(); CatalogService service1 = mock(CatalogService.class); when(service1.getAddress()).thenReturn("192.168.0.1"); services.add(service1); CatalogService service2 = mock(CatalogService.class); when(service2.getAddress()).thenReturn("192.168.0.2"); services.add(service2); CatalogService service3 = mock(CatalogService.class); when(service3.getAddress()).thenReturn("192.168.0.3"); services.add(service3); Response<List<CatalogService>> response = new Response<>(services, 1L, true, 1L); when(clientMock.getCatalogService(Mockito.anyString(), Mockito.anyString(), Mockito.any(QueryParams.class))).thenReturn(response); Service catalogService = service.getRandomService("service", "my-tag"); boolean foundMatch = false; for (CatalogService service : services) { if (service.getAddress().equals(catalogService.getHostname()) && service.getServicePort() == catalogService.getPort()) { foundMatch = true; } } assertTrue(foundMatch); Mockito.verify(clientMock).getCatalogService(Mockito.eq("service"), Mockito.eq("my-tag"), Mockito.any(QueryParams.class)); } }
rebuy-de/consul-java-client
src/test/java/com/rebuy/consul/ConsulServiceTest.java
Java
mit
5,239
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace XamarinFormsHello.WinPhone { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new XamarinFormsHello.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
xamarin-samples/XamarinFormsHello
XamarinFormsHello/XamarinFormsHello.WinPhone/MainPage.xaml.cs
C#
mit
1,557
<?php namespace LeadCommerce\Shopware\SDK\Query; use LeadCommerce\Shopware\SDK\Util\Constants; /** * Class CustomerQuery * * @author Alexander Mahrt <[email protected]> * @copyright 2016 LeadCommerce <[email protected]> */ class CustomerQuery extends Base { /** * @var array */ protected $methodsAllowed = [ Constants::METHOD_CREATE, Constants::METHOD_GET, Constants::METHOD_GET_BATCH, Constants::METHOD_UPDATE, Constants::METHOD_DELETE, ]; /** * @return mixed */ protected function getClass() { return 'LeadCommerce\\Shopware\\SDK\\Entity\\Customer'; } /** * Gets the query path to look for entities. * E.G: 'variants' or 'articles' * * @return string */ protected function getQueryPath() { return 'customers'; } }
LeadCommerceDE/shopware-sdk
src/LeadCommerce/Shopware/SDK/Query/CustomerQuery.php
PHP
mit
881
--- @module vline local BASE = (...):match("(.-)[^%.]+$") local core = require( BASE .. "core" ) local style = require( BASE .. "style" ) local group = {} ------------------------------------------------------------------------------- -- vertically allign all elements ------------------------------------------------------------------------------- function group.v_align( elements, align, x ) x = x or style.getCenterX() if align == "left" then for _, rect in ipairs( elements ) do rect.x = x end elseif align == "right" then for _, rect in ipairs( elements ) do rect.x = x - rect.w end elseif align == "center" then for _, rect in ipairs( elements ) do rect.x = x - rect.w / 2 end else error( "group.v_align invalid align: " .. tostring( align ) ) end end ------------------------------------------------------------------------------- -- horizontally allign all elements ------------------------------------------------------------------------------- function group.h_align( elements, align, y ) y = y or style.getCenterY() if align == "top" then for _, rect in ipairs( elements ) do rect.y = y end elseif align == "bottom" then for _, rect in ipairs( elements ) do rect.y = y - rect.h end elseif align == "center" then for _, rect in ipairs( elements ) do rect.y = y - rect.h / 2 end else error( "group.h_align invalid align: " .. tostring( align ) ) end end ------------------------------------------------------------------------------- -- arrange elements from top to bottom with vertical spacing in between ------------------------------------------------------------------------------- function group.v_distribute( elements, spacing ) if spacing and elements[ 1 ] then local y = elements[ 1 ].y for _, rect in ipairs( elements ) do rect.y = y y = y + rect.h + spacing end end end ------------------------------------------------------------------------------- -- make all elements have same width ------------------------------------------------------------------------------- function group.stretch_w( elements ) local w = 0 for _, rect in ipairs( elements ) do w = math.max( w, rect.w ) end for _, rect in ipairs( elements ) do rect.w = w end end ------------------------------------------------------------------------------- -- returns the arithmetic center of group ------------------------------------------------------------------------------- function group.get_center( elements ) local cx = 0 local cy = 0 local n = 0 for _, rect in ipairs( elements ) do cx = cx + rect.x + rect.w / 2 cy = cy + rect.y + rect.h / 2 n = n + 1 end if n == 0 then return style.getCenterX(), style.getCenterY() else return math.floor( cx / n ), math.floor( cy / n ) end end ------------------------------------------------------------------------------- -- centers whole group on screen; preserves element distances ------------------------------------------------------------------------------- function group.center_on_screen( elements ) local sx, sy = style.getCenterX(), style.getCenterY() local dx, dy = group.get_center( elements ) for _, rect in ipairs( elements ) do local rx = rect.x + rect.w / 2 local ry = rect.y + rect.h / 2 rect.x = math.floor( rect.x + sx - dx ) rect.y = math.floor( rect.y + sy - dy ) end end ------------------------------------------------------------------------------- return group
cohadar/love-graphics-experiments
imgui/group.lua
Lua
mit
3,459
**Blight** **School** necromancy; **Level** druid 4, sorcerer/wizard 5 **Casting Time** 1 standard action **Components** V, S, DF **Range** touch **Target** plant touched **Duration** instantaneous **Saving Throw** [Fortitude](../combat#_fortitude) half; see text; **[Spell Resistance](../glossary#_spell-resistance)** yes This spell withers a single plant of any size. An affected plant creature takes 1d6 points of damage per level (maximum 15d6) and may attempt a [Fortitude](../combat#_fortitude) saving throw for half damage. A plant that isn't a creature doesn't receive a save and immediately withers and dies. This spell has no effect on the soil or surrounding plant life.
brunokoga/pathfinder-markdown
prd_markdown/spells/blight.md
Markdown
mit
693
<?php namespace GFire\InvoiceBundle\Entity\Interfaces; interface InvoiceInterface{ }
jerickduguran/gfirev2
src/GFire/InvoiceBundle/Entity/Interfaces/InvoiceInterface.php
PHP
mit
87
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package test.thread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Administrator */ public class CallableAndFutureTest { private final ExecutorService executor = Executors.newFixedThreadPool(2); void start() throws Exception { final Callable<List<Integer>> task = new Callable<List<Integer>>() { public List<Integer> call() throws Exception { // get obj final List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { Thread.sleep(50); list.add(i); } return list; } }; final Future<List<Integer>> future = executor.submit(task); //do sthing others.. //example: due to show some data.. try { final List<Integer> list = future.get(); //这个函数还可以接受超时检测http://www.javaeye.com/topic/671314 System.out.println(list); } catch (final InterruptedException ex) { Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex); future.cancel(true); } catch (final ExecutionException ex) { Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex); throw new ExecutionException(ex); } finally { executor.shutdown(); } } public static void main(final String args[]) { try { new CallableAndFutureTest().start(); } catch (final Exception ex) { Logger.getLogger(CallableAndFutureTest.class.getName()).log(Level.SEVERE, null, ex); } } }
atealxt/work-workspaces
Test_Java/src/test/thread/CallableAndFutureTest.java
Java
mit
2,091
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IWorkbookFunctionsCumPrincRequestBuilder. /// </summary> public partial interface IWorkbookFunctionsCumPrincRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IWorkbookFunctionsCumPrincRequest Request(IEnumerable<Option> options = null); } }
garethj-msft/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IWorkbookFunctionsCumPrincRequestBuilder.cs
C#
mit
997
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.eventhubs.generated; import com.azure.core.util.Context; /** Samples for ConsumerGroups ListByEventHub. */ public final class ConsumerGroupsListByEventHubSamples { /* * x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/EHConsumerGroupListByEventHub.json */ /** * Sample code: ConsumerGroupsListAll. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void consumerGroupsListAll(com.azure.resourcemanager.AzureResourceManager azure) { azure .eventHubs() .manager() .serviceClient() .getConsumerGroups() .listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE); } }
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/eventhubs/generated/ConsumerGroupsListByEventHubSamples.java
Java
mit
1,031
/** @jsx m */ import m from 'mithril'; import { linkTo, hrefTo } from '@storybook/addon-links'; const Main = { view: vnode => ( <article style={{ padding: 15, lineHeight: 1.4, fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif', backgroundColor: '#ffffff', }} > {vnode.children} </article> ), }; const Title = { view: vnode => <h1>{vnode.children}</h1>, }; const Note = { view: vnode => ( <p style={{ opacity: 0.5, }} > {vnode.children} </p> ), }; const InlineCode = { view: vnode => ( <code style={{ fontSize: 15, fontWeight: 600, padding: '2px 5px', border: '1px solid #eae9e9', borderRadius: 4, backgroundColor: '#f3f2f2', color: '#3a3a3a', }} > {vnode.children} </code> ), }; const Link = { view: vnode => ( <a style={{ color: '#1474f3', textDecoration: 'none', borderBottom: '1px solid #1474f3', paddingBottom: 2, }} {...vnode.attrs} > {vnode.children} </a> ), }; const NavButton = { view: vnode => ( <button type="button" style={{ borderTop: 'none', borderRight: 'none', borderLeft: 'none', backgroundColor: 'transparent', padding: 0, cursor: 'pointer', font: 'inherit', }} {...vnode.attrs} > {vnode.children} </button> ), }; const StoryLink = { oninit: vnode => { // eslint-disable-next-line no-param-reassign vnode.state.href = '/'; // eslint-disable-next-line no-param-reassign vnode.state.onclick = () => { linkTo(vnode.attrs.kind, vnode.attrs.story)(); return false; }; StoryLink.updateHref(vnode); }, updateHref: async vnode => { const href = await hrefTo(vnode.attrs.kind, vnode.attrs.story); // eslint-disable-next-line no-param-reassign vnode.state.href = href; m.redraw(); }, view: vnode => ( <a href={vnode.state.href} style={{ color: '#1474f3', textDecoration: 'none', borderBottom: '1px solid #1474f3', paddingBottom: 2, }} onClick={vnode.state.onclick} > {vnode.children} </a> ), }; const Welcome = { view: vnode => ( <Main> <Title>Welcome to storybook</Title> <p>This is a UI component dev environment for your app.</p> <p> We've added some basic stories inside the <InlineCode>src/stories</InlineCode> directory. <br />A story is a single state of one or more UI components. You can have as many stories as you want. <br /> (Basically a story is like a visual test case.) </p> <p> See these sample&nbsp; {vnode.attrs.showApp ? ( <NavButton onclick={vnode.attrs.showApp}>stories</NavButton> ) : ( <StoryLink kind={vnode.attrs.showKind} story={vnode.attrs.showStory}> stories </StoryLink> )} &nbsp;for a component called <InlineCode>Button</InlineCode>. </p> <p> Just like that, you can add your own components as stories. <br /> You can also edit those components and see changes right away. <br /> (Try editing the <InlineCode>Button</InlineCode> stories located at&nbsp; <InlineCode>src/stories/1-Button.stories.js</InlineCode> .) </p> <p> Usually we create stories with smaller UI components in the app. <br /> Have a look at the&nbsp; <Link href="https://storybook.js.org/basics/writing-stories" target="_blank" rel="noopener noreferrer" > Writing Stories </Link> &nbsp;section in our documentation. </p> <Note> <b>NOTE:</b> <br /> Have a look at the <InlineCode>.storybook/webpack.config.js</InlineCode> to add webpack loaders and plugins you are using in this project. </Note> </Main> ), }; export default Welcome;
storybooks/react-storybook
lib/cli/generators/MITHRIL/template-csf/stories/Welcome.js
JavaScript
mit
4,185
from simtk.openmm import app import simtk.openmm as mm from simtk import unit def findForce(system, forcetype, add=True): """ Finds a specific force in the system force list - added if not found.""" for force in system.getForces(): if isinstance(force, forcetype): return force if add==True: system.addForce(forcetype()) return findForce(system, forcetype) return None def setGlobalForceParameter(force, key, value): for i in range(force.getNumGlobalParameters()): if force.getGlobalParameterName(i)==key: print('setting force parameter', key, '=', value) force.setGlobalParameterDefaultValue(i, value); def atomIndexInResidue(residue): """ list of atom index in residue """ index=[] for a in list(residue.atoms()): index.append(a.index) return index def getResiduePositions(residue, positions): """ Returns array w. atomic positions of residue """ ndx = atomIndexInResidue(residue) return np.array(positions)[ndx] def uniquePairs(index): """ list of unique, internal pairs """ return list(combinations( range(index[0],index[-1]+1),2 ) ) def addHarmonicConstraint(harmonicforce, pairlist, positions, threshold, k): """ add harmonic bonds between pairs if distance is smaller than threshold """ print('Constraint force constant =', k) for i,j in pairlist: distance = unit.norm( positions[i]-positions[j] ) if distance<threshold: harmonicforce.addBond( i,j, distance.value_in_unit(unit.nanometer), k.value_in_unit( unit.kilojoule/unit.nanometer**2/unit.mole )) print("added harmonic bond between", i, j, 'with distance',distance) def addExclusions(nonbondedforce, pairlist): """ add nonbonded exclusions between pairs """ for i,j in pairlist: nonbondedforce.addExclusion(i,j) def rigidifyResidue(residue, harmonicforce, positions, nonbondedforce=None, threshold=6.0*unit.angstrom, k=2500*unit.kilojoule/unit.nanometer**2/unit.mole): """ make residue rigid by adding constraints and nonbonded exclusions """ index = atomIndexInResidue(residue) pairlist = uniquePairs(index) addHarmonicConstraint(harmonic, pairlist, pdb.positions, threshold, k) if nonbondedforce is not None: for i,j in pairlist: print('added nonbonded exclusion between', i, j) nonbonded.addExclusion(i,j)
mlund/pyha
pyha/openmm.py
Python
mit
2,333
namespace InControl { using System; // @cond nodoc [AutoDiscover] public class EightBitdoSNES30AndroidProfile : UnityInputDeviceProfile { public EightBitdoSNES30AndroidProfile() { Name = "8Bitdo SNES30 Controller"; Meta = "8Bitdo SNES30 Controller on Android"; // Link = "https://www.amazon.com/Wireless-Bluetooth-Controller-Classic-Joystick/dp/B014QP2H1E"; DeviceClass = InputDeviceClass.Controller; DeviceStyle = InputDeviceStyle.NintendoSNES; IncludePlatforms = new[] { "Android" }; JoystickNames = new[] { "8Bitdo SNES30 GamePad", }; ButtonMappings = new[] { new InputControlMapping { Handle = "A", Target = InputControlType.Action2, Source = Button( 0 ), }, new InputControlMapping { Handle = "B", Target = InputControlType.Action1, Source = Button( 1 ), }, new InputControlMapping { Handle = "X", Target = InputControlType.Action4, Source = Button( 2 ), }, new InputControlMapping { Handle = "Y", Target = InputControlType.Action3, Source = Button( 3 ), }, new InputControlMapping { Handle = "L", Target = InputControlType.LeftBumper, Source = Button( 4 ), }, new InputControlMapping { Handle = "R", Target = InputControlType.RightBumper, Source = Button( 5 ), }, new InputControlMapping { Handle = "Select", Target = InputControlType.Select, Source = Button( 11 ), }, new InputControlMapping { Handle = "Start", Target = InputControlType.Start, Source = Button( 10 ), }, }; AnalogMappings = new[] { new InputControlMapping { Handle = "DPad Left", Target = InputControlType.DPadLeft, Source = Analog( 0 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Right", Target = InputControlType.DPadRight, Source = Analog( 0 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = Analog( 1 ), SourceRange = InputRange.ZeroToMinusOne, TargetRange = InputRange.ZeroToOne, }, new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = Analog( 1 ), SourceRange = InputRange.ZeroToOne, TargetRange = InputRange.ZeroToOne, }, }; } } // @endcond }
benthroop/Frankenweapon
Assets/InControl/Source/Unity/DeviceProfiles/EightBitdoSNES30AndroidProfile.cs
C#
mit
2,543
#pragma once #include "Component.h" #include "Transform.h" #include "CubeMesh.h" using namespace Beans; class PlayerController : public Component, public Utilities::AutoLister<PlayerController> { public: PlayerController(GameObject* owner); REFLECT_CLASS; static void UpdatePlayerControllers(double dt); void Update(double dt); double speed; private: Transform* transform_; CubeMesh* sprite_; };
jacobmcleman/MagicBeans
Engine/MagicBeansEngine/TestApplication/TestPlayerController.h
C
mit
414
package context import ( "github.com/Everlane/evan/common" "github.com/satori/go.uuid" ) // Stores state relating to a deployment. type Deployment struct { uuid uuid.UUID application common.Application environment string strategy common.Strategy ref string sha1 string flags map[string]interface{} store common.Store // Internal state currentState common.DeploymentState currentPhase common.Phase lastError error } // Create a deployment for the given application to an environment. func NewDeployment(app common.Application, environment string, strategy common.Strategy, ref string, flags map[string]interface{}) *Deployment { return &Deployment{ uuid: uuid.NewV1(), application: app, environment: environment, strategy: strategy, ref: ref, flags: flags, currentState: common.DEPLOYMENT_PENDING, } } func NewBareDeployment() *Deployment { return &Deployment{ flags: make(map[string]interface{}), } } func (deployment *Deployment) UUID() uuid.UUID { return deployment.uuid } func (deployment *Deployment) Application() common.Application { return deployment.application } func (deployment *Deployment) Environment() string { return deployment.environment } func (deployment *Deployment) Strategy() common.Strategy { return deployment.strategy } func (deployment *Deployment) Ref() string { return deployment.ref } func (deployment *Deployment) SHA1() string { return deployment.sha1 } func (deployment *Deployment) SetSHA1(sha1 string) { deployment.sha1 = sha1 } func (deployment *Deployment) MostPreciseRef() string { if deployment.sha1 != "" { return deployment.sha1 } else { return deployment.ref } } func (deployment *Deployment) SetStoreAndSave(store common.Store) error { deployment.store = store return store.SaveDeployment(deployment) } // Will panic if it is unable to save. This will be called *after* // `SetStoreAndSave` should have been called, so we're assuming that if that // worked then this should also work. func (deployment *Deployment) setStateAndSave(state common.DeploymentState) { deployment.currentState = state err := deployment.store.SaveDeployment(deployment) if err != nil { panic(err) } } func (deployment *Deployment) Flags() map[string]interface{} { return deployment.flags } func (deployment *Deployment) HasFlag(key string) bool { _, present := deployment.flags[key] return present } func (deployment *Deployment) Flag(key string) interface{} { return deployment.flags[key] } func (deployment *Deployment) SetFlag(key string, value interface{}) { deployment.flags[key] = value } // Looks for the "force" boolean in the `flags`. func (deployment *Deployment) IsForce() bool { if force, ok := deployment.Flag("force").(bool); ok { return force } else { return false } } func (deployment *Deployment) Status() common.DeploymentStatus { var phase common.Phase if deployment.currentState == common.RUNNING_PHASE { phase = deployment.currentPhase } return common.DeploymentStatus{ State: deployment.currentState, Phase: phase, Error: nil, } } func (deployment *Deployment) CheckPreconditions() error { deployment.setStateAndSave(common.RUNNING_PRECONDITIONS) preconditions := deployment.strategy.Preconditions() for _, precondition := range preconditions { err := precondition.Status(deployment) if err != nil { return err } } return nil } // Internal implementation of running phases. Manages setting // `deployment.currentPhase` to the phase currently executing. func (deployment *Deployment) runPhases(preloadResults PreloadResults) error { phases := deployment.strategy.Phases() for _, phase := range phases { deployment.currentPhase = phase preloadResult := preloadResults.Get(phase) err := phase.Execute(deployment, preloadResult) if err != nil { return err } } return nil } // Runs all the phases configured in the `Strategy`. Sets `currentState` and // `currentPhase` fields as appropriate. If an error occurs it will also set // the `lastError` field to that error. func (deployment *Deployment) RunPhases() error { results, err := deployment.RunPhasePreloads() if err != nil { deployment.lastError = err deployment.setStateAndSave(common.DEPLOYMENT_ERROR) return err } deployment.setStateAndSave(common.RUNNING_PHASE) err = deployment.runPhases(results) if err != nil { deployment.lastError = err deployment.setStateAndSave(common.DEPLOYMENT_ERROR) return err } else { deployment.setStateAndSave(common.DEPLOYMENT_DONE) return nil } } type preloadResult struct { data interface{} err error } type PreloadResults map[common.Phase]interface{} func (results PreloadResults) Get(phase common.Phase) interface{} { return results[phase] } func (results PreloadResults) Set(phase common.Phase, data interface{}) { results[phase] = data } // Phases can expose preloads to gather any additional information they may // need before executing. This will run those preloads in parallel. func (deployment *Deployment) RunPhasePreloads() (PreloadResults, error) { preloadablePhases := make([]common.PreloadablePhase, 0) for _, phase := range deployment.strategy.Phases() { if phase.CanPreload() { preloadablePhases = append(preloadablePhases, phase.(common.PreloadablePhase)) } } resultChan := make(chan preloadResult) for _, phase := range preloadablePhases { go func() { data, err := phase.Preload(deployment) resultChan <- preloadResult{data: data, err: err} }() } results := make(PreloadResults) for _, phase := range preloadablePhases { result := <-resultChan if result.err != nil { return nil, result.err } else { results.Set(phase.(common.Phase), result.data) } } return results, nil }
Everlane/evan
context/deployment.go
GO
mit
5,804
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Blue Project</title> <meta name="description" content="Complete Site"> <meta name="author" content="Vassilis Sponis"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/lightbox.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> <link href='http://fonts.googleapis.com/css?family=Trykker|Share+Tech' rel='stylesheet' type='text/css'> </head> <body> <!--<div id="wrapper">--> <header> <div id="tophead"> <div class="wrapper"> <span id="sub">Subscribe to:</span> <ul id="sub_list"> <li><a title="Posts" href="#">Posts</a></li> <li><a title="Comments" href="#">Comments</a></li> <li><a class="noborder" title="Email" href="#">Email</a></li> </ul> <div id="searchform"> <form name="search" action ="" method=""> <input type="text" name="searchvalue" placeholder=" Search Keywords"> <input class="magnglass" type="Submit" value=""> </form> </div> <div id="social"> <ul class="social_icons"> <li><a class="rss" title="RSS" href="#"></a></li> <li><a class="fb" title="Facebook" href="#"></a></li> <li><a class="tw" title="Twitter" href="#"></a></li> </ul> </div> </div> </div> <div id="bothead"> <div class="wrapper"> <h1 id="logo"> <span class="main">Blue Masters</span> <span class="sub">COMPLETELY UNIQUE WORDPRESS THEME</span> </h1> <nav> <ul> <li class="nav01"><a class="navi active" title="Home" href="/index.html">Home</a></li> <li class="nav02"><a class="navi" title="About" href="#">About</a></li> <li class="nav03"><a class="navi" title="Portfolio" href="#">Portfolio</a></li> <li class="nav04"><a class="navi" title="Blog" href="OurBlogs.html">Blog</a></li> <li class="nav05"><a class="navi" title="Contact" href="/contactpage.php">Contact</a></li> </ul> </nav> </div> </div> </header> <!--- END OF HEADER--> <div id="content"> <div class="wrapper"> <div id="slideshow"> <img src="img/main.jpg" alt="mainpic"> <img src="img/main2.jpg" alt="alt1pic"> <img src="img/main3.jpg" alt="alt2pic"> <img src="img/main4.jpg" alt="alt3pic"> </div> <div id="slidenav"> <a href="#"><span id="previousbutton"></span></a> <ul id="pagenavi"></ul> <a href="#"><span id="nextbutton"></span></a> </div> <div id="box"> <div id="boxA" class="mainbox"> <div class="boxhead"> <h3 class="boxhd boxAico">About iPadMasters</h3> </div> <div class="innerbox"> <img class="boxpic" src="img/boxApic.jpg" alt="picA"> <h4 class="subhead">All About iPadMasters</h4> <p id="boxAtext" class="textbox">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p> <a id="buttonA" class="buttontext" title="Learn More" href="#">Learn More</a> </div> </div> <div id="boxB" class="mainbox"> <div class="boxhead"> <h3 class="boxhd boxBico">Our Blog Updates</h3> </div> <div class="innerbox"> <img class="boxpic" src="img/boxBpic.jpg" alt="picB"> <h4 id="MyFirst"> <span class="subhead sechead">My First Website Creation</span> <span class="textbox secsub">Posted in <a title="Web Design" href="#">Web Design</a> on April 13,2010</span> </h4> <p id="boxBtext" class="textbox">Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p> <a id="buttonB" class="buttontext" title="Comments" href="#">23 Comments</a> <a id="buttonC" class="buttontext" title="Read More" href="#">Read More</a> </div> </div> <div id="boxC"> <div class="boxhead"> <h3 class="boxhd boxCico">Get In Touch</h3> </div> <div class="innerbox2"> <ul> <li> <h4 class="phoneico"> <span class="phoneinfo"> <span class="subhead phonehead">PHONE</span> <span class="textbox phonetext">1+ (123)456.789</span> </span> </h4> </li> <li> <h4 class="emailico"> <span class="phoneinfo"> <span class="subhead phonehead">EMAIL</span> <span class="textbox phonetext">[email protected]</span> </span> </h4> </li> <li> <h4 class="skypeico"> <span class="phoneinfo"> <span class="subhead phonehead">SKYPE</span> <span class="textbox phonetext">yourskypename</span> </span> </h4> </li> <li> <h4 class="skypeico"> <span class="phoneinfo"> <span class="subhead phonehead">OTHER REQUEST</span> <span class="textbox phonetext">Try Our Contact Form</span> </span> </h4> </li> </ul> </div> </div> <div id="boxD"> <ul> <li> <a class ="twitter_icon" title="twitter" href="#"></a> </li> <li> <a class ="facebook_icon" title="facebook" href="#"></a> </li> <li> <a class ="flickr_icon" title="flickr" href="#"></a> </li> <li> <a class ="linkedin_icon" title="linkedin" href="#"></a> </li> <li> <a class ="tumblr_icon" title="tumblr" href="#"></a> </li> <li> <a class ="youtube_icon" title="youtube" href="#"></a> </li> </ul> </div> </div> </div> </div> <div id="info"> <div class="wrapper"> <div id="about"> <h4 class="head">About Us</h4> <br> <ul> <li><a class="listlinks" href="#">Our Company</a></li> <li><a class="listlinks" href="#">Our Blog</a></li> <li><a class="listlinks" href="#">Submit A Site</a></li> <li><a class="listlinks" href="#">Contact Us</a></li> <li><a class="listlinks" href="#">Help & Terms</a></li> <li><a class="listlinks" href="#">Read Our FAQ</a></li> </ul> </div> <div id="Categories"> <h4 class="head">Categories</h4> <br> <ul> <li><a class="listlinks" href="#">Trends & Technology</a></li> <li><a class="listlinks" href="#">Desigh Companies</a></li> <li><a class="listlinks" href="#">Design Freelancers</a></li> <li><a class="listlinks" href="#">Web Portfolios</a></li> <li><a class="listlinks" href="#">Web Development</a></li> <li><a class="listlinks" href="#">General Icons</a></li> </ul> </div> <div id="Gallery"> <h4 class="head">From The Gallery</h4> <br> <table id="photos"> <tr> <td><a href="/img/gall01.jpg" data-lightbox="gallery" title="Image 01"><img src="img/gall01.jpg" alt="img01"></a></td> <td><a href="/img/gall02.jpg" data-lightbox="gallery" title="Image 02"><img src="img/gall02.jpg" alt="img02"></a></td> <td><a href="/img/gall03.jpg" data-lightbox="gallery" title="Image 03"><img src="img/gall03.jpg" alt="img03"></a></td> <td><a href="/img/gall04.jpg" data-lightbox="gallery" title="Image 04"><img src="img/gall04.jpg" alt="img04"></a></td> </tr> <tr> <td><a href="/img/gall05.jpg" data-lightbox="gallery" title="Image 05"><img src="img/gall05.jpg" alt="img05"></a></td> <td><a href="/img/gall06.jpg" data-lightbox="gallery" title="Image 06"><img src="img/gall06.jpg" alt="img06"></a></td> <td><a href="/img/gall07.jpg" data-lightbox="gallery" title="Image 07"><img src="img/gall07.jpg" alt="img07"></a></td> <td><a href="/img/gall08.jpg" data-lightbox="gallery" title="Image 08"><img src="img/gall08.jpg" alt="img08"></a></td> </tr> </table> </div> <div id="twupdates"> <h4 class="head">Twitter Updates</h4> <div id="example1"></div> </div> </div> </div> <footer> <div class="wrapper"> <p id="copyright">© 2010 Copyright iPadMasters Theme. All Rights Reserved.</p> <div id="links"> <ul> <li><a href="#">Log In</a></li> <li><a href="#">Privacy Policy</a></li> <li><a href="#">Terms and Conditions</a></li> <li><a href="#">Contact Us</a></li> <li><a class="noborder" href="#">Back to Top</a></li> </ul> </div> </div> </footer> <script src="js/vendor/jquery-1.10.2.min.js"></script> <script src="js/vendor/lightbox-2.6.min.js"></script> <script src="js/vendor/twitterFetcher_v10_min.js"></script> <script src="js/vendor/jquery.cycle.all.js"></script> <script src="js/main.js"></script> </body> </html>
Sponis/Blue-Project
index.html
HTML
mit
12,398
window.Lunchiatto.module('Transfer', function(Transfer, App, Backbone, Marionette, $, _) { return Transfer.Layout = Marionette.LayoutView.extend({ template: 'transfers/layout', ui: { receivedTransfers: '.received-transfers', submittedTransfers: '.submitted-transfers' }, behaviors: { Animateable: { types: ['fadeIn'] }, Titleable: {} }, regions: { receivedTransfers: '@ui.receivedTransfers', submittedTransfers: '@ui.submittedTransfers' }, onRender() { this._showTransfers('received'); this._showTransfers('submitted'); }, _showTransfers(type) { const transfers = new App.Entities.Transfers([], {type}); transfers.optionedFetch({ success: transfers => { App.getUsers().then(() => { const view = new App.Transfer.List({ collection: transfers}); this[`${type}Transfers`].show(view); }); } }); }, _htmlTitle() { return 'Transfers'; } }); });
lunchiatto/web
app/assets/javascripts/modules/transfer/views/layout.js
JavaScript
mit
1,061
body { font-family: Arial, Verdana, "Times New Roman", Times, serif; } div.pages { font-weight: bold; } a.page, span.page { padding: 4px 6px; } a.page { margin: 0 3px; border: 1px solid #ddd; text-decoration: none; color: #0063dc; } a.page:hover { border: 1px solid #003366; background-color: #0063dc; color: #fff; } span.disabled_page { color: #b1aab1; } span.current_page { color: #ff0084; }
binarylogic/searchlogic_example
public/stylesheets/application.css
CSS
mit
423
--- layout: post title: "Leetcode (48, 64, 542) Matrix Series" category: Leetcode tags: Leetcode --- * content {:toc} Leetcode Matrix Series ## Leetcode 48. Rotate Image * [Leetcode 48. Rotate Image](https://leetcode.com/problems/rotate-image/#/description) You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up: Could you do this in-place? ```cpp class Solution { public: void rotate(vector<vector<int>>& matrix) { if (matrix.empty()) return; const int n = matrix.size(); for (int i=0; i<n; i++) for (int j=0; j<i; j++) swap(matrix[i][j], matrix[j][i]); for (int j=0; j<n/2; j++) for (int i=0; i<n; i++) swap(matrix[i][j], matrix[i][n-1-j]); } }; ``` ## Leetcode 64. Minimum Path Sum * [Leetcode 64. Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/#/description) Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. ```cpp class Solution { public: int minPathSum(vector<vector<int>>& grid) { for (int i=0; i<grid.size(); i++) for (int j=0; j<grid[0].size(); j++) { if (i==0 && j==0) continue; else grid[i][j] = min((i-1>=0 ?grid[i-1][j]:INT_MAX), (j-1>=0?grid[i][j-1]:INT_MAX))+grid[i][j]; } return grid.back().back(); } }; ``` ## Leetcode 542. 01 Matrix * [Leetcode 542. 01 Matrix](https://leetcode.com/problems/01-matrix/#/description) Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1. Example 1: Input: ``` 0 0 0 0 1 0 0 0 0 ``` Output: ``` 0 0 0 0 1 0 0 0 0 ``` Example 2: Input: ``` 0 0 0 0 1 0 1 1 1 ``` Output: ``` 0 0 0 0 1 0 1 2 1 ``` Note: * The number of elements of the given matrix will not exceed 10,000. * There are at least one 0 in the given matrix. * The cells are adjacent in only four directions: up, down, left and right. ```cpp class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { const int n = matrix.size(); const int m = matrix[0].size(); typedef pair<int, int> p; queue<p> q; vector<vector<int>> ans(n, vector<int>(m, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) if (matrix[i][j] == 1) ans[i][j] = -1; else q.push(p(i, j)); } p direct[4] = {p(-1, 0), p(1,0),p(0,1), p(0, -1)}; while (q.size() > 0) { p temp = q.front(); for (int i = 0; i < 4; i++) { int x = temp.first+direct[i].first; int y = temp.second+direct[i].second; if (x>=0 && x<n && y>=0 && y<m) if (ans[x][y] == -1) { ans[x][y] = ans[temp.first][temp.second]+1; q.push(p(x, y)); } } q.pop(); } return ans; } }; ```
Shanshan-IC/Shanshan-IC.github.io
_posts/2017-02-20-leetcode-matrix-series.md
Markdown
mit
3,227
package analytics import ( "fmt" elastic "gopkg.in/olivere/elastic.v3" ) //Elasticsearch stores configuration related to the AWS elastic cache isntance. type Elasticsearch struct { URL string IndexName string DocType string client *elastic.Client } //Initialize initializes the analytics engine. func (e *Elasticsearch) Initialize() error { client, err := elastic.NewSimpleClient(elastic.SetURL(e.URL)) if err != nil { return err } e.client = client s := e.client.IndexExists(e.IndexName) exists, err := s.Do() if err != nil { return err } if !exists { s := e.client.CreateIndex(e.IndexName) _, err := s.Do() if err != nil { return err } } return nil } //SendAnalytics is used to send the data to the analytics engine. func (e *Elasticsearch) SendAnalytics(data string) error { fmt.Println(data) _, err := e.client.Index().Index(e.IndexName).Type(e.DocType).BodyJson(data).Do() if err != nil { return err } return nil }
awkhan/go-utility
analytics/elasticsearch.go
GO
mit
979
'use strict'; var i18n = require('./i18n.js') i18n.add_translation("pt-BR", { test: 'OK', greetings: { hello: 'Olá', welcome: 'Bem vindo' } }); i18n.locale = 'pt-BR'; console.log(i18n.t('greetings.hello')); console.log(i18n.t('greetings.welcome')); console.log("Hallo"); // Example 2 i18n.add_translation("pt-BR", { greetings: { hello: 'Olá', welcome: 'Bem vindo' } }); console.log(i18n.t('greetings.hello')); i18n.add_translation("pt-BR", { test: 'OK', greetings: { hello: 'Oi', bye: 'Tchau' } }); console.log(i18n.t('greetings.hello')); console.log(i18n.t('test'));
felipediesel/simple-i18n
node.js
JavaScript
mit
617
/** * @flow */ /* eslint-disable */ 'use strict'; /*:: import type { ReaderFragment } from 'relay-runtime'; export type ReactionContent = "CONFUSED" | "EYES" | "HEART" | "HOORAY" | "LAUGH" | "ROCKET" | "THUMBS_DOWN" | "THUMBS_UP" | "%future added value"; import type { FragmentReference } from "relay-runtime"; declare export opaque type emojiReactionsView_reactable$ref: FragmentReference; declare export opaque type emojiReactionsView_reactable$fragmentType: emojiReactionsView_reactable$ref; export type emojiReactionsView_reactable = {| +id: string, +reactionGroups: ?$ReadOnlyArray<{| +content: ReactionContent, +viewerHasReacted: boolean, +users: {| +totalCount: number |}, |}>, +viewerCanReact: boolean, +$refType: emojiReactionsView_reactable$ref, |}; export type emojiReactionsView_reactable$data = emojiReactionsView_reactable; export type emojiReactionsView_reactable$key = { +$data?: emojiReactionsView_reactable$data, +$fragmentRefs: emojiReactionsView_reactable$ref, }; */ const node/*: ReaderFragment*/ = { "kind": "Fragment", "name": "emojiReactionsView_reactable", "type": "Reactable", "metadata": null, "argumentDefinitions": [], "selections": [ { "kind": "ScalarField", "alias": null, "name": "id", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "reactionGroups", "storageKey": null, "args": null, "concreteType": "ReactionGroup", "plural": true, "selections": [ { "kind": "ScalarField", "alias": null, "name": "content", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "viewerHasReacted", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "users", "storageKey": null, "args": null, "concreteType": "ReactingUserConnection", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "totalCount", "args": null, "storageKey": null } ] } ] }, { "kind": "ScalarField", "alias": null, "name": "viewerCanReact", "args": null, "storageKey": null } ] }; // prettier-ignore (node/*: any*/).hash = 'fde156007f42d841401632fce79875d5'; module.exports = node;
atom/github
lib/views/__generated__/emojiReactionsView_reactable.graphql.js
JavaScript
mit
2,624
require 'bio-ucsc' describe "Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya" do describe "#find_by_interval" do context "given range chr1:1-100,000" do it "returns an array of results" do Bio::Ucsc::Hg19::DBConnection.default Bio::Ucsc::Hg19::DBConnection.connect i = Bio::GenomicInterval.parse("chr1:1-100,000") r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_all_by_interval(i) r.should have(1).items end it "returns an array of results with column accessors" do Bio::Ucsc::Hg19::DBConnection.default Bio::Ucsc::Hg19::DBConnection.connect i = Bio::GenomicInterval.parse("chr1:1-100,000") r = Bio::Ucsc::Hg19::WgEncodeAffyRnaChipFiltTransfragsKeratinocyteCytosolLongnonpolya.find_by_interval(i) r.chrom.should == "chr1" end end end end
misshie/bioruby-ucsc-api
spec/hg19/wgencodeaffyrnachipfilttransfragskeratinocytecytosollongnonpolya_spec.rb
Ruby
mit
935
# EETetris EETetris, a monogame application to play tetris in a style that looks like EE. Based off of an EE world ( PWNLqCFExbbUI ) # How to play 1) Download it from the releases 2) Know your hotkeys To make the tetris piece move left/right, <-- A | D --> (Arrow keys apply) To rotate the piece left ( 90 degrees counterclockwise ) Q To rotate the piece right ( 90 degrees clockwise ) E To convert the board from BETA style to BASIC stlye, L To swap out the piece on the board for your held piece, C To instant drop SPACE To fastly drop S
SirJosh3917/EETetris
README.md
Markdown
mit
548
<!doctype html> <html> <head> <title>Code coverage report for wizard/test/wizardSpecs.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta http-equiv="content-language" content="en-gb"> <link rel='stylesheet' href='../../prettify.css'> <style type='text/css'> body, html { margin:0; padding: 0; } body { font-family: "Helvetic Neue", Helvetica,Arial; font-size: 10pt; } div.header, div.footer { background: #eee; padding: 1em; } div.header { z-index: 100; position: fixed; top: 0; border-bottom: 1px solid #666; width: 100%; } div.footer { border-top: 1px solid #666; } div.body { margin-top: 10em; } div.meta { font-size: 90%; text-align: center; } h1, h2, h3 { font-weight: normal; } h1 { font-size: 12pt; } h2 { font-size: 10pt; } pre { font-family: consolas, menlo, monaco, monospace; margin: 0; padding: 0; line-height: 14px; font-size: 14px; } div.path { font-size: 110%; } div.path a:link, div.path a:visited { color: #000; } table.coverage { border-collapse: collapse; margin:0; padding: 0 } table.coverage td { margin: 0; padding: 0; color: #111; vertical-align: top; } table.coverage td.line-count { width: 50px; text-align: right; padding-right: 5px; } table.coverage td.line-coverage { color: #777 !important; text-align: right; border-left: 1px solid #666; border-right: 1px solid #666; } table.coverage td.text { } table.coverage td span.cline-any { display: inline-block; padding: 0 5px; width: 40px; } table.coverage td span.cline-neutral { background: #eee; } table.coverage td span.cline-yes { background: #b5d592; color: #999; } table.coverage td span.cline-no { background: #fc8c84; } .cstat-yes { color: #111; } .cstat-no { background: #fc8c84; color: #111; } .fstat-no { background: #ffc520; color: #111 !important; } .cbranch-no { background: yellow !important; color: #111; } .missing-if-branch { display: inline-block; margin-right: 10px; position: relative; padding: 0 4px; background: black; color: yellow; xtext-decoration: line-through; } .missing-if-branch .typ { color: inherit !important; } .entity, .metric { font-weight: bold; } .metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } .metric small { font-size: 80%; font-weight: normal; color: #666; } div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } div.coverage-summary th.file { border-right: none !important; } div.coverage-summary th.pic { border-left: none !important; text-align: right; } div.coverage-summary th.pct { border-right: none !important; } div.coverage-summary th.abs { border-left: none !important; text-align: right; } div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; } div.coverage-summary td.pic { min-width: 120px !important; } div.coverage-summary a:link { text-decoration: none; color: #000; } div.coverage-summary a:visited { text-decoration: none; color: #333; } div.coverage-summary a:hover { text-decoration: underline; } div.coverage-summary tfoot td { border-top: 1px solid #666; } div.coverage-summary .yui3-datatable-sort-indicator, div.coverage-summary .dummy-sort-indicator { height: 10px; width: 7px; display: inline-block; margin-left: 0.5em; } div.coverage-summary .yui3-datatable-sort-indicator { background: url("http://yui.yahooapis.com/3.6.0/build/datatable-sort/assets/skins/sam/sort-arrow-sprite.png") no-repeat scroll 0 0 transparent; } div.coverage-summary .yui3-datatable-sorted .yui3-datatable-sort-indicator { background-position: 0 -20px; } div.coverage-summary .yui3-datatable-sorted-desc .yui3-datatable-sort-indicator { background-position: 0 -10px; } .high { background: #b5d592 !important; } .medium { background: #ffe87c !important; } .low { background: #fc8c84 !important; } span.cover-fill, span.cover-empty { display:inline-block; border:1px solid #444; background: white; height: 12px; } span.cover-fill { background: #ccc; border-right: 1px solid #444; } span.cover-empty { background: white; border-left: none; } span.cover-full { border-right: none !important; } pre.prettyprint { border: none !important; padding: 0 !important; margin: 0 !important; } .com { color: #999 !important; } </style> </head> <body> <div class='header high'> <h1>Code coverage report for <span class='entity'>wizard/test/wizardSpecs.js</span></h1> <h2> Statements: <span class='metric'>100% <small>(91 / 91)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Branches: <span class='metric'>100% <small>(0 / 0)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Functions: <span class='metric'>100% <small>(22 / 22)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Lines: <span class='metric'>100% <small>(91 / 91)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; </h2> <div class="path"><a href="../../index.html">All files</a> &#187; <a href="index.html">wizard/test/</a> &#187; wizardSpecs.js</div> </div> <div class='body'> <pre><table class="coverage"> <tr><td class="line-count">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159</td><td class="line-coverage"><span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">6</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">6</span> <span class="cline-any cline-yes">6</span> <span class="cline-any cline-yes">6</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">6</span> <span class="cline-any cline-yes">6</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">4</span> <span class="cline-any cline-yes">4</span> <span class="cline-any cline-yes">4</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">5</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">describe('The Wizard Module', function(){ beforeEach(module('wizard')); &nbsp; describe('The Wizard Directive', function(){ var elm, scope, headings, panes; &nbsp; beforeEach(module('template/wizard/wizard.html')); beforeEach(module('template/wizard/pane.html')); beforeEach(module('wizard')); beforeEach(inject(function($compile, $rootScope){ &nbsp; elm = angular.element( '&lt;wizard&gt;' + '&lt;pane heading="Step 1"&gt;' + 'Content 1' + '&lt;/pane&gt;' + '&lt;pane heading="Step 2"&gt;' + 'Content 2' + '&lt;/pane&gt;' + '&lt;/wizard&gt;'); &nbsp; scope = $rootScope; $compile(elm)(scope); scope.$digest(); headings = elm.find('ul.steps li a') panes = elm.find('div.panes .pane'); })); &nbsp; it('should be a element with "wizard" class', function(){ expect(elm).toHaveClass('wizard'); }); &nbsp; it('should create clickable steps with their heading text in the navigation', function(){ expect(headings.length).toBe(2); expect(headings.eq(0).text()).toBe('Step 1'); expect(headings.eq(1).text()).toBe('Step 2'); }); &nbsp; it('should bind the content', function() { expect(panes.length).toBe(2); expect(panes.eq(0).text()).toBe('Content 1'); expect(panes.eq(1).text()).toBe('Content 2'); }); &nbsp; it('shoud activate the first step', function() { expect(headings.parent().eq(0)).toHaveClass('active'); expect(panes.eq(0)).toHaveClass('active'); &nbsp; expect(headings.parent().eq(1)).not.toHaveClass('active'); expect(panes.eq(1)).not.toHaveClass('active'); }); &nbsp; it('should activate the next step', function(){ elm.find('.btn-next').click(); &nbsp; expect(headings.parent().eq(1)).toHaveClass('active'); expect(panes.eq(1)).toHaveClass('active'); &nbsp; expect(headings.parent().eq(0)).toHaveClass('complete'); expect(panes.eq(0)).toHaveClass('complete'); }); &nbsp; it('should activate the prev step', function(){ elm.find('.btn-next').click(); elm.find('.btn-prev').click(); &nbsp; expect(headings.parent().eq(0)).toHaveClass('active'); expect(panes.eq(0)).toHaveClass('active'); &nbsp; expect(headings.parent().eq(1)).not.toHaveClass('active'); expect(panes.eq(1)).not.toHaveClass('active'); }); &nbsp; }); &nbsp; describe('The Wizard Controller', function(){ var ctrl, wizardScope, firstStep; &nbsp; beforeEach(inject(function($controller, $rootScope, Step) { ctrl = $controller('WizardCtrl', {$scope: wizardScope = $rootScope}); firstStep = new Step(); ctrl.addStep(firstStep); })); &nbsp; it('shoud add a child step scope to the wizardScope', inject(function($rootScope){ expect(wizardScope.steps).toBeDefined(); expect(wizardScope.steps.length).toBe(1); })); &nbsp; it('should set the first step as active', function(){ expect(firstStep.status).toBe('active'); }); &nbsp; it('should advance to next step', inject(function(Step){ var secondStep = new Step(); ctrl.addStep(secondStep); ctrl.nextStep(); expect(firstStep.status).toBe('complete'); expect(secondStep.status).toBe('active'); })); &nbsp; it('should back to previous step', inject(function(Step){ var secondStep = new Step(), thirdStep = new Step(); &nbsp; ctrl.addStep(secondStep); ctrl.addStep(thirdStep); &nbsp; ctrl.nextStep(); ctrl.nextStep(); expect(secondStep.status).toBe('complete'); expect(thirdStep.status).toBe('active'); &nbsp; ctrl.prevStep(); expect(secondStep.status).toBe('active'); expect(thirdStep.status).toBeUndefined(); })); }); describe('The Step Factory', function(){ var step; beforeEach(inject(function(Step){ step = new Step('Heading One'); })); &nbsp; it('should have a heading', function(){ expect(step.heading).toBe('Heading One'); }); &nbsp; it('should be initialized with undefined status', function(){ expect(step.status).toBeUndefined(); }); &nbsp; it('should became active', function(){ step.activate(); expect(step.status).toBe('active'); }); &nbsp; it('should became complete', function(){ step.complete(); expect(step.status).toBe('complete'); }); &nbsp; it('should revert his status', function(){ step.activate(); step.reset(); expect(step.status).toBeUndefined(); &nbsp; step.complete(); step.activate(); expect(step.status).toBe('active'); }); }); });</pre></td></tr> </table></pre> </div> <div class='footer'> <div class='meta'>Generated by <a href='http://istanbul-js.org' target='_blank'>istanbul</a> at Wed Mar 13 2013 08:34:08 GMT-0300 (BRT)</div> </div> </body> <script src="../../prettify.js"></script> <script src="http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js"></script> <script> YUI().use('datatable', function (Y) { var formatters = { pct: function (o) { o.className += o.record.get('classes')[o.column.key]; try { return o.value.toFixed(2) + '%'; } catch (ex) { return o.value + '%'; } }, html: function (o) { o.className += o.record.get('classes')[o.column.key]; return o.record.get(o.column.key + '_html'); } }, defaultFormatter = function (o) { o.className += o.record.get('classes')[o.column.key]; return o.value; }; function getColumns(theadNode) { var colNodes = theadNode.all('tr th'), cols = [], col; colNodes.each(function (colNode) { col = { key: colNode.getAttribute('data-col'), label: colNode.get('innerHTML') || ' ', sortable: !colNode.getAttribute('data-nosort'), className: colNode.getAttribute('class'), type: colNode.getAttribute('data-type'), allowHTML: colNode.getAttribute('data-html') === 'true' || colNode.getAttribute('data-fmt') === 'html' }; col.formatter = formatters[colNode.getAttribute('data-fmt')] || defaultFormatter; cols.push(col); }); return cols; } function getRowData(trNode, cols) { var tdNodes = trNode.all('td'), i, row = { classes: {} }, node, name; for (i = 0; i < cols.length; i += 1) { name = cols[i].key; node = tdNodes.item(i); row[name] = node.getAttribute('data-value') || node.get('innerHTML'); row[name + '_html'] = node.get('innerHTML'); row.classes[name] = node.getAttribute('class'); //Y.log('Name: ' + name + '; Value: ' + row[name]); if (cols[i].type === 'number') { row[name] = row[name] * 1; } } //Y.log(row); return row; } function getData(tbodyNode, cols) { var data = []; tbodyNode.all('tr').each(function (trNode) { data.push(getRowData(trNode, cols)); }); return data; } function replaceTable(node) { if (!node) { return; } var cols = getColumns(node.one('thead')), data = getData(node.one('tbody'), cols), table, parent = node.get('parentNode'); table = new Y.DataTable({ columns: cols, data: data, sortBy: 'file' }); parent.set('innerHTML', ''); table.render(parent); } Y.on('domready', function () { replaceTable(Y.one('div.coverage-summary table')); if (typeof prettyPrint === 'function') { prettyPrint(); } }); }); </script> </html>
odwayne/angular-kata
coverage/Chrome 25.0 (Mac)/wizard/test/wizardSpecs.js.html
HTML
mit
23,199
require File.expand_path("../../../test_helper", __FILE__) describe Redcarpet::Render::HTMLAbbreviations do before do @renderer = Class.new do include Redcarpet::Render::HTMLAbbreviations end end describe "#preprocess" do it "converts markdown abbrevations to HTML" do markdown = <<-EOS.strip_heredoc YOLO *[YOLO]: You Only Live Once EOS @renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp <abbr title="You Only Live Once">YOLO</abbr> EOS end it "converts hyphenated abbrevations to HTML" do markdown = <<-EOS.strip_heredoc JSON-P *[JSON-P]: JSON with Padding EOS @renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp <abbr title="JSON with Padding">JSON-P</abbr> EOS end it "converts abbrevations with numbers to HTML" do markdown = <<-EOS.strip_heredoc ES6 *[ES6]: ECMAScript 6 EOS @renderer.new.preprocess(markdown).must_equal <<-EOS.strip_heredoc.chomp <abbr title="ECMAScript 6">ES6</abbr> EOS end end describe "#acronym_regexp" do it "matches an acronym at the beginning of a line" do "FOO bar".must_match @renderer.new.acronym_regexp("FOO") end it "matches an acronym at the end of a line" do "bar FOO".must_match @renderer.new.acronym_regexp("FOO") end it "matches an acronym next to punctuation" do ".FOO.".must_match @renderer.new.acronym_regexp("FOO") end it "matches an acronym with hyphens" do "JSON-P".must_match @renderer.new.acronym_regexp("JSON-P") end it "doesn't match an acronym in the middle of a word" do "YOLOFOOYOLO".wont_match @renderer.new.acronym_regexp("FOO") end it "matches numbers" do "ES6".must_match @renderer.new.acronym_regexp("ES6") end end end
brandonweiss/redcarpet-abbreviations
test/redcarpet/render/html_abbreviations_test.rb
Ruby
mit
1,921
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateList extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('modelList', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('modelList'); } }
paufsc/Kanban
web/app/database/migrations/2014_10_24_214547_create_list.php
PHP
mit
488
--- type: docs order: 10 title: "Transloadit" module: "@uppy/transloadit" permalink: docs/transloadit/ category: "File Processing" tagline: "manipulate and transcode uploaded files using the <a href='https://transloadit.com'>transloadit.com</a> service" --- The `@uppy/transloadit` plugin can be used to upload files to [Transloadit](https://transloadit.com/) for all kinds of processing, such as transcoding video, resizing images, zipping/unzipping, [and much more](https://transloadit.com/services/). > If you’re okay to trade some flexibility for ergonomics, consider using > the [Robodog](/docs/robodog/) Plugin instead, which is a higher-level abstraction for > encoding files with Uppy and Transloadit. <a class="TryButton" href="/examples/transloadit/">Try it live</a> ```js import Transloadit from '@uppy/transloadit' uppy.use(Transloadit, { service: 'https://api2.transloadit.com', params: null, waitForEncoding: false, waitForMetadata: false, importFromUploadURLs: false, alwaysRunAssembly: false, signature: null, fields: {}, limit: 0, }) ``` As of Uppy version 0.24, the Transloadit plugin includes the [Tus](/docs/tus) plugin to handle the uploading, so you no longer have to add it manually. ## Installation This plugin is published as the `@uppy/transloadit` package. Install from NPM: ```shell npm install @uppy/transloadit ``` In the [CDN package](/docs/#With-a-script-tag), the plugin class is available on the `Uppy` global object: ```js const { Transloadit } = Uppy ``` ## Hosted Companion Service You can use this plugin together with Transloadit’s hosted Companion service to let your users import files from third party sources across the web. To do so each provider plugin must be configured with Transloadit’s Companion URLs: ```js uppy.use(Dropbox, { companionUrl: Transloadit.COMPANION, companionAllowedHosts: Transloadit.COMPANION_PATTERN, }) ``` This will already work. Transloadit’s OAuth applications are used to authenticate your users by default. Your users will be asked to provide Transloadit access to their files. Since your users are probably not aware of Transloadit, this may be confusing or decrease trust. You may also hit rate limits, because the OAuth application is shared between everyone using Transloadit. To solve that, you can use your own OAuth keys with Transloadit’s hosted Companion servers by using Transloadit Template Credentials. [Create a Template Credential][template-credentials] on the Transloadit site. Select “Companion OAuth” for the service, and enter the key and secret for the provider you want to use. Then you can pass the name of the new credentials to that provider: ```js uppy.use(Dropbox, { companionUrl: Transloadit.COMPANION, companionAllowedHosts: Transloadit.COMPANION_PATTERN, companionKeysParams: { key: 'YOUR_TRANSLOADIT_API_KEY', credentialsName: 'my_companion_dropbox_creds', }, }) ``` ## Properties ### `Transloadit.COMPANION` The main endpoint for Transloadit’s hosted companions. You can use this constant in remote provider options, like so: ```js import Dropbox from '@uppy/dropbox' import Transloadit from '@uppy/transloadit' uppy.use(Dropbox, { companionUrl: Transloadit.COMPANION, companionAllowedHosts: Transloadit.COMPANION_PATTERN, }) ``` When using `Transloadit.COMPANION`, you should also configure [`companionAllowedHosts: Transloadit.COMPANION_PATTERN`](#Transloadit-COMPANION-PATTERN). The value of this constant is `https://api2.transloadit.com/companion`. If you are using a custom [`service`](#service) option, you should also set a custom host option in your provider plugins, by taking a Transloadit API url and appending `/companion`: ```js uppy.use(Dropbox, { companionUrl: 'https://api2-us-east-1.transloadit.com/companion', }) ``` ### `Transloadit.COMPANION_PATTERN` A RegExp pattern matching Transloadit’s hosted companion endpoints. The pattern is used in remote provider `companionAllowedHosts` options, to make sure that third party authentication messages cannot be faked by an attacker’s page, but can only originate from Transloadit’s servers. Use it whenever you use `companionUrl: Transloadit.COMPANION`, like so: ```js import Dropbox from '@uppy/dropbox' import Transloadit from '@uppy/transloadit' uppy.use(Dropbox, { companionUrl: Transloadit.COMPANION, companionAllowedHosts: Transloadit.COMPANION_PATTERN, }) ``` The value of this constant covers _all_ Transloadit’s Companion servers, so it does not need to be changed if you are using a custom [`service`](#service) option. But, if you are not using the Transloadit Companion servers at `*.transloadit.com`, make sure to set the `companionAllowedHosts` option to something that matches what you do use. ## Options The `@uppy/transloadit` plugin has the following configurable options: ### `id: 'Transloadit'` A unique identifier for this plugin. It defaults to `'Transloadit'`. ### `service` The Transloadit API URL to use. It defaults to `https://api2.transloadit.com`, which will try to route traffic efficiently based on the location of your users. You can set this to something like `https://api2-us-east-1.transloadit.com` if you want to use a particular region. ### `params` The Assembly parameters to use for the upload. See the Transloadit documentation on [Assembly Instructions](https://transloadit.com/docs/#14-assembly-instructions) for further information. `params` should be a plain JavaScript object, or a JSON string if you are using the [`signature`](#signature) option. The `auth.key` Assembly parameter is required. You can also use the `steps` or `template_id` options here as described in the Transloadit documentation. ```js uppy.use(Transloadit, { params: { auth: { key: 'YOUR_TRANSLOADIT_KEY' }, steps: { encode: { robot: '/video/encode', use: { steps: [':original'], fields: ['file_input_field2'], }, preset: 'iphone', }, }, }, }) ``` <a id="waitForEncoding"></a> ### `waitForEncoding: false` By default, the Transloadit plugin uploads files to Assemblies and then marks the files as complete in Uppy. The Assemblies will complete (or error) in the background but Uppy won’t know or care about it. When `waitForEncoding` is set to true, the Transloadit plugin waits for Assemblies to complete before the files are marked as completed. This means users have to wait for a potentially long time, depending on how complicated your Assembly instructions are. But, you can receive transcoding results on the client side, and have a fully client-side experience this way. When this is enabled, you can listen for the [`transloadit:result`](#transloadit-result) and [`transloadit:complete`](#transloadit-complete) events. <a id="waitForMetadata"></a> ### `waitForMetadata: false` By default, the Transloadit plugin uploads files to Assemblies and then marks the files as complete in Uppy. The Assemblies will complete (or error) in the background but Uppy won’t know or care about it. When `waitForMetadata` is set to true, the Transloadit plugin waits for Transloadit’s backend to extract metadata from all the uploaded files. This is mostly handy if you want to have a quick user experience (so your users don’t necessarily need to wait for all the encoding to complete), but you do want to let users know about some types of errors that can be caught early on, like file format issues. When this is enabled, you can listen for the [`transloadit:upload`](#transloadit-upload) event. ### `importFromUploadURLs` Instead of uploading to Transloadit’s servers directly, allow another plugin to upload files, and then import those files into the Transloadit Assembly. This is set to `false` by default. When enabling this option, Transloadit will _not_ configure the Tus plugin to upload to Transloadit. Instead, a separate upload plugin must be used. Once the upload completes, the Transloadit plugin adds the uploaded file to the Assembly. For example, to upload files to an S3 bucket and then transcode them: ```js uppy.use(AwsS3, { getUploadParameters (file) { return { /* upload parameters */ } }, }) uppy.use(Transloadit, { importFromUploadURLs: true, params: { auth: { key: 'YOUR_API_KEY' }, template_id: 'YOUR_TEMPLATE_ID', }, }) ``` For this to work, the upload plugin must assign a publically accessible `uploadURL` property to the uploaded file object. The Tus and S3 plugins both do this automatically. For the XHRUpload plugin, you may have to specify a custom `getResponseData` function. ### `alwaysRunAssembly` When set to true, always create and run an Assembly when `uppy.upload()` is called, even if no files were selected. This allows running Assemblies that do not receive files, but instead use a robot like [`/s3/import`](https://transloadit.com/docs/transcoding/#s3-import) to download the files from elsewhere, for example, for a bulk transcoding job. ### `signature` An optional signature for the Assembly parameters. See the Transloadit documentation on [Signature Authentication](https://transloadit.com/docs/#26-signature-authentication) for further information. If a `signature` is provided, `params` should be a JSON string instead of a JavaScript object, as otherwise the generated JSON in the browser may be different from the JSON string that was used to generate the signature. ### `fields` An object of form fields to send along to the Assembly. Keys are field names, and values are field values. See also the Transloadit documentation on [Form Fields In Instructions](https://transloadit.com/docs/#23-form-fields-in-instructions). ```js uppy.use(Transloadit, { // ... fields: { message: 'This is a form field', }, }) ``` You can also pass an array of field names to send global or file metadata along to the Assembly. Global metadata is set using the [`meta` option](/docs/uppy/#meta) in the Uppy constructor, or using the [`setMeta` method](/docs/uppy/#uppy-setMeta-data). File metadata is set using the [`setFileMeta`](/docs/uppy/#uppy-setFileMeta-fileID-data) method. The [Form](/docs/form) plugin also sets global metadata based on the values of `<input />`s in the form, providing a handy way to use values from HTML form fields: ```js uppy.use(Form, { target: 'form#upload-form', getMetaFromForm: true }) uppy.use(Transloadit, { fields: ['field_name', 'other_field_name'], params: { /* ... */ }, }) ``` Form fields can also be computed dynamically using custom logic, by using the [`getAssemblyOptions(file)`](/docs/transloadit/#getAssemblyOptions-file) option. ### `getAssemblyOptions(file)` While `params`, `signature`, and `fields` must be determined ahead of time, the `getAssemblyOptions` allows using dynamically generated values for these options. This way, it’s possible to use different Assembly parameters for different files, or to use some user input in an Assembly. A custom `getAssemblyOptions()` option should return an object or a Promise for an object with properties `{ params, signature, fields }`. For example, to add a field with some user-provided data from the `MetaData` plugin: ```js uppy.use(MetaData, { fields: [ { id: 'caption' }, ], }) uppy.use(Transloadit, { getAssemblyOptions (file) { return { params: { auth: { key: 'TRANSLOADIT_AUTH_KEY_HERE' }, template_id: 'xyz', }, fields: { caption: file.meta.caption, }, } }, }) ``` Now, the `${fields.caption}` variable will be available in the Assembly template. Combine the `getAssemblyOptions()` option with the [Form](/docs/form) plugin to pass user input from a `<form>` to a Transloadit Assembly: ```js // This will add form field values to each file's `.meta` object: uppy.use(Form, { getMetaFromForm: true }) uppy.use(Transloadit, { getAssemblyOptions (file) { return { params: { /* ... */ }, // Pass through the fields you need: fields: { message: file.meta.message, }, } }, }) ``` `getAssemblyOptions()` may also return a Promise, so it could retrieve signed Assembly parameters from a server. For example, assuming an endpoint `/transloadit-params` that responds with a JSON object with `{ params, signature }` properties: ```js uppy.use(Transloadit, { getAssemblyOptions (file) { return fetch('/transloadit-params').then((response) => { return response.json() }) }, }) ``` ### `limit: 0` Limit the amount of uploads going on at the same time. Setting this to `0` means no limit on concurrent uploads. This option is passed through to the [`@uppy/tus`](/docs/tus) plugin that Transloadit plugin uses internally. ### `locale: {}` <!-- eslint-disable no-restricted-globals, no-multiple-empty-lines --> ```js module.exports = { strings: { // Shown while Assemblies are being created for an upload. creatingAssembly: 'Preparing upload...', // Shown if an Assembly could not be created. creatingAssemblyFailed: 'Transloadit: Could not create Assembly', // Shown after uploads have succeeded, but when the Assembly is still executing. // This only shows if `waitForMetadata` or `waitForEncoding` was enabled. encoding: 'Encoding...', }, } ``` ## Errors If an error occurs when an Assembly has already started, you can find the Assembly Status on the error object’s `assembly` property. ```js uppy.on('error', (error) => { if (error.assembly) { console.log(`Assembly ID ${error.assembly.assembly_id} failed!`) console.log(error.assembly) } }) ``` ## Events ### `transloadit:assembly-created` Fired when an Assembly is created. **Parameters** * `assembly` - The initial [Assembly Status][assembly-status]. * `fileIDs` - The IDs of the files that will be uploaded to this Assembly. ```js uppy.on('transloadit:assembly-created', (assembly, fileIDs) => { console.group('Created', assembly.assembly_id, 'for files:') for (const id of fileIDs) { console.log(uppy.getFile(id).name) } console.groupEnd() }) ``` ### `transloadit:upload` Fired when Transloadit has received an upload. **Parameters** * `file` - The Transloadit file object that was uploaded. * `assembly` - The [Assembly Status][assembly-status] of the Assembly to which the file was uploaded. ### `transloadit:assembly-executing` Fired when Transloadit has received all uploads, and is executing the Assembly. **Parameters** * `assembly` - The [Assembly Status](https://transloadit.com/docs/api/#assembly-status-response) of the Assembly that is executing. ### `transloadit:result` Fired when a result came in from an Assembly. **Parameters** * `stepName` - The name of the Assembly step that generated this result. * `result` - The result object from Transloadit. This result object has one more property, namely `localId`. This is the ID of the file in Uppy’s local state, and can be used with `uppy.getFile(id)`. * `assembly` - The [Assembly Status][assembly-status] of the Assembly that generated this result. ```js uppy.on('transloadit:result', (stepName, result) => { const file = uppy.getFile(result.localId) document.body.appendChild(html` <div> <h2>From ${file.name}</h2> <a href=${result.ssl_url}> View </a> </div> `) }) ``` ### `transloadit:complete` Fired when an Assembly completed. **Parameters** * `assembly` - The final [Assembly Status][assembly-status] of the completed Assembly. ```js uppy.on('transloadit:complete', (assembly) => { // Could do something fun with this! console.log(assembly.results) }) ``` [assembly-status]: https://transloadit.com/docs/api/#assembly-status-response [template-credentials]: https://transloadit.com/docs/#how-to-create-template-credentials
transloadit/uppy
website/src/docs/transloadit.md
Markdown
mit
15,797
module Tire module Model module Persistence # Provides infrastructure for storing records in _Elasticsearch_. # module Storage def self.included(base) base.class_eval do extend ClassMethods include InstanceMethods end end module ClassMethods def create(args={}) document = new(args) return false unless document.valid? if result = document.save document else result end end end module InstanceMethods def update_attribute(name, value) __update_attributes name => value save end def update_attributes(attributes={}) __update_attributes attributes save end def update_index run_callbacks :update_elasticsearch_index do if destroyed? response = index.remove self else if response = index.store( self, {:percolate => percolator} ) self.id ||= response['_id'] self._index = response['_index'] self._type = response['_type'] self._version = response['_version'] self.matches = response['matches'] end end response end end def save return false unless valid? run_callbacks :save do response = update_index !! response['ok'] end end def destroy run_callbacks :destroy do @destroyed = true response = update_index ! response.nil? end end def destroyed? ; !!@destroyed; end def persisted? ; !!id && !!_version; end def new_record? ; !persisted?; end end end end end end
HenleyChiu/tire
lib/tire/model/persistence/storage.rb
Ruby
mit
2,068
require 'googleanalytics/mobile'
mono0x/googleanalytics-mobile
lib/googleanalytics-mobile.rb
Ruby
mit
33
class ItemsController < ApplicationController def create item = Item.new(item_params) item.user_id = @user.id if item.save render json: item, status: 201 else render json: item.errors, status: 422 end end def destroy item = find_item item.destroy head 204 end def index render json: @user.items.as_json, status: 200 end def show item = find_item render json: item.as_json, status: 200 end def update item = find_item if item.update(item_params) render json: item.as_json, status: 200 end end def find_item Item.find(params[:id]) end private def item_params params.require(:item).permit(:type, :brand, :size, :color, :description) end end
StuartPearlman/ClosetKeeperAPI
app/controllers/items_controller.rb
Ruby
mit
701
# Build bootstrap Go compiler
frobware/dockerfiles
go-bootstrap/README.md
Markdown
mit
30
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QHTTPMULTIPART_H #define QHTTPMULTIPART_H #include <QtCore/QSharedDataPointer> #include <QtCore/QByteArray> #include <QtCore/QIODevice> #include <QtNetwork/QNetworkRequest> QT_BEGIN_NAMESPACE class QHttpPartPrivate; class QHttpMultiPart; class Q_NETWORK_EXPORT QHttpPart { public: QHttpPart(); QHttpPart(const QHttpPart &other); ~QHttpPart(); #ifdef Q_COMPILER_RVALUE_REFS QHttpPart &operator=(QHttpPart &&other) Q_DECL_NOTHROW { swap(other); return *this; } #endif QHttpPart &operator=(const QHttpPart &other); void swap(QHttpPart &other) Q_DECL_NOTHROW { qSwap(d, other.d); } bool operator==(const QHttpPart &other) const; inline bool operator!=(const QHttpPart &other) const { return !operator==(other); } void setHeader(QNetworkRequest::KnownHeaders header, const QVariant &value); void setRawHeader(const QByteArray &headerName, const QByteArray &headerValue); void setBody(const QByteArray &body); void setBodyDevice(QIODevice *device); private: QSharedDataPointer<QHttpPartPrivate> d; friend class QHttpMultiPartIODevice; }; Q_DECLARE_SHARED(QHttpPart) class QHttpMultiPartPrivate; class Q_NETWORK_EXPORT QHttpMultiPart : public QObject { Q_OBJECT public: enum ContentType { MixedType, RelatedType, FormDataType, AlternativeType }; explicit QHttpMultiPart(QObject *parent = Q_NULLPTR); explicit QHttpMultiPart(ContentType contentType, QObject *parent = Q_NULLPTR); ~QHttpMultiPart(); void append(const QHttpPart &httpPart); void setContentType(ContentType contentType); QByteArray boundary() const; void setBoundary(const QByteArray &boundary); private: Q_DECLARE_PRIVATE(QHttpMultiPart) Q_DISABLE_COPY(QHttpMultiPart) friend class QNetworkAccessManager; friend class QNetworkAccessManagerPrivate; }; QT_END_NAMESPACE #endif // QHTTPMULTIPART_H
Silveryard/Car_System
Old/3rdParty/linux_headers/qt/QtNetwork/qhttpmultipart.h
C
mit
3,856
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Killer : MonoBehaviour { public Transform RobotPlayer; public GameObject Robot; public Text GameOVER; // Use this for initialization void Start() { RobotPlayer = GetComponent<Transform>(); } void FixedUpdate() { if(RobotPlayer.gameObject.transform.position.y < -2) { GameOVER.gameObject.SetActive(true); } } }
ArcherSys/ArcherSys
C#/Unity/Capital Pursuit Alpha/Assets/Scripts/Killer.cs
C#
mit
487
--- title: Comment Section --- Sample comment section mblazonry can input to components. Elements can be added and removed easily. Base organism contains an icon+header section with text input and submit button.
JackGarrard/mblazonry_ARI
source/_patterns/02-organisms/activity window/comment-section.md
Markdown
mit
212
module S3Bear module ViewHelpers # def s3bear_bucket # S3Bear.config.bucket + '.s3.amazonaws.com/upload.html' # end end end ActionView::Base.send(:include, S3Bear::ViewHelpers)
cracell/s3bear
lib/view_helpers.rb
Ruby
mit
195
module Linter class Base def self.can_lint?(filename) self::FILE_REGEXP === filename end def initialize(hound_config:, build:, repository_owner_name:) @hound_config = hound_config @build = build @repository_owner_name = repository_owner_name end def file_review(commit_file) attributes = build_review_job_attributes(commit_file) file_review = FileReview.create!( build: build, filename: commit_file.filename, ) enqueue_job(attributes) file_review end def enabled? config.linter_names.any? do |linter_name| hound_config.enabled_for?(linter_name) end end def file_included?(*) true end def name self.class.name.demodulize.underscore end private attr_reader :hound_config, :build, :repository_owner_name def build_review_job_attributes(commit_file) { commit_sha: build.commit_sha, config: config.content, content: commit_file.content, filename: commit_file.filename, patch: commit_file.patch, pull_request_number: build.pull_request_number, } end def enqueue_job(attributes) Resque.enqueue(job_class, attributes) end def job_class "#{name.classify}ReviewJob".constantize end def config @config ||= ConfigBuilder.for(hound_config, name) end end end
Koronen/hound
app/models/linter/base.rb
Ruby
mit
1,430
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>Lighthouse: lapack/dsprfs.f File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="tabs.css" rel="stylesheet" type="text/css" /> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <!--<div id="titlearea"> </div>--> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_42b7da8b2ebcfce3aea4b69198a0a9ad.html">lapack</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#func-members">Functions/Subroutines</a> </div> <div class="headertitle"> <div class="title">dsprfs.f File Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions/Subroutines</h2></td></tr> <tr class="memitem:a494f27878d5670ad2570185062b96fc7"><td class="memItemLeft" align="right" valign="top">subroutine&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="dsprfs_8f.html#a494f27878d5670ad2570185062b96fc7">dsprfs</a> (UPLO, N, NRHS, AP, AFP, IPIV, B, LDB, X, LDX, FERR, BERR, WORK, IWORK, INFO)</td></tr> <tr class="memdesc:a494f27878d5670ad2570185062b96fc7"><td class="mdescLeft">&#160;</td><td class="mdescRight"><b>DSPRFS</b> <a href="#a494f27878d5670ad2570185062b96fc7">More...</a><br /></td></tr> <tr class="separator:a494f27878d5670ad2570185062b96fc7"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Function/Subroutine Documentation</h2> <a class="anchor" id="a494f27878d5670ad2570185062b96fc7"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">subroutine dsprfs </td> <td>(</td> <td class="paramtype">character&#160;</td> <td class="paramname"><em>UPLO</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>N</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>NRHS</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>AP</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>AFP</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer, dimension( * )&#160;</td> <td class="paramname"><em>IPIV</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( ldb, * )&#160;</td> <td class="paramname"><em>B</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDB</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( ldx, * )&#160;</td> <td class="paramname"><em>X</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>LDX</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>FERR</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>BERR</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double precision, dimension( * )&#160;</td> <td class="paramname"><em>WORK</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer, dimension( * )&#160;</td> <td class="paramname"><em>IWORK</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">integer&#160;</td> <td class="paramname"><em>INFO</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p><b>DSPRFS</b> </p> <p> Download DSPRFS + dependencies <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dsprfs.f"> [TGZ]</a> <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dsprfs.f"> [ZIP]</a> <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dsprfs.f"> [TXT]</a> </p><dl class="section user"><dt>Purpose: </dt><dd><pre class="fragment"> DSPRFS improves the computed solution to a system of linear equations when the coefficient matrix is symmetric indefinite and packed, and provides error bounds and backward error estimates for the solution.</pre> </dd></dl> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramdir">[in]</td><td class="paramname">UPLO</td><td><pre class="fragment"> UPLO is CHARACTER*1 = 'U': Upper triangle of A is stored; = 'L': Lower triangle of A is stored.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">N</td><td><pre class="fragment"> N is INTEGER The order of the matrix A. N &gt;= 0.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">NRHS</td><td><pre class="fragment"> NRHS is INTEGER The number of right hand sides, i.e., the number of columns of the matrices B and X. NRHS &gt;= 0.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">AP</td><td><pre class="fragment"> AP is DOUBLE PRECISION array, dimension (N*(N+1)/2) The upper or lower triangle of the symmetric matrix A, packed columnwise in a linear array. The j-th column of A is stored in the array AP as follows: if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1&lt;=i&lt;=j; if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j&lt;=i&lt;=n.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">AFP</td><td><pre class="fragment"> AFP is DOUBLE PRECISION array, dimension (N*(N+1)/2) The factored form of the matrix A. AFP contains the block diagonal matrix D and the multipliers used to obtain the factor U or L from the factorization A = U*D*U**T or A = L*D*L**T as computed by DSPTRF, stored as a packed triangular matrix.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">IPIV</td><td><pre class="fragment"> IPIV is INTEGER array, dimension (N) Details of the interchanges and the block structure of D as determined by DSPTRF.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">B</td><td><pre class="fragment"> B is DOUBLE PRECISION array, dimension (LDB,NRHS) The right hand side matrix B.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDB</td><td><pre class="fragment"> LDB is INTEGER The leading dimension of the array B. LDB &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[in,out]</td><td class="paramname">X</td><td><pre class="fragment"> X is DOUBLE PRECISION array, dimension (LDX,NRHS) On entry, the solution matrix X, as computed by DSPTRS. On exit, the improved solution matrix X.</pre></td></tr> <tr><td class="paramdir">[in]</td><td class="paramname">LDX</td><td><pre class="fragment"> LDX is INTEGER The leading dimension of the array X. LDX &gt;= max(1,N).</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">FERR</td><td><pre class="fragment"> FERR is DOUBLE PRECISION array, dimension (NRHS) The estimated forward error bound for each solution vector X(j) (the j-th column of the solution matrix X). If XTRUE is the true solution corresponding to X(j), FERR(j) is an estimated upper bound for the magnitude of the largest element in (X(j) - XTRUE) divided by the magnitude of the largest element in X(j). The estimate is as reliable as the estimate for RCOND, and is almost always a slight overestimate of the true error.</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">BERR</td><td><pre class="fragment"> BERR is DOUBLE PRECISION array, dimension (NRHS) The componentwise relative backward error of each solution vector X(j) (i.e., the smallest relative change in any element of A or B that makes X(j) an exact solution).</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">WORK</td><td><pre class="fragment"> WORK is DOUBLE PRECISION array, dimension (3*N)</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">IWORK</td><td><pre class="fragment"> IWORK is INTEGER array, dimension (N)</pre></td></tr> <tr><td class="paramdir">[out]</td><td class="paramname">INFO</td><td><pre class="fragment"> INFO is INTEGER = 0: successful exit &lt; 0: if INFO = -i, the i-th argument had an illegal value</pre> </td></tr> </table> </dd> </dl> <dl class="section user"><dt>Internal Parameters: </dt><dd><pre class="fragment"> ITMAX is the maximum number of steps of iterative refinement.</pre> </dd></dl> <dl class="section author"><dt>Author</dt><dd>Univ. of Tennessee </dd> <dd> Univ. of California Berkeley </dd> <dd> Univ. of Colorado Denver </dd> <dd> NAG Ltd. </dd></dl> <dl class="section date"><dt>Date</dt><dd>November 2011 </dd></dl> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Apr 1 2015 16:27:43 for Lighthouse by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
LighthouseHPC/lighthouse
sandbox/lily/django_orthg/orthg/static/Doxygen/docs/html/dsprfs_8f.html
HTML
mit
11,415
<?php /* * FluentDOM * * @link https://thomas.weinert.info/FluentDOM/ * @copyright Copyright 2009-2021 FluentDOM Contributors * @license http://www.opensource.org/licenses/mit-license.php The MIT License * */ namespace FluentDOM\Query { use FluentDOM\Query; use FluentDOM\TestCase; require_once __DIR__.'/../../TestCase.php'; class TraversingParentsTest extends TestCase { protected $_directory = __DIR__; /** * @group Traversing * @group TraversingFind * @covers \FluentDOM\Query::parents */ public function testParents(): void { $fd = $this->getQueryFixtureFromFunctionName(__FUNCTION__); $this->assertInstanceOf(Query::class, $fd); $parents = $fd ->find('//b') ->parents() ->map( function($node) { return $node->tagName; } ); $this->assertTrue(is_array($parents)); $this->assertContains('span', $parents); $this->assertContains('p', $parents); $this->assertContains('div', $parents); $this->assertContains('body', $parents); $this->assertContains('html', $parents); $parents = implode(', ', $parents); $doc = $fd ->find('//b') ->append('<strong>'.htmlspecialchars($parents).'</strong>'); $this->assertInstanceOf(Query::class, $doc); $this->assertFluentDOMQueryEqualsXMLFile(__FUNCTION__, $doc); } } }
FluentDOM/FluentDOM
tests/FluentDOM/Query/Traversing/ParentsTest.php
PHP
mit
1,420
(function() { 'use strict'; angular .module('app.match') .run(appRun); appRun.$inject = ['routerHelper']; /* @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [{ state: 'match', config: { url: '/match/:id', templateUrl: 'app/match/match.html', controller: 'MatchController', controllerAs: 'vm', title: 'Match', settings: { nav: 2, content: '<i class="fa fa-lock"></i> Match' } } }]; } })();
otaviosoares/f2f
src/client/app/match/match.route.js
JavaScript
mit
593
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-docu', templateUrl: './docu.component.html', styleUrls: ['./docu.component.scss'] }) export class DocuComponent implements OnInit { constructor() { } ngOnInit() { } }
TeoGia/http-on-fire
src/app/docu/docu.component.ts
TypeScript
mit
262
using System; using System.Linq; using Cresce.Datasources.Sql; using Cresce.Models; using NUnit.Framework; namespace Cresce.Business.Tests.Integration.Sql { [TestFixture] internal class InvoiceRepositoryTests : SqlTests { private SqlInvoiceRepository _repository; private Patient _patient; public InvoiceRepositoryTests() { _repository = new SqlInvoiceRepository(this); } [SetUp] public void CreateResources() { _patient = Utils.SavePatient(); } [Test] public void When_deleting_an_invoice_it_should_be_removed_from_the_database() { // Arrange var invoice = Utils.SaveInvoice(_patient); // Act _repository.Delete(invoice.Id); // Assert var invoiceById = _repository.GetById(invoice.Id); Assert.That(invoiceById, Is.Null); } [Test] public void When_deleting_an_invoice_linked_with_an_appointment_it_should_be_removed_from_the_database() { // Arrange var invoice = Utils.SaveInvoice(_patient); Utils.SaveAppointment(Utils.SaveUser(), _patient, Utils.SaveService(), new DateTime(), invoiceId: invoice.Id); // Act _repository.Delete(invoice.Id); // Assert var invoiceById = _repository.GetById(invoice.Id); Assert.That(invoiceById, Is.Null); } [Test] public void When_getting_an_invoice_by_id_it_should_return_the_previously_saved_invoice() { // Arrange var invoice = Utils.SaveInvoice(_patient); // Act var result = _repository.GetById(invoice.Id); // Assert Assert.That(result, Is.Not.Null); } [Test] public void When_getting_an_invoice_by_id_it_should_return_specific_information() { // Arrange var invoice = Utils.SaveInvoice( _patient, date: new DateTime(2017, 10, 23) ); // Act var result = _repository.GetById(invoice.Id); // Assert Assert.That(result, Is.Not.Null); Assert.That(result.PatientId, Is.EqualTo(_patient.Id)); Assert.That(result.Date, Is.EqualTo(new DateTime(2017, 10, 23))); Assert.That(result.Description, Is.EqualTo("some description")); Assert.That(result.Value, Is.EqualTo(23.4)); } [Test] public void When_getting_a_non_existing_invoice_by_id_it_should_return_null() { // Arrange var invoiceId = "-1"; // Act var result = _repository.GetById(invoiceId); // Assert Assert.That(result, Is.Null); } [Test] public void When_getting_an_invoices_for_patient_id_it_should_return_only_invoices_of_that_patient() { // Arrange Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23)); Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23)); // Act var result = _repository.GetInvoices(_patient.Id).ToList(); // Assert Assert.That(result.Count, Is.EqualTo(1)); } [Test] public void When_getting_all_invoices_it_should_return_all_persisted_invoices() { // Arrange Utils.SaveInvoice(_patient, date: new DateTime(2017, 10, 23)); Utils.SaveInvoice(Utils.SavePatient("2"), date: new DateTime(2017, 10, 23)); // Act var result = _repository.GetInvoices().ToList(); // Assert Assert.That(result.Count, Is.EqualTo(2)); } } }
AlienEngineer/Cresce
Cresce.Tests.Integration/Sql/InvoiceRepositoryTests.cs
C#
mit
3,910
### 我的博客 地址:[http://BTeam.github.io](http://BTeam.github.io) ### 安装说明 1. fork库到自己的github 2. 修改名字为:`username.github.io` 3. clone库到本地,参考`_posts`中的目录结构自己创建适合自己的文章目录结构 4. 修改CNAME,或者删掉这个文件,使用默认域名 5. 修改`_config.yml`配置项 6. It's done! ### 鸣谢 本博客框架来自 [闫肃](http://yansu.org)
BTeam/BTeam.github.io
README.md
Markdown
mit
443
class Portal::CollaborationPolicy < ApplicationPolicy end
concord-consortium/rigse
rails/app/policies/portal/collaboration_policy.rb
Ruby
mit
58
// // This is the main include file for the gcode library // It parses and executes G-code functions // // gcode.h // #ifndef GCODE_H #define GCODE_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdarg.h> #ifndef NRF51 // G-code debug print unsigned int debug(const char *format, ...); #else #include "uart.h" #endif // Single G-code parameter typedef struct { char type; float value; } gcode_parameter_t; // Parse G-code command int gcode_parse(const char *s); // Extract G-code parameter (similar to strtok) int gcode_get_parameter(char **s, gcode_parameter_t *gp); #endif
dlofstrom/3D-Printer-rev3
code/gcode/gcode.h
C
mit
634
import { DOCUMENT } from '@angular/common'; import { ApplicationRef, ComponentFactoryResolver, Inject, Injectable, Injector } from '@angular/core'; import { BaseService } from 'ngx-weui/core'; import { ToptipsComponent, ToptipsType } from './toptips.component'; @Injectable({ providedIn: 'root' }) export class ToptipsService extends BaseService { constructor( protected readonly resolver: ComponentFactoryResolver, protected readonly applicationRef: ApplicationRef, protected readonly injector: Injector, @Inject(DOCUMENT) protected readonly doc: any, ) { super(); } /** * 构建一个Toptips并显示 * * @param text 文本 * @param type 类型 * @param 显示时长后自动关闭(单位:ms) */ show(text: string, type: ToptipsType, time: number = 2000): ToptipsComponent { const componentRef = this.build(ToptipsComponent); if (type) { componentRef.instance.type = type; } if (text) { componentRef.instance.text = text; } componentRef.instance.time = time; componentRef.instance.hide.subscribe(() => { setTimeout(() => { this.destroy(componentRef); }, 100); }); return componentRef.instance.onShow(); } /** * 构建一个Warn Toptips并显示 * * @param text 文本 * @param time 显示时长后自动关闭(单位:ms) */ warn(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'warn', time); } /** * 构建一个Info Toptips并显示 * * @param text 文本 * @param time 显示时长后自动关闭(单位:ms) */ info(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'info', time); } /** * 构建一个Primary Toptips并显示 * * @param text 文本 * @param time 显示时长后自动关闭(单位:ms) */ primary(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'primary', time); } /** * 构建一个Success Toptips并显示 * * @param text 文本 * @param time 显示时长后自动关闭(单位:ms) */ success(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'primary', time); } /** * 构建一个Default Toptips并显示 * * @param text 文本 * @param time 显示时长后自动关闭(单位:ms) */ default(text: string, time: number = 2000): ToptipsComponent { return this.show(text, 'default', time); } }
cipchk/ngx-weui
components/toptips/toptips.service.ts
TypeScript
mit
2,518
require 'test_helper' class QuestionSubjectiveTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
Glastonbury/snusurvey
test/models/question_subjective_test.rb
Ruby
mit
132
var loadJsons = require('../lib/loadJsons'); describe("Get a recursive directory load of JSONs", function() { var data; beforeEach(function(done) { if(data) done(); else { loadJsons("./specs")(function(d) { data = d; done(); }); } }); it("Should return right number of jsons", function() { expect(data.length).toBe(6); }); it("Should have a @type field on all objects", function() { data.forEach(function(d) { expect(d['@type']).toBeDefined(); }); }); });
polidore/dfg
specs/fileBased.spec.js
JavaScript
mit
531
--- layout: post status: publish published: true title: Moved to Jekyll blog engine date: 2015-10-20 22:31:25.000000000 +05:30 comments: [] --- I have been using wordpress since the time I started blogging. I decided to make a move to the Jekyll static templating engine after I came to know about its simplicity and ability to host on github. Blogs are usually immutable once they are written. There is no reason use dynamic pages for blogs. The theme of this blog is based on [jekyll-incorporated](https://github.com/kippt/jekyll-incorporated). I generally don't like the WYSWYG editor that comes with the wordpress. I would prefer to write blog posts on vim as I write code. WYSWYG editors add lots of junk into the generated html. I had to to spend a lot of time migrating those editor generator markup into jekyll plain text. Blog is now hosted on [github](github.com/t3rm1n4l/t3rm1n4l.github.io). Luckly, I could import most of the comments into discuss. I hope to blog more frequently with this transition.
t3rm1n4l/t3rm1n4l.github.io
_posts/2015-10-20-moved-to-jekyll.markdown
Markdown
mit
1,016
using System; using System.Diagnostics; using System.Text; namespace BgeniiusUniversity.Logging { public class Logger : ILogger { public void Information(string message) { Trace.TraceInformation(message); } public void Information(string fmt, params object[] vars) { Trace.TraceInformation(fmt, vars); } public void Information(Exception exception, string fmt, params object[] vars) { Trace.TraceInformation(FormatExceptionMessage(exception, fmt, vars)); } public void Warning(string message) { Trace.TraceWarning(message); } public void Warning(string fmt, params object[] vars) { Trace.TraceWarning(fmt, vars); } public void Warning(Exception exception, string fmt, params object[] vars) { Trace.TraceWarning(FormatExceptionMessage(exception, fmt, vars)); } public void Error(string message) { Trace.TraceError(message); } public void Error(string fmt, params object[] vars) { Trace.TraceError(fmt, vars); } public void Error(Exception exception, string fmt, params object[] vars) { Trace.TraceError(FormatExceptionMessage(exception, fmt, vars)); } public void TraceApi(string componentName, string method, TimeSpan timespan) { TraceApi(componentName, method, timespan, ""); } public void TraceApi(string componentName, string method, TimeSpan timespan, string fmt, params object[] vars) { TraceApi(componentName, method, timespan, string.Format(fmt, vars)); } public void TraceApi(string componentName, string method, TimeSpan timespan, string properties) { string message = String.Concat("Component:", componentName, ";Method:", method, ";Timespan:", timespan.ToString(), ";Properties:", properties); Trace.TraceInformation(message); } private static string FormatExceptionMessage(Exception exception, string fmt, object[] vars) { // Simple exception formatting: for a more comprehensive version see // http://code.msdn.microsoft.com/windowsazure/Fix-It-app-for-Building-cdd80df4 var sb = new StringBuilder(); sb.Append(string.Format(fmt, vars)); sb.Append(" Exception: "); sb.Append(exception.ToString()); return sb.ToString(); } } }
bgeniius/bgUniversity
ContosoUniversity/Logging/Logger.cs
C#
mit
2,619
--- layout: article title: "The Zen of Design Patterns (2nd Edition)" categories: programing tags: [java, reading] toc: false image: teaser: programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/teaser.jpg date: 2017-11-05 --- 让设计模式成为一种习惯 --- ## 第一章 单一职责原则 缩略语: * SRP(Single Responsibility Principle,单一职责模式) * RBAC(Role-Based Access Control, 基于角色的访问控制) * BO(Business Object,业务对象),负责用户的属性 * Biz(Business Logic,业务逻辑),负责用户的行为 单一职责原则(SRP)指的是只有一个原因引起类的变更。 具体实践中应保证接口和方法一定做到单一职责,而类尽量做到。 ## 第二章 里氏替换原则 缩略语: * LSP(Liskov Substitution Principle,里氏替换原则) 里氏替换原则(LSP)是指只要父类能出现的地方子类都能出现。 实现里氏替换原则需要做到: 1. 子类必须完全实现父类的方法 2. 子类可以有自己的个性 3. 覆写(Override)或实现父类方法时输入参数可以被放大 4. 覆写(Override)或实现父类方法时输出结果可以被缩小 第三条指的是子类中的方法的前置条件必须与超类中被覆写方法的前置条件相同或更宽松。这是覆写的要求,也是重中之重。否则若方法的输入参数被缩小,则子类在没有覆写父类方法的前提下,子类方法可能被执行了,会引起业务逻辑混乱,歪曲了父类的意图。 注意输入参数不同就不能称为覆写(Override),加上@Override会出错,应该称为重载(Overload)。 ## 第三章 依赖倒置原则 缩略语: * DIP(Dependence Inversion Principle,依赖倒置原则) * OOD(Object-Oriented Design,面向对象设计,面向接口编程) * TDD(Test-Driven Development,测试驱动开发) 依赖倒置是指面向接口编程(OOD)。依赖正置就是类间的依赖是实实在在的实现类间的依赖,也就是面向实现编程。我要开奔驰车就依赖奔驰车。而抽象间的依赖代替了人们传统思维的事物间的依赖,“倒置”就是从这里产生的。 实现依赖倒置原则需要做到: 1. 高层模块不应该依赖低层模块,两者都应该依赖其抽象。即类之间不发生直接的依赖关系,其依赖是通过接口或抽象类产生的 2. 抽象不应该依赖细节。即接口或抽象类不依赖于实现类 3. 细节应该依赖抽象。即实现类依赖于接口或抽象类 依赖的三种写法: 1. 构造函数传递依赖对象 {% highlight java %} {% raw %} Public interface IDriver { public void drive(); } public class Driver implements IDriver { private ICar car; // 构造函数注入 public Driver(ICar _car) { this.car = _car; } public void drive() { this.car.run(); } } {% endraw %} {% endhighlight %} 2. Setter方法传递依赖对象 {% highlight java %} {% raw %} public interface IDriver { public void setCar(Icar car); public void drive(); } public class Driver implements IDriver { private ICar car; // Setter注入 public void setCar(ICar _car) { this.car = _car; } public void drive() { this.car.run(); } } {% endraw %} {% endhighlight %} 3. 接口声明传递依赖对象,也叫做接口注入。 {% highlight java %} {% raw %} public interface IDriver { // 接口注入 public void drive(ICar car); } public class Driver implements IDriver { public void drive(ICar car) { car.run(); } } {% endraw %} {% endhighlight %} 有依赖关系的不同开发人员,如甲负责IDriver,乙负责ICar,则两个开发人员只要定好接口就可以独立开发,并可以独立进行单元测试。这也就是测试驱动开发(TDD),是依赖倒置原则的最高级应用。比如可以引入JMock工具,根据抽象虚拟一个对象进行测试。 {% highlight java %} {% raw %} Public class DriverTest extends TestCase { Mockery context = new JUnit4Mockery(); @Test public void testDriver() { // 根据接口虚拟一个对象 final ICar car = context.mock(ICar.class); IDriver driver = new Driver(); // 内部类 context.checking(new Expectations(){{ oneOf(car).run(); }}); driver.drive(car); } } {% endraw %} {% endhighlight %} 具体实践中,实现依赖倒置需要遵守: 1. 每个类尽量都有接口或抽象类,或者二者兼备 2. 变量的表面类型尽量是接口或抽象类,工具类和需要使用clone方法的类除外 3. 任何类都不应该从具体类派生 4. 尽量不要覆写基类的方法。如果基类是抽象类,且该方法已经实现,则子类尽量不要覆写 5. 综合里氏替换原则 ## 第四章 接口隔离原则 缩略语 * ISP(Interface Segregation Principle,接口隔离原则) 接口隔离原则指的是类间的依赖关系应该建立在最小的接口上。即接口尽量细化,同时接口中的方法尽量少。 这与单一职责原则的审视角度是不同的,单一职责原则是业务逻辑的划分,而接口隔离原则要求接口的方法尽量少。提供几个模块就应该有几个接口,而不是建立一个庞大臃肿的接口容纳所有的客户端访问。注意,根据接口隔离原则拆分接口时,必须满足单一职责原则。 ## 第五章 迪米特原则 缩略语: * LoD(Law of Demeter,迪米特原则),也称为LKP(Least Knowledge Principle,最少知识原则) * RMI(Remote Method Invocation,远程方法调用) * VO(Value Object,值对象) 迪米特原则指的是一个类应该对自己需要耦合或调用的类知道的最少,不关心其内部的具体实现,只关心提供的public方法。即类间解耦,弱耦合。 迪米特原则要求: 1. 只与直接的朋友通信。出现在成员变量、方法的输入输出参数中的类称为成员朋友类,而出现在方法体内部的类不属于朋友类。一个方法中尽量不引入一个类中不存在的对象,JDK API提供的类除外 2. 朋友间也是有距离的。尽量不对外公布太多的public方法和非静态的public变量 3. 是自己的就是自己的。如果一个方法放在本类中,既不增加类间关系,对本类也不产生负面影响,那就放置在本类中 4. 谨慎使用Serializable。在一个项目中使用远程方法调用(RMI),传递一个值对象(VO),这个对象就必须实现Serializable接口(仅仅是一个标志性接口,不需要实现具体方法),否则就会出现NotSerializableException异常。当客户端VO修改了一个属性的访问权限,由private变更为public,访问权限扩大了,如果服务器上没有做出相应的变更,就会出现序列化失败。当然,这属于项目管理中客户端与服务器同步更新的问题。 在具体实践中,既要做到高内聚低耦合,又要让结构清晰。如果一个类跳转两次以上才能访问另一个类,则需要考虑重构了,这就是过度地解耦了。因为跳转次数越多,系统越复杂,维护就越难。 ## 第六章 开闭原则 缩略语: * OCP(Open Closed Principle,开闭原则) 开闭原则指的是软件实体如类、模块和方法应该对扩展开放,对修改关闭。这是Java世界中最基础的设计原则,以建立一个稳定灵活的系统。也就是说,一个软件实体应该通过扩展来实现变化,而不是通过修改已有的代码来实现变化。并不意味着不做任何修改,在业务规则改变或低层次模块变更的情况下高层模块必须有部分改变以适应新业务,改变要尽可能地少,防止变化风险的扩散。 一个方法的测试方法一般不少于3种,有业务逻辑测试,边界条件测试,异常测试等。 实现开闭原则需要做到: 1. 抽象约束。在子类中不允许出现接口或抽象类中不存在的public方法;参数类型、引用类型尽量使用接口或抽象类而不是实现类;抽象类尽量保持稳定,一旦确定不允许修改 2. 元数据(metadata)控制模块行为。元数据为描述环境和数据的数据,即配置参数。元数据控制模块行为的极致为控制反转(Inversion of Control),使用最多的就是Spring容器 3. 制定项目章程。如所有的Bean都自动注入,使用Annotation进行装配,进行扩展时,只用可以只用一个子类,然后由持久层生成对象 4. 封装可能的变化。将相同的变化封装到一个接口或抽象类中;将不同的变化封装到不同的接口或抽象类中 软件设计最大的难题就是应对需求的变化。6大设计原则和23个设计模式都是为了封装未来的变化。 6大设计原则有: 1. Single Responsibility Principle: 单一职责原则 2. Open Closed Principle: 开闭原则 3. Liskov Substitution Principle: 里氏替换原则 4. Law of Demeter: 迪米特原则 5. Interface Segregation Principle: 接口隔离原则 6. Dependence Inversion Principle: 依赖倒置原则 将6个原则的首字母联合起来,就是Solid(稳定的),里氏替换原则和迪米特原则的首字母都是L,只取一个。开闭原则是最基础的原则,是精神口号,其他5大原则是开闭原则的具体解释。 ## 第七章 单例模式 单例模式(Singleton Pattern)指的是确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。其实现方式可以分为饿汉式和懒汉式。 ![1-singleton](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/1-singleton.png) 单例模式的优点有: 1. 减少内存开支,特别是当一个对象需要频繁创建和销毁时 2. 减少了系统的性能开销 3. 避免对资源的多重占用 4. 可以在系统设置全局的访问点,优化共享资源的访问 在具体实践中,Spring的每个Bean默认就是单例的,这样Sring容器可以管理这些Bean的生命期,决定何时创建、何时销毁和如何销毁等。 ## 第八章 工厂方法模式 工厂方法模式指的是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。 ![2-factory](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/2-factory.png) 工厂方法模式的优点有: 1. 有良好的封装性,代码结构清晰。调用者需要创建一个具体产品对象时,只需要知道这个产品的类名(或约束字符串)就可以了,不用知道创建对象的过程,降低模块间的耦合性 2. 优秀的扩展性,在增加产品类的情况下,只需要适当修改或扩展工厂类即可 3. 屏蔽产品类,不需要关心产品类的实现,只关心产品类的接口 4. 工厂方法是典型的解耦框架,符合迪米特原则(最少知识原则),符合依赖倒置原则,也符合里氏替换原则 在具体实践中,工厂方法模式可以缩小为简单工厂模式,也叫做静态工厂模式。即将工厂类去掉继承抽象类,并添加具体生产方法前添加static关键字,其缺点是扩展比较困难,不符合开闭原则。 工厂方法模式还可以升级为多个工厂类,当然此时如果要扩展一个产品类,就需要建立一个相应的工厂类,这就增加了扩展的难度,所以一般会再添加一个协调类,用来封装子工厂类,为高层模块添加统一的访问接口。 工厂方法模式也可以替代单例模式,不过需要在工厂类中使用反射的方式建立单例对象。 工厂方法模式还可以延迟初始化,即一个对象被消费完毕之后并不立刻释放,工厂类会保持其初始状态,等待再次被使用。延迟加载框架是可以扩展的,比如限制某一产品类的最大实例化数量(数据库的最大连接数量等),可以通过判断Map中已有的对象数量来实现。 ## 第九章 抽象工厂方法 抽象工厂模式指的是为创建一组相关的或相互依赖的对象提供一个接口,而且无需指定它们的具体类。 ![3-abstract-factory](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/3-abstract-factory.png) 抽象工厂模式的优点有: 1. 封装性 2. 产品族内的约束为非公开状态,例如每生产一个产品A,就同时生产出1.2个产品B,这个约束是在工厂内实现的,对高层模块来说是透明的。 抽象工厂模式是工厂方法模式的升级版本。即拥有两个或两个以上互相影响的产品族,或者说产品的分类拥有两个或两个以上的维度,如不同性别和肤色的人。如果拥有两个维度,则抽象工厂模式比工厂方法模式多一个抽象产品类,以维护两个分类维度,即不同的抽象产品类维护一个维度,而不同的产品实现类维护另外一个维度;而抽象工厂类不增加,但需要增加不同的工厂实现类。 抽象工厂模式的缺点是产品族的扩展非常困难。例如增加一个产品C,则抽象类AbstractCreator要增加一个方法createProductC(),然后两个实现类都要修改。这样就违反了开闭原则。而另外一个维度产品等级是很容易扩展的,对于工厂类只需要增加一个实现类即可。也就是说,抽象工厂模式横向扩展容易,纵向扩展困难。对于横向,抽象工厂模式是符合开闭原则的。 ## 第十章 模板方法模式 模板方法模式值得是定义一个操作中的算法框架,而将一些步骤的实现延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。 ![4-template](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/4-template.png) 模板方法模式的抽象模板类一般包含两类方法,一种是基本方法,由子类实现,并且在模板方法中被调用;另一种是抽象方法,可以有一个或多个,一般是一个具体方法,也就是一个框架,实现对基本方法的调度,完成固定的逻辑。模板方法一般会加上final关键字,不允许覆写,以防恶意操作。 如果模板方法的执行结果受到基本方法的返回值或所设置的值的影响,则该基本方法称为钩子方法(Hook Method),即钩子方法可能会影响其公共部分(模板方法)的执行顺序。 模板方法模式的优点有: 1. 封装不变部分,扩展可变部分 2. 提取公共部分代码,便于维护。相同的一段代码如果复制过两次,就需要对设计产生怀疑 3. 行为由父类控制,子类实现,符合开闭原则 模板方法的缺点是子类的实现会影响父类的结果,也就是子类会对父类产生影响,在复杂项目中,会增加代码阅读的难度。 在具体实践中,如果被问到“父类如何调用子类的方法”,其实现方式可能有把子类传递到父类的有参构造中,然后调用;使用反射的方式调用;父类调用子类的静态方法。当然项目中强烈不建议这么做,如果要调用子类的方法,可以使用模板方法模式,影响父类行为的结果。 ## 第十一章 建造者模式 建造者模式也称为生成器模式,指的是将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。 ![5-builder](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/5-builder.png) 通常,建造者模式有4个角色,产品类,抽象建造者,建造者的实现类(如可以传入产品的模块顺序或数量配置,并生产产品),导演类(如负责安排已有模块的顺序或数量,然后告诉建造者开始建造)。 建造者模式的优点: 1. 封装性 2. 建造者独立,容易扩展 3. 便于控制细节风险 建造者模式关注的是零件类型和装配工艺(顺序),这是它与工厂方法模式最大的不同之处,虽然同为创建类模式,但关注点不同。工厂方法的重点是创建零件,而组装顺序不是它关心的内容。 在具体实践中,使用创建者模式的时候考虑一下模板方法模式,二者的配合可以作为创建者模式的扩展。 ## 第十二章 代理模式 缩略语: AOP(Aspect Oriented Programming,面向横切面编程) 代理模式又称为委托模式,指的是为其他对象提供一种代理以控制对这个对象的访问。其他的许多模式,如状态模式、策略模式和访问者模式本质上是在更特殊的场合使用了代理模式。 ![6-proxy](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/6-proxy.png) 代理类不仅可以实现主题接口,还可以为真实角色预处理信息、过滤信息、消息转发、事后处理信息等功能。 代理模式的优点有: 1. 职责清晰。真实的角色只实现实际的业务逻辑,而通过后期的代理完成某一件事务 2. 高扩展性 3. 智能化,例如动态代理 代理模式可以扩展为普通代理,要求客户端只能访问代理角色,而不能访问真实角色,真实角色由代理角色来实例化。 代理模式还可以作为强制代理,这个比较另类,所谓强制表示必须通过真实角色找到代理角色,否则不能访问。也就是说高层模块new了一个真实角色的对象,返回的却是代理角色。比如拨通明星的电话,确强制返回其经纪人作为代理,这就是强制代理。 代理模式还可以作为动态代理,动态代理是在实现阶段不用关心代理谁,在运行阶段才指定代理哪一个对象。相对来说,自己写代理类的方式就是静态代理。面向横切面编程(AOP)的核心就是动态代理机制。 一个类的动态代理类由InvocationHandler(JDK提供的动态代理接口)的实现类通过invoke方法实现所有的方法, 在具体实践中,关于AOP框架,需要弄清楚几个名词,包括切面(Aspect)、切入点(JoinPoint)、通知(Advice)和织入(Weave),这样在应用中就游刃有余了。 ## 第十三章 原型模式 原型模式指的是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。即不通过new关键字来产生一个对象,而是通过对象复制来实现。可以理解为一个对象的产生可以不由零起步,而是由正本通过二进制内存拷贝创建多个副本,然后再修改为生产需要的对象。 ![7-prototype](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/7-prototype.png) 原型模式的核心是一个clone方法,通过该方法进行对象的拷贝,Java提供了一个Cloneable接口来标识这个对象是可拷贝的,且还必须覆写clone方法。为什么说Cloneable接口仅作为标识还称clone方法为覆写,因为clone方法是Object类的,而每个类都默认继承了Object类。 原型模式的优点有: 1. 性能优良,内存二进制流的拷贝 2. 规避构造函数的约束,当然这个有时候也是缺点,直接内存拷贝,其构造函数是不会执行的 需要注意的是Object提供的clone方法只是拷贝对象,其对象内部的数组、引用对象都不拷贝,还是指向原生对象的内部元素地址,这种拷贝称为浅拷贝。两个对象共享了一个私有变量,并且都可以对其进行修改,这是一种很不安全的方式。 浅拷贝时,内部的数组和引用对象不拷贝,其他的基本类型如int、long和char等都会被拷贝,对于String类型,Java希望你把它当作基本类型,它是没有clone方法的,处理机制也比较特殊,通过字符串池(stringpool)在需要的时候才在内存中创建新的字符串。 深拷贝则需要考虑成员变量中所有的数组和可变的引用对象,进一步调用或覆写引用对象的clone方法,如JDK提供的ArrayList的clone方法。 此外要使用clone方法,类的成员变量上不要增加final关键字。 在具体实践中,原型模式很少单独出现,一般和工厂方法模式一起出现,通过clone方法创建一个对象,然后由工厂方法提供给调用者。 ## 第十四章 中介者模式 中介者模式指的是用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,并且可以独立地改变它们之间的交互。中介者类似于星型网络拓扑中的中心交换机连接各计算机。也称为调停者模式。 ![8-mediator](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/8-mediator.png) 中介者模式的优点就是减少了类间的依赖,把原有的一对多的依赖变成了一对一的依赖,同事类只依赖中介者,减少了依赖,当然同时也降低了类间的耦合。 中介者模式的缺点是中介者会膨胀得很大,而且同事类越多,逻辑越复杂。 在面向对象编程中,对象与对象之间必然存在依赖关系,如果某个类和其他类没有任何相互依赖的关系,那么这个类在项目中就没有存在的必要了。所以中介者模式适用于多个对象之间紧密耦合的情况,紧密耦合的标准是在类图中出现了蜘蛛网状结构。而中介者模式的使用可以将蜘蛛网结构梳理为星型结构。 在具体实践中,Struts的MVC框架中的C(Controller)就是一个中介者,叫做前端控制器。它的作用就是把M(Model,业务逻辑)和V(View,视图)隔离开来,减少M和V的依赖关系。 ## 第十五章 命令模式 命令模式指的是将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,将多个请求排队或者记录请求日志,也可以提供命令的撤销和恢复功能。 ![9-command](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/9-command.png) 命令模式的优点有: 1. 类间解耦。调用者角色和接收者角色之间没有任何的依赖关系,调用者实现功能时只需调用Command抽象类execute方法就可以了,不需要了解到底是哪个接收者执行 2. 可扩展性。Command的子类可以非常容易扩展 3. 命令模式与其他模式的结合会更优秀。命令模式结合责任链模式,实现命令族解析任务;命令模式结合模板方法模式,则可以减少Command子类的膨胀问题 命令模式的缺点是如果命令很多,则Command子类很容易增多,这个类就显得非常膨胀 在具体实践中,高层模块可以不需要知道具体的接收者,而是用具体的Command子类将接收者封装起来,每个命令完成单一的职责,解除高层模块对接收者的依赖关系。 ## 第十六章 责任链模式 责任链模式指的是使多个对象都有机会处理请求,从而避免了请求的发送者和接收者的耦合关系,将这些接收者对象连成一条链,并沿着这条链传递请求,知道有对象处理它为止。注意请求是由接收者对象来决定是否传递的,而不是在高层模块中判断。 ![10-chain-of-responsibility](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/10-chain-of-responsibility.png) 责任链模式的优点是将请求和处理分开,请求者不用知道是谁处理的,只问了责任链中的第一个接收者,只需要得到一个回复,而关于请求是否传递则由接收者来传递。同样的,接收者也不用知道请求的全貌。两者解耦,提高系统的灵活性。 责任链的缺点一个是性能问题,责任链比较长的时候遍历会带来性能问题;另一个是调试不方便,由于采用了类似递归的方式,逻辑可能比较复杂。 在具体实践中,一般会有一个封装类对责任链模式进行封装,也就是替代场景类client,直接返回责任链中的第一个处理者,具体链的设置不需要高层模块知道,这样更简化了高层模块的调用,减少模块间的耦合性。另外,责任链的接收者节点数量需要控制,一般做法是在Handler中设置一个最大的节点数量,在setNext方法中判断是否超过该阈值。责任链模式通常会与模板方法结合,每个实现类只需要实现response方法和getHandlerLevel获取处理级别。 ## 第十七章 装饰模式 装饰模式指的是动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式比由对象直接生成子类更为灵活。装饰模式可以任意选择所需要添加的装饰,下一次传递的被装饰对象为上一次装饰完毕的对象,都继承自同一个Component抽象类。装饰模式也可看成是特殊的代理模式。 ![11-decorator](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/11-decorator.png) 装饰模式的优点有: 1. 装饰类和被装饰类可以独立发展,而不会相互耦合。即Component类无须知道Decorator类,而Decorator类是从外部扩展Component类的功能,而不需要知道具体的Component类的构件。 2. 装饰模式是继承关系的一个替代方案。不管装饰多少层,返回的对象仍是Component,实现的还是is-a关系。 3. 装饰模式可以动态地扩展一个实现类的功能。 装饰模式的缺点是多层的装饰还是比较复杂的,因为可能剥离到最里面一层,才发现错误,所以尽量减少装饰类的数量,以降低系统的复杂度。 在具体实践中,装饰模式是对继承的一种有力补充。可以在高层模块中动态地给一个对象增加功能,这些功能也可以再动态地撤销。而继承是静态地给类增加功能。而且装饰模式的扩展性也非常好,比如要在继承关系Father、Sonh和GrandSon三层类中的Son增强一些功能,怎么办,如何评估对GrandSon造成的影响,特别是GrandSon有多个的时候,此时就可以通过建立SonDecorator类来修饰Son,很好地完成这次变更。 ## 第十八章 策略模式 策略模式指的是定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。策略模式也是一种特殊的代理模式,使用一个代理类(Context封装类)来代理多个对象(Strategy抽象类的具体实现)。 ![12-strategy](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/12-strategy.png) 策略模式的优点有: 1. 策略(算法)可以自由替换 2. 避免使用多重条件判断 3. 扩展性良好 策略模式的缺点有策略类数量增多导致类膨胀,另一个是所有的策略类都需要对外暴露。上层模块必须知道有哪些策略,才能决定使用哪一个策略,这与迪米特原则是违背的,要你的封装类有何用。 在具体实践中,一般通过工厂方法模式来实现策略类的声明,来避免所有策略都必须对高层模块暴露的问题。 ## 第十九章 适配器模式 适配器模式指的是将一个类的接口变换成客户端所期待的另一种接口,从而使原本不匹配的两个类能够共同工作。适配器模式又称为变压器模式。适配器模式也是包装模式的一种,包装模式还有装饰模式。 ![13-adapter](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/13-adapter.png) 适配器模式的优点有: 1. 让两个没有任何关系的类在一起运行 2. 增加了类的透明性。我们访问的Target目标角色,其具体实现都委托给了源角色,而这些对高层模块是不可见的 3. 提高了类的复用度。源角色在原有的系统中可以正常使用,通过适配器角色中也可以让Target目标角色使用 4. 灵活性非常好。适配器角色删除后不会影响其他代码 在具体实践中,在细节设计阶段不要考虑适配器模式,适配器模式不是为了解决还处于开发阶段的问题,而是为了解决正在服役的项目问题。换句话说,适配器模式是一种补救模式。适配器可分为对象适配器和类适配器,类适配器是类间适配,通过继承关系适配源角色,而对象适配器是通过关联聚合关系适配多个源角色。在实际项目中,对象适配器更为灵活,使用的也较多。 ## 第二十章 迭代器模式 迭代器模式指的是提供一种方法访问一个容器对象中各个元素,而又不需要暴露该对象的内部细节。迭代器是为容器服务的,能容纳对象的所有类型都可以称之为容器,例如Collection类型、Set类型等。 ![14-interator](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/14-interator.png) Java的的迭代器接口java.util.iterator有三个方法hasNext、next和remove。迭代器的remove方法应该完成两个逻辑:一是删除当前元素,而是当前游标指向下一个元素。而抽象容器类必须提供一个方法来创建并返回具体迭代器角色,Java中通常为iterator方法。 在具体实践中,Java的基本API中的容器类基本都融入了迭代器模式,所以尽量不要自己写迭代器模式。 ## 第二十一章 组合模式 组合模式指的是将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。 ![15-composite](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/15-composite.png) 组合模式的优点有: 1. 高层模块调用简单,一个树形结构中的所有节点都是Component,简化了高层模块的调用 2. 节点自由增加 组合模式的缺点是叶子类和树枝类直接继承了Component抽象类,这与面向接口编程相冲突,即不符合依赖倒置的原则。 组合模式有两种不同的实现,一种是安全模式,一种是透明模式。安全模式是指叶子对象和树枝对象的结构不同,而公共部分的Operation()方法放到Component抽象类中。而透明模式指的是,叶子对象和树枝对象的结构相同,所有方法全部集合到Component抽象类中,通过getChildren的返回值判断是叶子节点还是树枝节点。 具体实践中,建议使用安全模式的组合模式。但透明模式基本遵循了依赖倒置的原则,方便系统进行扩展。页面结构、XML结构和公司的组织结构都是树形结构,都可以采用组合模式。 ## 第二十二章 观察者模式 观察者模式指的是定义对象间一对多的依赖关系,使得当发布者对象的状态改变,则所有它依赖的订阅对象都会得到通知并自动更新。观察者模式也叫做发布/订阅模式。 ![16-observer](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/16-observer.png) 观察者模式的优点有: 1. 被观察者与观察者之间是抽象耦合,容易扩展 2. 建立了一套触发机制,很容易实现一条触发链 观察者模式的缺点是开发效率和运行效率的问题。一个被观察者和多个观察者,甚至会有多级触发情况,开发和调试就会相对比较复杂,而且一个观察者卡壳,会影响整体的执行效率。在这种情况下可以考虑异步的方式。 EJB(Enterprise JavaBean)中有3个类型的Bean,分别为Session Bean、Entity Bean和MessageDriven Bean(MDB),对于MDB,消息的发布者发布一个消息,也就是一个消息驱动Bean,通过EJB容器(一般是Message Queue消息队列)通知订阅者作出响应,这个就是观察者模式的升级版,或成为企业版。 在具体实践中,多级触发的广播链最多为两级,即消息最多传递两次。观察者模式的多级触发与责任链模式的区别是观察者模式传递的消息是可以随时更改的,而责任链模式传递的消息一般是保持不变的,如果需要改变,也只是在原有的消息上进行修正。JDK中提供了java.util.Observable实现类作为被观察者和java.util.Observer接口作为观察者。 ## 第二十三章 门面模式 门面模式指的是要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。门面模式提供一个高层次的接口使得子系统更容易使用。门面模式也叫做外观模式。 ![17-facade](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/17-facade.png) 门面模式注重统一的对象,也就是提供一个门面对象作为访问子系统的接口,除了这个接口不允许任何访问子系统的行为发生。 门面模式的优点有: 1. 减少系统的相互依赖。客户端所有的依赖都是对门面对象的依赖,与子系统无关。 2. 提高了灵活性。 3. 提高安全性。只能访问在门面对象上开通的方法。 门面模式的缺点是不符合开闭原则。在业务更改或出现错误时,需要修改门面对象的代码。 门面模式不应该参与子系统内的业务逻辑,如在一个方法中先调用了子系统的ClassA的方法,再调用子系统的ClassB的方法。门面对象只是提供访问子系统的一个路径而已,它不应该也不能参与具体的业务逻辑,否则子系统必须依赖门面对象才能被访问,违反了单一职责原则,也破坏了系统的封装性。对于这种情况,应该建立一个封装类,封装完毕后提供给门面对象。 在具体实践中,当算法或者业务比较复杂时,可以封装出一个或多个门面出来,项目的结构比较简单,而且扩展性良好。另外对于一个大项目,使用门面模式也可以避免低水平开发人员带来的风险。使用门面模式后,可以对门面进行单元测试,约束项目成员的代码质量。 ## 第二十四章 备忘录模式 备忘录模式指的是在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态。 ![18-memento](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/18-memento.png) 备忘录模式的备忘录角色可以由原型模式的clone方法创建。发起人角色只要实现Cloneable接口就成。这样发起人角色融合就融合发起人角色和备忘录角色,此时备忘录管理员角色直接依赖发起人角色。当然也可以再精简掉备忘录管理员角色,使发起人自主备份和恢复。这不是“在该对象之外保存这个状态”,而是把状态保存在了发起人内部,但这仍然可视为备忘录模式的一种。此外使用原型模式还必须要考虑深拷贝和浅拷贝的问题,所以Clone方式的备忘录模式只适用于较简单的场景。 备忘录模式还可以备份多状态,多备份。可以使用Map来实现。对于多备份,建议设置Map的上限,否则系统很容易产生内存溢出的情况。 在具体实践中,最好使用备忘录模式来代替使用数据库的临时表作为缓存备份数据,后者加大了数据库操作的频繁度,把压力下放到了数据库。 ## 第二十五章 访问者模式 访问者模式指的是封装一些作用于某种数据结构中的各元素的操作,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。 ![19-visitor](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/19-visitor.png) 访问者模式的优点有: 1. 符合单一职责原则。具体元素角色负责数据的加载,而Vistor类负责报表的展现。 2. 优秀的扩展性。 3. 灵活性非常高。 访问者模式的缺点有具体元素对访问者公布细节,这个并不符合迪米特法则。其次是具体元素的变更比较困难,可能牵扯到多个Vistor的修改。最后是违背了依赖倒置的原则,访问者依赖的是具体元素而不是抽象元素,抛弃了对接口的依赖,这方面的扩展比较难。 在具体实践中,访问者模式还可以用于统计功能,因为访问者可以知道具体元素的所有细节。当然还可以同时存在多个访问者来实现不同的访问功能(展示、汇总等)。 注意谈到访问者模式肯定要谈到双分派,双分派是多分派的一个特例。Java是单分派语言,但可以用访问者模式支持双分派,单分派语言处理一个操作是根据方法执行者的名称(覆写,动态绑定)和方法接收到的参数(重载,静态绑定)决定的。 {% highlight java %} {% raw %} // 演员抽象类,方法的执行者,动态绑定,场景类中会举例说明其含义 public abstract class AbsActor { //重载act方法,方法接收到的参数,静态绑定,场景类中会举例说明其含义 //演员都能够演一个角色 public void act(Role role){ System.out.println("演员可以扮演任何角色"); } //可以演功夫戏 public void act(KungFuRole role){ System.out.println("演员都可以演功夫角色"); } } // 青年演员和老年演员 public class YoungActor extends AbsActor { //年轻演员最喜欢演功夫戏 public void act(KungFuRole role){ System.out.println("最喜欢演功夫角色"); } } public class OldActor extends AbsActor { //不演功夫角色 public void act(KungFuRole role){ System.out.println("年龄大了,不能演功夫角色"); } } //场景类 public class Client { public static void main(String[] args) { //定义一个演员 AbsActor actor = new OldActor(); //定义一个角色 Role role = new KungFuRole(); //开始演戏 actor.act(role); actor.act(new KungFuRole()); } } {% endraw %} {% endhighlight %} 运行结果是什么呢?运行结果如下所示: {% raw %} 演员可以扮演任何角色 年龄大了,不能演功夫角色 {% endraw %} 重载在编译时就根据传进来的参数决定要调用哪个方法,这是静态绑定,而方法的执行者actor是动态绑定的。 引入访问者模式后,将重载拿掉,全部以动态绑定得到我们期望的结果。 {% highlight java %} {% raw %} //AbsActor为访问者,Role为元素 public interface Role { //演员要扮演的角色 public void accept(AbsActor actor); } public class KungFuRole implements Role { //武功天下第一的角色 public void accept(AbsActor actor){ actor.act(this); } } public class IdiotRole implements Role { //一个弱智角色,由谁来扮演 public void accept(AbsActor actor){ actor.act(this); } } //场景类 public class Client { public static void main(String[] args) { //定义一个演员 AbsActor actor = new OldActor(); //定义一个角色 Role role = new KungFuRole(); //开始演戏 role.accept(actor); } } {% endraw %} {% endhighlight %} 运行结果如下: {% raw %} 年龄大了,不能演功夫角色 {% endraw %} 双分派意味着方法的具体执行由执行者的类型和接收参数的类型决定,而单分派是由执行者的名称(编译的时候决定)和接收参数的类型决定,这就是二者的区别,Java是一个支持双分派的单分派语言。 访问者模式的目的是实现功能集中化,如一个统一的报表计算,UI呈现等。 ## 第二十六章 状态模式 状态模式指的是允许一个对象在其内部状态改变时改变它的行为,从外部看起来就好像这个对象对应的类发生了改变一样。状态模式是一种对象行为型模式。 ![20-state](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/20-state.png) 状态模式由状态角色和环境角色组成。 环境角色有两个不成文的约束,一是把状态对象声明为静态变量,有几个状态角色就声明几个静态变量;二是环境角色具有状态抽象角色定义的行为,具体执行使用委托方式。 状态模式的优点有: 1. 结构清晰,避免了过多的条件语句的使用。 2. 遵循开闭原则和单一职责原则,对扩展开放,对修改关闭。 3. 封装性良好,外部的调用不用知道类内部如何实现状态和行为的变换。 状态模式的缺点是如果状态过多,则会产生太多的子类,出现类膨胀的问题。 状态模式在具体实践中适用于行为随状态改变而改变的场景,作为条件、分支判断语句的替代者。使用的对象的状态最好不超过5个。建造者模式还可以将状态之间的顺序切换再重新组装一下,建造者模式加上状态模式得到一个非常好的封装效果。 ## 第二十七章 解释器模式 解释器模式是一种按照规定语法进行解析的方案,在现有的项目中使用较少。给定一门语言,定义它的文法的一种表示(表达式),并定义一个解释器,该解释器使用该表示啦解释语言中的句子。 ![21-interpreter](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/21-interpreter.png) 表达式分为终结符表达式(如某个变量,只关心自身的结果)和非终结符表达式(如加减乘除法则,只关心左右或附近表达式的结果),其实就是逐层递归的意思。 解释器模式的优点是扩展性良好,修改语法规则只需要修改相应的非终结表达式就可以了,若扩展语法,则只要增加非终结符类就可以了。 解释器模式的缺点是会容易引起类膨胀,递归调用的方式增加了调试难度,降低了执行效率。 解释器模式的在具体实践中适用于重复发生的问题,如对大量日志文件进行分析处理,由于日志格式不相同,但数据要素是相同的,这便是终结符表达式都相同,而非终结符表达式需要制定。此外,尽量不要在重要的模块中使用解释器模式,否则维护会是一个很大的问题,可以使用shell、JRuby、Groovy等脚本语言代替解释器模式,弥补Java编译型语言的不足。当准备使用解释器模式时,可以考虑Expression4J、MESP(Math Expression String Prser)、Jep等开元的数学解析工具包。 ## 第二十八章 享元模式 享元模式(Flyweight Pattern)是池技术的重要实现方式,使用共享对象可有效支持大量的细粒度的对象,从而避免内存溢出。 ![22-flyweight](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/22-flyweight.png) 细粒度对象的信息分为两个部分:内部状态(intrinsic)和外部状态(extrinsic)。 内部状态是对象可共享出来的信息,不会随环境的改变而改变,如id,可以作为一个对象的动态附加信息,不必直接存在具体的某个对象中,属于共享的部分。 外部状态是对象得以依赖的一个标记,是随环境改变而改变的,不可共享的状态,如考试科目+考试地点的复合字符串,它是对象的是唯一的索引值。 外部状态一般需要设置为final类型,初始化时一次赋值,避免无意修改导致池混乱,特别是Session级的常量或变量。 享元模式的优点是可以大大减少应用程序创建的对象,降低程序内存的占用,增强程序的性能,但它同时页提高了系统的复杂性,需要分离出外部状态和内部状态,且外部状态不随内部状态改变而改变,否则会导致系统的逻辑混乱。 享元模式在具体实践中适用于系统中存在大量相似对象的情况以及需要缓冲池的场景。在使用中需要注意线程安全的问题,此外尽量使用Java的基本类型作为外部状态,可以大幅提高效率,如果把一个对象作为Map类的键值,一定要确保重写了equals和hashCode方法,只有hashCode值相等,并且equals返回的结果为ture,两个对象的key才相等。 Java中String类的intern方法就使用了享元模式。 虽然使用享元模式可以实现对象池,但是二者还是有比较大的差异。对象池着重在对象的复用上,池中的每个对象是可替换的,从同一个池中获取A对象和B对象对客户端来说是完全相同的,它主要解决“复用”。而享元模式主要解决对象的共享问题,如何建立多个可“共享”的细粒度对象是其关注的重点。 ## 第二十九章 桥梁模式 桥梁模式也叫桥接模式,将抽象和实现解耦,使得二者可以独立地变化。抽象化角色(分为抽象类和具体类)引用实现角色(同样分为抽象类和具体类),或者说抽象角色的部分实现是由实现角色完成的。抽象化对象一般在构造函数中指定(聚合)实现对象。 ![23-bridge](/images/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition)/23-bridge.png) 桥梁模式的优点是将抽象和实现分离,解决继承的缺点,不再绑定在一个固定的抽象层次上,拥有更良好的扩展能力,用户不必关心实现细节。 桥梁模式在具体实践中适用于接口或抽象类不稳定的场景以及重用性较高且颗粒度更细的场景。当发现继承有N层时,可以考虑使用桥梁模式。对于比较明确不发生变化的,则通过继承来完成,若不能确定是否会发生变化的,则可以通过桥梁模式来完成。 --- The End. zhlinh Email: [email protected] 2017-11-05
zhlinh/zhlinh.github.io
_posts/programing/2017-11-05-The-Zen-of-Design-Patterns-(2nd-Edition).md
Markdown
mit
45,879
<?php /** * Rule for required elements * * PHP version 5 * * LICENSE: * * Copyright (c) 2006-2010, Alexey Borzov <[email protected]>, * Bertrand Mansion <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The names of the authors may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @category HTML * @package HTML_QuickForm2 * @author Alexey Borzov <[email protected]> * @author Bertrand Mansion <[email protected]> * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version SVN: $Id: Required.php 294057 2010-01-26 21:10:28Z avb $ * @link http://pear.php.net/package/HTML_QuickForm2 */ /** * Rule checking that the form field is not empty */ require_once 'HTML/QuickForm2/Rule/Nonempty.php'; /** * Rule for required elements * * The main difference from "nonempty" Rule is that * - elements to which this Rule is attached will be considered required * ({@link HTML_QuickForm2_Node::isRequired()} will return true for them) and * marked accordingly when outputting the form * - this Rule can only be added directly to the element and other Rules can * only be added to it via and_() method * * @category HTML * @package HTML_QuickForm2 * @author Alexey Borzov <[email protected]> * @author Bertrand Mansion <[email protected]> * @version Release: 0.4.0 */ class HTML_QuickForm2_Rule_Required extends HTML_QuickForm2_Rule_Nonempty { /** * Disallows adding a rule to the chain with an "or" operator * * Required rules are different from all others because they affect the * visual representation of an element ("* denotes required field"). * Therefore we cannot allow chaining other rules to these via or_(), since * this will effectively mean that the field is not required anymore and the * visual difference is bogus. * * @param HTML_QuickForm2_Rule * @throws HTML_QuickForm2_Exception */ public function or_(HTML_QuickForm2_Rule $next) { throw new HTML_QuickForm2_Exception( 'or_(): Cannot add a rule to "required" rule' ); } } ?>
N3X15/ATBBS-Plus
includes/3rdParty/HTML/QuickForm2/Rule/Required.php
PHP
mit
3,540
class String def split_on_unescaped(str) self.split(/\s*(?<!\\)#{str}\s*/).map{|s| s.gsub(/\\(?=#{str})/, '') } end end
rubysuperhero/hero-notes
lib/clitasks/split_on_unescaped.rb
Ruby
mit
128
import axios from 'axios'; import { updateRadius } from './radius-reducer'; import { AddBType } from './b-type-reducer'; // import { create as createUser } from './users'; // import history from '../history'; /* ------------------ ACTIONS --------------------- */ const ADD_B_TYPE = 'ADD_B_TYPE'; const ADD_LNG_LAT = 'ADD_LNG_LAT'; const UPDATE_RADIUS = 'UPDATE_RADIUS'; const SWITCH_MEASUREMENT = 'SWITCH_MEASUREMENT'; /* -------------- ACTION CREATORS ----------------- */ export const addLngLat = (latitude, longitude) => ({ type: ADD_LNG_LAT, latitude, longitude }); export const switchMeasurement = measurement => ({ type: SWITCH_MEASUREMENT, measurement }); /* ------------------ REDUCER --------------------- */ export default function reducer (state = { latitude: null, longitude: null, radius: null, businessType: null, distanceMeasurement: 'miles' }, action) { switch (action.type) { case ADD_B_TYPE: state.businessType = action.typeStr; break; case ADD_LNG_LAT: state.latitude = action.latitude; state.longitude = action.longitude; break; case UPDATE_RADIUS: state.radius = action.radInt; break; case SWITCH_MEASUREMENT: state.distanceMeasurement = action.measurement; break; default: return state; } return state; }
Bullseyed/Bullseye
app/reducers/report.js
JavaScript
mit
1,361
<h4>Lists</h4> <h5>Simple List</h5> <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> Bryan Cranston </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> Aaron Paul </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> Bob Odenkirk </mdl-list-item-primary-content> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> Bryan Cranston </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> Aaron Paul </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> Bob Odenkirk </mdl-list-item-primary-content> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Icons</h5> <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bryan Cranston </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-icon>person</mdl-icon> Aaron Paul </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bob Odenkirk </mdl-list-item-primary-content> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bryan Cranston </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-icon>person</mdl-icon> Aaron Paul </mdl-list-item-primary-content> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-icon>person</mdl-icon> Bob Odenkirk </mdl-list-item-primary-content> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Avatars and actions</h5> <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bryan Cranston</span> </mdl-list-item-primary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Aaron Paul</span> </mdl-list-item-primary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bob Odenkirk</span> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bryan Cranston</span> </mdl-list-item-primary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Aaron Paul</span> </mdl-list-item-primary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bob Odenkirk</span> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Avatars and controls</h5> <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> Bryan Cranston </mdl-list-item-primary-content> <mdl-list-item-secondary-action> <mdl-checkbox mdl-ripple></mdl-checkbox> </mdl-list-item-secondary-action> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> Aaron Paul </mdl-list-item-primary-content> <mdl-list-item-secondary-action> <mdl-radio ngModel="false" mdl-ripple></mdl-radio> </mdl-list-item-secondary-action> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> Bob Odenkirk </mdl-list-item-primary-content> <mdl-list-item-secondary-action> <mdl-switch mdl-ripple></mdl-switch> </mdl-list-item-secondary-action> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <style> mdl-radio, mdl-checkbox, mdl-switch { display: inline; } </style> <mdl-list> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> Bryan Cranston </mdl-list-item-primary-content> <mdl-list-item-secondary-action> <mdl-checkbox mdl-ripple></mdl-checkbox> </mdl-list-item-secondary-action> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> Aaron Paul </mdl-list-item-primary-content> <mdl-list-item-secondary-action> <mdl-radio ngModel="false" mdl-ripple></mdl-radio> </mdl-list-item-secondary-action> </mdl-list-item> <mdl-list-item> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> Bob Odenkirk </mdl-list-item-primary-content> <mdl-list-item-secondary-action> <mdl-switch mdl-ripple></mdl-switch> </mdl-list-item-secondary-action> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Two line</h5> <mdl-list> <mdl-list-item lines="2"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bryan Cranston</span> <mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <mdl-list-item-secondary-info>Actor</mdl-list-item-secondary-info> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="2"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Aaron Paul</span> <mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="2"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bob Odenkirk</span> <mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list> <mdl-list-item lines="2"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bryan Cranston</span> <mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <mdl-list-item-secondary-info>Actor</mdl-list-item-secondary-info> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="2"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Aaron Paul</span> <mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="2"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bob Odenkirk</span> <mdl-list-item-sub-title>62 Episodes</mdl-list-item-sub-title> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> </mdl-list> ]]> </pre> <h5>Three line</h5> <mdl-list style="width:650px"> <mdl-list-item lines="3"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bryan Cranston</span> <mdl-list-item-text-body> Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle. </mdl-list-item-text-body> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="3"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Aaron Paul</span> <mdl-list-item-text-body> Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie. </mdl-list-item-text-body> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="3"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bob Odenkirk</span> <mdl-list-item-text-body> Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul". </mdl-list-item-text-body> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> </mdl-list> <pre prism> <![CDATA[ <mdl-list style="width:650px"> <mdl-list-item lines="3"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bryan Cranston</span> <mdl-list-item-text-body> Bryan Cranston played the role of Walter in Breaking Bad. He is also known for playing Hal in Malcom in the Middle. </mdl-list-item-text-body> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="3"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Aaron Paul</span> <mdl-list-item-text-body> Aaron Paul played the role of Jesse in Breaking Bad. He also featured in the "Need For Speed" Movie. </mdl-list-item-text-body> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> <mdl-list-item lines="3"> <mdl-list-item-primary-content> <mdl-icon mdl-list-item-avatar>person</mdl-icon> <span>Bob Odenkirk</span> <mdl-list-item-text-body> Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the character, Bob stars in his own show now, called "Better Call Saul". </mdl-list-item-text-body> </mdl-list-item-primary-content> <mdl-list-item-secondary-content> <a href="#"><mdl-icon>star</mdl-icon></a> </mdl-list-item-secondary-content> </mdl-list-item> </mdl-list> ]]> </pre> <h5> List components</h5> <table class="docu" mdl-shadow="2"> <thead> <tr> <th>Component</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>mdl-list</td> <td> Basic container for any <i>mdl-list</i> component. </td> </tr> <tr> <td>mdl-list-item</td> <td> Defines a item in the list. The attribute <i>lines</i> will be used to specify of how many individual lines a list item consist. You can use <i>1</i>, <i>2</i> and <i>3</i>. <i>1</i> is the default value. </td> </tr> <tr> <td>mdl-list-item-primary-content</td> <td> Defines the primary content sub-division. </td> </tr> <tr> <td>mdl-list-item-secondary-action</td> <td> Defines the Action sub-division. Needs a 2 or 3 line list-item. </td> </tr> <tr> <td>mdl-list-item-secondary-content</td> <td> Defines the secondary content sub-division. Needs a 2 or 3 line list-item. </td> </tr> <tr> <td>mdl-list-item-secondary-info</td> <td> Defines the information sub-division. Needs a 2 or 3 line list-item. </td> </tr> <tr> <td>mdl-list-item-sub-title</td> <td> Defines the sub title in the <i>mdl-list-item-primary-content</i> component. </td> </tr> <tr> <td>mdl-list-item-text-body</td> <td> Defines the text-section in the <i>mdl-list-item-primary-content</i> component. </td> </tr> </tbody> </table> <h5>Additional attributes for mdl-icon</h5> <p>These attributes can be used to style <i>mdl-icons</i> in lists</p> <table class="docu" mdl-shadow="2"> <thead> <tr> <th>Attribute</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td>mdl-list-item-avatar></td> <td> avatar icon. </td> </tr> <tr> <td>mdl-list-item-icon</td> <td> Small icon. </td> </tr> <tr> <td>mdl-ripple</td> <td>Add <i>mdl-ripple</i> to the <i>mdl-list-item</i> component to create a ripple effect.</td> </tr> </tbody> </table>
c1rno/angelhack_frontend_prototype
src/demo-app/app/list/list.component.html
HTML
mit
14,091
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RS.TimeLogger { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string LastUser { get { return ((string)(this["LastUser"])); } set { this["LastUser"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("00000000-0000-0000-0000-000000000000")] public global::System.Guid LastActivity { get { return ((global::System.Guid)(this["LastActivity"])); } set { this["LastActivity"] = value; } } } }
RomanianSoftware/Tools
RS.TimeLogger/RS.TimeLogger/Settings.Designer.cs
C#
mit
1,971
module Softlayer module User class Customer module Access autoload :Authentication, 'softlayer/user/customer/access/authentication' end end end end
zertico/softlayer
lib/softlayer/user/customer/access.rb
Ruby
mit
180
(function (global, factory) { if (typeof define === 'function' && define.amd) { define(['exports', 'module', 'skatejs'], factory); } else if (typeof exports !== 'undefined' && typeof module !== 'undefined') { factory(exports, module, require('skatejs')); } else { var mod = { exports: {} }; factory(mod.exports, mod, global.skate); global.skate = mod.exports; } })(this, function (exports, module, _skatejs) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _skate = _interopRequireDefault(_skatejs); var auiSkate = _skate['default'].noConflict(); module.exports = auiSkate; }); //# sourceMappingURL=../../../js/aui/internal/skate.js.map
parambirs/aui-demos
node_modules/@atlassian/aui/lib/js/aui/internal/skate.js
JavaScript
mit
757
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIButton : MonoBehaviour { [SerializeField] private GameObject targetObject; [SerializeField] private string targetMessage; public Color highlightColor = Color.cyan; public void OnMouseOver() { SpriteRenderer sprite = GetComponent<SpriteRenderer>(); if (sprite != null) { sprite.color = highlightColor; } } public void OnMouseExit() { SpriteRenderer sprite = GetComponent<SpriteRenderer>(); if (sprite != null) { sprite.color = Color.white; } } public void OnMouseDown() { transform.localScale *= 1.1f; } public void OnMouseUp() { transform.localScale = Vector3.one; if (targetObject != null) { targetObject.SendMessage(targetMessage); } } }
ivanarellano/unity-in-action-book
Ch05/Assets/UIButton.cs
C#
mit
904
<footer class="main-footer"> <div class="pull-right hidden-xs"> </div> <strong>Orange TV.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 2.2.3 --> <script src="assets/plugins/jQuery/jquery-2.2.3.min.js"></script> <!-- jQuery UI 1.11.4 --> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip --> <script> $.widget.bridge('uibutton', $.ui.button); </script> <!-- DataTables --> <script src="assets/plugins/datatables/jquery.dataTables.min.js"></script> <script src="assets/plugins/datatables/dataTables.bootstrap.min.js"></script> <!--<script src="assets/plugins/ckeditor/adapters/jquery.js"></script>--> <!-- Bootstrap 3.3.6 --> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <!-- <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> --> <!-- Morris.js charts --> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="assets/plugins/morris/morris.min.js"></script> --> <!-- Sparkline --> <script src="assets/plugins/sparkline/jquery.sparkline.min.js"></script> <!-- jvectormap --> <script src="assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script> <script src="assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script> <!-- jQuery Knob Chart --> <script src="assets/plugins/knob/jquery.knob.js"></script> <!-- daterangepicker --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.min.js"></script> <script src="assets/plugins/daterangepicker/daterangepicker.js"></script> <!-- datepicker --> <script src="assets/plugins/datepicker/bootstrap-datepicker.js"></script> <!-- Bootstrap WYSIHTML5 --> <script src="assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script> <!-- Slimscroll --> <script src="assets/plugins/slimScroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="assets/plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="assets/dist/js/app.min.js"></script> <!-- AdminLTE dashboard demo (This is only for demo purposes) --> <!--<script src="assets/dist/js/pages/dashboard.js"></script>--> <!-- AdminLTE for demo purposes --> <script src="assets/dist/js/demo.js"></script> <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.flash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script> <!-- <script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script> <script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script> --> <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script> <script src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.print.min.js"></script> <script src="assets/dist/js/custom.js"></script> <script> $(function () { /* var table = $('#example').DataTable( { dom: 'Bfrtip', buttons: [ 'copy', 'csv', 'excel', 'pdf', 'print' ] } ); table.buttons().container() .appendTo( $('div.eight.column:eq(0)', table.table().container()) ); $('#example2').DataTable( { buttons: [ { extend: 'excel', text: 'Save current page', exportOptions: { modifier: { page: 'current' } } } ] } ); */ $('#example').DataTable( { dom: 'Bfrtip', pageLength: 5, //dom : 'Bflit', buttons: ['copy', 'csv', 'excel', 'pdf', 'print'], responsive: true } ); $("#example1").DataTable(); $("#example2").DataTable({ "paging": false }); $('#example3').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); $('#example30').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); }); // datatable paging $(function() { table = $('#example2c').DataTable({ "processing": true, //Feature control the processing indicator. "serverSide": true, //Feature control DataTables' server-side processing mode. "order": [], //Initial no order. // Load data for the table's content from an Ajax source "ajax": { "url": "<?php if(isset($url)) {echo $url; } ?>", "type": "POST" }, //Set column definition initialisation properties. "columnDefs": [ { "targets": [ 0 ], //first column / numbering column "orderable": false, //set not orderable }, ], }); }); </script> </body> </html>
ariefstd/cdone_server_new
application/views/footer.php
PHP
mit
5,358
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Neo.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Strings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Strings() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Neo.Properties.Strings", typeof(Strings).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to About. /// </summary> internal static string About { get { return ResourceManager.GetString("About", resourceCulture); } } /// <summary> /// Looks up a localized string similar to AntShares. /// </summary> internal static string AboutMessage { get { return ResourceManager.GetString("AboutMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version:. /// </summary> internal static string AboutVersion { get { return ResourceManager.GetString("AboutVersion", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed to add smart contract, corresponding private key missing in this wallet.. /// </summary> internal static string AddContractFailedMessage { get { return ResourceManager.GetString("AddContractFailedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Address. /// </summary> internal static string Address { get { return ResourceManager.GetString("Address", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Change password successful.. /// </summary> internal static string ChangePasswordSuccessful { get { return ResourceManager.GetString("ChangePasswordSuccessful", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Confirmation. /// </summary> internal static string DeleteAddressConfirmationCaption { get { return ResourceManager.GetString("DeleteAddressConfirmationCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Upon deletion, assets in these addresses will be permanently lost, are you sure to proceed?. /// </summary> internal static string DeleteAddressConfirmationMessage { get { return ResourceManager.GetString("DeleteAddressConfirmationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Assets cannot be recovered once deleted, are you sure to delete the assets?. /// </summary> internal static string DeleteAssetConfirmationMessage { get { return ResourceManager.GetString("DeleteAssetConfirmationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Confirmation. /// </summary> internal static string DeleteConfirmation { get { return ResourceManager.GetString("DeleteConfirmation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Enter remark here, which will be recorded on the blockchain. /// </summary> internal static string EnterRemarkMessage { get { return ResourceManager.GetString("EnterRemarkMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction Remark. /// </summary> internal static string EnterRemarkTitle { get { return ResourceManager.GetString("EnterRemarkTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Execution terminated in fault state.. /// </summary> internal static string ExecutionFailed { get { return ResourceManager.GetString("ExecutionFailed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Expired. /// </summary> internal static string ExpiredCertificate { get { return ResourceManager.GetString("ExpiredCertificate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Failed. /// </summary> internal static string Failed { get { return ResourceManager.GetString("Failed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Import Watch-Only Address. /// </summary> internal static string ImportWatchOnlyAddress { get { return ResourceManager.GetString("ImportWatchOnlyAddress", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction initiated, but the signature is incomplete.. /// </summary> internal static string IncompletedSignatureMessage { get { return ResourceManager.GetString("IncompletedSignatureMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Incomplete signature. /// </summary> internal static string IncompletedSignatureTitle { get { return ResourceManager.GetString("IncompletedSignatureTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You have cancelled the certificate installation.. /// </summary> internal static string InstallCertificateCancel { get { return ResourceManager.GetString("InstallCertificateCancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Install the certificate. /// </summary> internal static string InstallCertificateCaption { get { return ResourceManager.GetString("InstallCertificateCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Anthares must install Onchain root certificate to validate assets on the blockchain, install it now?. /// </summary> internal static string InstallCertificateText { get { return ResourceManager.GetString("InstallCertificateText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Insufficient funds, transaction cannot be initiated.. /// </summary> internal static string InsufficientFunds { get { return ResourceManager.GetString("InsufficientFunds", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invalid. /// </summary> internal static string InvalidCertificate { get { return ResourceManager.GetString("InvalidCertificate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Migrate Wallet. /// </summary> internal static string MigrateWalletCaption { get { return ResourceManager.GetString("MigrateWalletCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Opening wallet files in older versions, update to newest format? ///Note: updated files cannot be openned by clients in older versions!. /// </summary> internal static string MigrateWalletMessage { get { return ResourceManager.GetString("MigrateWalletMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Wallet file relocated. New wallet file has been saved at: . /// </summary> internal static string MigrateWalletSucceedMessage { get { return ResourceManager.GetString("MigrateWalletSucceedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Password Incorrect. /// </summary> internal static string PasswordIncorrect { get { return ResourceManager.GetString("PasswordIncorrect", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Data broadcast success, the hash is shown as follows:. /// </summary> internal static string RelaySuccessText { get { return ResourceManager.GetString("RelaySuccessText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Broadcast Success. /// </summary> internal static string RelaySuccessTitle { get { return ResourceManager.GetString("RelaySuccessTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Raw:. /// </summary> internal static string RelayTitle { get { return ResourceManager.GetString("RelayTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction sent, TXID:. /// </summary> internal static string SendTxSucceedMessage { get { return ResourceManager.GetString("SendTxSucceedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction successful. /// </summary> internal static string SendTxSucceedTitle { get { return ResourceManager.GetString("SendTxSucceedTitle", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The private key that can sign the data is not found.. /// </summary> internal static string SigningFailedKeyNotFoundMessage { get { return ResourceManager.GetString("SigningFailedKeyNotFoundMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to You must input JSON object pending signature data.. /// </summary> internal static string SigningFailedNoDataMessage { get { return ResourceManager.GetString("SigningFailedNoDataMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to System. /// </summary> internal static string SystemIssuer { get { return ResourceManager.GetString("SystemIssuer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Validation failed, the counterparty falsified the transaction content!. /// </summary> internal static string TradeFailedFakeDataMessage { get { return ResourceManager.GetString("TradeFailedFakeDataMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Validation failed, the counterparty generated illegal transaction content!. /// </summary> internal static string TradeFailedInvalidDataMessage { get { return ResourceManager.GetString("TradeFailedInvalidDataMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Validation failed, invalid transaction or unsynchronized blockchain, please try again when synchronized!. /// </summary> internal static string TradeFailedNoSyncMessage { get { return ResourceManager.GetString("TradeFailedNoSyncMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Need Signature. /// </summary> internal static string TradeNeedSignatureCaption { get { return ResourceManager.GetString("TradeNeedSignatureCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction generated, please send the following information to the counterparty for signing:. /// </summary> internal static string TradeNeedSignatureMessage { get { return ResourceManager.GetString("TradeNeedSignatureMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Trade Request. /// </summary> internal static string TradeRequestCreatedCaption { get { return ResourceManager.GetString("TradeRequestCreatedCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction request generated, please send it to the counterparty or merge it with the counterparty&apos;s request.. /// </summary> internal static string TradeRequestCreatedMessage { get { return ResourceManager.GetString("TradeRequestCreatedMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Trade Success. /// </summary> internal static string TradeSuccessCaption { get { return ResourceManager.GetString("TradeSuccessCaption", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction sent, this is the TXID:. /// </summary> internal static string TradeSuccessMessage { get { return ResourceManager.GetString("TradeSuccessMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to unconfirmed. /// </summary> internal static string Unconfirmed { get { return ResourceManager.GetString("Unconfirmed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to unknown issuer. /// </summary> internal static string UnknownIssuer { get { return ResourceManager.GetString("UnknownIssuer", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Blockchain unsynchronized, transaction cannot be sent.. /// </summary> internal static string UnsynchronizedBlock { get { return ResourceManager.GetString("UnsynchronizedBlock", resourceCulture); } } } }
AntShares/AntSharesCore
neo-gui/Properties/Strings.Designer.cs
C#
mit
18,152
# Velocity Library last modified: 5/1/2019 9:00 AM. A reusable library in Velocity for Cascade with examples. This is the code base the Upstate team use to implement our Brisk site. The other part of the Upstate library: https://github.com/drulykg/Cascade-CMS/tree/master/_brisk A note about filenames. All files whose filenames with a "chanw-" prefix contain code reusable by anyone. Those with the "upstate-" prefix contain business logic specific to Upstate. <ul> <li> <a href="http://www.upstate.edu/formats/velocity/courses/index.php">Velocity Tutorial</a></li> <li><a href="https://www.youtube.com/playlist?list=PL5FL7lAbKiG-AYX35qK8y0FN7RgJl9ISD">Velocity and More</a> recordings</li> <li><a href="https://www.youtube.com/playlist?list=PLiPcpR6GRx5dN3Z5-tAAMLgFX59Njkv6f">One Template, One Region, and Lots of Velocity Tricks</a></li> <li><a href="http://www.upstate.edu/formats/velocity/api-documentation/index.php">API Documentation</a></li> </ul>
wingmingchan/velocity
README.md
Markdown
mit
961
using Newtonsoft.Json; using System.Collections.Generic; namespace EaToGliffy.Gliffy.Model { public class GliffyParentObject : GliffyObject { [JsonProperty(PropertyName = "children")] public List<GliffyObject> Children { get; set; } } }
vzoran/eatogliffy
eatogliffy/gliffy/model/GliffyParentObject.cs
C#
mit
269
// Copyright (c) 2011-2015 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "JsonOutputStreamSerializer.h" #include <cassert> #include <stdexcept> #include "Common/StringTools.h" using Common::JsonValue; using namespace CryptoNote; namespace CryptoNote { std::ostream& operator<<(std::ostream& out, const JsonOutputStreamSerializer& enumerator) { out << enumerator.root; return out; } } namespace { template <typename T> void insertOrPush(JsonValue& js, Common::StringView name, const T& value) { if (js.isArray()) { js.pushBack(JsonValue(value)); } else { js.insert(std::string(name), JsonValue(value)); } } } JsonOutputStreamSerializer::JsonOutputStreamSerializer() : root(JsonValue::OBJECT) { chain.push_back(&root); } JsonOutputStreamSerializer::~JsonOutputStreamSerializer() { } ISerializer::SerializerType JsonOutputStreamSerializer::type() const { return ISerializer::OUTPUT; } bool JsonOutputStreamSerializer::beginObject(Common::StringView name) { JsonValue& parent = *chain.back(); JsonValue obj(JsonValue::OBJECT); if (parent.isObject()) { chain.push_back(&parent.insert(std::string(name), obj)); } else { chain.push_back(&parent.pushBack(obj)); } return true; } void JsonOutputStreamSerializer::endObject() { assert(!chain.empty()); chain.pop_back(); } bool JsonOutputStreamSerializer::beginArray(size_t& size, Common::StringView name) { JsonValue val(JsonValue::ARRAY); JsonValue& res = chain.back()->insert(std::string(name), val); chain.push_back(&res); return true; } void JsonOutputStreamSerializer::endArray() { assert(!chain.empty()); chain.pop_back(); } bool JsonOutputStreamSerializer::operator()(uint64_t& value, Common::StringView name) { int64_t v = static_cast<int64_t>(value); return operator()(v, name); } bool JsonOutputStreamSerializer::operator()(uint16_t& value, Common::StringView name) { uint64_t v = static_cast<uint64_t>(value); return operator()(v, name); } bool JsonOutputStreamSerializer::operator()(int16_t& value, Common::StringView name) { int64_t v = static_cast<int64_t>(value); return operator()(v, name); } bool JsonOutputStreamSerializer::operator()(uint32_t& value, Common::StringView name) { uint64_t v = static_cast<uint64_t>(value); return operator()(v, name); } bool JsonOutputStreamSerializer::operator()(int32_t& value, Common::StringView name) { int64_t v = static_cast<int64_t>(value); return operator()(v, name); } bool JsonOutputStreamSerializer::operator()(int64_t& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool JsonOutputStreamSerializer::operator()(double& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool JsonOutputStreamSerializer::operator()(std::string& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool JsonOutputStreamSerializer::operator()(uint8_t& value, Common::StringView name) { insertOrPush(*chain.back(), name, static_cast<int64_t>(value)); return true; } bool JsonOutputStreamSerializer::operator()(bool& value, Common::StringView name) { insertOrPush(*chain.back(), name, value); return true; } bool JsonOutputStreamSerializer::binary(void* value, size_t size, Common::StringView name) { std::string hex = Common::toHex(value, size); return (*this)(hex, name); } bool JsonOutputStreamSerializer::binary(std::string& value, Common::StringView name) { return binary(const_cast<char*>(value.data()), value.size(), name); }
tobeyrowe/StarKingdomCoin
src/Serialization/JsonOutputStreamSerializer.cpp
C++
mit
3,698
# Be sure to restart your server when you modify this file. Refinery::Application.config.session_store :cookie_store, :key => '_skwarcan_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") # Refinery::Application.config.session_store :active_record_store
mskwarcan/skwarcan
config/initializers/session_store.rb
Ruby
mit
409
/* * author: Lisa * Info: Base64 / UTF8 * 编码 & 解码 */ function base64Encode(input) { var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv" + "wxyz0123456789+/" + "="; var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input[i++]; chr2 = input[i++]; chr3 = input[i++]; enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function base64Decode(input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; var base64test = /[^A-Za-z0-9/+///=]/g; if (base64test.exec(input)) { alert("There were invalid base64 characters in the input text./n" + "Valid base64 characters are A-Z, a-z, 0-9, '+', '/', and '='/n" + "Expect errors in decoding."); } input = input.replace(/[^A-Za-z0-9/+///=]/g, ""); output=new Array(); do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output.push(chr1); if (enc3 != 64) { output.push(chr2); } if (enc4 != 64) { output.push(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while (i < input.length); return output; } function UTF8Encode(str){ var temp = "",rs = ""; for( var i=0 , len = str.length; i < len; i++ ){ temp = str.charCodeAt(i).toString(16); rs += "\\u"+ new Array(5-temp.length).join("0") + temp; } return rs; } function UTF8Decode(str){ return str.replace(/(\\u)(\w{4}|\w{2})/gi, function($0,$1,$2){ return String.fromCharCode(parseInt($2,16)); }); } exports.base64Encode = base64Encode; exports.base64Decode = base64Decode; exports.UTF8Encode = UTF8Encode; exports.UTF8Decode = UTF8Decode;
jrcjing/cbg-log
lib/Tool/base64.js
JavaScript
mit
2,332
<?php namespace ShinyDeploy\Domain\Database; use ShinyDeploy\Core\Crypto\PasswordCrypto; use ShinyDeploy\Core\Helper\StringHelper; use ShinyDeploy\Exceptions\DatabaseException; use ShinyDeploy\Exceptions\MissingDataException; use ShinyDeploy\Traits\CryptableDomain; class ApiKeys extends DatabaseDomain { use CryptableDomain; /** * Generates new API key and stores it to database. * * @param int $deploymentId * @throws DatabaseException * @throws MissingDataException * @throws \ShinyDeploy\Exceptions\CryptographyException * @return array */ public function addApiKey(int $deploymentId): array { if (empty($this->encryptionKey)) { throw new MissingDataException('Encryption key not set.'); } if (empty($deploymentId)) { throw new MissingDataException('Deployment id can not be empty.'); } $apiKey = StringHelper::getRandomString(20); $passwordForUrl = StringHelper::getRandomString(16); $password = $passwordForUrl . $this->config->get('auth.secret'); $passwordHash = hash('sha256', $password); $encryption = new PasswordCrypto(); $encryptionKeySave = $encryption->encrypt($this->encryptionKey, $password); $statement = "INSERT INTO api_keys (`api_key`,`deployment_id`,`password`,`encryption_key`)" . " VALUES (%s,%i,%s,%s)"; $result = $this->db->prepare($statement, $apiKey, $deploymentId, $passwordHash, $encryptionKeySave)->execute(); if ($result === false) { throw new DatabaseException('Could not store API key to database.'); } return [ 'apiKey' => $apiKey, 'apiPassword' => $passwordForUrl ]; } /** * Deletes all existing API keys for specified deployment. * * @param int $deploymentId * @throws MissingDataException * @return bool */ public function deleteApiKeysByDeploymentId(int $deploymentId): bool { if (empty($deploymentId)) { throw new MissingDataException('Deployment id can not be empty.'); } try { $statement = "DELETE FROM api_keys WHERE `deployment_id` = %i"; return $this->db->prepare($statement, $deploymentId)->execute(); } catch (DatabaseException $e) { return false; } } /** * Fetches API key data by api-key. * * @param string $apiKey * @return array * @throws MissingDataException * @throws DatabaseException */ public function getDataByApiKey(string $apiKey): array { if (empty($apiKey)) { throw new MissingDataException('API key can not be empty.'); } $statement = "SELECT * FROM api_keys WHERE `api_key` = %s"; return $this->db->prepare($statement, $apiKey)->getResult(); } }
nekudo/shiny_deploy
src/ShinyDeploy/Domain/Database/ApiKeys.php
PHP
mit
2,903
require File.dirname(__FILE__) + '/../spec_helper' describe "Standard Tags" do dataset :users_and_pages, :file_not_found, :snippets it '<r:page> should allow access to the current page' do page(:home) page.should render('<r:page:title />').as('Home') page.should render(%{<r:find url="/radius"><r:title /> | <r:page:title /></r:find>}).as('Radius | Home') end [:breadcrumb, :slug, :title, :url].each do |attr| it "<r:#{attr}> should render the '#{attr}' attribute" do value = page.send(attr) page.should render("<r:#{attr} />").as(value.to_s) end end it "<r:url> with a nil relative URL root should scope to the relative root of /" do ActionController::Base.relative_url_root = nil page(:home).should render("<r:url />").as("/") end it '<r:url> with a relative URL root should scope to the relative root' do page(:home).should render("<r:url />").with_relative_root("/foo").as("/foo/") end it '<r:parent> should change the local context to the parent page' do page(:parent) page.should render('<r:parent><r:title /></r:parent>').as(pages(:home).title) page.should render('<r:parent><r:children:each by="title"><r:title /></r:children:each></r:parent>').as(page_eachable_children(pages(:home)).collect(&:title).join("")) page.should render('<r:children:each><r:parent:title /></r:children:each>').as(@page.title * page.children.count) end it '<r:if_parent> should render the contained block if the current page has a parent page' do page.should render('<r:if_parent>true</r:if_parent>').as('true') page(:home).should render('<r:if_parent>true</r:if_parent>').as('') end it '<r:unless_parent> should render the contained block unless the current page has a parent page' do page.should render('<r:unless_parent>true</r:unless_parent>').as('') page(:home).should render('<r:unless_parent>true</r:unless_parent>').as('true') end it '<r:if_children> should render the contained block if the current page has child pages' do page(:home).should render('<r:if_children>true</r:if_children>').as('true') page(:childless).should render('<r:if_children>true</r:if_children>').as('') end it '<r:unless_children> should render the contained block if the current page has no child pages' do page(:home).should render('<r:unless_children>true</r:unless_children>').as('') page(:childless).should render('<r:unless_children>true</r:unless_children>').as('true') end describe "<r:children:each>" do it "should iterate through the children of the current page" do page(:parent) page.should render('<r:children:each><r:title /> </r:children:each>').as('Child Child 2 Child 3 ') page.should render('<r:children:each><r:page><r:slug />/<r:child:slug /> </r:page></r:children:each>').as('parent/child parent/child-2 parent/child-3 ') page(:assorted).should render(page_children_each_tags).as('a b c d e f g h i j ') end it 'should not list draft pages' do page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ') end it 'should include draft pages with status="all"' do page.should render('<r:children:each status="all" by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ') end it "should include draft pages by default on the dev host" do page.should render('<r:children:each by="slug"><r:slug /> </r:children:each>').as('a b c d draft e f g h i j ').on('dev.site.com') end it 'should not list draft pages on dev.site.com when Radiant::Config["dev.host"] is set to something else' do Radiant::Config['dev.host'] = 'preview.site.com' page.should render('<r:children:each by="title"><r:slug /> </r:children:each>').as('a b c d e f g h i j ').on('dev.site.com') end it 'should paginate results when "paginated" attribute is "true"' do page.pagination_parameters = {:page => 1, :per_page => 10} page.should render('<r:children:each paginated="true" per_page="10"><r:slug /> </r:children:each>').as('a b c d e f g h i j ') page.should render('<r:children:each paginated="true" per_page="2"><r:slug /> </r:children:each>').matching(/div class="pagination"/) end it 'should error with invalid "limit" attribute' do message = "`limit' attribute of `each' tag must be a positive number between 1 and 4 digits" page.should render(page_children_each_tags(%{limit="a"})).with_error(message) page.should render(page_children_each_tags(%{limit="-10"})).with_error(message) page.should render(page_children_each_tags(%{limit="50000"})).with_error(message) end it 'should error with invalid "offset" attribute' do message = "`offset' attribute of `each' tag must be a positive number between 1 and 4 digits" page.should render(page_children_each_tags(%{offset="a"})).with_error(message) page.should render(page_children_each_tags(%{offset="-10"})).with_error(message) page.should render(page_children_each_tags(%{offset="50000"})).with_error(message) end it 'should error with invalid "by" attribute' do message = "`by' attribute of `each' tag must be set to a valid field name" page.should render(page_children_each_tags(%{by="non-existant-field"})).with_error(message) end it 'should error with invalid "order" attribute' do message = %{`order' attribute of `each' tag must be set to either "asc" or "desc"} page.should render(page_children_each_tags(%{order="asdf"})).with_error(message) end it "should limit the number of children when given a 'limit' attribute" do page.should render(page_children_each_tags(%{limit="5"})).as('a b c d e ') end it "should limit and offset the children when given 'limit' and 'offset' attributes" do page.should render(page_children_each_tags(%{offset="3" limit="5"})).as('d e f g h ') end it "should change the sort order when given an 'order' attribute" do page.should render(page_children_each_tags(%{order="desc"})).as('j i h g f e d c b a ') end it "should sort by the 'by' attribute" do page.should render(page_children_each_tags(%{by="breadcrumb"})).as('f e d c b a j i h g ') end it "should sort by the 'by' attribute according to the 'order' attribute" do page.should render(page_children_each_tags(%{by="breadcrumb" order="desc"})).as('g h i j a b c d e f ') end describe 'with "status" attribute' do it "set to 'all' should list all children" do page.should render(page_children_each_tags(%{status="all"})).as("a b c d e f g h i j draft ") end it "set to 'draft' should list only children with 'draft' status" do page.should render(page_children_each_tags(%{status="draft"})).as('draft ') end it "set to 'published' should list only children with 'draft' status" do page.should render(page_children_each_tags(%{status="published"})).as('a b c d e f g h i j ') end it "set to an invalid status should render an error" do page.should render(page_children_each_tags(%{status="askdf"})).with_error("`status' attribute of `each' tag must be set to a valid status") end end end describe "<r:children:each:if_first>" do it "should render for the first child" do tags = '<r:children:each><r:if_first>FIRST:</r:if_first><r:slug /> </r:children:each>' expected = "FIRST:article article-2 article-3 article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:unless_first>" do it "should render for all but the first child" do tags = '<r:children:each><r:unless_first>NOT-FIRST:</r:unless_first><r:slug /> </r:children:each>' expected = "article NOT-FIRST:article-2 NOT-FIRST:article-3 NOT-FIRST:article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:if_last>" do it "should render for the last child" do tags = '<r:children:each><r:if_last>LAST:</r:if_last><r:slug /> </r:children:each>' expected = "article article-2 article-3 LAST:article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:unless_last>" do it "should render for all but the last child" do tags = '<r:children:each><r:unless_last>NOT-LAST:</r:unless_last><r:slug /> </r:children:each>' expected = "NOT-LAST:article NOT-LAST:article-2 NOT-LAST:article-3 article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:each:header>" do it "should render the header when it changes" do tags = '<r:children:each><r:header>[<r:date format="%b/%y" />] </r:header><r:slug /> </r:children:each>' expected = "[Dec/00] article [Feb/01] article-2 article-3 [Mar/01] article-4 " page(:news).should render(tags).as(expected) end it 'with "name" attribute should maintain a separate header' do tags = %{<r:children:each><r:header name="year">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>} expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 " page(:news).should render(tags).as(expected) end it 'with "restart" attribute set to one name should restart that header' do tags = %{<r:children:each><r:header name="year" restart="month">[<r:date format='%Y' />] </r:header><r:header name="month">(<r:date format="%b" />) </r:header><r:slug /> </r:children:each>} expected = "[2000] (Dec) article [2001] (Feb) article-2 article-3 (Mar) article-4 " page(:news).should render(tags).as(expected) end it 'with "restart" attribute set to two names should restart both headers' do tags = %{<r:children:each><r:header name="year" restart="month;day">[<r:date format='%Y' />] </r:header><r:header name="month" restart="day">(<r:date format="%b" />) </r:header><r:header name="day"><<r:date format='%d' />> </r:header><r:slug /> </r:children:each>} expected = "[2000] (Dec) <01> article [2001] (Feb) <09> article-2 <24> article-3 (Mar) <06> article-4 " page(:news).should render(tags).as(expected) end end describe "<r:children:count>" do it 'should render the number of children of the current page' do page(:parent).should render('<r:children:count />').as('3') end it "should accept the same scoping conditions as <r:children:each>" do page.should render('<r:children:count />').as('10') page.should render('<r:children:count status="all" />').as('11') page.should render('<r:children:count status="draft" />').as('1') page.should render('<r:children:count status="hidden" />').as('0') end end describe "<r:children:first>" do it 'should render its contents in the context of the first child page' do page(:parent).should render('<r:children:first:title />').as('Child') end it 'should accept the same scoping attributes as <r:children:each>' do page.should render(page_children_first_tags).as('a') page.should render(page_children_first_tags(%{limit="5"})).as('a') page.should render(page_children_first_tags(%{offset="3" limit="5"})).as('d') page.should render(page_children_first_tags(%{order="desc"})).as('j') page.should render(page_children_first_tags(%{by="breadcrumb"})).as('f') page.should render(page_children_first_tags(%{by="breadcrumb" order="desc"})).as('g') end it "should render nothing when no children exist" do page(:first).should render('<r:children:first:title />').as('') end end describe "<r:children:last>" do it 'should render its contents in the context of the last child page' do page(:parent).should render('<r:children:last:title />').as('Child 3') end it 'should accept the same scoping attributes as <r:children:each>' do page.should render(page_children_last_tags).as('j') page.should render(page_children_last_tags(%{limit="5"})).as('e') page.should render(page_children_last_tags(%{offset="3" limit="5"})).as('h') page.should render(page_children_last_tags(%{order="desc"})).as('a') page.should render(page_children_last_tags(%{by="breadcrumb"})).as('g') page.should render(page_children_last_tags(%{by="breadcrumb" order="desc"})).as('f') end it "should render nothing when no children exist" do page(:first).should render('<r:children:last:title />').as('') end end describe "<r:content>" do it "should render the 'body' part by default" do page.should render('<r:content />').as('Assorted body.') end it "with 'part' attribute should render the specified part" do page(:home).should render('<r:content part="extended" />').as("Just a test.") end it "should prevent simple recursion" do page(:recursive_parts).should render('<r:content />').with_error("Recursion error: already rendering the `body' part.") end it "should prevent deep recursion" do page(:recursive_parts).should render('<r:content part="one"/>').with_error("Recursion error: already rendering the `one' part.") page(:recursive_parts).should render('<r:content part="two"/>').with_error("Recursion error: already rendering the `two' part.") end it "should allow repetition" do page(:recursive_parts).should render('<r:content part="repeat"/>').as('xx') end it "should not prevent rendering a part more than once in sequence" do page(:home).should render('<r:content /><r:content />').as('Hello world!Hello world!') end describe "with inherit attribute" do it "missing or set to 'false' should render the current page's part" do page.should render('<r:content part="sidebar" />').as('') page.should render('<r:content part="sidebar" inherit="false" />').as('') end describe "set to 'true'" do it "should render an ancestor's part" do page.should render('<r:content part="sidebar" inherit="true" />').as('Assorted sidebar.') end it "should render nothing when no ancestor has the part" do page.should render('<r:content part="part_that_doesnt_exist" inherit="true" />').as('') end describe "and contextual attribute" do it "set to 'true' should render the part in the context of the current page" do page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Parent sidebar.') page(:child).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Child sidebar.') page(:grandchild).should render('<r:content part="sidebar" inherit="true" contextual="true" />').as('Grandchild sidebar.') end it "set to 'false' should render the part in the context of its containing page" do page(:parent).should render('<r:content part="sidebar" inherit="true" contextual="false" />').as('Home sidebar.') end it "should maintain the global page" do page(:first) page.should render('<r:content part="titles" inherit="true" contextual="true"/>').as('First First') page.should render('<r:content part="titles" inherit="true" contextual="false"/>').as('Home First') end end end it "set to an erroneous value should render an error" do page.should render('<r:content part="sidebar" inherit="weird value" />').with_error(%{`inherit' attribute of `content' tag must be set to either "true" or "false"}) end it "should render parts with respect to the current contextual page" do expected = "Child body. Child 2 body. Child 3 body. " page(:parent).should render('<r:children:each><r:content /> </r:children:each>').as(expected) end end end describe "<r:if_content>" do it "without 'part' attribute should render the contained block if the 'body' part exists" do page.should render('<r:if_content>true</r:if_content>').as('true') end it "should render the contained block if the specified part exists" do page.should render('<r:if_content part="body">true</r:if_content>').as('true') end it "should not render the contained block if the specified part does not exist" do page.should render('<r:if_content part="asdf">true</r:if_content>').as('') end describe "with more than one part given (separated by comma)" do it "should render the contained block only if all specified parts exist" do page(:home).should render('<r:if_content part="body, extended">true</r:if_content>').as('true') end it "should not render the contained block if at least one of the specified parts does not exist" do page(:home).should render('<r:if_content part="body, madeup">true</r:if_content>').as('') end describe "with inherit attribute set to 'true'" do it 'should render the contained block if the current or ancestor pages have the specified parts' do page(:guests).should render('<r:if_content part="favors, extended" inherit="true">true</r:if_content>').as('true') end it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do page(:guests).should render('<r:if_content part="favors, madeup" inherit="true">true</r:if_content>').as('') end describe "with find attribute set to 'any'" do it 'should render the contained block if the current or ancestor pages have any of the specified parts' do page(:guests).should render('<r:if_content part="favors, madeup" inherit="true" find="any">true</r:if_content>').as('true') end it 'should still render the contained block if first of the specified parts has not been found' do page(:guests).should render('<r:if_content part="madeup, favors" inherit="true" find="any">true</r:if_content>').as('true') end end end describe "with inherit attribute set to 'false'" do it 'should render the contained block if the current page has the specified parts' do page(:guests).should render('<r:if_content part="favors, games" inherit="false">true</r:if_content>').as('') end it 'should not render the contained block if the current or ancestor pages do not have all of the specified parts' do page(:guests).should render('<r:if_content part="favors, madeup" inherit="false">true</r:if_content>').as('') end end describe "with the 'find' attribute set to 'any'" do it "should render the contained block if any of the specified parts exist" do page.should render('<r:if_content part="body, asdf" find="any">true</r:if_content>').as('true') end end describe "with the 'find' attribute set to 'all'" do it "should render the contained block if all of the specified parts exist" do page(:home).should render('<r:if_content part="body, sidebar" find="all">true</r:if_content>').as('true') end it "should not render the contained block if all of the specified parts do not exist" do page.should render('<r:if_content part="asdf, madeup" find="all">true</r:if_content>').as('') end end end end describe "<r:unless_content>" do describe "with inherit attribute set to 'true'" do it 'should not render the contained block if the current or ancestor pages have the specified parts' do page(:guests).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('') end it 'should render the contained block if the current or ancestor pages do not have the specified parts' do page(:guests).should render('<r:unless_content part="madeup, imaginary" inherit="true">true</r:unless_content>').as('true') end it "should not render the contained block if the specified part does not exist but does exist on an ancestor" do page.should render('<r:unless_content part="sidebar" inherit="true">false</r:unless_content>').as('') end describe "with find attribute set to 'any'" do it 'should not render the contained block if the current or ancestor pages have any of the specified parts' do page(:guests).should render('<r:unless_content part="favors, madeup" inherit="true" find="any">true</r:unless_content>').as('') end it 'should still not render the contained block if first of the specified parts has not been found' do page(:guests).should render('<r:unless_content part="madeup, favors" inherit="true" find="any">true</r:unless_content>').as('') end end end it "without 'part' attribute should not render the contained block if the 'body' part exists" do page.should render('<r:unless_content>false</r:unless_content>').as('') end it "should not render the contained block if the specified part exists" do page.should render('<r:unless_content part="body">false</r:unless_content>').as('') end it "should render the contained block if the specified part does not exist" do page.should render('<r:unless_content part="asdf">false</r:unless_content>').as('false') end it "should render the contained block if the specified part does not exist but does exist on an ancestor" do page.should render('<r:unless_content part="sidebar">false</r:unless_content>').as('false') end describe "with more than one part given (separated by comma)" do it "should not render the contained block if all of the specified parts exist" do page(:home).should render('<r:unless_content part="body, extended">true</r:unless_content>').as('') end it "should render the contained block if at least one of the specified parts exists" do page(:home).should render('<r:unless_content part="body, madeup">true</r:unless_content>').as('true') end describe "with the 'inherit' attribute set to 'true'" do it "should render the contained block if the current or ancestor pages have none of the specified parts" do page.should render('<r:unless_content part="imaginary, madeup" inherit="true">true</r:unless_content>').as('true') end it "should not render the contained block if all of the specified parts are present on the current or ancestor pages" do page(:party).should render('<r:unless_content part="favors, extended" inherit="true">true</r:unless_content>').as('') end end describe "with the 'find' attribute set to 'all'" do it "should not render the contained block if all of the specified parts exist" do page(:home).should render('<r:unless_content part="body, sidebar" find="all">true</r:unless_content>').as('') end it "should render the contained block unless all of the specified parts exist" do page.should render('<r:unless_content part="body, madeup" find="all">true</r:unless_content>').as('true') end end describe "with the 'find' attribute set to 'any'" do it "should not render the contained block if any of the specified parts exist" do page.should render('<r:unless_content part="body, madeup" find="any">true</r:unless_content>').as('') end end end end describe "<r:author>" do it "should render the author of the current page" do page.should render('<r:author />').as('Admin') end it "should render nothing when the page has no author" do page(:no_user).should render('<r:author />').as('') end end describe "<r:gravatar>" do it "should render the Gravatar URL of author of the current page" do page.should render('<r:gravatar />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32') end it "should render the Gravatar URL of the name user" do page.should render('<r:gravatar name="Admin" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=G&size=32') end it "should render the default avatar when the user has not set an email address" do page.should render('<r:gravatar name="Designer" />').as('http://testhost.tld/images/admin/avatar_32x32.png') end it "should render the specified size" do page.should render('<r:gravatar name="Designer" size="96px" />').as('http://testhost.tld/images/admin/avatar_96x96.png') end it "should render the specified rating" do page.should render('<r:gravatar rating="X" />').as('http://www.gravatar.com/avatar.php?gravatar_id=e64c7d89f26bd1972efa854d13d7dd61&rating=X&size=32') end end describe "<r:date>" do before :each do page(:dated) end it "should render the published date of the page" do page.should render('<r:date />').as('Wednesday, January 11, 2006') end it "should format the published date according to the 'format' attribute" do page.should render('<r:date format="%d %b %Y" />').as('11 Jan 2006') end describe "with 'for' attribute" do it "set to 'now' should render the current date in the current Time.zone" do page.should render('<r:date for="now" />').as(Time.zone.now.strftime("%A, %B %d, %Y")) end it "set to 'created_at' should render the creation date" do page.should render('<r:date for="created_at" />').as('Tuesday, January 10, 2006') end it "set to 'updated_at' should render the update date" do page.should render('<r:date for="updated_at" />').as('Thursday, January 12, 2006') end it "set to 'published_at' should render the publish date" do page.should render('<r:date for="published_at" />').as('Wednesday, January 11, 2006') end it "set to an invalid attribute should render an error" do page.should render('<r:date for="blah" />').with_error("Invalid value for 'for' attribute.") end end it "should use the currently set timezone" do Time.zone = "Tokyo" format = "%H:%m" expected = page.published_at.in_time_zone(ActiveSupport::TimeZone['Tokyo']).strftime(format) page.should render(%Q(<r:date format="#{format}" />) ).as(expected) end end describe "<r:link>" do it "should render a link to the current page" do page.should render('<r:link />').as('<a href="/assorted/">Assorted</a>') end it "should render its contents as the text of the link" do page.should render('<r:link>Test</r:link>').as('<a href="/assorted/">Test</a>') end it "should pass HTML attributes to the <a> tag" do expected = '<a href="/assorted/" class="test" id="assorted">Assorted</a>' page.should render('<r:link class="test" id="assorted" />').as(expected) end it "should add the anchor attribute to the link as a URL anchor" do page.should render('<r:link anchor="test">Test</r:link>').as('<a href="/assorted/#test">Test</a>') end it "should render a link for the current contextual page" do expected = %{<a href="/parent/child/">Child</a> <a href="/parent/child-2/">Child 2</a> <a href="/parent/child-3/">Child 3</a> } page(:parent).should render('<r:children:each><r:link /> </r:children:each>' ).as(expected) end it "should scope the link within the relative URL root" do page(:assorted).should render('<r:link />').with_relative_root('/foo').as('<a href="/foo/assorted/">Assorted</a>') end end describe "<r:snippet>" do it "should render the contents of the specified snippet" do page.should render('<r:snippet name="first" />').as('test') end it "should render an error when the snippet does not exist" do page.should render('<r:snippet name="non-existant" />').with_error('snippet not found') end it "should render an error when not given a 'name' attribute" do page.should render('<r:snippet />').with_error("`snippet' tag must contain `name' attribute") end it "should filter the snippet with its assigned filter" do page.should render('<r:page><r:snippet name="markdown" /></r:page>').matching(%r{<p><strong>markdown</strong></p>}) end it "should maintain the global page inside the snippet" do page(:parent).should render('<r:snippet name="global_page_cascade" />').as("#{@page.title} " * @page.children.count) end it "should maintain the global page when the snippet renders recursively" do page(:child).should render('<r:snippet name="recursive" />').as("Great GrandchildGrandchildChild") end it "should render the specified snippet when called as an empty double-tag" do page.should render('<r:snippet name="first"></r:snippet>').as('test') end it "should capture contents of a double tag, substituting for <r:yield/> in snippet" do page.should render('<r:snippet name="yielding">inner</r:snippet>'). as('Before...inner...and after') end it "should do nothing with contents of double tag when snippet doesn't yield" do page.should render('<r:snippet name="first">content disappears!</r:snippet>'). as('test') end it "should render nested yielding snippets" do page.should render('<r:snippet name="div_wrap"><r:snippet name="yielding">Hello, World!</r:snippet></r:snippet>'). as('<div>Before...Hello, World!...and after</div>') end it "should render double-tag snippets called from within a snippet" do page.should render('<r:snippet name="nested_yields">the content</r:snippet>'). as('<snippet name="div_wrap">above the content below</snippet>') end it "should render contents each time yield is called" do page.should render('<r:snippet name="yielding_often">French</r:snippet>'). as('French is Frencher than French') end end it "should do nothing when called from page body" do page.should render('<r:yield/>').as("") end it '<r:random> should render a randomly selected contained <r:option>' do page.should render("<r:random> <r:option>1</r:option> <r:option>2</r:option> <r:option>3</r:option> </r:random>").matching(/^(1|2|3)$/) end it '<r:random> should render a randomly selected, dynamically set <r:option>' do page(:parent).should render("<r:random:children:each:option:title />").matching(/^(Child|Child\ 2|Child\ 3)$/) end it '<r:comment> should render nothing it contains' do page.should render('just a <r:comment>small </r:comment>test').as('just a test') end describe "<r:navigation>" do it "should render the nested <r:normal> tag by default" do tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/"> <r:normal><r:title /></r:normal> </r:navigation>} expected = %{Home Assorted Parent} page.should render(tags).as(expected) end it "should render the nested <r:selected> tag for URLs that match the current page" do tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/ | Radius: /radius/"> <r:normal><r:title /></r:normal> <r:selected><strong><r:title/></strong></r:selected> </r:navigation>} expected = %{<strong>Home</strong> Assorted <strong>Parent</strong> Radius} page(:parent).should render(tags).as(expected) end it "should render the nested <r:here> tag for URLs that exactly match the current page" do tags = %{<r:navigation urls="Home: Boy: / | Assorted: /assorted/ | Parent: /parent/"> <r:normal><a href="<r:url />"><r:title /></a></r:normal> <r:here><strong><r:title /></strong></r:here> <r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected> <r:between> | </r:between> </r:navigation>} expected = %{<strong><a href="/">Home: Boy</a></strong> | <strong>Assorted</strong> | <a href="/parent/">Parent</a>} page.should render(tags).as(expected) end it "should render the nested <r:between> tag between each link" do tags = %{<r:navigation urls="Home: / | Assorted: /assorted/ | Parent: /parent/"> <r:normal><r:title /></r:normal> <r:between> :: </r:between> </r:navigation>} expected = %{Home :: Assorted :: Parent} page.should render(tags).as(expected) end it 'without urls should render nothing' do page.should render(%{<r:navigation><r:normal /></r:navigation>}).as('') end it 'without a nested <r:normal> tag should render an error' do page.should render(%{<r:navigation urls="something:here"></r:navigation>}).with_error( "`navigation' tag must include a `normal' tag") end it 'with urls without trailing slashes should match corresponding pages' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><r:title /></r:normal> <r:here><strong><r:title /></strong></r:here> </r:navigation>} expected = %{Home <strong>Assorted</strong> Parent Radius} page.should render(tags).as(expected) end it 'should prune empty blocks' do tags = %{<r:navigation urls="Home: Boy: / | Archives: /archive/ | Radius: /radius/ | Docs: /documentation/"> <r:normal><a href="<r:url />"><r:title /></a></r:normal> <r:here></r:here> <r:selected><strong><a href="<r:url />"><r:title /></a></strong></r:selected> <r:between> | </r:between> </r:navigation>} expected = %{<strong><a href="/">Home: Boy</a></strong> | <a href="/archive/">Archives</a> | <a href="/documentation/">Docs</a>} page(:radius).should render(tags).as(expected) end it 'should render text under <r:if_first> and <r:if_last> only on the first and last item, respectively' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><r:if_first>(</r:if_first><a href="<r:url />"><r:title /></a><r:if_last>)</r:if_last></r:normal> <r:here><r:if_first>(</r:if_first><r:title /><r:if_last>)</r:if_last></r:here> <r:selected><r:if_first>(</r:if_first><strong><a href="<r:url />"><r:title /></a></strong><r:if_last>)</r:if_last></r:selected> </r:navigation>} expected = %{(<strong><a href=\"/\">Home</a></strong> <a href=\"/assorted\">Assorted</a> <a href=\"/parent\">Parent</a> Radius)} page(:radius).should render(tags).as(expected) end it 'should render text under <r:unless_first> on every item but the first' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><r:unless_first>&gt; </r:unless_first><a href="<r:url />"><r:title /></a></r:normal> <r:here><r:unless_first>&gt; </r:unless_first><r:title /></r:here> <r:selected><r:unless_first>&gt; </r:unless_first><strong><a href="<r:url />"><r:title /></a></strong></r:selected> </r:navigation>} expected = %{<strong><a href=\"/\">Home</a></strong> &gt; <a href=\"/assorted\">Assorted</a> &gt; <a href=\"/parent\">Parent</a> &gt; Radius} page(:radius).should render(tags).as(expected) end it 'should render text under <r:unless_last> on every item but the last' do tags = %{<r:navigation urls="Home: / | Assorted: /assorted | Parent: /parent | Radius: /radius"> <r:normal><a href="<r:url />"><r:title /></a><r:unless_last> &gt;</r:unless_last></r:normal> <r:here><r:title /><r:unless_last> &gt;</r:unless_last></r:here> <r:selected><strong><a href="<r:url />"><r:title /></a></strong><r:unless_last> &gt;</r:unless_last></r:selected> </r:navigation>} expected = %{<strong><a href=\"/\">Home</a></strong> &gt; <a href=\"/assorted\">Assorted</a> &gt; <a href=\"/parent\">Parent</a> &gt; Radius} page(:radius).should render(tags).as(expected) end end describe "<r:find>" do it "should change the local page to the page specified in the 'url' attribute" do page.should render(%{<r:find url="/parent/child/"><r:title /></r:find>}).as('Child') end it "should render an error without the 'url' attribute" do page.should render(%{<r:find />}).with_error("`find' tag must contain `url' attribute") end it "should render nothing when the 'url' attribute does not point to a page" do page.should render(%{<r:find url="/asdfsdf/"><r:title /></r:find>}).as('') end it "should render nothing when the 'url' attribute does not point to a page and a custom 404 page exists" do page.should render(%{<r:find url="/gallery/asdfsdf/"><r:title /></r:find>}).as('') end it "should scope contained tags to the found page" do page.should render(%{<r:find url="/parent/"><r:children:each><r:slug /> </r:children:each></r:find>}).as('child child-2 child-3 ') end it "should accept a path relative to the current page" do page(:great_grandchild).should render(%{<r:find url="../../../child-2"><r:title/></r:find>}).as("Child 2") end end it '<r:escape_html> should escape HTML-related characters into entities' do page.should render('<r:escape_html><strong>a bold move</strong></r:escape_html>').as('&lt;strong&gt;a bold move&lt;/strong&gt;') end it '<r:rfc1123_date> should render an RFC1123-compatible date' do page(:dated).should render('<r:rfc1123_date />').as('Wed, 11 Jan 2006 00:00:00 GMT') end describe "<r:breadcrumbs>" do it "should render a series of breadcrumb links separated by &gt;" do expected = %{<a href="/">Home</a> &gt; <a href="/parent/">Parent</a> &gt; <a href="/parent/child/">Child</a> &gt; <a href="/parent/child/grandchild/">Grandchild</a> &gt; Great Grandchild} page(:great_grandchild).should render('<r:breadcrumbs />').as(expected) end it "with a 'separator' attribute should use the separator instead of &gt;" do expected = %{<a href="/">Home</a> :: Parent} page(:parent).should render('<r:breadcrumbs separator=" :: " />').as(expected) end it "with a 'nolinks' attribute set to 'true' should not render links" do expected = %{Home &gt; Parent} page(:parent).should render('<r:breadcrumbs nolinks="true" />').as(expected) end it "with a relative URL root should scope links to the relative root" do expected = '<a href="/foo/">Home</a> &gt; Assorted' page(:assorted).should render('<r:breadcrumbs />').with_relative_root('/foo').as(expected) end end describe "<r:if_url>" do describe "with 'matches' attribute" do it "should render the contained block if the page URL matches" do page.should render('<r:if_url matches="a.sorted/$">true</r:if_url>').as('true') end it "should not render the contained block if the page URL does not match" do page.should render('<r:if_url matches="fancypants">true</r:if_url>').as('') end it "set to a malformatted regexp should render an error" do page.should render('<r:if_url matches="as(sorted/$">true</r:if_url>').with_error("Malformed regular expression in `matches' argument of `if_url' tag: unmatched (: /as(sorted\\/$/") end it "without 'ignore_case' attribute should ignore case by default" do page.should render('<r:if_url matches="asSorted/$">true</r:if_url>').as('true') end describe "with 'ignore_case' attribute" do it "set to 'true' should use a case-insensitive match" do page.should render('<r:if_url matches="asSorted/$" ignore_case="true">true</r:if_url>').as('true') end it "set to 'false' should use a case-sensitive match" do page.should render('<r:if_url matches="asSorted/$" ignore_case="false">true</r:if_url>').as('') end end end it "with no attributes should render an error" do page.should render('<r:if_url>test</r:if_url>').with_error("`if_url' tag must contain a `matches' attribute.") end end describe "<r:unless_url>" do describe "with 'matches' attribute" do it "should not render the contained block if the page URL matches" do page.should render('<r:unless_url matches="a.sorted/$">true</r:unless_url>').as('') end it "should render the contained block if the page URL does not match" do page.should render('<r:unless_url matches="fancypants">true</r:unless_url>').as('true') end it "set to a malformatted regexp should render an error" do page.should render('<r:unless_url matches="as(sorted/$">true</r:unless_url>').with_error("Malformed regular expression in `matches' argument of `unless_url' tag: unmatched (: /as(sorted\\/$/") end it "without 'ignore_case' attribute should ignore case by default" do page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('') end describe "with 'ignore_case' attribute" do it "set to 'true' should use a case-insensitive match" do page.should render('<r:unless_url matches="asSorted/$">true</r:unless_url>').as('') end it "set to 'false' should use a case-sensitive match" do page.should render('<r:unless_url matches="asSorted/$" ignore_case="false">true</r:unless_url>').as('true') end end end it "with no attributes should render an error" do page.should render('<r:unless_url>test</r:unless_url>').with_error("`unless_url' tag must contain a `matches' attribute.") end end describe "<r:cycle>" do it "should render passed values in succession" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second') end it "should return to the beginning of the cycle when reaching the end" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" /> <r:cycle values="first, second" />').as('first second first') end it "should use a default cycle name of 'cycle'" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" name="cycle" />').as('first second') end it "should maintain separate cycle counters" do page.should render('<r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" /> <r:cycle values="first, second" /> <r:cycle values="one, two" name="numbers" />').as('first one second two') end it "should reset the counter" do page.should render('<r:cycle values="first, second" /> <r:cycle values="first, second" reset="true"/>').as('first first') end it "should require the values attribute" do page.should render('<r:cycle />').with_error("`cycle' tag must contain a `values' attribute.") end end describe "<r:if_dev>" do it "should render the contained block when on the dev site" do page.should render('-<r:if_dev>dev</r:if_dev>-').as('-dev-').on('dev.site.com') end it "should not render the contained block when not on the dev site" do page.should render('-<r:if_dev>dev</r:if_dev>-').as('--') end describe "on an included page" do it "should render the contained block when on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('-dev-').on('dev.site.com') end it "should not render the contained block when not on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="if_dev" /></r:find>-').as('--') end end end describe "<r:unless_dev>" do it "should not render the contained block when not on the dev site" do page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('--').on('dev.site.com') end it "should render the contained block when not on the dev site" do page.should render('-<r:unless_dev>not dev</r:unless_dev>-').as('-not dev-') end describe "on an included page" do it "should not render the contained block when not on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('--').on('dev.site.com') end it "should render the contained block when not on the dev site" do page.should render('-<r:find url="/devtags/"><r:content part="unless_dev" /></r:find>-').as('-not dev-') end end end describe "<r:status>" do it "should render the status of the current page" do status_tag = "<r:status/>" page(:a).should render(status_tag).as("Published") page(:hidden).should render(status_tag).as("Hidden") page(:draft).should render(status_tag).as("Draft") end describe "with the downcase attribute set to 'true'" do it "should render the lowercased status of the current page" do status_tag_lc = "<r:status downcase='true'/>" page(:a).should render(status_tag_lc).as("published") page(:hidden).should render(status_tag_lc).as("hidden") page(:draft).should render(status_tag_lc).as("draft") end end end describe "<r:if_ancestor_or_self>" do it "should render the tag's content when the current page is an ancestor of tag.locals.page" do page(:radius).should render(%{<r:find url="/"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('true') end it "should not render the tag's content when current page is not an ancestor of tag.locals.page" do page(:parent).should render(%{<r:find url="/radius"><r:if_ancestor_or_self>true</r:if_ancestor_or_self></r:find>}).as('') end end describe "<r:unless_ancestor_or_self>" do it "should render the tag's content when the current page is not an ancestor of tag.locals.page" do page(:parent).should render(%{<r:find url="/radius"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('true') end it "should not render the tag's content when current page is an ancestor of tag.locals.page" do page(:radius).should render(%{<r:find url="/"><r:unless_ancestor_or_self>true</r:unless_ancestor_or_self></r:find>}).as('') end end describe "<r:if_self>" do it "should render the tag's content when the current page is the same as the local contextual page" do page(:home).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('true') end it "should not render the tag's content when the current page is not the same as the local contextual page" do page(:radius).should render(%{<r:find url="/"><r:if_self>true</r:if_self></r:find>}).as('') end end describe "<r:unless_self>" do it "should render the tag's content when the current page is not the same as the local contextual page" do page(:radius).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('true') end it "should not render the tag's content when the current page is the same as the local contextual page" do page(:home).should render(%{<r:find url="/"><r:unless_self>true</r:unless_self></r:find>}).as('') end end describe "<r:meta>" do it "should render <meta> tags for the description and keywords" do page(:home).should render('<r:meta/>').as(%{<meta name="description" content="The homepage" /><meta name="keywords" content="Home, Page" />}) end it "should render <meta> tags with escaped values for the description and keywords" do page.should render('<r:meta/>').as(%{<meta name="description" content="sweet &amp; harmonious biscuits" /><meta name="keywords" content="sweet &amp; harmonious biscuits" />}) end describe "with 'tag' attribute set to 'false'" do it "should render the contents of the description and keywords" do page(:home).should render('<r:meta tag="false" />').as(%{The homepageHome, Page}) end it "should escape the contents of the description and keywords" do page.should render('<r:meta tag="false" />').as("sweet &amp; harmonious biscuitssweet &amp; harmonious biscuits") end end end describe "<r:meta:description>" do it "should render a <meta> tag for the description" do page(:home).should render('<r:meta:description/>').as(%{<meta name="description" content="The homepage" />}) end it "should render a <meta> tag with escaped value for the description" do page.should render('<r:meta:description />').as(%{<meta name="description" content="sweet &amp; harmonious biscuits" />}) end describe "with 'tag' attribute set to 'false'" do it "should render the contents of the description" do page(:home).should render('<r:meta:description tag="false" />').as(%{The homepage}) end it "should escape the contents of the description" do page.should render('<r:meta:description tag="false" />').as("sweet &amp; harmonious biscuits") end end end describe "<r:meta:keywords>" do it "should render a <meta> tag for the keywords" do page(:home).should render('<r:meta:keywords/>').as(%{<meta name="keywords" content="Home, Page" />}) end it "should render a <meta> tag with escaped value for the keywords" do page.should render('<r:meta:keywords />').as(%{<meta name="keywords" content="sweet &amp; harmonious biscuits" />}) end describe "with 'tag' attribute set to 'false'" do it "should render the contents of the keywords" do page(:home).should render('<r:meta:keywords tag="false" />').as(%{Home, Page}) end it "should escape the contents of the keywords" do page.should render('<r:meta:keywords tag="false" />').as("sweet &amp; harmonious biscuits") end end end private def page(symbol = nil) if symbol.nil? @page ||= pages(:assorted) else @page = pages(symbol) end end def page_children_each_tags(attr = nil) attr = ' ' + attr unless attr.nil? "<r:children:each#{attr}><r:slug /> </r:children:each>" end def page_children_first_tags(attr = nil) attr = ' ' + attr unless attr.nil? "<r:children:first#{attr}><r:slug /></r:children:first>" end def page_children_last_tags(attr = nil) attr = ' ' + attr unless attr.nil? "<r:children:last#{attr}><r:slug /></r:children:last>" end def page_eachable_children(page) page.children.select(&:published?).reject(&:virtual) end end
joshfrench/radiant
spec/models/standard_tags_spec.rb
Ruby
mit
51,194
module ParametresHelper end
Henrik41/jQuery-Validation-Engine-rails
thingo2/app/helpers/parametres_helper.rb
Ruby
mit
28
class CreateMappableMaps < ActiveRecord::Migration def change create_table :mappable_maps do |t| t.string :subject t.string :attr t.string :from t.string :to t.timestamps end end end
mikebannister/mappable
db/migrate/20110919042052_create_mappable_maps.rb
Ruby
mit
226
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=ASCII"> <link rel="stylesheet" href="style.css" type="text/css"> <title>MXML Only Components - Adobe Flex 2 Language Reference</title> </head> <body class="classFrameContent"> <h3>MXML Only Components</h3> <a href="mxml/binding.html" target="classFrame">&lt;mx:Binding&gt;</a> <br> <a href="mxml/component.html" target="classFrame">&lt;mx:Component&gt;</a> <br> <a href="mxml/metadata.html" target="classFrame">&lt;mx:Metadata&gt;</a> <br> <a href="mxml/model.html" target="classFrame">&lt;mx:Model&gt;</a> <br> <a href="mxml/script.html" target="classFrame">&lt;mx:Script&gt;</a> <br> <a href="mxml/style.html" target="classFrame">&lt;mx:Style&gt;</a> <br> <a href="mxml/xml.html" target="classFrame">&lt;mx:XML&gt;</a> <br> <a href="mxml/xmlList.html" target="classFrame">&lt;mx:XMLList&gt;</a> <br> </body> <!--MMIX | John Dalziel | The Computus Engine | www.computus.org | All source code licenced under the MIT Licence--> </html>
crashposition/computus
docs/mxml-tags.html
HTML
mit
1,145
LinkLuaModifier("modifier_cleric_berserk", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_cleric_berserk_target", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_cleric_berserk_no_order", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_cleric_prayer", "heroes/cleric/cleric_modifiers.lua", LUA_MODIFIER_MOTION_NONE) function ClericMeteorShower(keys) ProcsArroundingMagicStick(keys.caster) local iMeteorCount = keys.ability:GetSpecialValueFor("meteor_count") local vTarget= keys.target_points[1] local fMeteorRadius = keys.ability:GetSpecialValueFor("meteor_radius") AddFOWViewer(keys.caster:GetTeamNumber(), vTarget, 500, 3, true) local fCastRadius = keys.ability:GetSpecialValueFor("cast_radius") local iDamage if keys.caster:FindAbilityByName("special_bonus_cleric_4") then iDamage = keys.ability:GetSpecialValueFor("damage")+keys.caster:FindAbilityByName("special_bonus_cleric_4"):GetSpecialValueFor("value") else iDamage = keys.ability:GetSpecialValueFor("damage") end local fStunDuration if keys.caster:FindAbilityByName("special_bonus_cleric_1") then fStunDuration = keys.ability:GetSpecialValueFor("stun_duration")+keys.caster:FindAbilityByName("special_bonus_cleric_1"):GetSpecialValueFor("value") else fStunDuration = keys.ability:GetSpecialValueFor("stun_duration") end for i = 1, iMeteorCount do Timers:CreateTimer(0.2*(i-1), function () local vRelative = Vector(RandomFloat(-fCastRadius, fCastRadius), RandomFloat(-fCastRadius, fCastRadius), 0) while vRelative:Length2D() > fCastRadius do vRelative = Vector(RandomFloat(-fCastRadius, fCastRadius), RandomFloat(-fCastRadius, fCastRadius), 0) end local iParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_invoker/invoker_chaos_meteor_fly.vpcf", PATTACH_CUSTOMORIGIN, PlayerResource:GetPlayer(0):GetAssignedHero()) ParticleManager:SetParticleControl(iParticle, 0, vTarget+vRelative+Vector(0,0,2000)) ParticleManager:SetParticleControl(iParticle, 1, vTarget+vRelative+Vector(0,0,-2250)) ParticleManager:SetParticleControl(iParticle, 2, Vector(0.7,0,0)) local hThinker = CreateModifierThinker(keys.caster, keys.ability, "modifier_stunned", {Duration = 1}, vTarget+vRelative+Vector(0,0,2000), keys.caster:GetTeamNumber(), false) hThinker:EmitSound("Hero_Invoker.ChaosMeteor.Cast") hThinker:EmitSound("Hero_Invoker.ChaosMeteor.Loop") Timers:CreateTimer(0.6,function () StartSoundEventFromPosition("Hero_Invoker.ChaosMeteor.Impact", vTarget+vRelative) hThinker:StopSound("Hero_Invoker.ChaosMeteor.Loop") GridNav:DestroyTreesAroundPoint(vTarget+vRelative, fMeteorRadius, true) local tTargets = FindUnitsInRadius(keys.caster:GetTeamNumber(), vTarget+vRelative, nil, fMeteorRadius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC+DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false) local damageTable = { damage = iDamage, attacker = keys.caster, damage_type = DAMAGE_TYPE_MAGICAL, ability = keys.ability } for k, v in ipairs(tTargets) do damageTable.victim = v ApplyDamage(damageTable) v:AddNewModifier(keys.caster, keys.ability, "modifier_stunned", {Duration = fStunDuration*CalculateStatusResist(v)}) end end) end) end end cleric_berserk = class({}) function cleric_berserk:GetBehavior() if not self.bSpecial2 then self.hSpecial2 = Entities:First() while self.hSpecial2 and (self.hSpecial2:GetName() ~= "special_bonus_cleric_5" or self.hSpecial2:GetCaster() ~= self:GetCaster()) do self.hSpecial2 = Entities:Next(self.hSpecial2) end self.bSpecial2 = true end if self.hSpecial2 and self.hSpecial2:GetLevel() > 0 then return DOTA_ABILITY_BEHAVIOR_POINT+DOTA_ABILITY_BEHAVIOR_AOE else return DOTA_ABILITY_BEHAVIOR_UNIT_TARGET end end function cleric_berserk:GetAOERadius() if self.hSpecial2 then return self.hSpecial2:GetSpecialValueFor("value") else return 0 end end function cleric_berserk:OnSpellStart() if self.hSpecial2 and self.hSpecial2:GetLevel() > 0 then local hCaster = self:GetCaster() local tTargets = FindUnitsInRadius(hCaster:GetTeamNumber(), self:GetCursorPosition(), nil, self.hSpecial2:GetSpecialValueFor("value"), DOTA_UNIT_TARGET_TEAM_BOTH, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, FIND_ANY_ORDER, false) for k, v in ipairs(tTargets) do v:EmitSound("Hero_Axe.Berserkers_Call") v:AddNewModifier(hCaster, self, "modifier_cleric_berserk", {Duration = self:GetSpecialValueFor("duration")*CalculateStatusResist(v)}) end else local hTarget = self:GetCursorTarget() if hTarget:TriggerSpellAbsorb( self ) then return end hTarget:EmitSound("Hero_Axe.Berserkers_Call") hTarget:AddNewModifier(self:GetCaster(), self, "modifier_cleric_berserk", {Duration = self:GetSpecialValueFor("duration")*CalculateStatusResist(hTarget)}) end end function cleric_berserk:GetCooldown(iLevel) if not self.bSpecial then self.hSpecial = Entities:First() while self.hSpecial and (self.hSpecial:GetName() ~= "special_bonus_cleric_2" or self.hSpecial:GetCaster() ~= self:GetCaster()) do self.hSpecial = Entities:Next(self.hSpecial) end self.bSpecial = true end if self.hSpecial then return self.BaseClass.GetCooldown(self, iLevel)-self.hSpecial:GetSpecialValueFor("value") else return self.BaseClass.GetCooldown(self, iLevel) end end function ClericPrayer(keys) ProcsArroundingMagicStick(keys.caster) local hSpecial = Entities:First() while hSpecial and hSpecial:GetName() ~= "special_bonus_cleric_3" do hSpecial = Entities:Next(hSpecial) end keys.caster:EmitSound("Hero_Omniknight.GuardianAngel.Cast") local iDuration = keys.ability:GetSpecialValueFor("duration") for k, v in pairs(keys.target_entities) do local hModifier = v:FindModifierByName("modifier_cleric_prayer") if not hModifier then v:AddNewModifier(keys.caster, keys.ability, "modifier_cleric_prayer", {Duration = iDuration}) v:EmitSound("Hero_Omniknight.GuardianAngel") v:EmitSound("DOTA_Item.Refresher.Activate") ParticleManager:SetParticleControlEnt(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", PATTACH_ABSORIGIN_FOLLOW, v), 0, v, PATTACH_POINT_FOLLOW, "attach_hitloc", v:GetAbsOrigin(), true) for i = 0, 23 do if v:GetAbilityByIndex(i) then v:GetAbilityByIndex(i):EndCooldown() end end for j,i in ipairs(tItemInventorySlotTable) do if v:GetItemInSlot(i) then v:GetItemInSlot(i):EndCooldown() end end elseif hSpecial and hModifier:GetStackCount() < hSpecial:GetSpecialValueFor("value") then local iOriginalStackCount = hModifier:GetStackCount() v:AddNewModifier(keys.caster, keys.ability, "modifier_cleric_prayer", {Duration = iDuration}) v:FindModifierByName("modifier_cleric_prayer"):SetStackCount(iOriginalStackCount+1) v:EmitSound("Hero_Omniknight.GuardianAngel") v:EmitSound("DOTA_Item.Refresher.Activate") ParticleManager:SetParticleControlEnt(ParticleManager:CreateParticle("particles/items2_fx/refresher.vpcf", PATTACH_ABSORIGIN_FOLLOW, v), 0, v, PATTACH_POINT_FOLLOW, "attach_hitloc", v:GetAbsOrigin(), true) for i = 0, 23 do if v:GetAbilityByIndex(i) then v:GetAbilityByIndex(i):EndCooldown() end end for j,i in ipairs(tItemInventorySlotTable) do if v:GetItemInSlot(i) then v:GetItemInSlot(i):EndCooldown() end end end end end cleric_magic_mirror = class({}) function cleric_magic_mirror:GetCooldown(iLevel) if IsClient() then if self:GetCaster():HasScepter() then return 20-iLevel*5 end else if self:GetCaster():HasScepter() then return self:GetLevelSpecialValueFor("scepter_cooldown", iLevel) end end return self.BaseClass.GetCooldown(self, iLevel) end
tontyoutoure/DOTA2-AI-Fun
game/dota_addons/dota2_ai_fun/scripts/vscripts/heroes/cleric/cleric.lua
Lua
mit
7,858
export function mockGlobalFile() { // @ts-ignore global.File = class MockFile { name: string; size: number; type: string; parts: (string | Blob | ArrayBuffer | ArrayBufferView)[]; properties?: FilePropertyBag; lastModified: number; constructor( parts: (string | Blob | ArrayBuffer | ArrayBufferView)[], name: string, properties?: FilePropertyBag ) { this.parts = parts; this.name = name; this.size = parts.join('').length; this.type = 'txt'; this.properties = properties; this.lastModified = 1234567890000; // Sat Feb 13 2009 23:31:30 GMT+0000. } }; } export function testFile(filename: string, size: number = 42) { return new File(['x'.repeat(size)], filename, undefined); }
ProtonMail/WebClient
applications/drive/src/app/helpers/test/file.ts
TypeScript
mit
879
package net.talayhan.android.vibeproject.Controller; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.ipaulpro.afilechooser.utils.FileUtils; import net.talayhan.android.vibeproject.R; import net.talayhan.android.vibeproject.Util.Constants; import java.io.File; import butterknife.ButterKnife; import butterknife.InjectView; import cn.pedant.SweetAlert.SweetAlertDialog; public class MainActivity extends Activity { @InjectView(R.id.fileChooser_bt) Button mFileChooser_bt; @InjectView(R.id.playBack_btn) Button mPlayback_bt; @InjectView(R.id.chart_bt) Button mChart_bt; private String videoPath; private String vidAddress = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4"; private SweetAlertDialog pDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mFileChooser_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /* Progress dialog */ pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE); pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86")); pDialog.setTitleText("Network Type"); pDialog.setContentText("How would you like to watch video?"); pDialog.setConfirmText("Local"); pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { // Local // Create the ACTION_GET_CONTENT Intent Intent getContentIntent = FileUtils.createGetContentIntent(); Intent intent = Intent.createChooser(getContentIntent, "Select a file"); startActivityForResult(intent, Constants.REQUEST_CHOOSER); sweetAlertDialog.dismissWithAnimation(); } }); pDialog.setCancelText("Internet"); pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { /* check the device network state */ if (!isOnline()){ new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE) .setContentText("Your device is now offline!\n" + "Please open your Network.") .setTitleText("Open Network Connection") .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { showNoConnectionDialog(MainActivity.this); sweetAlertDialog.dismissWithAnimation(); } }) .show(); }else { // Create the intent to start video activity Intent i = new Intent(MainActivity.this, LocalVideoActivity.class); i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE, vidAddress); startActivity(i); sweetAlertDialog.dismissWithAnimation(); } } }); pDialog.setCancelable(true); pDialog.show(); } }); mPlayback_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new SweetAlertDialog(MainActivity.this, SweetAlertDialog.NORMAL_TYPE) .setContentText("Please first label some video!\n" + "Later come back here!.") .setTitleText("Playback") .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { sweetAlertDialog.dismissWithAnimation(); } }) .show(); } }); mChart_bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, ChartRecyclerView.class); startActivityForResult(i, Constants.REQUEST_CHART); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Constants.REQUEST_CHOOSER: if (resultCode == RESULT_OK) { final Uri uri = data.getData(); // Get the File path from the Uri String path = FileUtils.getPath(this, uri); Toast.makeText(this, "Choosen file: " + path,Toast.LENGTH_LONG).show(); // Alternatively, use FileUtils.getFile(Context, Uri) if (path != null && FileUtils.isLocal(path)) { File file = new File(path); } // Create the intent to start video activity Intent i = new Intent(MainActivity.this, LocalVideoActivity.class); i.putExtra(Constants.EXTRA_ANSWER_IS_TRUE,path); startActivity(i); } break; } } /* * This method checks network situation, if device is airplane mode or something went wrong on * network stuff. Method returns false, otherwise return true. * * - This function inspired by below link, * http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts * * @return boolean - network state * * * */ public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo != null && netInfo.isConnectedOrConnecting(); } /** * Display a dialog that user has no internet connection * @param ctx1 * * Code from: http://osdir.com/ml/Android-Developers/2009-11/msg05044.html */ public static void showNoConnectionDialog(Context ctx1) { final Context ctx = ctx1; final SweetAlertDialog builder = new SweetAlertDialog(ctx, SweetAlertDialog.SUCCESS_TYPE); builder.setCancelable(true); builder.setContentText("Open internet connection"); builder.setTitle("No connection error!"); builder.setConfirmText("Open wirless."); builder.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { ctx.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); builder.dismissWithAnimation(); } }); builder.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; }else if (id == R.id.action_search){ openSearch(); return true; } return super.onOptionsItemSelected(item); } private void openSearch() { Toast.makeText(this,"Clicked Search button", Toast.LENGTH_SHORT).show(); } }
stalayhan/vibeapp
app/src/main/java/net/talayhan/android/vibeproject/Controller/MainActivity.java
Java
mit
9,208
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Marionette Components</title> </head> <body> Marionette View Test <script src='../build/view.js'></script> </body> </html>
jmeas-test/test-umd-modules
html/view.html
HTML
mit
201
--- title: 分享-认同 的魅力 tags: ---
ZongWenlong/ZongWenlong.github.io
source/_drafts/分享-认同-的魅力.md
Markdown
mit
45
<?php namespace Oro\Bundle\ApiBundle\Processor\Shared\Rest; use Oro\Bundle\ApiBundle\Metadata\RouteLinkMetadata; use Oro\Bundle\ApiBundle\Processor\Context; use Oro\Bundle\ApiBundle\Provider\ResourcesProvider; use Oro\Bundle\ApiBundle\Request\AbstractDocumentBuilder as ApiDoc; use Oro\Bundle\ApiBundle\Request\ApiAction; use Oro\Bundle\ApiBundle\Request\RequestType; use Oro\Bundle\ApiBundle\Request\Rest\RestRoutesRegistry; use Oro\Component\ChainProcessor\ContextInterface; use Oro\Component\ChainProcessor\ProcessorInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; /** * Adds "self" HATEOAS link to a whole document of success response. * @link https://jsonapi.org/recommendations/#including-links */ class AddHateoasLinks implements ProcessorInterface { /** @var RestRoutesRegistry */ private $routesRegistry; /** @var UrlGeneratorInterface */ private $urlGenerator; /** @var ResourcesProvider */ private $resourcesProvider; /** * @param RestRoutesRegistry $routesRegistry * @param UrlGeneratorInterface $urlGenerator * @param ResourcesProvider $resourcesProvider */ public function __construct( RestRoutesRegistry $routesRegistry, UrlGeneratorInterface $urlGenerator, ResourcesProvider $resourcesProvider ) { $this->routesRegistry = $routesRegistry; $this->urlGenerator = $urlGenerator; $this->resourcesProvider = $resourcesProvider; } /** * {@inheritdoc} */ public function process(ContextInterface $context) { /** @var Context $context */ $documentBuilder = $context->getResponseDocumentBuilder(); if (null === $documentBuilder || !$context->isSuccessResponse()) { return; } $requestType = $context->getRequestType(); $entityClass = $context->getClassName(); if (ApiAction::GET_LIST !== $context->getAction() && $this->isGetListActionExcluded($entityClass, $context->getVersion(), $requestType) ) { return; } $documentBuilder->addLinkMetadata(ApiDoc::LINK_SELF, new RouteLinkMetadata( $this->urlGenerator, $this->routesRegistry->getRoutes($requestType)->getListRouteName(), [], ['entity' => $documentBuilder->getEntityAlias($entityClass, $requestType)] )); } /** * @param string $entityClass * @param string $version * @param RequestType $requestType * * @return bool */ private function isGetListActionExcluded(string $entityClass, string $version, RequestType $requestType): bool { return \in_array( ApiAction::GET_LIST, $this->resourcesProvider->getResourceExcludeActions($entityClass, $version, $requestType), true ); } }
orocrm/platform
src/Oro/Bundle/ApiBundle/Processor/Shared/Rest/AddHateoasLinks.php
PHP
mit
2,893
Başardım :)
PAU-Projects/Github-Odev
sefa.md
Markdown
mit
14
const path = require('path'), fs = require('fs'), glob = require('glob'), pug = require('pug'), stylus = require('stylus'), nib = require('nib'), autoprefixer = require('autoprefixer-stylus'), {rollup} = require('rollup'), rollupPluginPug = require('rollup-plugin-pug'), rollupPluginResolve = require('rollup-plugin-node-resolve'), rollupPluginReplace = require('rollup-plugin-replace'), rollupPluginCommonjs = require('rollup-plugin-commonjs'), rollupPluginGlobImport = require('rollup-plugin-glob-import'), rollupPluginAlias = require('rollup-plugin-alias'), rollupPluginBabel = require('rollup-plugin-babel'), sgUtil = require('./util'); class AppBuilder { constructor(conf, CollectorStore) { this.conf = conf; this.CollectorStore = CollectorStore; this.name = this.conf.get('package.name'); this.viewerDest = this.conf.get('viewerDest'); this.source = path.resolve(__dirname, '..', 'app'); this.sections = []; this.generateViewerPages = this.generateViewerPages.bind(this); this.generateViewerStyles = this.generateViewerStyles.bind(this); this.rollupViewerScripts = this.rollupViewerScripts.bind(this); this.getViewerPagesLocals = this.getViewerPagesLocals.bind(this); this.onEnd = this.onEnd.bind(this); } renderCollected() { if (!this.watcher) { this.CollectorStore.getFiles() .forEach(async (file) => { if (!file.exclude) { await file.render; } }); } return this; } saveCollectedData() { if (!this.watcher) { const {viewerDest, CollectorStore: {getCollectedData}} = this; sgUtil.writeJsonFile(path.join(viewerDest, 'structure.json'), getCollectedData()); } } getViewerPagesLocals() { return { description: this.conf.get('package.description', 'No description'), version: this.conf.get('version', this.conf.get('package.version') || 'dev') }; } onEnd(message) { return (error) => { if (error) { throw error; } sgUtil.log(`[✓] ${this.name} ${message}`, 'info'); }; } async generateViewerPages() { const {source, viewerDest, getViewerPagesLocals} = this, onEnd = this.onEnd('viewer html generated.'), templateFile = path.join(source, 'templates', 'viewer', 'index.pug'), renderOptions = Object.assign({ pretty: true, cache: false }, getViewerPagesLocals()); sgUtil.writeFile(path.join(viewerDest, 'index.html'), pug.renderFile(templateFile, renderOptions), onEnd); } async generateViewerStyles() { const {source, viewerDest} = this, onEnd = this.onEnd('viewer css generated.'), stylusStr = glob.sync(`${source}/style/**/!(_)*.styl`) .map((file) => fs.readFileSync(file, 'utf8')) .join('\n'); stylus(stylusStr) .set('include css', true) .set('prefix', 'dsc-') .use(nib()) .use(autoprefixer({ browsers: ['> 5%', 'last 1 versions'], cascade: false })) .include(path.join(source, 'style')) .import('_reset') .import('_mixins') .import('_variables') .render((err, css) => { if (err) { onEnd(err); } else { sgUtil.writeFile(path.join(viewerDest, 'css', 'app.css'), css, onEnd); } }); } async rollupViewerScripts() { const {source, viewerDest} = this, destFile = path.join(viewerDest, 'scripts', 'app.js'); sgUtil.createPath(destFile); try { const bundle = await rollup({ input: path.join(source, 'scripts', 'index.js'), plugins: [ rollupPluginGlobImport({ rename(name, id) { if (path.basename(id) !== 'index.js') { return null; } return path.basename(path.dirname(id)); } }), rollupPluginAlias({ vue: 'node_modules/vue/dist/vue.esm.js' }), rollupPluginResolve({ jsnext: true, main: true, module: true }), rollupPluginPug(), rollupPluginReplace({ 'process.env.NODE_ENV': JSON.stringify('development') }), rollupPluginCommonjs(), rollupPluginBabel() ] }); await bundle.write({ file: destFile, format: 'iife', sourcemap: false }); } catch (error) { throw error; } this.onEnd('viewer js bundle generated.'); } } module.exports = AppBuilder;
stefan-lehmann/atomatic
lib/AppBuilder.js
JavaScript
mit
4,620
package org.xcolab.client.contest.pojo; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.xcolab.client.contest.pojo.tables.pojos.ContestCollectionCard; @JsonDeserialize(as = ContestCollectionCard.class) public interface IContestCollectionCard { Long getId(); void setId(Long id); Long getParent(); void setParent(Long parent); Long getBigOntologyTerm(); void setBigOntologyTerm(Long bigOntologyTerm); Long getSmallOntologyTerm(); void setSmallOntologyTerm(Long smallOntologyTerm); String getDescription(); void setDescription(String description); String getShortName(); void setShortName(String shortName); Boolean isVisible(); void setVisible(Boolean visible); Integer getSortOrder(); void setSortOrder(Integer sortOrder); Long getOntologyTermToLoad(); void setOntologyTermToLoad(Long ontologyTermToLoad); Boolean isOnlyFeatured(); void setOnlyFeatured(Boolean onlyFeatured); }
CCI-MIT/XCoLab
microservices/clients/contest-client/src/main/java/org/xcolab/client/contest/pojo/IContestCollectionCard.java
Java
mit
1,010