code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package com.andrewswan.cashflow.web; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.andrewswan.cashflow.domain.Person; @RooWebScaffold(path = "person", formBackingObject = Person.class) @RequestMapping("/person/**") @Controller public class PersonController { }
andrewswan/cash-flow
src/main/java/com/andrewswan/cashflow/web/PersonController.java
Java
mit
423
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CoolCompiler { class CommonLexerError : CompilerError { string Message; public CommonLexerError(string message, int number, int? line, int? columnStart, int? columnStop = null) : base(number, line, columnStart, columnStop) { Message = message; } public override string Description { get { return Message; } } public override enmCompilerErrorStage Stage { get { return enmCompilerErrorStage.Lexer; } } public override enmCompilerErrorType Type { get { return enmCompilerErrorType.CommonLexer; } } } }
KvanTTT/Cool-Compiler
CoolCompiler/CompilerErrors/ComminLexerError.cs
C#
mit
678
--- title: aae25 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: e25 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
pblack/kaldi-hugo-cms-template
site/content/pages2/aae25.md
Markdown
mit
339
<?php Part::input($participant, 'participant'); ?> <form method="POST" action="<?php echo Url::action('participantController::delete', $participant->id) ?>"> <fieldset> <h3><?php echo Html::anchor(Url::action('participantController::details', $participant->id), 'participant #' . $participant->id) ?></h3> <p> <strong>Fname</strong>: <?php echo $participant->fname; ?><br /> <strong>Lname</strong>: <?php echo $participant->lname; ?><br /> <strong>Token</strong>: <?php echo $participant->token; ?><br /> </p> <?php echo Html::anchor(Url::action('participantController::editForm', $participant->id), 'Edit') ?> - <input type="hidden" name="_METHOD" value="DELETE" /> <input type="submit" name="delete" value="Delete" /> </fieldset> </form>
harwoodr/degree
apps/degree/views/participant/details.part.php
PHP
mit
771
/** * @license Highcharts JS v8.0.2 (2020-03-03) * @module highcharts/modules/sonification * @requires highcharts * * Sonification module * * (c) 2012-2019 Øystein Moseng * * License: www.highcharts.com/license */ 'use strict'; import '../../modules/sonification/sonification.js';
cdnjs/cdnjs
ajax/libs/highcharts/8.0.2/es-modules/masters/modules/sonification.src.js
JavaScript
mit
294
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Compilation; using System.Web.Routing; using System.Web.UI; public class CustomRouteHandler : IRouteHandler { public string VirtualPath { get; private set; } public CustomRouteHandler(string virtualPath) { this.VirtualPath = virtualPath; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler; return page; } }
lonekorean/regex-storm
Core/CustomRouteHandler.cs
C#
mit
582
"use strict"; exports.__esModule = true; exports.OTPRequiredError = void 0; var _base = require("./base"); var _includes = _interopRequireDefault(require("lodash/includes")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class OTPRequiredError extends _base.BaseError { static hasError({ headers } = {}) { if (!headers || !headers['otp-token']) { return false; } return (0, _includes.default)(['OPTIONAL', 'REQUIRED'], headers['otp-token'].toUpperCase()); } constructor() { super('otp_required', ...arguments); } } exports.OTPRequiredError = OTPRequiredError;
uphold/uphold-sdk-javascript
dist/core/errors/otp-required.js
JavaScript
mit
654
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("06. User Logs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06. User Logs")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a1811c9e-cad1-4531-8156-3eefa794a543")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
stoyanovmiroslav/Tech-Module-SoftUni
Programming Fundamentals/Dictionaries, Lambda and LINQ - Exercises/06. User Logs/Properties/AssemblyInfo.cs
C#
mit
1,402
# Pegasus Bot This is the slack bot used for team pegasus at M&S. Its most useful feature is the Pull Request Checker which informs the team about open PRs across our various repos. Example output: ![Pegasus PR example](/doc/images/Pegasus-Bot.png?raw=true) The bot is built using a [python real-time messaging bot](https://github.com/errror/python-rtmbot) ## Pegasus Bot Plugins All of the additions made to our pegasus bot are available within the plugins directory. Created Plugins --------------- 1. Standup.py * Notifies the pegasus team that it is time to have our standup. 2. Lunch.py * Notifies the pegsus team that it is time to go eat some lunch. * On specific days it will remind the team about good places to eat, for example the food market by MSQ on Thursdays. 3. pegasus_responder.py * Watches the pegsus channel for '@pegasus' and replies with relevant messages. 4. PR_checker.py * Notifies the pegasus team of all the open pull requests in their repos. * If a pull request is more than 2 days old it will be added to a separate list so that the team knows which PRs to prioritise. * Note - If you want to setup pr_checker.py you need to create your own github token that has read access to your repos. Place this token into a file called /plugins/helpers/github_token.py (an example version can be seen in this folder). ## Other Additions --------------- When creating plugins that will be triggered at a certain time it is adviseable to use the helper script "time_fixer.py" to create a datetime object as has been done in all of the quick order plugins. This is so that the time when the plugin is triggered is correct irrespective of whether it is british summer time or if the server it is being ran from is using UTC or GMT time. ## Setting up your own slackbot ---------------------------- If you wish to setup your own slackbot you will need to create the bot as an integration within slack. (https://<team>.slack.com/services/new/bot) You will then need to add the bot integration to the channel of your choice (/invite @<botname> in your desired channel) and place the created slack token for the bot into a file called rtmbot.conf within the root directory of your repo. ## TODO list: ---------- - Add music suggestion feature inspiried by Tara - Add meme generator ability similar to thinking Gavin
ChrisBentley/slackbot
README.md
Markdown
mit
2,369
""" Base class for exporters """ # Standard library modules. import os # Third party modules. # Local modules. from pyhmsa.util.monitorable import _Monitorable, _MonitorableThread # Globals and constants variables. class _ExporterThread(_MonitorableThread): def __init__(self, datafile, dirpath, *args, **kwargs): args = (datafile, dirpath,) + args super().__init__(args=args, kwargs=kwargs) def _run(self, datafile, dirpath, *args, **kwargs): raise NotImplementedError class _Exporter(_Monitorable): def _create_thread(self, datafile, dirpath, *args, **kwargs): args = (datafile, dirpath,) + args super()._create_thread(*args, **kwargs) def validate(self, datafile): pass def can_export(self, datafile): try: self.validate(datafile) except: return False else: return True def export(self, datafile, dirpath): self.validate(datafile) if not os.path.exists(dirpath): raise ValueError('Path does not exist: %s' % dirpath) if not os.path.isdir(dirpath): raise ValueError('Path is not a directory: %s' % dirpath) self._start(datafile, dirpath)
pyhmsa/pyhmsa
pyhmsa/fileformat/exporter/exporter.py
Python
mit
1,242
# Dump files to my filedump, because dump function dump { rsync -avh --progress "$@" -e ssh mercy:/mnt/data/dump.jemu.name FILE=$(basename $1) if [[ $ME == "Lukas" ]]; then echo "https://dump.jemu.name/$FILE" | pbcopy else echo "https://dump.jemu.name/$FILE" fi echo "$(date '+%Y-%m-%d %H:%M:%S'): $FILE – http://dump.jemu.name/$FILE" >> $HOME/.dumplog terminal-notifier -title "Filedump" -message "$FILE" -execute code $HOME/.dumplog; } function reload() { echo "Updating syncbin at $SYNCBIN..." git -C $SYNCBIN pull origin main git -C $SYNCBIN submodule update --recursive echo "" echo "Re-installing..." $SYNCBIN/install.sh echo "" echo "Nuking zcompdump at $ZSH_COMPDUMP..." rm -f $ZSH_COMPDUMP echo "Reloading ZSH via omz reload..." echo "" omz reload } ############## ## Updating ## ############## function upall() { case $( uname -s ) in Linux) echo "################################" echo "## Updating platform packages ##" echo "################################" sudo apt update sudo apt upgrade -y sudo apt autoremove -y if (( $+commands[brew] )); then echo "" echo "" echo "#######################" echo "## Updating homebrew ##" echo "#######################" brew upgrade fi ;; Darwin) if (( $+commands[brew] )); then echo "#######################" echo "## Updating homebrew ##" echo "#######################" echo "" brew upgrade echo "" echo "#############################" echo "## Updating homebrew casks ##" echo "#############################" echo "" brew upgrade --cask fi # if (( $+commands[mas] )); then # echo "" # echo "########################" # echo "## Updating App Store ##" # echo "########################" # echo "" # echo "mas version $(mas version)" # mas upgrade # echo "" # fi echo "#########################" echo "## Updating R packages ##" echo "#########################" echo "" Rscript --quiet -e \ 'remotes::update_packages(type = "binary")' ;; FreeBSD) echo "################################" echo "## Updating platform packages ##" echo "################################" echo "" if [[ $ME = root ]]; then pkg update pkg upgrade -y pkg clean pkg autoremove -y else sudo pkg update sudo pkg upgrade -y sudo pkg clean sudo pkg autoremove -y fi ;; *) echo "Don't know how to update on this platform: $(uname -s)" ;; esac echo "" echo "######################" echo "## Updating syncbin ##" echo "######################" git -C $SYNCBIN pull origin main # git -C $SYNCBIN submodule update --recursive --remote git -C $SYNCBIN submodule update --recursive --rebase --remote omz reload echo "" echo "## Syncbin updated ##" echo "" echo "##---- Done updating --- $(timestamp) ----##" } # Benachmarking ZSH startup function zsh_bench() { zsh -xvlic 'source ~/.zshrc' 2>&1 | ts -i '%.s' > zsh_startup_${HOST/.*/}_$(date +%F_%T).log echo DONE } #################################################################################### ### Combining PDFs using gs because I needed it once and want to never forget it ### #################################################################################### # Using gs because it keeps outline items and bookmarks, which pdfunite did not keep. function pdfcombine () { echo "Output: $1" echo "Input: $@[2,-1]" gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$1 $@[2,-1] } # Compress video with fixed CRF 23, append suffix, make it an mp4 compavc () { ffmpeg -i $1 -vcodec libx264 -crf 23 $(echo $1 | sed -e 's/\.(mp4|mkv)//')-comp.mp4 } # Silence a video function ffsilent { ffmpeg -i $1 -c copy -an "$1-nosound.${1#*.}" } # From https://stackoverflow.com/a/42544963/409362 function git-find-large-files () { git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort --numeric-sort --key=2 | cut -c 1-12,41- | $(command -v gnumfmt || echo numfmt) --field=2 --to=iec-i --suffix=B --padding=7 --round=nearest } function prefer-conda () { export PATH="$HOME/Library/r-miniconda/bin:$PATH" typeset -aU path }
jemus42/syncbin
zsh/functions.sh
Shell
mit
4,460
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace App { class JacobiMethod { private Matrix matrixA; private Matrix matrixB; private float epsilon; private int maxIterations = 100000; private Dictionary<int, Matrix> x; public JacobiMethod(Matrix matrixA, Matrix matrixB, Matrix matrixX, float epsilon) { this.matrixA = matrixA; this.matrixB = matrixB; this.epsilon = epsilon; this.x = new Dictionary<int, Matrix>(); this.x.Add(0, matrixX); } public void solve() { solve(true); } public void solve(bool print) { if (!converges()) { Console.WriteLine("Matrix A does not satisfiy convergence conditions"); } else { int k = 0; int n = matrixA.getSize(); float sigma; Matrix matrix = null; do { matrix = new Matrix(getZeroMatrixForX(n)); for (int i = 0; i < n; i++) { sigma = 0; for (int j = 0; j < n; j++) { if (i != j) { sigma += matrixA.matrix[i, j] * x[k].matrix[j, 0]; } } matrix.matrix[i, 0] = (matrixB.matrix[i, 0] - sigma) / matrixA.matrix[i, i]; } x.Add(k + 1, matrix); if (print) { printIteration(k, matrix); } if (isAccurateEnough(k + 1)) { break; } k++; if (k >= maxIterations) { Console.WriteLine("Reached max number of iterations: " + maxIterations); break; } } while (true); if (print) { Console.WriteLine("Calculated in " + (k + 1) + " iterations"); } } } private bool converges() { float sum; for (int i = 0; i < matrixA.getSize(); i++) { sum = 0; for (int j = 0; j < matrixA.getSize(); j++) { if (i != j) { sum += matrixA.matrix[i, j]; } } if (Math.Abs(matrixA.matrix[i, i]) < Math.Abs(sum)) { return false; } } return true; } private void printIteration(int k, Matrix matrix) { Console.Write("Iteration: " + (k + 1) + " X: ["); int n = matrix.getSize(); for (int i = 0; i < n; i++) { if (i + 1 == n) { Console.Write(matrix.matrix[i, 0] + "]\n"); } else { Console.Write(matrix.matrix[i, 0] + ", "); } } } private bool isAccurateEnough(int k) { float result; bool accurate = true; float accuracy = 0; for (int i = 0; i < matrixA.getSize(); i++) { result = 0; for (int j = 0; j < matrixA.getSize(); j++) { result += matrixA.matrix[i, j] * x[k].matrix[j, 0]; } result -= matrixB.matrix[i, 0]; if (epsilon < Math.Abs(result)) { accurate = false; } if (accuracy < Math.Abs(result)) { accuracy = Math.Abs(result); } } //Console.WriteLine("Iteration: " + (k + 1) + " Accuracy = " + accuracy); return accurate; } private float[,] getZeroMatrixForX(int n) { float[,] matrix = new float[n, 1]; for (int i = 0; i < n; i++) { matrix[i, 0] = 0; } return matrix; } public Matrix getResult() { return x.Last().Value; } } }
aistis-/linear-equations
App/JacobiMethod.cs
C#
mit
4,733
<html><body><p><!-- saved from url=(0024)http://docs.autodesk.com --> <!DOCTYPE html> <!-- Mirrored from help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/generated/functions/pymel.core.datatypes/pymel.core.datatypes.fmod.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 01 Aug 2015 05:28:20 GMT --> <!-- Added by HTTrack --><meta content="text/html;charset=utf-8" http-equiv="content-type"/><!-- /Added by HTTrack --> </p> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>pymel.core.datatypes.fmod — PyMEL 1.0.7 documentation</title> <link href="../../../_static/nature.css" rel="stylesheet" type="text/css"/> <link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../../', VERSION: '1.0.7', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script src="../../../_static/jquery.js" type="text/javascript"></script> <script src="../../../_static/underscore.js" type="text/javascript"></script> <script src="../../../_static/doctools.js" type="text/javascript"></script> <link href="../../../index-2.html" rel="top" title="PyMEL 1.0.7 documentation"/> <link href="../../pymel.core.datatypes.html" rel="up" title="pymel.core.datatypes"/> <link href="pymel.core.datatypes.frexp.html" rel="next" title="pymel.core.datatypes.frexp"/> <link href="pymel.core.datatypes.floor.html" rel="prev" title="pymel.core.datatypes.floor"/> <link href="../../../../style/adsk.cpm.css" rel="stylesheet" type="text/css"/><meta content="expert" name="experiencelevel"/><meta content="programmer" name="audience"/><meta content="enable" name="user-comments"/><meta content="ENU" name="language"/><meta content="MAYAUL" name="product"/><meta content="2016" name="release"/><meta content="Customization" name="book"/><meta content="Maya-Tech-Docs" name="component"/><meta content="/view/MAYAUL/2016/ENU/" name="helpsystempath"/><meta content="04/03/2015" name="created"/><meta content="04/03/2015" name="modified"/><meta content="Navigation index modules | next | previous | PyMEL 1.0.7 documentation » pymel.core.datatypes » pymel.core.datatypes.fmod ¶ fmod ( x , y ) ¶ Return fmod(x, y), according to platform C. x % y may differ. This function has been overriden from math.fmod to work element-wise on iterables Previous topic pymel.core.datatypes.floor Next topic pymel.core.datatypes.frexp Core Modules animation effects..." name="description"/><meta content="__PyMel_generated_functions_pymel_core_datatypes_pymel_core_datatypes_fmod_html" name="topicid"/> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a accesskey="I" href="../../../genindex.html" title="General Index">index</a></li> <li class="right"> <a href="../../../py-modindex.html" title="Python Module Index">modules</a> |</li> <li class="right"> <a accesskey="N" href="pymel.core.datatypes.frexp.html" title="pymel.core.datatypes.frexp">next</a> |</li> <li class="right"> <a accesskey="P" href="pymel.core.datatypes.floor.html" title="pymel.core.datatypes.floor">previous</a> |</li> <li><a href="../../../index-2.html">PyMEL 1.0.7 documentation</a> »</li> <li><a accesskey="U" href="../../pymel.core.datatypes.html">pymel.core.datatypes</a> »</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="pymel-core-datatypes-fmod"> <h1>pymel.core.datatypes.fmod<a class="headerlink" href="#pymel-core-datatypes-fmod" title="Permalink to this headline">¶</a></h1> <dl class="function"> <dt id="pymel.core.datatypes.fmod"><a name="//apple_ref/cpp/Function/pymel.core.datatypes.fmod"></a> <tt class="descname">fmod</tt><big>(</big><em>x</em>, <em>y</em><big>)</big><a class="headerlink" href="#pymel.core.datatypes.fmod" title="Permalink to this definition">¶</a></dt> <dd><p>Return fmod(x, y), according to platform C. x % y may differ. This function has been overriden from math.fmod to work element-wise on iterables</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="pymel.core.datatypes.floor.html" title="previous chapter">pymel.core.datatypes.floor</a></p> <h4>Next topic</h4> <p class="topless"><a href="pymel.core.datatypes.frexp.html" title="next chapter">pymel.core.datatypes.frexp</a></p> <h3><a href="../../../modules.html">Core Modules</a></h3> <ul> <li><a class="reference external" href="../../pymel.core.animation.html#module-pymel.core.animation"><tt class="xref">animation</tt></a></li> <li><a class="reference external" href="../../pymel.core.effects.html#module-pymel.core.effects"><tt class="xref">effects</tt></a></li> <li><a class="reference external" href="../../pymel.core.general.html#module-pymel.core.general"><tt class="xref">general</tt></a></li> <li><a class="reference external" href="../../pymel.core.language.html#module-pymel.core.language"><tt class="xref">language</tt></a></li> <li><a class="reference external" href="../../pymel.core.modeling.html#module-pymel.core.modeling"><tt class="xref">modeling</tt></a></li> <li><a class="reference external" href="../../pymel.core.rendering.html#module-pymel.core.rendering"><tt class="xref">rendering</tt></a></li> <li><a class="reference external" href="../../pymel.core.system.html#module-pymel.core.system"><tt class="xref">system</tt></a></li> <li><a class="reference external" href="../../pymel.core.windows.html#module-pymel.core.windows"><tt class="xref">windows</tt></a></li> </ul> <h3><a href="../../../modules.html">Type Modules</a></h3> <ul> <li><a class="reference external" href="../../pymel.core.datatypes.html#module-pymel.core.datatypes"><tt class="xref">datatypes</tt></a></li> <li><a class="reference external" href="../../pymel.core.nodetypes.html#module-pymel.core.nodetypes"><tt class="xref">nodetypes</tt></a></li> <li><a class="reference external" href="../../pymel.core.uitypes.html#module-pymel.core.uitypes"><tt class="xref">uitypes</tt></a></li> </ul> <h3><a href="../../../modules.html">Other Modules</a></h3> <ul> <li><a class="reference external" href="../../pymel.api.plugins.html#module-pymel.api.plugins"><tt class="xref">plugins</tt></a></li> <li><a class="reference external" href="../../pymel.mayautils.html#module-pymel.mayautils"><tt class="xref">mayautils</tt></a></li> <li><a class="reference external" href="../../pymel.util.html#module-pymel.util"><tt class="xref">util</tt></a></li> <li><a class="reference external" href="../../pymel.versions.html#module-pymel.versions"><tt class="xref">versions</tt></a> </li><li><a class="reference external" href="../../pymel.tools.html#module-pymel.tools"><tt class="xref">tools</tt></a></li> </ul> <!-- <ul> <li><a class="reference external" href="../../pymel.core.animation.html.html#module-pymel.core.animation"><tt class="xref">animation</tt></a></li> <li><a class="reference external" href="../../pymel.core.datatypes.html.html#module-pymel.core.datatypes"><tt class="xref">datatypes</tt></a></li> <li><a class="reference external" href="../../pymel.core.effects.html.html#module-pymel.core.effects"><tt class="xref">effects</tt></a></li> <li><a class="reference external" href="../../pymel.core.general.html.html#module-pymel.core.general"><tt class="xref">general</tt></a></li> <li><a class="reference external" href="../../pymel.core.language.html.html#module-pymel.core.language"><tt class="xref">language</tt></a></li> <li><a class="reference external" href="../../pymel.core.modeling.html.html#module-pymel.core.modeling"><tt class="xref">modeling</tt></a></li> <li><a class="reference external" href="../../pymel.core.nodetypes.html.html#module-pymel.core.nodetypes"><tt class="xref">nodetypes</tt></a></li> <li><a class="reference external" href="../../pymel.core.rendering.html.html#module-pymel.core.rendering"><tt class="xref">rendering</tt></a></li> <li><a class="reference external" href="../../pymel.core.system.html.html#module-pymel.core.system"><tt class="xref">system</tt></a></li> <li><a class="reference external" href="../../pymel.core.windows.html.html#module-pymel.core.windows"><tt class="xref">windows</tt></a></li> <li><a class="reference external" href="../../pymel.util.html.html#module-pymel.util"><tt class="xref">pymel.util</tt></a></li> </ul> --> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../../_sources/generated/functions/pymel.core.datatypes/pymel.core.datatypes.fmod.txt" rel="nofollow">Show Source</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form action="http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/search.html" class="search" method="get"></form> <input name="q" type="text"/> <input type="submit" value="Go"/> <input name="check_keywords" type="hidden" value="yes"/> <input name="area" type="hidden" value="default"/> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../../genindex.html" title="General Index">index</a></li> <li class="right"> <a href="../../../py-modindex.html" title="Python Module Index">modules</a> |</li> <li class="right"> <a href="pymel.core.datatypes.frexp.html" title="pymel.core.datatypes.frexp">next</a> |</li> <li class="right"> <a href="pymel.core.datatypes.floor.html" title="pymel.core.datatypes.floor">previous</a> |</li> <li><a href="../../../index-2.html">PyMEL 1.0.7 documentation</a> »</li> <li><a href="../../pymel.core.datatypes.html">pymel.core.datatypes</a> »</li> </ul> </div> <div class="footer"> © Copyright 2009, Chad Dombrova. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.3. </div> <!-- Mirrored from help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/generated/functions/pymel.core.datatypes/pymel.core.datatypes.fmod.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 01 Aug 2015 05:28:20 GMT --> </body></html>
alexwidener/PyMelDocset
PyMel.docset/Contents/Resources/Documents/generated/functions/pymel.core.datatypes/pymel.core.datatypes.fmod.html
HTML
mit
10,394
# DOCKER-VERSION 0.7.2 FROM jarosser06/nodejs MAINTAINER Jim Rosser "jarosser06@gmail.com" RUN apt-get update && apt-get -y install libexpat1-dev libicu-dev RUN npm install --global coffee-script hubot@v2.6.4 RUN hubot --create /opt/hubot WORKDIR /opt/hubot RUN npm install RUN npm install --save hubot-hipchat RUN npm install --save nodepie ADD ./hubot-scripts.json /opt/hubot/hubot-scripts.json CMD ["/opt/hubot/bin/hubot", "--adapter", "hipchat", "--name", "Hubot"]
jarosser06/docker-hubot-hipchat
Dockerfile
Dockerfile
mit
475
package imj.clustering; import static java.lang.Math.abs; import static java.lang.Math.sqrt; import static multij.tools.MathTools.square; /** * @author codistmonk (creation 2013-03-31) */ public abstract interface Distance { public abstract double getDistance(double[] sample1, double[] sample2); public abstract double getDistance(float[] sample1, float[] sample2); public abstract double getDistance(int[] sample1, int[] sample2); /** * @author codistmonk (creation 2013-03-31) */ public static enum Predefined implements Distance { EUCLIDEAN { @Override public final double getDistance(final double[] sample1, final double[] sample2) { final int n = sample1.length; double sumOfSquares = 0.0; for (int i = 0; i < n; ++i) { sumOfSquares += square(sample2[i] - sample1[i]); } return sqrt(sumOfSquares); } @Override public final double getDistance(final float[] sample1, final float[] sample2) { final int n = sample1.length; double sumOfSquares = 0.0; for (int i = 0; i < n; ++i) { sumOfSquares += square(sample2[i] - sample1[i]); } return sqrt(sumOfSquares); } @Override public final double getDistance(final int[] sample1, final int[] sample2) { final int n = sample1.length; double sumOfSquares = 0.0; for (int i = 0; i < n; ++i) { sumOfSquares += square(sample2[i] - sample1[i]); } return sqrt(sumOfSquares); } }, CHI_SQUARE { @Override public final double getDistance(final double[] sample1, final double[] sample2) { final int n = sample1.length; double sumOfSquares = 0.0; for (int i = 0; i < n; ++i) { sumOfSquares += (1.0 + square(sample2[i] - sample1[i])) / (1.0 + abs(sample1[i] + sample2[i])); } return sumOfSquares / 2.0; } @Override public final double getDistance(final float[] sample1, final float[] sample2) { final int n = sample1.length; double sumOfSquares = 0.0; for (int i = 0; i < n; ++i) { sumOfSquares += (1.0 + square(sample2[i] - sample1[i])) / (1.0 + abs(sample1[i] + sample2[i])); } return sumOfSquares / 2.0; } @Override public final double getDistance(final int[] sample1, final int[] sample2) { final int n = sample1.length; double sumOfSquares = 0.0; for (int i = 0; i < n; ++i) { sumOfSquares += (1.0 + square(sample2[i] - sample1[i])) / (1.0 + abs(sample1[i] + sample2[i])); } return sumOfSquares / 2.0; } }, CITYBLOCK { @Override public final double getDistance(final double[] sample1, final double[] sample2) { final int n = sample1.length; double result = 0.0; for (int i = 0; i < n; ++i) { result += abs(sample2[i] - sample1[i]); } return result; } @Override public final double getDistance(final float[] sample1, final float[] sample2) { final int n = sample1.length; double result = 0.0; for (int i = 0; i < n; ++i) { result += abs(sample2[i] - sample1[i]); } return result; } @Override public final double getDistance(final int[] sample1, final int[] sample2) { final int n = sample1.length; double result = 0.0; for (int i = 0; i < n; ++i) { result += abs(sample2[i] - sample1[i]); } return result; } }, CHESSBOARD { @Override public final double getDistance(final double[] sample1, final double[] sample2) { final int n = sample1.length; double result = 0.0; for (int i = 0; i < n; ++i) { final double d = abs(sample2[i] - sample1[i]); if (result < d) { result = d; } } return result; } @Override public final double getDistance(final float[] sample1, final float[] sample2) { final int n = sample1.length; double result = 0.0; for (int i = 0; i < n; ++i) { final double d = abs(sample2[i] - sample1[i]); if (result < d) { result = d; } } return result; } @Override public final double getDistance(final int[] sample1, final int[] sample2) { final int n = sample1.length; double result = 0.0; for (int i = 0; i < n; ++i) { final double d = abs(sample2[i] - sample1[i]); if (result < d) { result = d; } } return result; } }; } }
codistmonk/IMJ
src/imj/clustering/Distance.java
Java
mit
4,471
'use strict'; const gulpMocha = require('gulp-mocha'); module.exports = function (simpleBuild) { const gulp = simpleBuild.gulp; gulp.task('test', ['test:server']); gulp.task('test:watch', ['test:server:watch']); gulp.task('test:server', function () { return gulp.src('./src/server/**/*.spec.js', { read: false }) .pipe(gulpMocha({ reporter: 'spec' })); }); gulp.task('test:server:watch', ['test:server'], function () { gulp.watch('./src/server/**/*.js', ['test:server']); }); };
andrewaramsay/aramsay-build
src/tasks/test.js
JavaScript
mit
513
const EventEmitter = require('events') const stable = require('stable') const glMatrix = require('gl-matrix') const Transform = require('./transform') const AnimatedNumber = require('./animated-number') const AnimatedBoolean = require('./animated-boolean') const Utils = require('./utils') module.exports = class TraceObject extends EventEmitter { constructor () { super() this.parentNode = null this.transform = new Transform() this.opacity = new AnimatedNumber(1) this.enabled = new AnimatedBoolean(true) this.zIndex = new AnimatedNumber(0) this.children = new Set() this.on('connected', () => { for (let i of this.children.values()) i.emit('connected') }) this.on('disconnected', () => { for (let i of this.children.values()) i.emit('disconnected') }) } sortChildren (currentTime, deltaTime) { let values = new Map() for (let i of this.children.values()) { values.set(i, [i.zIndex.getValue(currentTime, deltaTime), i.enabled.getValue(currentTime, deltaTime)]) } let sortedChildren = stable([...values.keys()], (a, b) => { return values.get(a)[0] > values.get(b)[0] }) return { values, children: sortedChildren } } drawChildren (ctx, transform, currentTime, deltaTime) { let {values, children} = this.sortChildren(currentTime, deltaTime) for (let node of children) { if (values.get(node)[1] === true) { Utils.resetCtx(ctx) node.draw(ctx, transform, currentTime, deltaTime) } } } draw (ctx, parentTransform, currentTime, deltaTime) { let rawTransform = this.transform.getMatrix(currentTime, deltaTime) let transform = glMatrix.mat4.create() glMatrix.mat4.multiply(transform, parentTransform, rawTransform) this.drawSelf(ctx, transform, currentTime, deltaTime) this.drawChildren(ctx, transform, currentTime, deltaTime) } drawSelf (ctx, transform, currentTime, deltaTime) {} addChild (...childNodes) { for (let childNode of childNodes) { if (childNode.parentNode !== null && childNode.parentNode !== this) { throw new Error('Child node already has a parent') } this.children.add(childNode) childNode.parentNode = this childNode.emit('connected') } } removeChild (...childNodes) { let removed = [] for (let childNode of childNodes) { if (childNode.parentNode !== this) { throw new Error('Not a child node of this object') } childNode.emit('disconnected') childNode.parentNode = null removed.push(this.children.delete(childNode)) } return removed.length === 1 ? removed[0] : removed } hasChild (childNode) { return this.children.has(childNode) } closest (fn) { if (fn(this)) return this if (this.parentNode) return this.parentNode.closest(fn) return null } addKeys (props) { for (let prop in props) { let property = this for (let key of prop.split('.')) { property = property[key] if (!property) break } if (!property) { console.warn('property not found: ' + prop) continue } let val = props[prop] let didWarn = false if (typeof val === 'object') { for (let time in val) { if (!time.match(/^[+-]?(?:\d+?(?:\.\d+?)?|\.\d+?)?$/)) { this.addKeys({ [`${prop}.${time}`]: val[time] }) continue } let t = parseFloat(time) let v = val[time] if (!Array.isArray(v)) v = [v] if (property.addKey) property.addKey(t, ...v) else if (!didWarn) { console.warn(prop + ' has no addKey method') didWarn = true } } } else { property.defaultValue = val } } } }
cpsdqs/trace-api
trace/object.js
JavaScript
mit
3,832
QString HQt_LatexShowAlert (QString String);
Harrix/HarrixQtLibraryForLaTeX
source_library/Текст/HQt_LatexShowAlert.h
C
mit
44
package com.equinix.amphibia.test; /** * * @author dgofman */ import com.equinix.amphibia.components.ProjectDialog; import junit.framework.Test; import junit.framework.TestCase; import javax.swing.*; import org.junit.Ignore; public class AmphibiaTest extends BaseTest { public AmphibiaTest(String name) throws Exception { super(name); } @Ignore public void testCreateNewProject() throws Exception { JMenu mnuFile = $(instance, "mnuFile"); JMenuItem mnuNewProject = $(instance, "mnuNewProject"); ProjectDialog projectDialog = $(instance, "projectDialog"); JTextField txtSwaggerUrl = $(projectDialog, "txtSwaggerUrl"); JButton btnSwaggerUrl = $(projectDialog, "btnSwaggerUrl"); JButton btnFinish = $(projectDialog, "btnFinish"); JPanel pnlWaitOverlay = $(projectDialog, "pnlWaitOverlay"); JPanel pnlAddHeader = $(mainPanel.wizard, "pnlAddHeader"); JPanel pnlInterface = $(mainPanel.wizard, "pnlInterface"); JButton btnAddRow = $(mainPanel.wizard, "btnAddRow"); JTextField txtHeaderName = $(mainPanel.wizard, "txtHeaderName"); JTextField txtHeaderValue = $(mainPanel.wizard, "txtHeaderValue"); JCheckBox ckbAsGlobal = $(mainPanel.wizard, "ckbAsGlobal"); doClick(mnuFile); invokeLater(() -> { doClick(mnuNewProject); }); findDialog("Amphibia12", projectDialog); txtSwaggerUrl.setText("https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/json/api-with-examples.json"); doClick(btnSwaggerUrl); waitIsTrue(() -> { return !pnlWaitOverlay.isVisible(); }); doClick(btnFinish); findDialog("Amphibia3", pnlInterface); invokeLater(() -> { doClick(btnAddRow); }); Dialog popupPnlAddHeader = findDialog("Amphibia17", pnlAddHeader); JButton apply = popupPnlAddHeader.getButton("apply"); setText(txtHeaderName, "CONTENT-TYPE"); setText(txtHeaderValue, "application/json"); doClick(ckbAsGlobal); doClick(apply); JButton applyInterfaceButton = $(mainPanel.wizard, "applyInterfaceButton"); doClick(applyInterfaceButton); TestCase.assertEquals("SimpleAPIoverview", getCollection().project.getLabel()); } public static Test suite() { return BaseTest.suite(AmphibiaTest.class); } }
equinix/amphibia
client/src/test/java/com/equinix/amphibia/test/AmphibiaTest.java
Java
mit
2,456
require File.expand_path('../../test_helper', __FILE__) module KickstarterStripe class AccountTest < Test::Unit::TestCase should "account should be retrievable" do resp = {:email => "test+bindings@stripe.com", :charge_enabled => false, :details_submitted => false} @mock.expects(:get).once.returns(test_response(resp)) a = KickstarterStripe::Account.retrieve assert_equal "test+bindings@stripe.com", a.email assert !a.charge_enabled assert !a.details_submitted end should "be able to deauthorize an account" do resp = {:id => 'acct_1234', :email => "test+bindings@stripe.com", :charge_enabled => false, :details_submitted => false} @mock.expects(:get).once.returns(test_response(resp)) a = KickstarterStripe::Account.retrieve @mock.expects(:post).once.with do |url, api_key, params| url == "#{KickstarterStripe.connect_base}/oauth/deauthorize" && api_key.nil? && CGI.parse(params) == { 'client_id' => [ 'ca_1234' ], 'stripe_user_id' => [ a.id ]} end.returns(test_response({ 'stripe_user_id' => a.id })) a.deauthorize('ca_1234', 'sk_test_1234') end end end
finbarr/kickstarter_stripe
test/stripe/account_test.rb
Ruby
mit
1,160
// // The MIT License (MIT) // // Copyright (c) 2015 Microsoft // // 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. // // ThaliMobile // THEAppContext.h // #import <Foundation/Foundation.h> // THEAppContext interface. @interface THEAppContext : NSObject // Class singleton. + (instancetype)singleton; // Starts communications. - (void)startCommunications; // Stops communications. - (void)stopCommunications; @end
thaliproject/ThaliMobile-iOS-OLD
ThaliMobile/Classes/THEAppContext.h
C
mit
1,461
<!-- Generated by documentation.js. Update this documentation by updating the source code. --> ### Table of Contents - [DOM Interaction Helpers](#dom-interaction-helpers) - [click](#click) - [tap](#tap) - [focus](#focus) - [blur](#blur) - [triggerEvent](#triggerevent) - [triggerKeyEvent](#triggerkeyevent) - [fillIn](#fillin) - [DOM Query Helpers](#dom-query-helpers) - [find](#find) - [findAll](#findall) - [getRootElement](#getrootelement) - [Routing Helpers](#routing-helpers) - [visit](#visit) - [currentRouteName](#currentroutename) - [currentURL](#currenturl) - [Rendering Helpers](#rendering-helpers) - [render](#render) - [clearRender](#clearrender) - [Wait Helpers](#wait-helpers) - [waitFor](#waitfor) - [waitUntil](#waituntil) - [settled](#settled) - [isSettled](#issettled) - [getSettledState](#getsettledstate) - [Pause Helpers](#pause-helpers) - [pauseTest](#pausetest) - [resumeTest](#resumetest) - [Test Framework APIs](#test-framework-apis) - [setResolver](#setresolver) - [getResolver](#getresolver) - [setupContext](#setupcontext) - [getContext](#getcontext) - [setContext](#setcontext) - [unsetContext](#unsetcontext) - [teardownContext](#teardowncontext) - [setupRenderingContext](#setuprenderingcontext) - [teardownRenderingContext](#teardownrenderingcontext) - [getApplication](#getapplication) - [setApplication](#setapplication) - [setupApplicationContext](#setupapplicationcontext) - [teardownApplicationContext](#teardownapplicationcontext) - [validateErrorHandler](#validateerrorhandler) ## DOM Interaction Helpers ### click Clicks on the specified target. Sends a number of events intending to simulate a "real" user clicking on an element. For non-focusable elements the following events are triggered (in order): - `mousedown` - `mouseup` - `click` For focusable (e.g. form control) elements the following events are triggered (in order): - `mousedown` - `focus` - `focusin` - `mouseup` - `click` The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle clicking a given element. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to click on Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### tap Taps on the specified target. Sends a number of events intending to simulate a "real" user tapping on an element. For non-focusable elements the following events are triggered (in order): - `touchstart` - `touchend` - `mousedown` - `mouseup` - `click` For focusable (e.g. form control) elements the following events are triggered (in order): - `touchstart` - `touchend` - `mousedown` - `focus` - `focusin` - `mouseup` - `click` The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle tapping on a given element. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to tap on - `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the options to be provided to the touch events (optional, default `{}`) Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### focus Focus the specified target. Sends a number of events intending to simulate a "real" user focusing an element. The following events are triggered (in order): - `focus` - `focusin` The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle focusing a given element. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to focus Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when the application is settled ### blur Unfocus the specified target. Sends a number of events intending to simulate a "real" user unfocusing an element. The following events are triggered (in order): - `blur` - `focusout` The exact listing of events that are triggered may change over time as needed to continue to emulate how actual browsers handle unfocusing a given element. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to unfocus (optional, default `document.activeElement`) Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### triggerEvent Triggers an event on the specified target. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to trigger the event on - `eventType` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the type of event to trigger - `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** additional properties to be set on the event Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when the application is settled ### triggerKeyEvent Triggers a keyboard event of given type in the target element. It also requires the developer to provide either a string with the [`key`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) or the numeric [`keyCode`](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) of the pressed key. Optionally the user can also provide a POJO with extra modifiers for the event. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to trigger the event on - `eventType` **(`"keydown"` \| `"keyup"` \| `"keypress"`)** the type of event to trigger - `key` **([number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) \| [string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String))** the `keyCode`(number) or `key`(string) of the event being triggered - `modifiers` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** the state of various modifier keys (optional, default `DEFAULT_MODIFIERS`) - `modifiers.ctrlKey` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** if true the generated event will indicate the control key was pressed during the key event (optional, default `false`) - `modifiers.altKey` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** if true the generated event will indicate the alt key was pressed during the key event (optional, default `false`) - `modifiers.shiftKey` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** if true the generated event will indicate the shift key was pressed during the key event (optional, default `false`) - `modifiers.metaKey` **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** if true the generated event will indicate the meta key was pressed during the key event (optional, default `false`) Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when the application is settled ### fillIn Fill the provided text into the `value` property (or set `.innerHTML` when the target is a content editable element) then trigger `change` and `input` events on the specified target. **Parameters** - `target` **([string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String) \| [Element](https://developer.mozilla.org/docs/Web/API/Element))** the element or selector to enter text into - `text` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the text to fill into the target element Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when the application is settled ## DOM Query Helpers ### find Find the first element matched by the given selector. Equivalent to calling `querySelector()` on the test root element. **Parameters** - `selector` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the selector to search for Returns **[Element](https://developer.mozilla.org/docs/Web/API/Element)** matched element or null ### findAll Find all elements matched by the given selector. Equivalent to calling `querySelectorAll()` on the test root element. **Parameters** - `selector` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the selector to search for Returns **[Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)** array of matched elements ### getRootElement Get the root element of the application under test (usually `#ember-testing`) Returns **[Element](https://developer.mozilla.org/docs/Web/API/Element)** the root element ## Routing Helpers ### visit Navigate the application to the provided URL. Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### currentRouteName Returns **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the currently active route name ### currentURL Returns **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the applications current url ## Rendering Helpers ### render Renders the provided template and appends it to the DOM. **Parameters** - `template` **CompiledTemplate** the template to render Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### clearRender Clears any templates previously rendered. This is commonly used for confirming behavior that is triggered by teardown (e.g. `willDestroyElement`). Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ## Wait Helpers ### waitFor Used to wait for a particular selector to appear in the DOM. Due to the fact that it does not wait for general settledness, this is quite useful for testing interim DOM states (e.g. loading states, pending promises, etc). **Parameters** - `selector` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the selector to wait for - `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** the options to be used (optional, default `{}`) - `options.timeout` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the time to wait (in ms) for a match (optional, default `1000`) - `options.count` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the number of elements that should match the provided selector (null means one or more) (optional, default `null`) - `options.timeoutMessage` (optional, default `'waitFor timed out'`) Returns **([Element](https://developer.mozilla.org/docs/Web/API/Element) \| [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array)&lt;[Element](https://developer.mozilla.org/docs/Web/API/Element)>)** the element (or array of elements) that were being waited upon ### waitUntil Wait for the provided callback to return a truthy value. This does not leverage `settled()`, and as such can be used to manage async while _not_ settled (e.g. "loading" or "pending" states). **Parameters** - `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** the callback to use for testing when waiting should stop - `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** options used to override defaults (optional, default `{}`) - `options.timeout` **[number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)** the maximum amount of time to wait (optional, default `1000`) - `options.timeoutMessage` **[string](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String)** the message to use in the reject on timeout (optional, default `'waitUntil timed out'`) Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)** resolves with the callback value when it returns a truthy value ### settled Returns a promise that resolves when in a settled state (see `isSettled` for a definition of "settled state"). Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### isSettled Checks various settledness metrics (via `getSettledState()`) to determine if things are settled or not. Settled generally means that there are no pending timers, no pending waiters, no pending AJAX requests, and no current run loop. However, new settledness metrics may be added and used as they become available. Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** `true` if settled, `false` otherwise ### getSettledState Check various settledness metrics, and return an object with the following properties: `hasRunLoop` - Checks if a run-loop has been started. If it has, this will be `true` otherwise it will be `false`. `hasPendingTimers` - Checks if there are scheduled timers in the run-loop. These pending timers are primarily registered by `Ember.run.schedule`. If there are pending timers, this will be `true`, otherwise `false`. `hasPendingWaiters` - Checks if any registered test waiters are still pending (e.g. the waiter returns `true`). If there are pending waiters, this will be `true`, otherwise `false`. `hasPendingRequests` - Checks if there are pending AJAX requests (based on `ajaxSend` / `ajaxComplete` events triggered by `jQuery.ajax`). If there are pending requests, this will be `true`, otherwise `false`. `pendingRequestCount` - The count of pending AJAX requests. Returns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** object with properties for each of the metrics used to determine settledness ## Pause Helpers ### pauseTest Returns a promise to be used to pauses the current test (due to being returned from the test itself). This is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. The test framework wrapper (e.g. `ember-qunit` or `ember-mocha`) should ensure that when `pauseTest()` is used, any framework specific test timeouts are disabled. **Examples** _Usage via ember-qunit_ ```javascript import { setupRenderingTest } from 'ember-qunit'; import { render, click, pauseTest } from '@ember/test-helpers'; module('awesome-sauce', function(hooks) { setupRenderingTest(hooks); test('does something awesome', async function(assert) { await render(hbs`{{awesome-sauce}}`); // added here to visualize / interact with the DOM prior // to the interaction below await pauseTest(); click('.some-selector'); assert.equal(this.element.textContent, 'this sauce is awesome!'); }); }); ``` Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves _only_ when `resumeTest()` is invoked ### resumeTest Resumes a test previously paused by `await pauseTest()`. ## Test Framework APIs ### setResolver Stores the provided resolver instance so that tests being ran can resolve objects in the same way as a normal application. Used by `setupContext` and `setupRenderingContext` as a fallback when `setApplication` was _not_ used. **Parameters** - `resolver` **Ember.Resolver** the resolver to be used for testing ### getResolver Retrieve the resolver instance stored by `setResolver`. Returns **Ember.Resolver** the previously stored resolver ### setupContext Used by test framework addons to setup the provided context for testing. Responsible for: - sets the "global testing context" to the provided context (`setContext`) - create an owner object and set it on the provided context (e.g. `this.owner`) - setup `this.set`, `this.setProperties`, `this.get`, and `this.getProperties` to the provided context - setting up AJAX listeners - setting up `pauseTest` (also available as `this.pauseTest()`) and `resumeTest` helpers **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to setup - `options` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)?** options used to override defaults (optional, default `{}`) - `options.resolver` **Resolver?** a resolver to use for customizing normal resolution Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>** resolves with the context that was setup ### getContext Retrive the "global testing context" as stored by `setContext`. Returns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the previously stored testing context ### setContext Stores the provided context as the "global testing context". Generally setup automatically by `setupContext`. **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to use ### unsetContext Clear the "global testing context". Generally invoked from `teardownContext`. ### teardownContext Used by test framework addons to tear down the provided context after testing is completed. Responsible for: - un-setting the "global testing context" (`unsetContext`) - destroy the contexts owner object - remove AJAX listeners **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to setup Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### setupRenderingContext Used by test framework addons to setup the provided context for rendering. `setupContext` must have been ran on the provided context prior to calling `setupRenderingContext`. Responsible for: - Setup the basic framework used for rendering by the `render` helper. - Ensuring the event dispatcher is properly setup. - Setting `this.element` to the root element of the testing container (things rendered via `render` will go _into_ this element). **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to setup for rendering Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>** resolves with the context that was setup ### teardownRenderingContext Used by test framework addons to tear down the provided context after testing is completed. Responsible for: - resetting the `ember-testing-container` to its original state (the value when `setupRenderingContext` was called). **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to setup Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### getApplication Retrieve the application instance stored by `setApplication`. Returns **Ember.Application** the previously stored application instance under test ### setApplication Stores the provided application instance so that tests being ran will be aware of the application under test. - Required by `setupApplicationContext` method. - Used by `setupContext` and `setupRenderingContext` when present. **Parameters** - `application` **Ember.Application** the application that will be tested ### setupApplicationContext Used by test framework addons to setup the provided context for working with an application (e.g. routing). `setupContext` must have been ran on the provided context prior to calling `setupApplicatinContext`. Sets up the basic framework used by application tests. **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to setup Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)>** resolves with the context that was setup ### teardownApplicationContext Used by test framework addons to tear down the provided context after testing is completed. **Parameters** - `context` **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** the context to setup Returns **[Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)&lt;void>** resolves when settled ### validateErrorHandler Validate the provided error handler to confirm that it properly re-throws errors when `Ember.testing` is true. This is intended to be used by test framework hosts (or other libraries) to ensure that `Ember.onerror` is properly configured. Without a check like this, `Ember.onerror` could _easily_ swallow all errors and make it _seem_ like everything is just fine (and have green tests) when in reality everything is on fire... **Parameters** - `callback` **[Function](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function)** the callback to validate (optional, default `Ember.onerror`) **Examples** _Example implementation for `ember-qunit`_ ```javascript import { validateErrorHandler } from '@ember/test-helpers'; test('Ember.onerror is functioning properly', function(assert) { let result = validateErrorHandler(); assert.ok(result.isValid, result.message); }); ``` Returns **[Object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object)** object with `isValid` and `message`
gabz75/ember-cli-deploy-redis-publish
node_modules/@ember/test-helpers/API.md
Markdown
mit
23,876
// @formatter:off /* * --------------------------------------------------------- * Copyright(C) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. See License.txt in the project root. * --------------------------------------------------------- * * --------------------------------------------------------- * Generated file, DO NOT EDIT * --------------------------------------------------------- * * See following wiki page for instructions on how to regenerate: * https://vsowiki.com/index.php?title=Rest_Client_Generation */ package com.microsoft.alm.teamfoundation.core.webapi; /** */ public class WebApiProjectCollection extends WebApiProjectCollectionRef { /** * Project collection description */ private String description; /** * Project collection state */ private String state; /** * Project collection description */ public String getDescription() { return description; } /** * Project collection description */ public void setDescription(final String description) { this.description = description; } /** * Project collection state */ public String getState() { return state; } /** * Project collection state */ public void setState(final String state) { this.state = state; } }
Microsoft/vso-httpclient-java
Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/core/webapi/WebApiProjectCollection.java
Java
mit
1,375
from __future__ import absolute_import from .base import * from bundle_config import config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config['postgres']['database'], 'USER': config['postgres']['username'], 'PASSWORD': config['postgres']['password'], 'HOST': config['postgres']['host'], } } CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': '{host}:{port}'.format( host=config['redis']['host'], port=config['redis']['port']), 'OPTIONS': { 'PASSWORD': config['redis']['password'], }, 'VERSION': config['core']['version'], }, } DEBUG = False
almet/whiskerboard
settings/epio.py
Python
mit
751
$(function() { var select = $( "#minbeds" ); var slider = $( "<div id='slider'></div>" ).insertAfter( select ).slider({ min: 1, max: 4, range: "min", value: select[ 0 ].selectedIndex + 1, slide: function( event, ui ) { select[ 0 ].selectedIndex = ui.value - 1; } }); $( "#minbeds" ).change(function() { slider.slider( "value", this.selectedIndex + 1 ); }); });
volterra-luo/cocoa
alipay/templates/alipay/myapp.js
JavaScript
mit
447
package com.sap.openui5; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.tools.shell.Global; /** * The class <code>LessFilter</code> is used to compile CSS for Less files * on the fly - once they are requested by the application. * <p> * <i>This class must not be used in productive systems.</i> * * @author Peter Muessig, Matthias Osswald */ public class LessFilter implements Filter { /** default prefix for the classpath */ private static final String CLASSPATH_PREFIX = "META-INF"; /** pattern to identify a theme request */ private static final Pattern PATTERN_THEME_REQUEST = Pattern.compile("(.*)/(library\\.css|library-RTL\\.css|library-parameters\\.json)$"); /** pattern to identify a theme request */ private static final Pattern PATTERN_THEME_REQUEST_PARTS = Pattern.compile("(/resources/(.*)/themes/)([^/]*)/.*"); /** base path for the less JS sources*/ private static final String LESS_PATH = CLASSPATH_PREFIX + "/less/"; /** array of scripts for the rhino less instance */ private static final String[] LESS_JS = { "less-env.js", "less.js", "less-rtl-plugin.js", "less-api.js" }; /** keeps the scope of the rhino */ private Scriptable scope; /** function to parse the less input */ private Function parse; /** filter configuration */ private FilterConfig config; /** map for the lastModified timestamps for up-to-date check (library.source.less path --> max timestamp of all less files) */ private Map<String, Long> lastModified = new HashMap<String, Long>(); /** cache for the generated resources (resource path --> content) */ private Map<String, String> cache = new HashMap<String, String>(); /* (non-Javadoc) * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ public void init(FilterConfig filterConfig) throws ServletException { // keep the filter configuration this.config = filterConfig; // initialize the Less Compiler in the Rhino container try { // create a new JS execution context Context context = Context.enter(); context.setOptimizationLevel(9); context.setLanguageVersion(Context.VERSION_1_7); // initialize the global context sharing object Global global = new Global(); global.init(context); // create the scope this.scope = context.initStandardObjects(global); // load the scripts and evaluate them in the Rhino context ClassLoader loader = LessFilter.class.getClassLoader(); for (String script : LESS_JS) { URL url = loader.getResource(LESS_PATH + script); Reader reader = new InputStreamReader(url.openStream(), "UTF-8"); context.evaluateReader(this.scope, reader, script, 1, null); } // get environment object and set the resource loader used in less (see less-api.js) Scriptable env = (Scriptable) this.scope.get("__env", this.scope); env.put("resourceLoader", env, Context.javaToJS(new ResourceLoader(), this.scope)); // keep the reference to the JS less API this.parse = (Function) this.scope.get("parse", this.scope); } catch (Exception ex) { String message = "Failed to initialize LESS compiler!"; throw new ServletException(message, ex); } finally { // exit the context Context.exit(); } } // method: init /* (non-Javadoc) * @see javax.servlet.Filter#destroy() */ public void destroy() { this.parse = null; this.scope = null; this.config = null; } // method: destroy /* (non-Javadoc) * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // make sure that the request/response are http request/response if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { // determine the path of the request HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String method = httpRequest.getMethod().toUpperCase(); // NOSONAR String path = httpRequest.getServletPath() + httpRequest.getPathInfo(); // only process GET or HEAD requests if (method.matches("GET|HEAD")) { // compile the less if required (up-to-date check happens in the compile function) Matcher m = PATTERN_THEME_REQUEST.matcher(path); if (m.matches()) { // check for existence of the resource URL url = this.findResource(path); if (url == null) { String prefixPath = m.group(1); String sourcePath = prefixPath + "/library.source.less"; this.compile(sourcePath, false, false); // return the cached CSS or JSON file if (this.cache.containsKey(path)) { httpResponse.setStatus(HttpServletResponse.SC_OK); response.setContentType(this.config.getServletContext().getMimeType(path)); httpResponse.addDateHeader("Last-Modified", this.lastModified.get(sourcePath)); if ("GET".equals(method)) { OutputStream os = response.getOutputStream(); IOUtils.write(this.cache.get(path), os, "UTF-8"); IOUtils.closeQuietly(os); os.flush(); os.close(); } return; } } else { this.log("The resource " + path + " already exists and will not be compiled on-the-fly."); } } } } // proceed in the filter chain chain.doFilter(request, response); } // method: doFilter /** * logs the message prepended by the filter name (copy of {@link GenericServlet#log(String)}) * @param msg the message */ private void log(String msg) { this.config.getServletContext().log(this.config.getFilterName() + ": "+ msg); } // method: log /** * logs the message and <code>Throwable</code> prepended by the filter name (copy of {@link GenericServlet#log(String, Throwable)}) * @param msg the message * @param t the <code>Throwable</code> */ private void log(String msg, Throwable t) { this.config.getServletContext().log(this.config.getFilterName() + ": "+ msg, t); } // method: log /** * finds the resource for the given path * @param path path of the resource * @return URL to the resource or null * @throws MalformedURLException */ private URL findResource(String path) throws MalformedURLException { // normalize the path (JarURLConnection cannot resolve non-normalized paths) String normalizedPath = URI.create(path).normalize().toString(); // define the classpath for the classloader lookup String classPath = CLASSPATH_PREFIX + normalizedPath; // first lookup the resource in the web context path URL url = this.config.getServletContext().getResource(normalizedPath); // lookup the resource in the current threads classloaders if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(classPath); } // lookup the resource in the local classloader if (url == null) { url = ResourceServlet.class.getClassLoader().getResource(classPath); } return url; } // method: findResource /** * determines the max last modified timestamp for the given paths * @param paths array of paths * @return max last modified timestamp */ private long getMaxLastModified(String[] paths) { long lastModified = -1; try { for (String path : paths) { URL url = this.findResource(path); if (url != null) { URLConnection c = url.openConnection(); c.connect(); lastModified = Math.max(lastModified, c.getLastModified()); } } } catch (Exception ex) { this.log("Failed to determine max last modified timestamp.", ex); } return lastModified; } // method: getMaxLastModified /** * compiles the CSS, RTL-CSS and theme parameters as JSON * @param sourcePath source path * @param compressCSS true, if CSS should be compressed * @param compressJSON true if JSON should be compressed */ private void compile(String sourcePath, boolean compressCSS, boolean compressJSON) { Matcher m = PATTERN_THEME_REQUEST_PARTS.matcher(sourcePath); if (m.matches()) { // extract the relevant parts from the request path String prefixPath = m.group(1); String library = m.group(2); String libraryName = library.replace('/', '.'); String theme = m.group(3); String path = prefixPath + theme + "/"; try { URL url = this.findResource(sourcePath); if (url != null) { // read the library.source.less URLConnection conn = url.openConnection(); conn.connect(); // up-to-date check String resources = this.cache.get(path + "resources"); long lastModified = resources != null ? this.getMaxLastModified(resources.split(";")) : -1; if (!this.lastModified.containsKey(sourcePath) || this.lastModified.get(sourcePath) < lastModified) { // some info this.log("Compiling CSS/JSON of library " + libraryName + " for theme " + theme); // read the content InputStream is = conn.getInputStream(); String input = IOUtils.toString(is, "UTF-8"); IOUtils.closeQuietly(is); // time measurement begin long millis = System.currentTimeMillis(); // compile the CSS/JSON Scriptable result = this.compileCSS(input, path, compressCSS, compressJSON, libraryName); // cache the result String css = Context.toString(ScriptableObject.getProperty((Scriptable) result, "css")); this.cache.put(path + "library.css", css); String rtlCss = Context.toString(ScriptableObject.getProperty((Scriptable) result, "cssRtl")); this.cache.put(path + "library-RTL.css", rtlCss); String json = Context.toString(ScriptableObject.getProperty((Scriptable) result, "json")); this.cache.put(path + "library-parameters.json", json); resources = Context.toString(ScriptableObject.getProperty((Scriptable) result, "resources")); this.cache.put(path + "resources", resources); // log the compile duration this.log(" => took " + (System.currentTimeMillis() - millis) + "ms"); // store when the resource has been compiled this.lastModified.put(sourcePath, this.getMaxLastModified(resources.split(";"))); } } else { this.log("The less source file cannot be found: " + sourcePath); } } catch (Exception ex) { // in case of error we also cleanup the cache! this.log("Failed to compile CSS for " + sourcePath, ex); this.cache.remove(path + "library.css"); this.cache.remove(path + "library-RTL.css"); this.cache.remove(path + "library-parameters.json"); this.cache.remove(path + "resources"); this.lastModified.remove(sourcePath); } } } // method: compile /** * compiles the CSS, RTL-CSS and theme parameters as JSON * @param input less input * @param path source path * @param compressCSS true, if CSS should be compressed * @param compressJSON true if JSON should be compressed * @param libraryName name of the library */ private synchronized Scriptable compileCSS(String input, String path, boolean compressCSS, boolean compressJSON, String libraryName) { // compile the CSS/JSON within the Rhino environment return (Scriptable) Context.call(null, this.parse, this.scope, this.scope, new Object[] { input, path, compressCSS, compressJSON, libraryName }); } // method: compileCSS /** * The <code>ResourceLoader</code> is used to load dedicated resources * requested by Rhino out of the classpath. */ public class ResourceLoader { /** * loads a resource for the specified path * @param path path of the resource */ public String load(String path) throws IOException { String content = null; URL resource = LessFilter.this.findResource(path); if (resource != null) { InputStream is = resource.openStream(); content = IOUtils.toString(is, "UTF-8"); IOUtils.closeQuietly(is); } return content; } // method: load } // inner class: ResourceLoader } // class: LessFilter
awolfish/timetableservices
client/src/main/java/com/sap/openui5/LessFilter.java
Java
mit
13,634
angular.module('app.controllers.kda', ['app.services.data', 'app.services.options']) .controller('KdaController', ['$scope', 'Data', 'Options', function ($scope, Data, Options) { console.log('kda chart controller', $scope) Data.data.getKdaData($scope); $scope.$watch('kills + deaths + assists', function() { if($scope.kills && $scope.deaths && $scope.assists) { $scope.chart = [ { value: $scope.kills, color: "rgba(22,79,16,1)" }, { value : $scope.deaths, color : "rgba(189,16,13,1)" }, { value: $scope.assists, color: "rgba(88,156,173,1)" } ]; } }) $scope.options = Options.kdaOptions }])
ekiwan/Dotametrics
public/scripts/controllers/kda.js
JavaScript
mit
774
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_console_w32_execv_62b.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-62b.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: w32_execv * BadSink : execute command with execv * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT "cmd.exe" #define COMMAND_ARG1 "/c" #define COMMAND_ARG2 "dir" #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH "/bin/sh" #define COMMAND_INT "sh" #define COMMAND_ARG1 "ls" #define COMMAND_ARG2 "-la" #define COMMAND_ARG3 data #endif namespace CWE78_OS_Command_Injection__char_console_w32_execv_62 { #ifndef OMITBAD void badSource(char * &data) { { /* Read input from the console */ size_t dataLen = strlen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgets() */ dataLen = strlen(data); if (dataLen > 0 && data[dataLen-1] == '\n') { data[dataLen-1] = '\0'; } } else { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ void goodG2BSource(char * &data) { /* FIX: Append a fixed string to data (not user / external input) */ strcat(data, "*.*"); } #endif /* OMITGOOD */ } /* close namespace */
maurer/tiamat
samples/Juliet/testcases/CWE78_OS_Command_Injection/s02/CWE78_OS_Command_Injection__char_console_w32_execv_62b.cpp
C++
mit
2,302
<!DOCTYPE html> <html lang="en"> <head> <title>Classes Reference</title> <link rel="stylesheet" type="text/css" href="css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="css/highlight.css" /> <meta charset='utf-8'> <script src="js/jquery.min.js" defer></script> <script src="js/jazzy.js" defer></script> </head> <body> <a title="Classes Reference"></a> <header> <div class="content-wrapper"> <p><a href="index.html"> Docs</a> (92% documented)</p> </div> </header> <div class="content-wrapper"> <p id="breadcrumbs"> <a href="index.html"> Reference</a> <img id="carat" src="img/carat.png" /> Classes Reference </p> </div> <div class="content-wrapper"> <nav class="sidebar"> <ul class="nav-groups"> <li class="nav-group-name"> <a href="Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Classes/WPJsonDecoder.html">WPJsonDecoder</a> </li> <li class="nav-group-task"> <a href="Classes/WPJsonEncoder.html">WPJsonEncoder</a> </li> <li class="nav-group-task"> <a href="Classes/WPXmlEncoder.html">WPXmlEncoder</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Enums.html">Enums</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Enums/WPValue.html">WPValue</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Extensions/Bool.html">Bool</a> </li> <li class="nav-group-task"> <a href="Extensions/Double.html">Double</a> </li> <li class="nav-group-task"> <a href="Extensions/Int.html">Int</a> </li> <li class="nav-group-task"> <a href="Extensions/String.html">String</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Protocols/WPDecoder.html">WPDecoder</a> </li> <li class="nav-group-task"> <a href="Protocols/WPElement.html">WPElement</a> </li> <li class="nav-group-task"> <a href="Protocols/WPEncodable.html">WPEncodable</a> </li> <li class="nav-group-task"> <a href="Protocols/WPEncoder.html">WPEncoder</a> </li> </ul> </li> <li class="nav-group-name"> <a href="Structs.html">Structs</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a href="Structs/WPJson.html">WPJson</a> </li> <li class="nav-group-task"> <a href="Structs/WPXml.html">WPXml</a> </li> <li class="nav-group-task"> <a href="Structs/WPXmlDecoder.html">WPXmlDecoder</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section> <section class="section"> <h1>Classes</h1> <p>The following classes are available globally.</p> </section> <section class="section task-group-section"> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:C10WebParsing13WPJsonDecoder"></a> <a name="//apple_ref/swift/Class/WPJsonDecoder" class="dashAnchor"></a> <a class="token" href="#/s:C10WebParsing13WPJsonDecoder">WPJsonDecoder</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Undocumented</p> <a href="Classes/WPJsonDecoder.html" class="slightly-smaller">See more</a> </div> </section> </div> </li> </ul> </div> <div class="task-group"> <ul> <li class="item"> <div> <code> <a name="/s:C10WebParsing13WPJsonEncoder"></a> <a name="//apple_ref/swift/Class/WPJsonEncoder" class="dashAnchor"></a> <a class="token" href="#/s:C10WebParsing13WPJsonEncoder">WPJsonEncoder</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>This class is used to encode <code><a href="Protocols/WPEncodable.html">WPEncodable</a></code> objects as Json. When attributes are tried to encode, the class simply does nothing as Json doesn&rsquo;t support element attributes.</p> <a href="Classes/WPJsonEncoder.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="kt">WPJsonEncoder</span><span class="p">:</span> <span class="kt"><a href="Protocols/WPEncoder.html">WPEncoder</a></span></code></pre> </div> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/s:C10WebParsing12WPXmlEncoder"></a> <a name="//apple_ref/swift/Class/WPXmlEncoder" class="dashAnchor"></a> <a class="token" href="#/s:C10WebParsing12WPXmlEncoder">WPXmlEncoder</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>This class is used to encode <code><a href="Protocols/WPEncodable.html">WPEncodable</a></code> objects as Xml. Attributes</p> <a href="Classes/WPXmlEncoder.html" class="slightly-smaller">See more</a> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="kt">WPXmlEncoder</span><span class="p">:</span> <span class="kt"><a href="Protocols/WPEncoder.html">WPEncoder</a></span></code></pre> </div> </div> </section> </div> </li> </ul> </div> </section> </section> <section id="footer"> <p>&copy; 2016 <a class="link" href="" target="_blank" rel="external"></a>. All rights reserved. (Last updated: 2016-12-28)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.7.3</a>, a <a class="link" href="http://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </article> </div> </body> </div> </html>
borchero/WebParsing
docs/docsets/.docset/Contents/Resources/Documents/Classes.html
HTML
mit
8,548
.iliveinomaha { display: block; text-align: center; font-family: sans-serif; } .iliveinomaha a { display: block; padding: .1em 0; text-decoration: none; font-weight: bold; color: #3399ff; } @media only all { .iliveinomaha { position: absolute; top: 0; right: 0; width: 7em; height: 7em; font-size: .625em; line-height: 120%; overflow: hidden; pointer-events: none; } .iliveinomaha a { font-weight: normal; background: #3399ff; width: 10em; pointer-events: auto; -webkit-transform: translateY(2.3em) translateX(-.8em) rotate(45deg); -ms-transform: translateY(2.3em) translateX(-.8em) rotate(45deg); transform: translateY(2.3em) translateX(-.8em) rotate(45deg); } .iliveinomaha a, .iliveinomaha :link, .iliveinomaha :visited { color: #fff; } .iliveinomaha :hover { background: rgba(51, 153, 255, .9); } .iliveinomaha.left { right: auto; left: 0; } .iliveinomaha.left a { -webkit-transform: translateY(2.3em) translateX(-2em) rotate(-45deg); -ms-transform: translateY(2.3em) translateX(-2em) rotate(-45deg); transform: translateY(2.3em) translateX(-2em) rotate(-45deg); } } @media (min-width: 30em) { .iliveinomaha { font-size: 1em; width: 9em; height: 9em; } .iliveinomaha a { width: 15em; -webkit-transform: translateY(2.2em) translateX(-1.5em) rotate(45deg); -ms-transform: translateY(2.2em) translateX(-1.5em) rotate(45deg); transform: translateY(2.2em) translateX(-1.5em) rotate(45deg); } .iliveinomaha.left a { -webkit-transform: translateY(2.2em) translateX(-4.5em) rotate(-45deg); -ms-transform: translateY(2.2em) translateX(-4.5em) rotate(-45deg); transform: translateY(2.2em) translateX(-4.5em) rotate(-45deg); } }
zachleat/iliveinomaha-banner
iliveinomaha.css
CSS
mit
1,718
// // Created by Yuanjun Xiong on 18/11/2015. // #ifndef DENSEFLOW_UTILS_H #define DENSEFLOW_UTILS_H #include "common.h" void writeZipFile(std::vector<std::vector<uchar> >& data, std::string name_temp, std::string archive_name); #endif //DENSEFLOW_UTILS_H
gss-ucas/dense_flow
include/utils.h
C
mit
260
md5Check() { # DESC: Compares an md5 hash to the md5 hash of a file # ARGS: None # OUTS: None # USAGE: md5Check <md5> <filename> local opt local OPTIND=1 local md5="$1" local file="$2" if ! command -v md5sum &>/dev/null; then echo "Can not find 'md5sum' utility" return 1 fi [ ! -e "${file}" ] \ && { echo "Can not find ${file}" return 1 } # Get md5 has of file local filemd5 filemd5="$(md5sum "${file}" | awk '{ print $1 }')" if [[ $filemd5 == "$md5" ]]; then success "The two md5 hashes match" return 0 else warning "The two md5 hashes do not match" return 1 fi } zipf() { zip -r "$1".zip "$1"; } # Create a ZIP archive of a folder or file alias numFiles='echo $(ls -1 | wc -l)' # Count of non-hidden files in current dir alias make1mb='mkfile 1m ./1MB.dat' # Creates a file of 1mb size (all zeros) # Creates a file of 5mb size (all zeros) alias make5mb='mkfile 5m ./5MB.dat' # Creates a file of 10mb size (all zeros) alias make10mb='mkfile 10m ./10MB.dat' copyfile() ( # DESC: Copy contents of a file to the clipboard # ARGS: 1 (Required) - Path to file if [ -n "$1" ] && [ -f "$1" ]; then pbcopy <"${1}" return 0 else printf "File not found: %s\n" "$1" return 1 fi ) buf() { # buf : Backup file with time stamp local filename local filetime filename="${1}" filetime=$(date +%Y%m%d_%H%M%S) cp -a "${filename}" "${filename}_${filetime}" } extract() { # DESC: Extracts a compressed file from multiple formats # ARGS: None # OUTS: None # USAGE: extract -v <file> # NOTE: local opt local OPTIND=1 while getopts "hv" opt; do case "$opt" in h) cat <<End-Of-Usage $ ${FUNCNAME[0]} [option] <archives> options: -h show this message and exit -v verbosely list files processed End-Of-Usage return ;; v) local -r verbose='v' ;; ?) extract -h >&2 return 1 ;; esac done shift $((OPTIND - 1)) [ $# -eq 0 ] && extract -h && return 1 while [ $# -gt 0 ]; do if [ -f "$1" ]; then case "$1" in *.tar.bz2 | *.tbz | *.tbz2) tar "x${verbose}jf" "$1" ;; *.tar.gz | *.tgz) tar "x${verbose}zf" "$1" ;; *.tar.xz) xz --decompress "$1" set -- "$@" "${1:0:-3}" ;; *.tar.Z) uncompress "$1" set -- "$@" "${1:0:-2}" ;; *.bz2) bunzip2 "$1" ;; *.deb) dpkg-deb -x${verbose} "$1" "${1:0:-4}" ;; *.pax.gz) gunzip "$1" set -- "$@" "${1:0:-3}" ;; *.gz) gunzip "$1" ;; *.pax) pax -r -f "$1" ;; *.pkg) pkgutil --expand "$1" "${1:0:-4}" ;; *.rar) unrar x "$1" ;; *.rpm) rpm2cpio "$1" | cpio -idm${verbose} ;; *.tar) tar "x${verbose}f" "$1" ;; *.txz) mv "$1" "${1:0:-4}.tar.xz" set -- "$@" "${1:0:-4}.tar.xz" ;; *.xz) xz --decompress "$1" ;; *.zip | *.war | *.jar) unzip "$1" ;; *.Z) uncompress "$1" ;; *.7z) 7za x "$1" ;; *) echo "'$1' cannot be extracted via extract" >&2 ;; esac else echo "extract: '$1' is not a valid file" >&2 fi shift done } chgext() { # chgext: Batch change extension # For example 'chgext html php' will turn a directory of HTML files # into PHP files. local f for f in *."$1"; do mv "$f" "${f%.$1}.$2"; done } j2y() { # convert json files to yaml using python and PyYAML python -c 'import sys, yaml, json; yaml.safe_dump(json.load(sys.stdin), sys.stdout, default_flow_style=False)' <"$1" } y2j() { # convert yaml files to json using python and PyYAML python -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' <"$1" }
natelandau/dotfiles
shell/files.sh
Shell
mit
4,413
import * as React from "react" import { useEffect, useState } from "react" import classnames from "classnames" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { faCheck } from "@fortawesome/free-solid-svg-icons/faCheck" import { Action, getTodayDate } from "./CookiePreferencesManager" export const CookieNotice = ({ accepted, outdated, dispatch, }: { accepted: boolean outdated: boolean dispatch: any }) => { const [mounted, setMounted] = useState(false) useEffect(() => { setTimeout(() => { setMounted(true) }, 200) }, []) return ( <div className={classnames("cookie-notice", { open: mounted && (!accepted || outdated), })} data-test="cookie-notice" > <div className="wrapper"> <div className="owid-row"> <div className="owid-col owid-col--lg-1 explanation"> <p> We use cookies to give you the best experience on our website. By continuing without changing your cookie settings, we assume you agree to this. </p> </div> <div className="owid-col owid-col--lg-0 actions"> <a href="/privacy-policy" className="button"> Manage preferences </a> <button className="button accept" onClick={() => dispatch({ type: Action.Accept, payload: { date: getTodayDate() }, }) } data-test="accept" data-track-note="cookie-notice" > <span className="icon"> <FontAwesomeIcon icon={faCheck} /> </span> I agree </button> </div> </div> </div> </div> ) }
OurWorldInData/owid-grapher
site/CookieNotice.tsx
TypeScript
mit
2,316
# frozen_string_literal: true require 'rake' describe 'desif_abrasf_tasks' do before do Rake.application.rake_require 'tasks/desif_abrasf_tasks' Rake::Task.define_task :environment end describe 'abrasf-desif:db:seed' do let(:rake) { 'abrasf-desif:db:seed' } before do allow(Abrasf::Desif::Engine).to receive :load_seed Rake.application.invoke_task rake end it { expect(Abrasf::Desif::Engine).to have_received :load_seed } end describe 'abrasf-desif:city_tax_code:seed[city_ibge]' do let(:id) { '234567' } let(:rake) { "abrasf-desif:city_tax_code:seed[#{id}]" } before do allow(Abrasf::Desif::TaxCodeToCity).to receive :create Rake.application.invoke_task rake end it do expect(Abrasf::Desif::TaxCodeToCity) .to have_received(:create).with(city_id: id) end end end
marcomoura/abrasf-desif
spec/tasks/desif_abrasf_tasks_rake_spec.rb
Ruby
mit
870
#define TRACE using System; using System.Collections.Generic; using System.Text; using NGIOdotNET; using VSTCoreDefsdotNET; using System.Diagnostics; using System.Globalization; namespace GoTweet { /// <summary> /// A mediator for Go!Tweet that connects to the NGIO and passes its data /// </summary> class NGIOController { /// <summary> /// The controller's handle of the NGIO components /// </summary> private NGIOLibrary ngiolib; /// <summary> /// The device currently being tracked /// </summary> private Device device; /// <summary> /// The sensor currently being tracked /// </summary> private Sensor sensor; /// <summary> /// A queue of previous values to spit out in case of emergencies /// </summary> private Queue<float> dataCache; /// <summary> /// Whether or not <paramref name="device"/> is taking measurments /// </summary> private bool measuring = false; /// <summary> /// Initializes the NGIO library and pauses the program to allow for USB drivers to startup /// </summary> public NGIOController() { try { dataCache = new Queue<float>(); dataCache.Enqueue(0); ngiolib = new NGIOLibrary(); trace("NGIO Library opened"); System.Threading.Thread.Sleep(1000); } catch (NGIOException e) { trace(e.Message); } } /// <summary> /// Gets the last measurment taken from the tracked sensor. In case of errors, /// previous, garbage values are returned until the program can recover /// </summary> /// <returns>The last measurement or a garbage value</returns> public float getData() { float f = device.getLastMeasurment(sensor); if (f != float.MaxValue) dataCache.Enqueue(f); else { f = dataCache.Dequeue(); //back to the end of the line! dataCache.Enqueue(f); } trace("Got measurement: " + f.ToString()); return f; } /// <summary> /// Gets the units of the tracked sensor, sans parantheses /// </summary> /// <returns>Prettified Unit string</returns> public string getSensorUnits() { return sensor.getUnits().Replace("(","").Replace(")",""); //strip the units of parantheses } /// <summary> /// Closes the device and uninitializes the NGIO library. Very important to call this function /// when you are done! /// </summary> public void dispose() { if (isDeviceOpen()) { closeDevice(); trace("Device closed"); } ngiolib.uninit(); trace("Library uninitialized"); } /// <summary> /// Checks the status of the attached device /// </summary> /// <returns>If the device is not null and <see cref="Device.open"/></returns> public bool isDeviceOpen() { return (device != null && device.open); } /// <summary> /// Checks the status of the tracked sensor /// </summary> /// <returns>If the sensor is not null</returns> public bool isSensorConnected() { return (sensor != null); } /// <summary> /// Nullifies the sensor to prevent further measurments, tells the device to stop measuring, /// and tells it to close itself. /// </summary> public void closeDevice() { sensor = null; device.stopMeasuring(); device.closeDevice(); measuring = false; } /// <summary> /// Searches for LabQuests and LabQuest Minis, respectively, and connects to the first one it /// finds and it opens it. /// </summary> /// <returns>0 if successful, -1 if unable to find any device or errors out</returns> public int searchAndOpenDevice() { try{ trace("Trying to find LabQuests"); string[] names = ngiolib.getAllConnectedDeviceNames(NGIO.DEVTYPE_LABQUEST); if (names.Length != 0) { if (isDeviceOpen()) this.closeDevice(); device = ngiolib.openDeviceByName(names[0],NGIO.DEVTYPE_LABQUEST); return 0; } trace("No LabQuests found"); trace("Looking for LabQuest Minis"); names = ngiolib.getAllConnectedDeviceNames(NGIO.DEVTYPE_LABQUEST_MINI); if (names.Length != 0) { if (isDeviceOpen()) this.closeDevice(); device = ngiolib.openDeviceByName(names[0],NGIO.DEVTYPE_LABQUEST_MINI); return 0; } trace("No devices found"); device = null; return -1; } catch (NGIOException e) { trace(e.Message); return -1; } } /// <summary> /// Queries the device for connected a <see cref="Sensor"/> on an analog channel /// on the NGIO <see cref="Device"/>, finds the first one, and begins measuring /// </summary> /// <returns></returns> public int connectToSensor() { Sensor[] sensors = null; try { trace("Looking for connected sensors"); sensors = device.getConnectedSensors(); } catch (NGIOException e) { } for (int i = 0; i < sensors.Length; i++) { if (sensors[i] != null) { trace("Sensor found!"); sensor = sensors[i]; if (!measuring) { device.startMeasuring(); measuring = true; } return 0; } } this.sensor = null; return -1; } /// <summary> /// Returns the attached sensor's long name /// </summary> /// <returns>Sensor's long name</returns> public string getSensorLongName() { return sensor.getLongName(); } /// <summary> /// Returns the number of decimal places /// </summary> /// <returns>The calibrated number of decimal places</returns> public int getPrecision() { return sensor.getDecimalPlaces(); } /// <summary> /// Outputs debug information about NGIO connections and measurements /// </summary> /// <param name="message">The message to write</param> private void trace(string message) { //if (Properties.Settings.Default.logNGIO) { Trace.WriteLine(message); } } } }
VernierSoftwareTechnology/GoTweet
GoTweet/Controllers/NGIOController.cs
C#
mit
7,397
--- layout: default --- {% assign minutes = content | number_of_words | divided_by: 180 %} {% if minutes == 0 %} {% assign minutes = 2 %} {% endif %} <div class="post-header mb2"> <h1>{{ page.title }}</h1> <span class="post-meta"> <!-- Whitespace added for readability. source: http://alanwsmith.com/jekyll-liquid-date-formatting-examples --> {% assign m = page.date | date: "%-m" %} {{ page.date | date: "%-d." }} {% case m %} {% when '1' %}Januar {% when '2' %}Februar {% when '3' %}M&auml;rz {% when '4' %}April {% when '5' %}Mai {% when '6' %}Juni {% when '7' %}Juli {% when '8' %}August {% when '9' %}September {% when '10' %}Oktober {% when '11' %}November {% when '12' %}Dezember {% endcase %} {{ page.date | date: "%Y" }} </span><br> {% if page.update_date %} <span class="post-meta">Updated: {% assign m = page.update_date | date: "%-m" %} {{ page.update_date | date: "%-d." }} {% case m %} {% when '1' %}Januar {% when '2' %}Februar {% when '3' %}M&auml;rz {% when '4' %}April {% when '5' %}Mai {% when '6' %}Juni {% when '7' %}Juli {% when '8' %}August {% when '9' %}September {% when '10' %}Oktober {% when '11' %}November {% when '12' %}Dezember {% endcase %} {{ page.update_date | date: "%Y" }} </span><br> {% endif %} <span class="post-meta small">{{ minutes }} Minuten Lesezeit</span> </div> <article class="post-content"> {{ content }} </article> {% if site.show_post_footers %} {% include post_footer.html %} {% endif %} {% if site.disqus_shortname %} <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = '{{ site.disqus_shortname }}'; var disqus_identifier = '{{ page.id }}'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> {% endif %} {% if site.show_related_posts %} <h3 class="related-post-title">Related Posts</h3> {% for post in site.related_posts %} <div class="post ml2"> <a href="{{ post.url | prepend: site.baseurl }}" class="post-link"> <h4 class="post-title">{{ post.title }}</h4> <p class="post-summary">{{ post.summary }}</p> </a> </div> {% endfor %} {% endif %}
sam-d/sam-d.github.io
_layouts/post.html
HTML
mit
2,704
<?php /* WebProfilerBundle:Collector:events.html.twig */ class __TwigTemplate_c80d6f9a862ff41e72ff6eb631d60058 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->blocks = array( 'menu' => array($this, 'block_menu'), 'panel' => array($this, 'block_panel'), ); } protected function doGetParent(array $context) { return "WebProfilerBundle:Profiler:layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { // line 3 $context["__internal_c80d6f9a862ff41e72ff6eb631d60058_1"] = $this; $this->getParent($context)->display($context, array_merge($this->blocks, $blocks)); } // line 5 public function block_menu($context, array $blocks = array()) { // line 6 echo "<span class=\"label\"> <span class=\"icon\"><img src=\""; // line 7 echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/webprofiler/images/profiler/events.png"), "html", null, true); echo "\" alt=\"Events\" /></span> <strong>Events</strong> </span> "; } // line 12 public function block_panel($context, array $blocks = array()) { // line 13 echo " <h2>Called Listeners</h2> <table> <tr> <th>Event name</th> <th>Listener</th> </tr> "; // line 20 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getContext($context, "collector"), "calledlisteners")); foreach ($context['_seq'] as $context["_key"] => $context["listener"]) { // line 21 echo " <tr> <td><code>"; // line 22 echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "listener"), "event"), "html", null, true); echo "</code></td> <td><code>"; // line 23 echo $context["__internal_c80d6f9a862ff41e72ff6eb631d60058_1"]->getdisplay_listener($this->getContext($context, "listener")); echo "</code></td> </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['listener'], $context['_parent'], $context['loop']); $context = array_merge($_parent, array_intersect_key($context, $_parent)); // line 26 echo " </table> "; // line 28 if ($this->getAttribute($this->getContext($context, "collector"), "notcalledlisteners")) { // line 29 echo " <h2>Not Called Listeners</h2> <table> <tr> <th>Event name</th> <th>Listener</th> </tr> "; // line 36 $context["listeners"] = $this->getAttribute($this->getContext($context, "collector"), "notcalledlisteners"); // line 37 echo " "; $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable(twig_sort_filter(twig_get_array_keys_filter($this->getContext($context, "listeners")))); foreach ($context['_seq'] as $context["_key"] => $context["listener"]) { // line 38 echo " <tr> <td><code>"; // line 39 echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getContext($context, "listeners"), $this->getContext($context, "listener"), array(), "array"), "event"), "html", null, true); echo "</code></td> <td><code>"; // line 40 echo $context["__internal_c80d6f9a862ff41e72ff6eb631d60058_1"]->getdisplay_listener($this->getAttribute($this->getContext($context, "listeners"), $this->getContext($context, "listener"), array(), "array")); echo "</code></td> </tr> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['listener'], $context['_parent'], $context['loop']); $context = array_merge($_parent, array_intersect_key($context, $_parent)); // line 43 echo " </table> "; } } // line 47 public function getdisplay_listener($listener = null) { $context = array_merge($this->env->getGlobals(), array( "listener" => $listener, )); $blocks = array(); ob_start(); try { // line 48 echo " "; if (($this->getAttribute($this->getContext($context, "listener"), "type") == "Closure")) { // line 49 echo " Closure "; } elseif (($this->getAttribute($this->getContext($context, "listener"), "type") == "Function")) { // line 51 echo " "; $context["link"] = $this->env->getExtension('code')->getFileLink($this->getAttribute($this->getContext($context, "listener"), "file"), $this->getAttribute($this->getContext($context, "listener"), "line")); // line 52 echo " "; if ($this->getContext($context, "link")) { echo "<a href=\""; echo twig_escape_filter($this->env, $this->getContext($context, "link"), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "listener"), "function"), "html", null, true); echo "</a>"; } else { echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "listener"), "function"), "html", null, true); } // line 53 echo " "; } elseif (($this->getAttribute($this->getContext($context, "listener"), "type") == "Method")) { // line 54 echo " "; $context["link"] = $this->env->getExtension('code')->getFileLink($this->getAttribute($this->getContext($context, "listener"), "file"), $this->getAttribute($this->getContext($context, "listener"), "line")); // line 55 echo " "; echo $this->env->getExtension('code')->abbrClass($this->getAttribute($this->getContext($context, "listener"), "class")); echo "::"; if ($this->getContext($context, "link")) { echo "<a href=\""; echo twig_escape_filter($this->env, $this->getContext($context, "link"), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "listener"), "method"), "html", null, true); echo "</a>"; } else { echo twig_escape_filter($this->env, $this->getAttribute($this->getContext($context, "listener"), "method"), "html", null, true); } // line 56 echo " "; } } catch(Exception $e) { ob_end_clean(); throw $e; } return ob_get_clean(); } public function getTemplateName() { return "WebProfilerBundle:Collector:events.html.twig"; } public function isTraitable() { return false; } }
richpolis/sf2Pruebas
app/cache/dev/twig/c8/0d/6f9a862ff41e72ff6eb631d60058.php
PHP
mit
7,783
<?php /** * Plugin Name: Hackerspace * Plugin URI: https://github.com/nicelab/wp-hackerspace * Author: Nicelab.org * Author URI: http://nicelab.org/ * Description: Add custom post types useful for hackerspaces and expose informations trough the Space API. * Version: 0.3 * Copyright: (c) 2014 Nicelab.org * License: Expat/MIT License * Text Domain: wp-hackerspace * Domain Path: /languages */ // define global constants for versions and base directory define('HACKERSPACE_PLUGIN_VERSION', '0.3'); define('HACKERSPACE_SPACE_API_VERSION', '0.13'); define('HACKERSPACE_PLUGIN_DIR', plugin_dir_path(__FILE__)); /** * Main class for the plugin * * @since 0.1 */ class Hackerspace { /** * Constructor for the Hackerspace class * * Register Wordpress plugins hooks */ public function __construct() { // include the required external classes files require_once(HACKERSPACE_PLUGIN_DIR.'includes/class-plugin-setup.php'); require_once(HACKERSPACE_PLUGIN_DIR.'includes/class-space-api.php'); require_once(HACKERSPACE_PLUGIN_DIR.'includes/class-settings-features.php'); require_once(HACKERSPACE_PLUGIN_DIR.'includes/class-settings-space-api.php'); require_once(HACKERSPACE_PLUGIN_DIR.'includes/class-post-type-project.php'); require_once(HACKERSPACE_PLUGIN_DIR.'includes/class-space-state.php'); // instantiate the required external classes $this->Plugin_Setup = new Plugin_Setup(); $this->Post_Type_Project = new Post_Type_Project(); $this->Settings_Features = new Settings_Features(); $this->Settings_Space_Api = new Settings_Space_Api(); $this->Space_Api = new Space_Api(); // register activation, deactivation hooks for the plugin register_activation_hook(__FILE__, array($this->Plugin_Setup, 'activate')); register_deactivation_hook(__FILE__, array($this->Plugin_Setup, 'deactivate')); // enable the plugin updater add_action('admin_init', array($this->Plugin_Setup, 'update')); // load translations load_plugin_textdomain('wp-hackerspace', false, HACKERSPACE_PLUGIN_DIR.'/languages'); // register the plugin settings add_action('admin_init', array($this, 'admin_init')); // enable the admin setting menu add_action('admin_menu', array($this, 'admin_menu')); // enable the spaceapi rel element in the blog headers add_action('wp_head', array($this, 'spaceapi_rel')); // enable the contextual help add_action('contextual_help', array($this, 'plugin_contextual_help'), 10, 3); // enable a settings link in the WordPress plugins menu add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'plugin_action_links')); // enable the Project post type add_action('init', array($this->Post_Type_Project, 'register_project_post_type')); // enable the Space Api json endpoint add_action('init', array($this->Space_Api, 'spaceapi_endpoint')); } /** Register the plugin settings */ public function admin_init() { $this->Settings_Features->register_settings(); $this->Settings_Space_Api->register_settings(); } /** Configure the plugin settings menu */ public function admin_menu() { add_options_page( __('Hackerspace', 'wp-hackerspace'), __('Hackerspace', 'wp-hackerspace'), 'manage_options', 'hackerspace_options', array($this, 'plugin_settings_template') ); } /** Render the settings template */ public function plugin_settings_template() { if (! current_user_can('manage_options')) { wp_die(__('You do not have sufficient permissions to access this page.', 'wp-hackerspace')); } include(sprintf(HACKERSPACE_PLUGIN_DIR.'templates/settings.php')); } /** Render the contextual help drop-down menu * * @param object $contextual_help Actual contaxtual help * @param text $screen_id ID of the WordPress screen * @param WP_Screen $screen WordPress $screen global * * @return object Modified contextual help */ public function plugin_contextual_help($contextual_help, $screen_id, $screen) { $features_help_tab = $this->Settings_Features->help_tab(); $spaceapi_help_tab = $this->Settings_Space_Api->help_tab(); $projects_help_tab = $this->Post_Type_Project->help_tab(); if ($screen_id == 'settings_page_hackerspace_options') { $screen->add_help_tab(array( 'id' => 'wp-hackerspace-overview', 'title' => __('Overview', 'wp-hackerspace'), 'content' => '<p>Overview help text</p>', )); $screen->add_help_tab(array( 'id' => $features_help_tab->id, 'title' => $features_help_tab->title, 'content' => $features_help_tab->content, )); $screen->add_help_tab(array( 'id' => $spaceapi_help_tab->id, 'title' => $spaceapi_help_tab->title, 'content' => $spaceapi_help_tab->content, )); // help sidebar links $screen->set_help_sidebar('<p><strong>'.__('For more information:', 'wp-hackerspace').'</strong></p>'); } if ($screen_id == 'hackerspace_project' || $screen_id == 'edit-hackerspace_project') { $screen->add_help_tab(array( 'id' => $projects_help_tab->id, 'title' => $projects_help_tab->title, 'content' => $projects_help_tab->content, )); } return $contextual_help; } /** * Render the settings link in the in the WordPress plugins menu * * @param array $links Array of links displayed in the WordPress plugins menu * * @return array */ public function plugin_action_links($links) { $links[] = '<a href="'.get_admin_url(null, 'options-general.php?page=hackerspace_options').'">'.__('Settings', 'wp-hackerspace').'</a>'; return $links; } /** Add the spaceapi rel element to the blog headers */ public function spaceapi_rel() { echo '<link rel="space-api" href="'.get_bloginfo('url').'?feed=spaceapi" />'."\n"; } } // instantiate the plugin class $Hackerspace = new Hackerspace();
Nicelab/wp-hackerspace
wp-hackerspace.php
PHP
mit
6,578
package com.jetbrains.crucible.model; import org.jetbrains.annotations.NotNull; /** * @author Kirill Likhodedov */ public class Repository { @NotNull private final String myName; @NotNull private final String myUrl; public Repository(@NotNull String name, @NotNull String url) { myName = name; myUrl = url; } @NotNull public String getUrl() { return myUrl; } @NotNull public String getName() { return myName; } }
ktisha/Crucible4IDEA
src/com/jetbrains/crucible/model/Repository.java
Java
mit
458
Namespaces ========== This is a complete list of available namespaces: - [`Phine`](Phine) - [`Phine\Test`](Phine/Test) - [`Phine\Test\Exception`](Phine/Test/Exception)
kherge-abandoned/lib-test
docs/1.0.0/1. Namespaces.md
Markdown
mit
170
/** * Copyright (c) 2016 Peter Cannici * Licensed under the MIT (X11) license. See LICENSE. */ #include "test.h" int main(int argc __attribute__((unused)), char **argv __attribute__((unused))) { ptrdiff_t num_suites = suite_registry_end - suite_registry_begin; for (int i = 0; i < num_suites; i++) pt_add_suite(suite_registry_begin[i]); return pt_run(); }
alpha123/yu
test/test.c
C
mit
381
# Copyright (c) 2014-2020 Yegor Bugayenko # # 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 NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'shellwords' require 'English' require_relative 'source' module PDD # Code base abstraction class Sources # Ctor. # +dir+:: Directory with source code files def initialize(dir, ptns = []) @dir = File.absolute_path(dir) @exclude = ptns + ['.git/**/*'] end # Fetch all sources. def fetch files = Dir.glob( File.join(@dir, '**/*'), File::FNM_DOTMATCH ).reject { |f| File.directory?(f) } excluded = 0 @exclude.each do |ptn| Dir.glob(File.join(@dir, ptn), File::FNM_DOTMATCH) do |f| files.delete_if { |i| i == f } excluded += 1 end end PDD.log.info "#{files.size} file(s) found, #{excluded} excluded" files.reject { |f| binary?(f) }.map do |file| path = file[@dir.length + 1, file.length] VerboseSource.new(path, Source.new(file, path)) end end def exclude(ptn) Sources.new(@dir, @exclude.push(ptn)) end private # @todo #98:30min Change the implementation of this method # to also work in Windows machines. Investigate the possibility # of use a gem for this. After that, remove the skip of the test # `test_ignores_binary_files` in `test_sources.rb`. def binary?(file) return false if Gem.win_platform? `grep -qI '.' #{Shellwords.escape(file)}` if $CHILD_STATUS.success? false else PDD.log.info "#{file} is a binary file (#{File.size(file)} bytes)" true end end end end
teamed/pdd
lib/pdd/sources.rb
Ruby
mit
2,631
# Get twilio-ruby from twilio.com/docs/ruby/install require 'twilio-ruby' # Get your Account SID and Auth Token from twilio.com/console # To set up environmental variables, see http://twil.io/secure account_sid = ENV['TWILIO_ACCOUNT_SID'] auth_token = ENV['TWILIO_AUTH_TOKEN'] # Initialize Twilio client @client = Twilio::REST::Client.new(account_sid, auth_token) # Loop over accounts and print out a property for each one @client.api.accounts.list.each do |account| puts account.date_created end
TwilioDevEd/api-snippets
rest/accounts/list-get-example-1/list-get-example-1.5.x.rb
Ruby
mit
502
<?php /**********************************************\ * Copyright (c) 2013 Manolis Agkopian * * See the file LICENCE for copying permission. * \**********************************************/ require_once 'vendor/autoload.php'; session_start(); $msg = ''; // Check if form has been submited if ( isset($_POST['submit']) && !empty($_POST['submit']) ) { // Check if user answered the question if ( !isset($_POST['captcha_ans']) || $_POST['captcha_ans'] === '' ) { $msg = '<span class="error">Please fill the answer to the math question</span>'; } else { $mathCaptcha = new MathCaptcha\MathCaptcha(); // Validate the answer if ( $mathCaptcha->check($_POST['captcha_ans']) === true ) { // In a real application here you can register/login the user, insert a comment in the database etc $msg = '<span class="success">SUCCESS</span>'; } else { $msg = '<span class="error">You didn\'t answered the question correctly</span>'; } } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>PHP Math Captcha</title> <style type="text/css"> .error { color: red; } .success { color: green; } </style> </head> <body> <p id="msg"><?php echo $msg; ?></p> <p>Answer to this simple math question:</p> <form action="" method="POST"> <img src="captcha.png" alt=""> <input type="text" name="captcha_ans"> <input type="submit" name="submit" value="Submit"> </form> </body> </html>
magkopian/php-math-captcha
test_form.php
PHP
mit
1,490
#ifndef FLTPROPSLIDER_H #define FLTPROPSLIDER_H #include <QWidget> #include "util.h" namespace Ui { class FltPropSlider; } class FltPropSlider : public QWidget { Q_OBJECT public: explicit FltPropSlider(QWidget *parent = 0); FltPropSlider(QString caption, float minVal, float maxVal, float step, float divisor, QWidget *parent = 0); ~FltPropSlider(); float getValue(); void setValue(float val); public slots: signals: void valChanged(float val); private slots: void on_slider_valueChanged(int value); private: Ui::FltPropSlider *ui; float minValue, maxValue, valStep, divisor; }; #endif // FLTPROPSLIDER_H
SergeyStaroletov/Patterns17
CourseWorkReports/Курсовой проект Хышов ПИ-42/Исходный код/VidEff/fltpropslider.h
C
mit
675
package examples; import ciayn.elements.Callable; import ciayn.elements.Input; import ciayn.elements.Output; import ciayn.elements.signal.ReadingFloat; import ciayn.elements.signal.Signal; import ciayn.elements.signal.SignalFloat; import ciayn.elements.signal.ValueFloat; import ciayn.elements.signal.unit.Unit; import ciayn.elements.signal.unit.Voltage; import ciayn.environmantal.Env; import ciayn.environmantal.EnvController; import ciayn.environmantal.EnvPlant; import ciayn.logger.ConsoleLogger; import ciayn.logger.Logger; import java.util.List; import java.util.concurrent.TimeUnit; /** * Created by lukas on 14.01.17. */ public class useSignal { public static void main(String args[]) throws Exception { float deltaTime = 0.01f; //sec Unit Volt = Voltage.getUnit(); Signal uSignal = new SignalFloat(Volt); Logger ulog = new ConsoleLogger("controller output u ="); uSignal.setLogger(ulog); Input w = new Input(new ReadingFloat(2.0f, Volt)); //Output u = new Output(new ReadingFloat(0f, Volt),uActual); Output x = new Output(new ReadingFloat(0f, Voltage.getUnit())); // same as use of Volt, because Voltage is a singleton class Env pid = EnvController.createEnvPI(ValueFloat.class, 0.1f, 0.2f, deltaTime, w, x.createInput(), uSignal.getOutput()); Env pt1 = EnvPlant.createEnvPT1(ValueFloat.class, 2f, 1f, 0.001f, uSignal.getInput(), x); int i = 0; System.out.println("Start Simulation"); while (i <= 4) { pid.runOneIteration(); pt1.runOneIteration(); i++; TimeUnit.MILLISECONDS.sleep((long) (deltaTime * 1000)); } System.out.println("END simulation"); System.out.println("print Signal values!"); List<ValueFloat> Values = uSignal.getSignalValues(); for (ValueFloat value : Values) { System.out.println("timestemp=" + value.getTimeStamp() + " : " + value.getValue() + " " + uSignal.getUnit().toString()); } System.out.println("END print Signal values!"); } }
lki1354/Ciayn
src/examples/useSignal.java
Java
mit
2,109
--- title: ahd20 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: d20 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
pblack/kaldi-hugo-cms-template
site/content/pages2/ahd20.md
Markdown
mit
339
require 'drb' require 'digest/md5' require 'thread' require 'singleton' require 'backgroundrb/thread_pool' require 'backgroundrb/worker' require 'backgroundrb/scheduler' require 'backgroundrb/trigger' require 'backgroundrb/cron_trigger' require 'backgroundrb/results' require 'rubygems' require 'slave' require 'yaml' class BackgrounDRbDuplicateKeyError < ArgumentError; end class BackgrounDRbUnknownTriggerType < ArgumentError; end class BackgrounDRbWorkerClassNotRegistered < ArgumentError; end module BackgrounDRb #http://onestepback.org/index.cgi/Tech/Ruby/BuilderObjects.rdoc class BlankSlate # :nodoc: instance_methods.each { |m| undef_method m unless m =~ /^__/ } end # The WorkerProxy is used to make the DRb connection go from the # MiddleMan to the slave process. It allows us to catch exception on # the server side without the client (which get the MiddleMan # DRbObject) having to deal the cases where a slave/worker goes away. # This is also where we provide a uniform access to worker results, # even after the worker is terminated. From a results standpoint, # named workers become singletons. class WorkerProxy < BlankSlate include DRbUndumped include BackgrounDRb::Worker include BackgrounDRb::Results def initialize(worker) @worker = worker @jobkey = worker.jobkey end # this one is snagged from DRb::DRbObject#respond_to? def respond_to?(msg_id, priv=false) case msg_id when :_dump true when :marshal_dump false else method_missing(:respond_to?, msg_id, priv) end end def method_missing(sym, *args, &block) case sym when :delete, :results begin @worker.__send__(sym, *args, &block) rescue DRb::DRbConnError => e # This will return the results for the worker even after it # has terminated. if sym == :results results = {} results.extend(BackgrounDRb::Results) results.init(@jobkey) results end end else #puts "Sending #{sym}(#{args.join(',')}) to obj" @worker.__send__(sym, *args, &block) end end end class MiddleMan include DRbUndumped include Singleton attr_accessor :scheduler attr_reader :worker_classes def setup(opts={}) @jobs = Hash.new @in_setup = Hash.new @mutex = Mutex.new @timestamps = Hash.new @thread_pool = ThreadPool.new(opts[:pool_size] || 30) @scheduler = opts[:scheduler] @worker_dir = opts[:worker_dir] @worker_classes = [] #BackgrounDRb::Worker::WorkerLogger.register #BackgrounDRb::Worker::WorkerResults.register new_worker(:class => :'BackgrounDRb::Worker::WorkerLogger', :job_key => :backgroundrb_logger) new_worker(:class => :'BackgrounDRb::Worker::WorkerResults', :job_key => :backgroundrb_results) self.load_worker_classes self.scheduler.run self.load_worker_schedules self end def load_worker_schedules schedule_file = "#{BACKGROUNDRB_ROOT}/config/backgroundrb_schedules.yml" begin schedules = {} raw = YAML.load(ERB.new(IO.read(schedule_file)).result) schedules.merge!(raw) rescue => e schedules = {} end schedules.each do |label, data| if data[:class] and data[:trigger_args] # convert stinrgs to Time objects [ :start, :end ].each do |k| if data[:trigger_args][k] data[:trigger_args][k] = Time.parse(data[:trigger_args][k]) end end self.schedule_worker(data) end end end def load_worker_classes Dir["#{@worker_dir}/*.rb"].each do |worker| begin BackgrounDRb::ServerLogger.logger.info('middleman') do "Loading Worker Class File: #{worker}" end load worker rescue Exception => e BackgrounDRb::ServerLogger.logger.info('middleman') do "Failed to load: #{worker}" end BackgrounDRb::ServerLogger.log_exception('middleman', e) end end end # mimic rails console reload! alias :reload! :load_worker_classes def register_worker_class(arg) unless @worker_classes.include?(arg) @worker_classes << arg end end # Clean this up at some point, just here since constants don't go # well over DRb, and in the spec we wanted to check that a # particular worker class was registered. def loaded_worker_classes @worker_classes.map { |klass| klass.to_s } end def new_worker(opts={}) is_gen_key = false job_key = opts[:job_key] || lambda { is_gen_key = true; gen_key }.call w_klass = opts[:class] w_args = opts[:args] worker_klass = worker_klass_constant(w_klass) # Require non-builtin worker classes to be registered case w_klass.to_s when 'BackgrounDRb::Worker::WorkerLogger', 'BackgrounDRb::Worker::WorkerResults' else unless @worker_classes.include?(worker_klass) raise BackgrounDRbWorkerClassNotRegistered, "#{worker_klass}: Not a registered BackgrounDRb worker class" end end if not jobs[job_key] m = self # Use in_setup to keep track of job_keys not in jobs[yet]. Avoid # a jobs[job_key] race where a second call to new_worker with # the same job_key could result in a second dispatch. unless in_setup?(job_key) @thread_pool.dispatch do # Set ps name for the slave process case job_key when :backgroundrb_logger, :backgroundrb_results psname = job_key.to_s else psname = "#{w_klass}_#{job_key}".gsub('::', '_').downcase end begin slave_obj = Slave.new({ :psname => psname, :threadsafe => true, :object => worker_klass.new(w_args, job_key)}) do |s| end rescue => e BackgrounDRb::ServerLogger.log_exception('middleman', e) end slave_obj.wait(:non_block=>true) do self.delete_worker(job_key) end #ObjectSpace.define_finalizer(slave_obj){ # self.delete_worker job_key #} BackgrounDRb::ServerLogger.logger.info('middleman') { "Starting worker: #{w_klass} #{job_key} (#{psname}) (#{w_args})" } # add Slave#delete to allow self destruct class << slave_obj def delete MiddleMan.instance.delete_worker(self.obj.jobkey) end end # we can't call this inside the Server.new block since #delete # and @process is not set up. slave_obj.object.work_thread(:method => :do_work, :args => :@args) m[job_key] = slave_obj end.join out_of_setup(job_key) else # If we get here, it means that a worker with the given # job_key is already dispatched. We'll wait around until it is # available in jobs[] until jobs[job_key] sleep 0.1 end end elsif is_gen_key == false # do nothing and fall through to return the job key of an # existing worker. else raise ::BackgrounDRbDuplicateKeyError end return job_key end def schedule_worker(opts={}) job_key = opts[:job_key] # If the worker is already instantiated, then we really only need # the job_key. Otherwise we'll need the worker class as well. begin unless jobs[job_key] worker_klass_constant(opts[:class]) end rescue ArgumentError, NameError => e BackgrounDRb::ServerLogger.log_exception('middleman', e) return nil end if job_key new_worker_arg = { :class => opts[:class], :args => opts[:args], :job_key => job_key } else new_worker_arg = {:class => opts[:class], :args => opts[:args] } end # primitive auto-detection of trigger type, based on # trigger_args unless opts[:trigger_type] case opts[:trigger_args] when String opts[:trigger_type] = :cron_trigger when Hash opts[:trigger_type] = :trigger end end case opts[:trigger_type] when :cron_trigger # most likely bad default :) cron_args = opts[:trigger_args] || "0 0 0 0 0" trigger = BackgrounDRb::CronTrigger.new(cron_args) when :trigger trigger = BackgrounDRb::Trigger.new(opts[:trigger_args]) else raise ::BackgrounDRbUnknownTriggerType end # do_work special case case opts[:worker_method] when :do_work opts[:worker_method_args] ||= opts[:args] end case when opts[:worker_method] && opts[:worker_method_args] args = opts[:worker_method_args].dup sched_proc = lambda do m = MiddleMan.instance job_key = m.new_worker(new_worker_arg) case opts[:worker_method] when :do_work unless m.worker(job_key).initial_do_work m.worker(job_key).send(opts[:worker_method], args) else m.worker(job_key).initial_do_work = false end else m.worker(job_key).send(opts[:worker_method], args) end end when opts[:worker_method] sched_proc = lambda do m = MiddleMan.instance job_key = m.new_worker(new_worker_arg) case opts[:worker_method] when :do_work unless m.worker(job_key).initial_do_work m.worker(job_key).send(opts[:worker_method], nil) else m.worker(job_key).initial_do_work = false end else m.worker(job_key).send(opts[:worker_method]) end end else # FIXME: make this just call do_work #raise RuntimeError, new_worker_arg sched_proc = lambda do m = MiddleMan.instance job_key = m.new_worker(new_worker_arg) m.worker(job_key).initial_do_work = false end end # TODO: format this better BackgrounDRb::ServerLogger.logger.info('middleman') { "Loading Sechedule: #{new_worker_arg} #{opts} #{trigger}" } self.scheduler.schedule(sched_proc, trigger) end def delete_worker(key) m = self slave_obj = m[key] ex { @jobs.delete(key) @timestamps.delete(key) } begin slave_obj.shutdown rescue Errno::ESRCH end end alias :delete_cache :delete_worker def cache(named_key, object) ex { self[named_key] = object } end def gc!(age) @timestamps.each do |job_key, timestamp| if timestamp < age delete_worker(job_key) end end end def worker(key) slave = nil give_up = false attempts = 0 until give_up or slave slave = ex { @jobs[key] } attempts += 1 give_up = true if attempts == 42 sleep 0.1 end if slave worker = ex { slave.object } return WorkerProxy.new(worker) else # Should we really return nil if we can't get a worker? return nil end end def [](key) ex { @jobs[key] } end def []=(key, val) ex { @jobs[key] = val @timestamps[key] = Time.now } end def jobs ex { @jobs } end def in_setup?(key) ex { not_in_setup = lambda { |k| @in_setup[k] = true ; false } @in_setup.has_key?(key) ? true : not_in_setup[key] } end def out_of_setup(key) ex { @in_setup.delete(key) } end def timestamps ex { @timestamps } end def stats { :jobs => jobs, :timestamps => timestamps } end private def ex @mutex.synchronize { yield } end def worker_klass_constant(klass) klass_string = klass.to_s.split('_').inject('') { |total,part| total << part.sub(/\A\S/) {|m| m.upcase} } if klass_string.match(/::/) worker_klass = klass_string.split(/::/).inject(Object) do |full,part| full.const_get(part) end else worker_klass = Object.const_get(klass_string) end worker_klass end def gen_key begin key = Digest::MD5.hexdigest("#{inspect}#{Time.now}#{rand}") end until self[key].nil? key end end end if __FILE__ == $0 middleman = BackgrounDRb::MiddleMan.instance.setup :pool_size => 5 DRb.start_service("druby://localhost:2000", middleman) ##File.open("#{BACKGROUNDRB_ROOT}/log/backgroundrb.pid", 'w+'){|f| f.write(Process.pid)} DRb.thread.join #cnt = 0 #loop{ break if cnt>15 ; puts M.stats; sleep 0.05; cnt+=1} #500.times {|i| M.new_worker :class => :worker, :args => i;puts M.stats} # #puts "All Done" end
google-code/backgroundrb
server/lib/backgroundrb/middleman.rb
Ruby
mit
13,456
var elements = document.getElementsByTagName('script') Array.prototype.forEach.call(elements, function(element) { if (element.type.indexOf('math/tex') != -1) { // Extract math markdown var textToRender = element.innerText || element.textContent; // Create span for KaTeX var katexElement = document.createElement('span'); katexElement.style = "text-align:center"; // Support inline and display math if (element.type.indexOf('mode=display') != -1){ katexElement.className += "math-display"; textToRender = '\\displaystyle {' + textToRender + '}'; } else { katexElement.className += "math-inline"; } katex.render(textToRender, katexElement); element.parentNode.insertBefore(katexElement, element); } });
abisee/abisee.github.io
js/katex_init.js
JavaScript
mit
786
# DeepLearning Coursera- Deep Learning Course by DeepLearning.ai Introduction to Neural Networks Improving Deep Neural Network: Hyperparameter Tuning, Optimization, Regularization Structuring Machine Learning Convolutional Neural Networks Sequence Models
radu941208/DeepLearning
README.md
Markdown
mit
260
Hi there. I'm Alex (aka tinnvec) and I'm a nerd with a passion for coding starting in the mid-90s. Currently, I use a lot of C# and .NET at work but tend to prefer JavaScript and Ruby for personal projects. Though I have my favorites, I'm always learning new things I find interesting (this site is done in Jekyll, for example). --- # Projects ## [stonebot](https://github.com/tinnvec/stonebot/) > Hearthstone Bot for Discord. Features commands for card information and community features. [website](https://tinnvec.github.io/stonebot/) ## [hearthstone_json](https://github.com/tinnvec/hearthstone_json/) > Ruby Gem for HearthstoneJSON. ## [cinch-strawpoll](https://github.com/tinnvec/cinch-strawpoll/) > Cinch plugin for Strawpoll. ## [tinnvec.github.io](https://github.com/tinnvec/tinnvec.github.io/) > Jekyll website for personal landing page and blog. [website](http://tinnvec.github.io/) --- # Contact * [tinnvec@gmail.com](mailto:tinnvec@gmail.com) * [Discord](https://discordapp.com/): tinnvec#3217 ## Social * [GitHub]({{ site.github.owner_url }}) * [StackExchange](https://stackexchange.com/users/5352118/tinnvec/) * [LinkedIn](https://www.linkedin.com/in/tinnvec/)
tinnvec/tinnvec.github.io
index.md
Markdown
mit
1,230
package com.teamw.ysm0622.app_when.group; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.util.DisplayMetrics; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.teamw.ysm0622.app_when.R; import com.teamw.ysm0622.app_when.global.Gl; import com.teamw.ysm0622.app_when.meet.CreateMeet; import com.teamw.ysm0622.app_when.menu.About; import com.teamw.ysm0622.app_when.menu.Settings; import com.teamw.ysm0622.app_when.object.Group; import com.teamw.ysm0622.app_when.object.Meet; import com.teamw.ysm0622.app_when.object.User; import com.teamw.ysm0622.app_when.server.ServerConnection; import com.kakao.kakaolink.KakaoLink; import com.kakao.kakaolink.KakaoTalkLinkMessageBuilder; import com.kakao.util.KakaoParameterException; import org.apache.http.NameValuePair; import java.util.ArrayList; public class GroupManage extends Activity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener { // TAG private static final String TAG = GroupManage.class.getName(); // Const private static final int mToolBtnNum = 2; private static final int mTabBtnNum = 2; // Intent private Intent mIntent; // Toolbar private ImageView mToolbarAction[]; private TextView mToolbarTitle; // Tabbar private LinearLayout mTabbarAction[]; private ImageView mTabbarImage[]; private View mTabbarLine[]; private DrawerLayout mDrawer; private NavigationView mNavView; private View mTabContent[]; private LinearLayout mEmptyView; private FloatingActionButton mFab[]; // List View private ListView mListView[]; // Adapter private UserDataAdapter UserAdapter; private MeetDataAdapter MeetAdapter; // Data private Group g; private ArrayList<User> userData = new ArrayList<>(); private ArrayList<Meet> meetData = new ArrayList<>(); //Shared Preferences private SharedPreferences mSharedPref; private SharedPreferences.Editor mEdit; private AlertDialog mDialBox; public static final int PROGRESS_DIALOG = 1001; public ProgressDialog progressDialog; public Bitmap temp; ImageView ImageView0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.groupmanage_drawer); mSharedPref = getSharedPreferences(Gl.FILE_NAME_LOGIN, MODE_PRIVATE); mEdit = mSharedPref.edit(); mIntent = getIntent(); g = (Group) mIntent.getSerializableExtra(Gl.GROUP); Log.d("Gl", "GroupId : " + g.getId() + "Enter"); userData = Gl.getUsers(g); Drawable[] toolbarIcon = new Drawable[2]; toolbarIcon[0] = getResources().getDrawable(R.drawable.ic_menu_white); toolbarIcon[1] = getResources().getDrawable(R.drawable.ic_refresh_white_24dp); String toolbarTitle = ""; if (mIntent.getIntExtra(Gl.TAB_NUMBER, 1) == 0) toolbarTitle = getResources().getString(R.string.meet_list); if (mIntent.getIntExtra(Gl.TAB_NUMBER, 1) == 1) toolbarTitle = getResources().getString(R.string.member); initEmptyScreen(); initToolbar(toolbarIcon, toolbarTitle); initTabbar(mIntent.getIntExtra(Gl.TAB_NUMBER, 1)); initNavigationView(); initialize(); BackgroundTask mTask = new BackgroundTask(); mTask.execute(g); } class BackgroundTask extends AsyncTask<Group, Integer, Integer> { protected void onPreExecute() { showDialog(PROGRESS_DIALOG); } @Override protected Integer doInBackground(Group... args) { String result1 = ServerConnection.getStringFromServer(new ArrayList<NameValuePair>(), Gl.SELECT_MEET_BY_GROUP);//Meeting 정보 가져오기 String result2 = ServerConnection.getStringFromServer(new ArrayList<NameValuePair>(), Gl.SELECT_MEETDATE_BY_GROUP);//Meeting 정보 가져오기 ArrayList<NameValuePair> param1 = ServerConnection.SelectTimeByMeet(args[0]); String result = ServerConnection.getStringFromServer(param1, Gl.SELECT_TIME_BY_MEET); ServerConnection.SelectMeetByGroup(result1); ServerConnection.SelectMeetDateByGroup(result2); ServerConnection.SelectTimeByMeet(result); return null; } protected void onPostExecute(Integer a) { if (progressDialog != null) progressDialog.dismiss(); meetData = Gl.getMeets(g); MeetAdapter.clear(); MeetAdapter.addAll(meetData); meetDataEmptyCheck(); MeetAdapter.notifyDataSetChanged(); } } //로딩 다이어로그 public Dialog onCreateDialog(int id) { if (id == PROGRESS_DIALOG) { progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage(getString(R.string.meetInfo_progress)); return progressDialog; } return null; } //Meeting 데이터 확인 public void meetDataEmptyCheck() { if (meetData.size() == 0) { mEmptyView.setVisibility(View.VISIBLE); mEmptyView.setEnabled(true); LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mEmptyView.setLayoutParams(param); } else { mEmptyView.setEnabled(false); LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0); mEmptyView.setLayoutParams(param); Log.w(TAG, "GroupData size : " + meetData.size()); } } private void initEmptyScreen() { mEmptyView = (LinearLayout) findViewById(R.id.EmptyView); ImageView image[] = new ImageView[3]; TextView text; image[0] = (ImageView) findViewById(R.id.emptyImageView0); image[1] = (ImageView) findViewById(R.id.emptyImageView1); image[2] = (ImageView) findViewById(R.id.emptyImageView2); text = (TextView) findViewById(R.id.emptyTextView0); image[1].setImageDrawable(getResources().getDrawable(R.drawable.ic_date_range_white_24dp)); text.setText(R.string.nomeet_msg); for (int i = 0; i < 2; i++) { image[i].setColorFilter(getResources().getColor(R.color.colorPrimary)); } for (int i = 0; i < image.length; i++) { image[i].setAlpha((float) 0.4); } } @Override protected void onResume() { super.onResume(); mNavView.setCheckedItem(R.id.nav_group);//nav item home으로 초기화 } @Override protected void onPause() { super.onPause(); //save state data (background color) for future use //Bitmap이 차지하는 Heap Memory 를 반환한다. ImageView0.setImageBitmap(null); temp.recycle(); } @Override protected void onRestart() { super.onRestart(); initNavigationView(); } private void initialize() { // Array allocation mFab = new FloatingActionButton[2]; mListView = new ListView[2]; // Create instance UserAdapter = new UserDataAdapter(this, R.layout.member_item, userData); MeetAdapter = new MeetDataAdapter(this, R.layout.meet_item, meetData, mIntent); // View allocation mFab[0] = (FloatingActionButton) mTabContent[0].findViewById(R.id.fab); mFab[1] = (FloatingActionButton) mTabContent[1].findViewById(R.id.fab); mListView[0] = (ListView) mTabContent[0].findViewById(R.id.ListView); mListView[1] = (ListView) mTabContent[1].findViewById(R.id.ListView); mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, mDrawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close); mDrawer.setDrawerListener(toggle); toggle.syncState(); // Add listener for (int i = 0; i < 2; i++) mFab[i].setOnClickListener(this); // Default setting mListView[0].setAdapter(MeetAdapter); mListView[0].setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); mListView[1].setAdapter(UserAdapter); mListView[1].setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { } }); MeetAdapter.notifyDataSetChanged(); UserAdapter.notifyDataSetChanged(); } private void initNavigationView() { DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics(); float mScale = getResources().getDisplayMetrics().density; int width = (int) (dm.widthPixels - (56 * mScale + 0.5f)); mNavView = (NavigationView) findViewById(R.id.nav_view); LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0); param.height = (int) (width * 9.0 / 16.0); mNavView.getHeaderView(0).setLayoutParams(param); setRandomNavHeader((int) (Math.random() * 4)); ImageView0 = (ImageView) mNavView.getHeaderView(0).findViewById(R.id.MyProfile); ImageView0.setColorFilter(getResources().getColor(R.color.white)); TextView TextView0 = (TextView) mNavView.getHeaderView(0).findViewById(R.id.MyName); TextView TextView1 = (TextView) mNavView.getHeaderView(0).findViewById(R.id.MyEmail); User user = (User) mIntent.getSerializableExtra(Gl.USER); if (user.ImageFilePath != null && !user.ImageFilePath.equals("") && Gl.PROFILES.get(String.valueOf(user.getId())) != null) {//프로필 이미지가 존재 ImageView0.clearColorFilter(); temp = BitmapFactory.decodeFile(Gl.ImageFilePath + user.getId() + ".jpg"); ImageView0.setImageBitmap(Gl.getCircleBitmap(temp)); } else { ImageView0.clearColorFilter(); temp = Gl.getDefaultImage(user.getId()); ImageView0.setImageBitmap(Gl.getCircleBitmap(temp)); } TextView0.setText(user.getName()); TextView1.setText(user.getEmail()); mNavView.setNavigationItemSelectedListener(this); } private void setRandomNavHeader(int i) { if (i == 0) mNavView.getHeaderView(0).setBackground(getResources().getDrawable(R.drawable.wallpaper1_resize)); if (i == 1) mNavView.getHeaderView(0).setBackground(getResources().getDrawable(R.drawable.wallpaper2_resize)); if (i == 2) mNavView.getHeaderView(0).setBackground(getResources().getDrawable(R.drawable.wallpaper3_resize)); if (i == 3) mNavView.getHeaderView(0).setBackground(getResources().getDrawable(R.drawable.wallpaper4_resize)); } private void initToolbar(Drawable Icon[], String Title) { mToolbarAction = new ImageView[2]; mToolbarAction[0] = (ImageView) findViewById(R.id.Toolbar_Action0); mToolbarAction[1] = (ImageView) findViewById(R.id.Toolbar_Action1); mToolbarTitle = (TextView) findViewById(R.id.Toolbar_Title); for (int i = 0; i < mToolBtnNum; i++) { mToolbarAction[i].setOnClickListener(this); mToolbarAction[i].setImageDrawable(Icon[i]); mToolbarAction[i].setBackground(getResources().getDrawable(R.drawable.selector_btn)); } mToolbarTitle.setText(Title); } private void initTabbar(int v) { mTabbarAction = new LinearLayout[mTabBtnNum]; mTabbarImage = new ImageView[mTabBtnNum]; mTabbarLine = new View[mTabBtnNum]; mTabContent = new View[mTabBtnNum]; mTabbarAction[0] = (LinearLayout) findViewById(R.id.Tabbar_Tab0); mTabbarAction[1] = (LinearLayout) findViewById(R.id.Tabbar_Tab2); mTabbarImage[0] = (ImageView) findViewById(R.id.Tabbar_Image0); mTabbarImage[1] = (ImageView) findViewById(R.id.Tabbar_Image2); mTabbarLine[0] = (View) findViewById(R.id.Tabbar_Line0); mTabbarLine[1] = (View) findViewById(R.id.Tabbar_Line2); mTabContent[0] = (View) findViewById(R.id.Include0); mTabContent[1] = (View) findViewById(R.id.Include2); for (int i = 0; i < mTabBtnNum; i++) { mTabbarAction[i].setOnClickListener(this); mTabbarImage[i].setColorFilter(getResources().getColor(R.color.grey4)); mTabContent[i].setVisibility(View.GONE); } mTabbarImage[v].setColorFilter(getResources().getColor(R.color.white)); mTabbarLine[v].setBackgroundColor(getResources().getColor(R.color.white)); mTabContent[v].setVisibility(View.VISIBLE); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { setResult(RESULT_OK, mIntent);//인텐트 공유를 위한 부분 finish(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_group) { } else if (id == R.id.nav_setting) {//환경설정 mIntent.setClass(GroupManage.this, Settings.class); startActivityForResult(mIntent, Gl.GROUPMANAGE_SETTINGS); } else if (id == R.id.nav_rate) {//앱 평가 createDialogBox(); } else if (id == R.id.nav_about) {//개발자 정보 startActivity(new Intent(GroupManage.this, About.class)); } else if (id == R.id.nav_share) {//카카오톡 공유 try { final KakaoLink kakaoLink = KakaoLink.getKakaoLink(this); final KakaoTalkLinkMessageBuilder kakaoBuilder = kakaoLink.createKakaoTalkLinkMessageBuilder(); /*메시지 추가*/ //kakaoBuilder.addText("편리한 시간 관리 앱 WHEN"); /*이미지 가로/세로 사이즈는 80px 보다 커야하며, 이미지 용량은 500kb 이하로 제한된다.*/ String url = "http://upload2.inven.co.kr/upload/2015/09/27/bbs/i12820605286.jpg"; kakaoBuilder.addImage(url, 1080, 1920); /*앱 실행버튼 추가*/ kakaoBuilder.addAppButton("설치"); /*앱 링크 추가*/ kakaoBuilder.addAppLink("편리한 그룹 일정 관리 앱 WHEN"); kakaoBuilder.build(); /*메시지 발송*/ kakaoLink.sendMessage(kakaoBuilder, this); } catch (KakaoParameterException e) { e.printStackTrace(); } } else if (id == R.id.nav_logout) {//로그아웃 logout(); setResult(Gl.RESULT_LOGOUT); finish(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == Gl.GROUPMANAGE_CREATEMEET) { if (resultCode == RESULT_OK) { mIntent = intent; Gl.add((Meet) mIntent.getSerializableExtra(Gl.MEET)); meetData.add((Meet) mIntent.getSerializableExtra(Gl.MEET)); MeetAdapter.add((Meet) mIntent.getSerializableExtra(Gl.MEET)); meetDataEmptyCheck(); MeetAdapter.notifyDataSetChanged(); } } if (requestCode == Gl.GROUPMANAGE_INVITEPEOPLE) { if (resultCode == RESULT_OK) { mIntent = intent; Group g = (Group) mIntent.getSerializableExtra(Gl.GROUP); userData.clear(); userData.addAll(g.getMember()); UserAdapter.notifyDataSetChanged(); for (int i = 0; g != null && i < g.getMemberNum(); i++) { Log.w(TAG, "User(" + i + ") : " + g.getMember(i).getName()); } Log.w(TAG, "UserAdapter count : " + UserAdapter.getCount()); } } if (requestCode == Gl.GROUPMANAGE_SELECTDAY) { if (resultCode == RESULT_OK) { mIntent = intent; Meet m = (Meet) mIntent.getSerializableExtra(Gl.MEET); Gl.add(m); MeetAdapter.clear(); MeetAdapter.addAll(Gl.getMeets(g)); MeetAdapter.notifyDataSetChanged(); } } if (requestCode == Gl.GROUPMANAGE_SETTINGS) { if (resultCode == RESULT_OK) { mIntent = intent; initNavigationView(); } if (resultCode == com.teamw.ysm0622.app_when.global.Gl.RESULT_DELETE) { setResult(com.teamw.ysm0622.app_when.global.Gl.RESULT_DELETE); finish(); } } } @Override public void onClick(View v) { if (v.getId() == mToolbarAction[0].getId()) { // back button mDrawer.openDrawer(mNavView); } if (v.getId() == mToolbarAction[1].getId()) {//Meeting 데이터 새로고침 BackgroundTask mTask = new BackgroundTask(); mTask.execute(g); } if (v.getId() == mTabbarAction[0].getId() || v.getId() == mTabbarAction[1].getId()) {//일정 목록, 구성원 선택 for (int i = 0; i < mTabBtnNum; i++) { mTabbarImage[i].clearColorFilter(); mTabbarImage[i].setColorFilter(getResources().getColor(R.color.grey4), PorterDuff.Mode.SRC_ATOP); mTabbarLine[i].setBackgroundColor(getResources().getColor(R.color.colorPrimary)); mTabContent[i].setVisibility(View.GONE); if (v.getId() == mTabbarAction[i].getId()) { mTabbarImage[i].setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP); mTabbarLine[i].setBackgroundColor(getResources().getColor(R.color.white)); mTabContent[i].setVisibility(View.VISIBLE); if (i == 0) mToolbarTitle.setText(getResources().getString(R.string.meet_list)); if (i == 1) { mToolbarTitle.setText(getResources().getString(R.string.member)); } // if (i == 2)mToolbarTitle.setText(getResources().getString(R.string.meet_info)); } } } if (v.equals(mFab[0])) {//일정 생성 mIntent.setClass(GroupManage.this, CreateMeet.class); mIntent.putExtra(Gl.SELECT_DAY_MODE, 0); startActivityForResult(mIntent, Gl.GROUPMANAGE_CREATEMEET); } if (v.equals(mFab[1])) {//그룹으로 새로운 유저 초대 mIntent.setClass(GroupManage.this, InvitePeople.class); mIntent.putExtra(Gl.INVITE_MODE, 1); startActivityForResult(mIntent, Gl.GROUPMANAGE_INVITEPEOPLE); } } //Remove Shared Preferences of LOGIN_DATA public void logout() { mEdit.clear(); mEdit.commit(); } //평가 다이어로그 public void createDialogBox() { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.rate_alert, null); TextView Title = (TextView) view.findViewById(R.id.drop_title); TextView Content = (TextView) view.findViewById(R.id.drop_content); ImageView Btn[] = new ImageView[3]; Btn[0] = (ImageView) view.findViewById(R.id.drop_btn1); Btn[1] = (ImageView) view.findViewById(R.id.drop_btn2); Btn[2] = (ImageView) view.findViewById(R.id.drop_btn3); for (int i = 0; i < 3; i++) { Btn[i].setColorFilter(getResources().getColor(R.color.colorAccent)); } Btn[0].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialBox.cancel(); mNavView.setCheckedItem(R.id.nav_group); } }); Btn[1].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialBox.cancel(); mNavView.setCheckedItem(R.id.nav_group); } }); Btn[2].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialBox.cancel(); mNavView.setCheckedItem(R.id.nav_group); } }); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(view); mDialBox = builder.create(); mDialBox.show(); } }
TeamWHEN/WHEN
app/src/main/java/com/teamw/ysm0622/app_when/group/GroupManage.java
Java
mit
22,331
<?php /* * This file is part of php-cache organization. * * (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Cache\AdapterBundle\Factory; use Cache\Adapter\MongoDB\MongoDBCachePool; use MongoDB\Driver\Manager; use Symfony\Component\OptionsResolver\OptionsResolver; /** * @author Tobias Nyholm <tobias.nyholm@gmail.com> * @author Aaron Scherer <aequasi@gmail.com> */ final class MongoDBFactory extends AbstractDsnAdapterFactory { protected static $dependencies = [ ['requiredClass' => 'Cache\Adapter\MongoDB\MongoDBCachePool', 'packageName' => 'cache/mongodb-adapter'], ]; /** * {@inheritdoc} */ public function getAdapter(array $config) { $dsn = $this->getDsn(); if (empty($dsn)) { $manager = new Manager(sprintf('mongodb://%s:%s', $config['host'], $config['port'])); } else { $manager = new Manager($dsn->getDsn()); } $collection = MongoDBCachePool::createCollection($manager, $config['namespace']); return new MongoDBCachePool($collection); } /** * {@inheritdoc} */ protected static function configureOptionResolver(OptionsResolver $resolver) { parent::configureOptionResolver($resolver); $resolver->setDefaults( [ 'host' => '127.0.0.1', 'port' => 11211, 'namespace' => 'cache', ] ); $resolver->setAllowedTypes('host', ['string']); $resolver->setAllowedTypes('port', ['string', 'int']); $resolver->setAllowedTypes('namespace', ['string']); } }
aequasi/adapter-bundle
src/Factory/MongoDBFactory.php
PHP
mit
1,796
# ckSlider jQuery content slider I developed while working at Moresoda. I needed something that I knew inside out and was extensible. It has extension points to run custom code on load as well as before and after a transition. ## Getting Started Download the [production version][min] or the [development version][max]. [min]: https://raw.github.com/ckimrie/ckslider/master/dist/ckslider.min.js [max]: https://raw.github.com/ckimrie/ckslider/master/dist/ckslider.js In your web page: ```html <script src="jquery.js"></script> <script src="dist/ckslider.min.js"></script> <script> $(document).ready(function($) { $('.slider').ckslider(); }); </script> ``` ## Documentation Complete list of configuration options and defaults: ```javascript defaultConfig = { 'fadeInDuration' : 800, 'slideDuration' : 800, 'delay' : 5000, 'start' : 1, 'transition' : 'fade', //Accepts 'fade' or 'slide' 'autoplay' : true, 'interactionDisablesAutoplay': true, 'preloadImages' : true, 'slideInactiveOpacity': 0.5, 'inactiveZIndex' : 1, 'zIndexLayer1' : 5, 'zIndexLayer2' : 10, 'zIndexLayer3' : 15, 'pauseOnClick' : true, 'hideInactiveSlides' : true, 'legacyIEMode' : jQuery('html').is('.ie6, .ie7, .ie8'), 'height' : null, 'width' : null, 'loadingClass' : 'loading', 'slideActiveClass' : 'active', 'slideClass' : 'slide', 'indicatorActiveClass' : 'active', 'slideIndicatorWrapper' : '.counter', 'slideIndicatorElement' : 'a', 'nextBtn' : '.next', 'prevBtn' : '.previous', 'direction' : 'forward', 'onStart' : function () { }, 'onBeforeTransition' : function () { }, 'onAfterTransition' : function () { }, 'onPause' : function () { } }; ``` ## Example ### HTML The root `loading` class is removed after the JS initialises. This is handy for controlling the display on first load ```html <!-- HTML Markup template --> <div class='slider loading'> <!-- Slides --> <div class='slide'>Slide 1</div> <div class='slide'>Slide 2</div> <div class='slide'>Slide 3</div> <!-- Progress/count indicators [Optional] --> <div class='counter'> <a href="#">1</a> <a href="#">2</a> <a href="#">3</a> </div> <!-- Prev/Next buttons [Optional] --> <a href="#" class="previous">Prev</a> <a href="#" class="next">Next</a> </div> ``` ### CSS The slider requires some basic CSS scaffolding ```css .slider { position: relative; } .slider, .slide { height: 400px; width: 700px; } .slide { position: absolute; left:0; right:0; } ``` ### JS _Simple example_ ```javascript //Simply select and initialise with some optional configurations $(document).ready(function($) { $('.slider').ckslider({ 'fadeInDuration' : 800, 'delay' : 5000, }); }); ``` _Advanced example_ The onBeforeTransition config can return a jQuery Deferred object [Optional] in order to halt the slider progress until your custom code / animation finishes. Resolving the Deferred object causes the slider to resume. ```javascript //Simply select and initialise with some optional configurations $(document).ready(function($) { $('.slider').ckslider({ onBeforeTransition: function() { var def = new $.Deferred(); //Do something that takes time setTimeout(function(){ //Resolving the deferred object causes the slider to continue as normal def.resolve(); }, 2000); return def; } }); }); ``` ## Release History * 0.2 Added slide transition * 0.1 Public Release
ckimrie/ckslider
README.md
Markdown
mit
3,412
--- title: apa49 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: a49 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
pblack/kaldi-hugo-cms-template
site/content/pages2/apa49.md
Markdown
mit
339
from django.apps import AppConfig from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType class AppConfig(AppConfig): name = '.'.join(__name__.split('.')[:-1]) label = 'icekit_plugins_iiif' verbose_name = "IIIF Basics" def ready(self): # Create custom permission pointing to User, because we have no other # model to hang it off for now... # TODO This is a hack, find a better way User = get_user_model() try: # this doesn't work if migrations haven't been updated, resulting # in "RuntimeError: Error creating new content types. Please make # sure contenttypes is migrated before trying to migrate apps # individually." content_type = ContentType.objects.get_for_model(User) Permission.objects.get_or_create( codename='can_use_iiif_image_api', name='Can Use IIIF Image API', content_type=content_type, ) except RuntimeError: pass
ic-labs/django-icekit
icekit/plugins/iiif/apps.py
Python
mit
1,144
$(function () { $('div').browser(); });
tomasbulva/browserdetector
demo/demo.js
JavaScript
mit
40
<?php /** * This file is part of RedisClient. * git: https://github.com/cheprasov/php-redis-client * * (C) Alexander Cheprasov <acheprasov84@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Test\Integration\Version4x0; include_once(__DIR__ . '/../Version3x2/ClusterTest.php'); class ClusterTest extends \Test\Integration\Version3x2\ClusterTest { }
cheprasov/php-redis-client
tests/Integration/Version4x0/ClusterTest.php
PHP
mit
461
package restaurant_haus.test.mock; /** * This is the base class for all mocks. * * @author Sean Turner * */ public class Mock { private String name; public EventLog log = new EventLog(); public Mock(String name) { this.name = name; } public String getName() { return name; } public String toString() { return this.getClass().getName() + ": " + name; } }
Narwhalprime/simcity201-team-project
src/restaurant_haus/test/mock/Mock.java
Java
mit
381
import { PipeTransform, Pipe } from '@angular/core'; @Pipe({ name: 'hlKeys' }) export class KeysPipe implements PipeTransform { transform(value, args: string[]): any { let keys = []; for (let key in value) { keys.push(key); } return keys; } }
ivanna-ostrovets/flask-headlines
front-end/src/pipes/keys.pipe.ts
TypeScript
mit
270
package com.everest.pontointeligente.api.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Optional; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Transient; import com.everest.pontointeligente.api.enums.PerfilEnum; @Entity @Table(name = "funcionario") public class Funcionario implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "nome", nullable = false) private String nome; @Column(name = "email", nullable = false) private String email; @Column(name = "senha", nullable = false) private String senha; @Column(name = "cpf", nullable = false) private String cpf; @Column(name = "valor_hora", nullable = true) private BigDecimal valorHora; @Column(name = "qtd_horas_trabalho_dia", nullable = true) private Float qtdHorasTrabalhoDia; @Column(name = "qtd_horas_almoco", nullable = true) private Float qtdHorasAlmoco; @Column(name = "perfil", nullable = true) @Enumerated(EnumType.STRING) private PerfilEnum perfil; @Column(name = "data_criacao", nullable = false) private Date dataCriacao; @Column(name = "data_atualizacao", nullable = false) private Date dataAtualizacao; @ManyToOne(fetch = FetchType.EAGER) private Empresa empresa; @OneToMany(mappedBy = "funcionario", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Lancamento> lancamentos; public Funcionario() { } @Transient public Optional<BigDecimal> getValorHoraOpt(){ return Optional.ofNullable(this.valorHora); } @Transient public Optional<Float> getQtdHorasTrabalhoDiaOpt(){ return Optional.ofNullable(this.qtdHorasTrabalhoDia); } @Transient public Optional<Float> getQtdHorasAlmocoOpt(){ return Optional.ofNullable(this.qtdHorasAlmoco); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public BigDecimal getValorHora() { return valorHora; } public void setValorHora(BigDecimal valorHora) { this.valorHora = valorHora; } public Float getQtdHorasTrabalhoDia() { return qtdHorasTrabalhoDia; } public void setQtdHorasTrabalhoDia(Float qtdHorasTrabalhoDia) { this.qtdHorasTrabalhoDia = qtdHorasTrabalhoDia; } public Float getQtdHorasAlmoco() { return qtdHorasAlmoco; } public void setQtdHorasAlmoco(Float qtdHorasAlmoco) { this.qtdHorasAlmoco = qtdHorasAlmoco; } public PerfilEnum getPerfil() { return perfil; } public void setPerfil(PerfilEnum perfil) { this.perfil = perfil; } public Date getDataCriacao() { return dataCriacao; } public void setDataCriacao(Date dataCriacao) { this.dataCriacao = dataCriacao; } public Date getDataAtualizacao() { return dataAtualizacao; } public void setDataAtualizacao(Date dataAtualizacao) { this.dataAtualizacao = dataAtualizacao; } public Empresa getEmpresa() { return empresa; } public void setEmpresa(Empresa empresa) { this.empresa = empresa; } public List<Lancamento> getLancamentos() { return lancamentos; } public void setLancamentos(List<Lancamento> lancamentos) { this.lancamentos = lancamentos; } @PrePersist public void prePersist(){ final Date atual = new Date(); this.dataCriacao = atual; this.dataAtualizacao = atual; } @PreUpdate public void preUpdate() { this.dataAtualizacao = new Date(); } @Override public String toString() { return "Funcionario [id=" + id + ", nome=" + nome + ", email=" + email + ", senha=" + senha + ", cpf=" + cpf + ", valorHora=" + valorHora + ", qtdHorasTrabalhoDia=" + qtdHorasTrabalhoDia + ", qtdHorasAlmoco=" + qtdHorasAlmoco + ", perfil=" + perfil + ", dataCriacao=" + dataCriacao + ", dataAtualizacao=" + dataAtualizacao + ", empresa=" + empresa + ", lancamentos=" + lancamentos + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Funcionario other = (Funcionario) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
rinaldo-santana/ponto-inteligente-api
src/main/java/com/everest/pontointeligente/api/entities/Funcionario.java
Java
mit
5,335
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_03.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow.label.xml Template File: point-flaw-03.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * Sinks: type_overrun_memcpy * GoodSink: Perform the memcpy() and prevent overwriting part of the structure * BadSink : Overwrite part of the structure by incorrectly using the sizeof(struct) in memcpy() * Flow Variant: 03 Control flow: if(5==5) and if(5!=5) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #define SRC_STR L"0123456789abcde0123" typedef struct _charVoid { wchar_t charFirst[16]; void * voidSecond; void * voidThird; } charVoid; #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_03_bad() { if(5==5) { { charVoid * structCharVoid = (charVoid *)malloc(sizeof(charVoid)); structCharVoid->voidSecond = (void *)SRC_STR; /* Print the initial block pointed to by structCharVoid->voidSecond */ printWLine((wchar_t *)structCharVoid->voidSecond); /* FLAW: Use the sizeof(*structCharVoid) which will overwrite the pointer y */ memcpy(structCharVoid->charFirst, SRC_STR, sizeof(*structCharVoid)); structCharVoid->charFirst[(sizeof(structCharVoid->charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */ printWLine((wchar_t *)structCharVoid->charFirst); printWLine((wchar_t *)structCharVoid->voidSecond); free(structCharVoid); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(5!=5) instead of if(5==5) */ static void good1() { if(5!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { charVoid * structCharVoid = (charVoid *)malloc(sizeof(charVoid)); structCharVoid->voidSecond = (void *)SRC_STR; /* Print the initial block pointed to by structCharVoid->voidSecond */ printWLine((wchar_t *)structCharVoid->voidSecond); /* FIX: Use the sizeof(structCharVoid->charFirst) to avoid overwriting the pointer y */ memcpy(structCharVoid->charFirst, SRC_STR, sizeof(structCharVoid->charFirst)); structCharVoid->charFirst[(sizeof(structCharVoid->charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */ printWLine((wchar_t *)structCharVoid->charFirst); printWLine((wchar_t *)structCharVoid->voidSecond); free(structCharVoid); } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(5==5) { { charVoid * structCharVoid = (charVoid *)malloc(sizeof(charVoid)); structCharVoid->voidSecond = (void *)SRC_STR; /* Print the initial block pointed to by structCharVoid->voidSecond */ printWLine((wchar_t *)structCharVoid->voidSecond); /* FIX: Use the sizeof(structCharVoid->charFirst) to avoid overwriting the pointer y */ memcpy(structCharVoid->charFirst, SRC_STR, sizeof(structCharVoid->charFirst)); structCharVoid->charFirst[(sizeof(structCharVoid->charFirst)/sizeof(wchar_t))-1] = L'\0'; /* null terminate the string */ printWLine((wchar_t *)structCharVoid->charFirst); printWLine((wchar_t *)structCharVoid->voidSecond); free(structCharVoid); } } } void CWE122_Heap_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_03_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_03_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_03_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
maurer/tiamat
samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s11/CWE122_Heap_Based_Buffer_Overflow__wchar_t_type_overrun_memcpy_03.c
C
mit
4,687
./_rel/calcjs_release/bin/calcjs_release attach
calcjs/calc.js
attach.sh
Shell
mit
47
#include "stdafx.h" #include "TerrainTileset.h" namespace GameScope { ////////////////////////////////////////////////////////////////////////// bool TerrainTilesetDesc::ReadDescription(FileSystem& fileSystem, JsonElement jsonSource) { if (!jsonSource) { return false; } // read tileset palette std::string palettePath; std::string filesource = JsonGet(jsonSource, "palette", ""); if (!fileSystem.PathToFile(filesource, palettePath)) { Logf("Warning: terrain tileset palette not found"); return false; } if (!tilesetPalette.LoadFromFile(palettePath)) { Logf("Warning: cannot load terrain tileset palette"); return false; } // get sprite sheet path filesource = FSCombinePath({"tilesets", tilesetName, "terrain", tilesetName + ".png"}); if (!fileSystem.PathToFile(filesource, terrainSpriteSheet)) { Logf("Warning: cannot locate terrain sprite sheet for %s", tilesetName.c_str()); return false; } // read palette color cycing effects for (JsonElement effect = jsonSource.FindElement("palette_color_cycling").FirstChild(); effect; effect = effect.NextSibling()) { PaletteColorCycling effectDescription {}; if (!effect.GetElementName(effectDescription.effectName)) { Logf("Warning: cannot find effect name"); continue; } // read effect properties effectDescription.colorFirst = JsonGet(effect, "from", 0); effectDescription.colorLast = JsonGet(effect, "to", 0); // verify effect properties bool goodEffect = (effectDescription.colorFirst > -1 && effectDescription.colorFirst < NUM_PALETTE_COLORS) && (effectDescription.colorLast > -1 && effectDescription.colorLast < NUM_PALETTE_COLORS) && (effectDescription.colorFirst <= effectDescription.colorLast); assert(goodEffect); if(!goodEffect) { Logf("Warning: palette effect has bad parameters"); continue; } paletteEffects.emplace_back(effectDescription); } // read solid tiles int32_t itype = 0; for (JsonElement terrainTile = jsonSource.FindElement("solid_tiles").FirstChild(); terrainTile; terrainTile = terrainTile.NextSibling()) { assert(itype < NUM_TERRAIN_TILE_TYPES); if (itype == NUM_TERRAIN_TILE_TYPES) { break; } JsonReadArray(terrainTile, solidTiles.indices[itype++]); } // read mixed tiles itype = 0; for (JsonElement mixed = jsonSource.FindElement("mixed_tiles").FirstChild(); mixed; mixed = mixed.NextSibling()) { assert(itype < NUM_MIXED_TERRAIN_TILE_TYPES); if (itype == NUM_MIXED_TERRAIN_TILE_TYPES) { break; } int32_t itile = 0; for (JsonElement tile = mixed.FirstChild(); tile; tile = tile.NextSibling()) { JsonReadArray(tile, mixedTiles.indices[itype][itile++]); } ++itype; } return true; } ////////////////////////////////////////////////////////////////////////// bool TerrainTileset::Initialize(const TerrainTilesetDesc& desc) { m_NumTilesPerX = {}; m_NumTilesPerY = {}; m_TilesetImage = GfxLoadImage(m_RenderDeviceInstance, desc.terrainSpriteSheet); assert(m_TilesetImage); if (!m_TilesetImage) { return false; } m_TerrainTilesetDesc = desc; m_NumTilesPerX = m_TilesetImage->GetTextureSizeW() / MAP_TILE_SIZE_W; m_NumTilesPerY = m_TilesetImage->GetTextureSizeH() / MAP_TILE_SIZE_H; assert(m_NumTilesPerX > 0 || m_NumTilesPerY > 0); if (m_NumTilesPerX < 1 || m_NumTilesPerY < 1) { return false; } return true; } void TerrainTileset::DrawTerrainTile(const Point& topLeftCorner, int32_t terrainTileIndex) { const Rectangle rcImage = { (terrainTileIndex % m_NumTilesPerX) * MAP_TILE_SIZE_W, (terrainTileIndex / m_NumTilesPerX) * MAP_TILE_SIZE_H, MAP_TILE_SIZE_W, MAP_TILE_SIZE_H }; const Point3D position = { topLeftCorner.x, topLeftCorner.y, 0 }; GfxDrawImageParams params; params.paletteIndex = GFX_PALETTE_PRIMARY; params.flipx = 0; params.flipy = 0; m_RenderDeviceInstance.RenderSubImage(m_TilesetImage, rcImage, position, params); } bool TerrainTileset::GetSolidTerrainTile(eTerrainTile terrainTile, int32_t& tileIndex) const { bool isTerrainTile = terrainTile < NUM_TERRAIN_TILE_TYPES; assert(isTerrainTile); if (isTerrainTile) { tileIndex = m_TerrainTilesetDesc.solidTiles.indices[terrainTile][0]; } return isTerrainTile; } bool TerrainTileset::GetMixedTerrainTile(eMixedTerrainTile terrainTile, int32_t index, int32_t& tileIndex) const { bool isTerrainTile = terrainTile < NUM_MIXED_TERRAIN_TILE_TYPES; assert(isTerrainTile); if (isTerrainTile) { assert(index < 15); if (index > 14) { return false; } tileIndex = m_TerrainTilesetDesc.mixedTiles.indices[terrainTile][index][0]; } return isTerrainTile; } void TerrainTileset::UpdatePaletteCyclingEffects(int32_t msDeltaTime) { m_CyclingEffectsTime += msDeltaTime; if (m_CyclingEffectsTime < TIME_FOR_CYCLING_FRAME_MSECONDS) { return; } for (const PaletteColorCycling& effect: m_TerrainTilesetDesc.paletteEffects) { ShiftPaletteColors(m_TerrainTilesetDesc.tilesetPalette, effect.colorFirst, effect.colorLast); } m_CyclingEffectsTime -= TIME_FOR_CYCLING_FRAME_MSECONDS; } void TerrainTileset::ApplyPaletteCycling() { for (const PaletteColorCycling& effect: m_TerrainTilesetDesc.paletteEffects) { m_RenderDeviceInstance.SetPaletteEntries( m_TerrainTilesetDesc.tilesetPalette.entries + effect.colorFirst, effect.colorLast - effect.colorFirst + 1, effect.colorFirst, GFX_PALETTE_PRIMARY ); } } ////////////////////////////////////////////////////////////////////////// bool TerrainTilesetManager::Initialize(FileSystem& fileSystem) { std::string descDocumentPath; if (!fileSystem.PathToFile("Configurations/TerrainTilesets.json", descDocumentPath)) { Logf("Warning: cannot find terrain tilesets configuration file"); return false; } JsonDocument document; if (!document.LoadFromFile(descDocumentPath, document)) { Logf("Warning: cannot load terrain tilesets configuration file"); return false; } // elements mTilesets[TILESET_SUMMER].tilesetName = "summer"; mTilesets[TILESET_WINTER].tilesetName = "winter"; mTilesets[TILESET_SWAMP].tilesetName = "swamp"; mTilesets[TILESET_WASTELAND].tilesetName = "wasteland"; // load descriptions for (TerrainTilesetDesc& element: mTilesets) { JsonElement descElement = document.GetRootElement().FindElement(element.tilesetName); if (!element.ReadDescription(fileSystem, descElement)) { Logf("Warning: description for %s not found", element.tilesetName.c_str()); continue; } } // for element return true; } // Load specified terrain tileset // @param renderDeviceInstance: Render device instance // @param terrainTilesetID: Terrain tileset identifier Reference<TerrainTileset> TerrainTilesetManager::LoadTileset(GfxRenderDevice& renderDeviceInstance, eTileset terrainTilesetID) const { assert(terrainTilesetID < NUM_TILESETS); return TerrainTileset::CreateInstance(renderDeviceInstance, mTilesets[terrainTilesetID]); } } // namespace GameScope
codenamecpp/RTS2
RTS2/TerrainTileset.cpp
C++
mit
7,781
#include <config/enums.h> #include <h5pp/h5pp.h> #include <tools/common/h5.h> #include <tools/common/log.h> std::string tools::common::h5::resume::extract_state_name(std::string_view state_prefix) { constexpr std::string_view state_pattern = "state_"; std::string state_name; std::string::size_type start_pos = state_prefix.find(state_pattern); if(start_pos != std::string::npos) { std::string::size_type len = state_prefix.find('/', start_pos) - start_pos; state_name = state_prefix.substr(start_pos, len); // E.g. "/xDMRG/state_0/results/..." would match state_0 } return state_name; } std::optional<size_t> tools::common::h5::resume::extract_state_number(std::string_view state_prefix) { std::string state_name = extract_state_name(state_prefix); std::string state_number; for(const auto &c : state_name) { if(std::isdigit(c)) state_number.push_back(c); } try { size_t number = std::stoul(state_number); return number; } catch(const std::exception &err) { tools::log->info("Could not convert {} to a number: {}", state_number, err.what()); return std::nullopt; } } std::vector<std::string> tools::common::h5::resume::find_resumable_states(const h5pp::File &h5file, AlgorithmType algo_type, std::string_view search) { std::string_view algo_name = enum2sv(algo_type); std::vector<std::string> state_prefix_candidates; if(search.empty()) tools::log->info("Searching for resumable states from algorithm [{}] in file [{}]", algo_name, h5file.getFilePath()); else tools::log->info("Searching for resumable states with keyword [{}] from algorithm [{}] in file [{}]", search, algo_name, h5file.getFilePath()); for(const auto &candidate : h5file.getAttributeNames("common/storage_level")) { if(candidate.find(algo_name) != std::string::npos and h5file.readAttribute<std::string>(candidate, "common/storage_level") == "FULL") state_prefix_candidates.push_back(candidate); } tools::log->info("Found state candidates: {}", state_prefix_candidates); // Apply the search filter if(not search.empty()) { auto search_filter = [search](std::string_view x) { return x.find(search) == std::string::npos; }; state_prefix_candidates.erase(std::remove_if(state_prefix_candidates.begin(), state_prefix_candidates.end(), search_filter), state_prefix_candidates.end()); tools::log->info("States matching keyword [{}]: {}", search, state_prefix_candidates); } // Return the results if done if(state_prefix_candidates.empty()) return {}; if(state_prefix_candidates.size() == 1) return {state_prefix_candidates[0]}; // Here we collect unique state names std::vector<std::string> state_names; for(const auto &pfx : state_prefix_candidates) { auto name = h5file.readAttribute<std::string>(pfx, "common/state_name"); if(not name.empty()) { if(std::find(state_names.begin(), state_names.end(), name) == state_names.end()) { state_names.emplace_back(name); } } } // Sort state names in ascending order std::sort(state_names.begin(), state_names.end(), std::less<>()); // For each state name, we find the one with highest step number std::vector<std::string> state_candidates_latest; for(const auto &name : state_names) { // Collect the candidates that have the current state name and their step std::vector<std::pair<size_t, std::string>> matching_candidates; for(const auto &candidate : state_prefix_candidates) { if(candidate.find(name) == std::string::npos) continue; auto steps = h5file.readAttribute<size_t>(candidate, "common/step"); matching_candidates.emplace_back(std::make_pair(steps, candidate)); } // Sort according to step number in decreasing order std::sort(matching_candidates.begin(), matching_candidates.end(), [](auto &lhs, auto &rhs) { if(lhs.first != rhs.first) return lhs.first > rhs.first; // Take care of cases with repeated step numbers else if(lhs.second.find("finished") != std::string::npos and rhs.second.find("finished") == std::string::npos) return true; else if(lhs.second.find("iter") != std::string::npos and rhs.second.find("iter") == std::string::npos) return true; return false; }); for(const auto &candidate : matching_candidates) tools::log->info("Candidate step {} : [{}]", candidate.first, candidate.second); // Add the front candidate state_candidates_latest.emplace_back(matching_candidates.front().second); } return state_candidates_latest; }
DavidAce/DMRG
source/tools/common/h5/resume.cpp
C++
mit
4,881
using Cofoundry.Domain.Data; namespace Cofoundry.Domain.Internal { /// <summary> /// Common mapping functionality for <see cref="EntityAccessRule"/> projections. /// </summary> public interface IEntityAccessRuleSetMapper { /// <summary> /// Maps an entity with access restrictions to a new <see cref="EntityAccessRuleSet"/> /// instance. If there are no access rules, then null is returned. The AccessRules collection /// must be included in the <paramref name="entity"/> EF query. /// </summary> /// <param name="entity"> /// The entity to map from. Cannot be null. The AccessRules collection must be included in the /// <paramref name="entity"/> EF query. /// </param> EntityAccessRuleSet Map<TAccessRule>(IEntityAccessRestrictable<TAccessRule> entity) where TAccessRule : IEntityAccessRule; } }
cofoundry-cms/cofoundry
src/Cofoundry.Domain/Domain/AccessRules/Mappers/IEntityAccessRuleSetMapper.cs
C#
mit
921
class QuestionsController < ApplicationController def index @questions = Question.all end def show @question = Question.find(params[:id]) # @answers = @question.answers end end
sebsonic2o/stack-overflaw
stack_overflaw/app/controllers/questions_controller.rb
Ruby
mit
198
#ifndef ScheduledAction_h #define ScheduledAction_h #include "script/include/squirrel.h" #include <wtf/Timer.h> class DOMTimer; class ThreadTimers; class ScheduledAction { public: ScheduledAction(HSQUIRRELVM v, HSQOBJECT* function, int timeout, bool singleShot, ThreadTimers* threadTimers, DOMTimer* pDOMTimer); ~ScheduledAction(); void Fire(Timer<ScheduledAction>*); void ref() {refCount++;} void deref(); void SetTimerId(int timerId) {m_timerId = timerId;} protected: void Start(int timeout, bool singleShot); int refCount; HSQOBJECT m_function; HSQUIRRELVM m_v; Timer<ScheduledAction> m_timer; int m_bSingleShot; DOMTimer* m_DOMTimer; int m_timerId; }; #endif // ScheduledAction_h
weolar/kdguigl
kdgui/Core/ScheduledAction.h
C
mit
709
package com.bkahlert.nebula.information; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.text.AbstractInformationControl; import org.eclipse.jface.text.IInformationControlExtension2; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.menus.IMenuService; import com.bkahlert.nebula.InformationManagerSourceProvider; import com.bkahlert.nebula.information.extender.IInformationControlExtender; /** * This is a typed version of the {@link IInformationControlExtension2}.<br> * Instead of having to override * {@link IInformationControlExtension2#setInput(Object)} you have to override * {@link #load(Object)} that returns a boolean whether to show information or * not. * <p> * <strong>Make sure to override * {@link #getInformationPresenterControlCreator()} if you want to allow the * user to hover the popup and get an enhanced version.</strong> * <p> * Using the {@link IInformationControlExtender}s {@link InformationControl}s * can be extended. * * @author bkahlert * * @param <INFORMATION> */ public abstract class InformationControl<INFORMATION> extends AbstractInformationControl implements IInformationControlExtension2 { private static final Logger LOGGER = Logger .getLogger(InformationControl.class); @SuppressWarnings("unchecked") protected static <INFORMATION> List<IInformationControlExtender<INFORMATION>> getExtenders( ClassLoader classLoader, Class<INFORMATION> targetInformationClass) { IConfigurationElement[] config = Platform.getExtensionRegistry() .getConfigurationElementsFor("com.bkahlert.nebula.information"); final List<IInformationControlExtender<INFORMATION>> extenders = new ArrayList<IInformationControlExtender<INFORMATION>>(); for (IConfigurationElement configElement : config) { try { Object instance = configElement .createExecutableExtension("extenderClass"); if (instance instanceof IInformationControlExtender<?>) { IInformationControlExtender<?> extender = (IInformationControlExtender<?>) instance; Class<?> informationClass = extender.getInformationClass(); boolean sameClass = informationClass == targetInformationClass; if (!sameClass) { boolean sameClassByForeignClassLoader = false; if (classLoader != null) { try { sameClassByForeignClassLoader = classLoader .loadClass(informationClass.getName()) == targetInformationClass; } catch (ClassNotFoundException e) { } } if (!sameClassByForeignClassLoader) { boolean sameClassByOwnClassLoader = false; try { sameClassByOwnClassLoader = Class .forName(informationClass.getName()) == targetInformationClass; } catch (ClassNotFoundException e) { LOGGER.error(e); } if (!sameClassByOwnClassLoader) { LOGGER.info(IInformationControlExtender.class .getSimpleName() + " for type " + extender.getInformationClass() .getSimpleName() + " is not compatible with " + targetInformationClass .getSimpleName()); continue; } } } try { extenders .add((IInformationControlExtender<INFORMATION>) extender); } catch (ClassCastException ex) { LOGGER.error( IInformationControlExtender.class .getSimpleName() + " could not be cast.", ex); } } } catch (CoreException e2) { LOGGER.error("Error instantiating " + configElement.getAttribute("extenderClass")); } } return extenders; } private ClassLoader extenderInformationClassLoader; private List<IInformationControlExtender<INFORMATION>> extenders = null; private Class<INFORMATION> informationClass = null; private boolean hasContents = false; private Composite parent = null; protected InformationControl(ClassLoader extenderInformationClassLoader, Class<INFORMATION> informationClass, Shell parentShell, String statusFieldText, Object noCreate) { super(parentShell, statusFieldText); this.extenderInformationClassLoader = extenderInformationClassLoader; this.informationClass = informationClass; } protected InformationControl(ClassLoader extenderInformationClassLoader, Class<INFORMATION> informationClass, Shell parentShell, ToolBarManager toolBarManager, Object noCreate) { super(parentShell, toolBarManager); this.informationClass = informationClass; toolBarManager.add(new GroupMarker( IWorkbenchActionConstants.MB_ADDITIONS)); this.addMenuServiceContributions(toolBarManager); } public InformationControl(ClassLoader extenderInformationClassLoader, Class<INFORMATION> informationClass, Shell parentShell, String statusFieldText) { this(extenderInformationClassLoader, informationClass, parentShell, statusFieldText, null); this.create(); } /** * Constructs a new {@link InformationControl} using the specified * {@link ToolBarManager}. * <p> * You can make contributions to your toolBarManager using the * <code>plugin.xml-menuContributions</code> with location set to * <code>toolbar:com.bkahlert.nebula.information</code>. * <p> * An {@link IWorkbenchActionConstants#MB_ADDITIONS} is automatically added * to the end of the {@link ToolBarManager}. * * @param parentShell * @param toolBarManager */ public InformationControl(ClassLoader extenderInformationClassLoader, Class<INFORMATION> informationClass, Shell parentShell, ToolBarManager toolBarManager) { this(extenderInformationClassLoader, informationClass, parentShell, toolBarManager, null); this.create(); } protected void addMenuServiceContributions(ToolBarManager toolBarManager) { IMenuService menuService = (IMenuService) PlatformUI.getWorkbench() .getService(IMenuService.class); menuService.populateContributionManager(toolBarManager, "toolbar:com.bkahlert.nebula.information"); } @Override protected final void createContent(final Composite parent) { this.parent = parent; this.extenders = InformationControl.<INFORMATION> getExtenders( this.extenderInformationClassLoader, this.informationClass); Composite extensionComposite = this.create(parent); if (extensionComposite != null) { for (IInformationControlExtender<INFORMATION> extender : this.extenders) { extender.extend(this, extensionComposite); } } } @SuppressWarnings("unchecked") @Override public final void setInput(Object input) { try { INFORMATION information = (INFORMATION) input; InformationManagerSourceProvider.controlChanged(this); InformationManagerSourceProvider.inputChanged(information); this.hasContents = this.load(information); for (IInformationControlExtender<INFORMATION> extender : this.extenders) { extender.extend(this, information); } this.parent.layout(); } catch (ClassCastException e) { this.hasContents = false; } } @Override public void setVisible(boolean visible) { if (!visible) { InformationManagerSourceProvider.controlChanged(null); InformationManagerSourceProvider.inputChanged(null); } super.setVisible(visible); } @Override public boolean isVisible() { return this.getShell().isVisible(); } /** * Creates the popup's user content (not the technical stuff like the * toolbar) * * @param parent * @return the part that may be extended */ public abstract Composite create(Composite parent); public abstract boolean load(INFORMATION input); /** * This implementation delegates this method's return value computation to * {@link #load(Object)}. */ @Override public final boolean hasContents() { return this.hasContents; } @Override public Point computeSizeHint() { // FIXME currently ignores size constraints return this.getShell().computeSize(1000, SWT.DEFAULT, true); // return super.computeSizeHint(); } @Override public InformationControlCreator<INFORMATION> getInformationPresenterControlCreator() { return null; } }
bkahlert/com.bkahlert.nebula
src/com/bkahlert/nebula/information/InformationControl.java
Java
mit
8,459
<div id="currency" class="form-group has-feedback formio-component formio-component-currency formio-component-currency required" ref="component"> <label class="control-label field-required" for="currency-currency"> Currency </label> <div ref="element"> <input ref="input" name="data[currency]" type="text" class="form-control" lang="en" inputmode="decimal" value="" id="currency-currency"></input> </div> <div ref="messageContainer" class="formio-errors invalid-feedback"></div> </div>
formio/formio.js
test/renders/component-bootstrap3-currency-required.html
HTML
mit
505
class ExportMailer < ActionMailer::Base default_url_options[:host] = SITE_URL def zip(address, zip_path) recipients address from Settings.export_mail_address || %(Tirade <tirade+no-reply@lanpartei.de>) subject "Your exported Site" body :zip_path => zip_path sent_on Time.now # attachment :content_type => "application/zip", :body => File.read(zip_path) end end
niklas/Tirade
app/models/export_mailer.rb
Ruby
mit
420
<?php namespace Elastica\ResultSet; use Elastica\ResultSet; /** * Allows multiple ProcessorInterface instances to operate on the same * ResultSet, calling each in turn. */ class ChainProcessor implements ProcessorInterface { /** * @var ProcessorInterface[] */ private $processors; /** * @param ProcessorInterface[] $processors */ public function __construct(array $processors) { $this->processors = $processors; } /** * {@inheritdoc} */ public function process(ResultSet $resultSet) { foreach ($this->processors as $processor) { $processor->process($resultSet); } } }
p365labs/Elastica
lib/Elastica/ResultSet/ChainProcessor.php
PHP
mit
682
'use strict'; import assert from 'assert'; import bot from '../bot.js'; import * as interval from '../interval.js'; import FakeClient from './util/fakeclient.js'; import FakeMessage from './util/fakemessage.js'; describe('./bot.js', () => { let client; beforeEach(() => { interval.enableTestMode(); client = bot(new FakeClient()); client.emit('ready'); }); afterEach(() => { client.emit('disconnected'); interval.disableTestMode(); }); it('help doesn\'t fail', () => { const message = new FakeMessage('!help'); client.emit('message', message); assert.equal(message.replies.length, 1); }); it('ping works', () => { const message = new FakeMessage('!ping'); client.emit('message', message); assert.equal(message.replies.length, 1); assert.equal(message.replies[0], 'pong'); }); });
Tasemu/Gnarly
test/bot.js
JavaScript
mit
819
package main import ( "flag" "fmt" "image/png" "math" "os" "runtime" ) const ( MAX_DIST = 1999999999 PI_180 = 0.017453292 SMALL = 0.000000001 ) func calcShadow(r *Ray, collisionObj int) float64 { shadow := 1.0 //starts with no shadow for i, obj := range scene.objectList { r.interObj = -1 r.interDist = MAX_DIST if obj.Intersect(r, i) && i != collisionObj { shadow *= scene.materialList[obj.Material()].transmitCol } } return shadow } func trace(r *Ray, depth int) (c Color) { for i, obj := range scene.objectList { obj.Intersect(r, i) } if r.interObj >= 0 { matIndex := scene.objectList[r.interObj].Material() interPoint := r.origin.Add(r.direction.Mul(r.interDist)) incidentV := interPoint.Sub(r.origin) originBackV := r.direction.Mul(-1.0) originBackV = originBackV.Normalize() vNormal := scene.objectList[r.interObj].getNormal(interPoint) for _, light := range scene.lightList { switch light.kind { case "ambient": c = c.Add(light.color) case "point": lightDir := light.position.Sub(interPoint) lightDir = lightDir.Normalize() lightRay := Ray{interPoint, lightDir, MAX_DIST, -1} shadow := calcShadow(&lightRay, r.interObj) NL := vNormal.Dot(lightDir) if NL > 0.0 { if scene.materialList[matIndex].difuseCol > 0.0 { // ------- Difuso difuseColor := light.color.Mul(scene.materialList[matIndex].difuseCol).Mul(NL) difuseColor.r *= scene.materialList[matIndex].color.r * shadow difuseColor.g *= scene.materialList[matIndex].color.g * shadow difuseColor.b *= scene.materialList[matIndex].color.b * shadow c = c.Add(difuseColor) } if scene.materialList[matIndex].specularCol > 0.0 { // ----- Especular R := (vNormal.Mul(2).Mul(NL)).Sub(lightDir) spec := originBackV.Dot(R) if spec > 0.0 { spec = scene.materialList[matIndex].specularCol * math.Pow(spec, scene.materialList[matIndex].specularD) specularColor := light.color.Mul(spec).Mul(shadow) c = c.Add(specularColor) } } } } } if depth < scene.traceDepth { if scene.materialList[matIndex].reflectionCol > 0.0 { // -------- Reflexion T := originBackV.Dot(vNormal) if T > 0.0 { vDirRef := (vNormal.Mul(2).Mul(T)).Sub(originBackV) vOffsetInter := interPoint.Add(vDirRef.Mul(SMALL)) rayoRef := Ray{vOffsetInter, vDirRef, MAX_DIST, -1} c = c.Add(trace(&rayoRef, depth+1.0).Mul(scene.materialList[matIndex].reflectionCol)) } } if scene.materialList[matIndex].transmitCol > 0.0 { // ---- Refraccion RN := vNormal.Dot(incidentV.Mul(-1.0)) incidentV = incidentV.Normalize() var n1, n2 float64 if vNormal.Dot(incidentV) > 0.0 { vNormal = vNormal.Mul(-1.0) RN = -RN n1 = scene.materialList[matIndex].IOR n2 = 1.0 } else { n2 = scene.materialList[matIndex].IOR n1 = 1.0 } if n1 != 0.0 && n2 != 0.0 { par_sqrt := math.Sqrt(1 - (n1*n1/n2*n2)*(1-RN*RN)) refactDirV := incidentV.Add(vNormal.Mul(RN).Mul(n1 / n2)).Sub(vNormal.Mul(par_sqrt)) vOffsetInter := interPoint.Add(refactDirV.Mul(SMALL)) refractRay := Ray{vOffsetInter, refactDirV, MAX_DIST, -1} c = c.Add(trace(&refractRay, depth+1.0).Mul(scene.materialList[matIndex].transmitCol)) } } } } return c } func renderPixel(line chan int, done chan bool) { for y := range line { // 1: 1, 5: 2, 8: 3, for x := 0; x < scene.imgWidth; x++ { var c Color yo := y * scene.oversampling xo := x * scene.oversampling for i := 0; i < scene.oversampling; i++ { for j := 0; j < scene.oversampling; j++ { var dir Vector dir.x = float64(xo)*scene.Vhor.x + float64(yo)*scene.Vver.x + scene.Vp.x dir.y = float64(xo)*scene.Vhor.y + float64(yo)*scene.Vver.y + scene.Vp.y dir.z = float64(xo)*scene.Vhor.z + float64(yo)*scene.Vver.z + scene.Vp.z dir = dir.Normalize() r := Ray{scene.cameraPos, dir, MAX_DIST, -1} c = c.Add(trace(&r, 1.0)) yo += 1 } xo += 1 } srq_oversampling := float64(scene.oversampling * scene.oversampling) c.r /= srq_oversampling c.g /= srq_oversampling c.b /= srq_oversampling scene.image.SetRGBA(x, y, c.ToPixel()) //fmt.Println("check") } if y%10 == 0 { fmt.Printf("%d ", y) } } done <- true } var scene *Scene func main() { var sceneFilename string var numWorkers int flag.StringVar(&sceneFilename, "file", "samples/scene.txt", "Scene file to render.") flag.IntVar(&numWorkers, "workers", runtime.NumCPU(), "Number of worker threads.") flag.Parse() scene = NewScene(sceneFilename) done := make(chan bool, numWorkers) line := make(chan int) // launch the workers for i := 0; i < numWorkers; i++ { go renderPixel(line, done) } fmt.Println("Rendering: ", sceneFilename) fmt.Printf("Line (from %d to %d): ", scene.startline, scene.endline) for y := scene.startline; y < scene.endline; y++ { line <- y } close(line) // wait for all workers to finish for i := 0; i < numWorkers; i++ { <-done } output, err := os.Create(sceneFilename[0:len(sceneFilename)-4] + ".png") if err != nil { panic(err) } if err = png.Encode(output, scene.image); err != nil { panic(err) } fmt.Println(" DONE!") }
phrozen/rayito
main.go
GO
mit
5,252
# db Database design Environment: * MySQL Ver 14.14 Distrib 5.6.27, for debian-linux-gnu (x86_64)
mindsurf/db
README.md
Markdown
mit
101
using System; using System.Threading.Tasks; using Bade.IdentityServer.Mappers; using Bade.IdentityServer.Models.ApiResourceViewModels; using IdentityServer4.EntityFramework.DbContexts; using IdentityServer4.EntityFramework.Entities; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Bade.IdentityServer.Controllers { public class ApiResourceController : Controller { private readonly ConfigurationDbContext _context; public ApiResourceController(ConfigurationDbContext context) { _context = context; } public async Task<IActionResult> Index() { var list = await _context.ApiResources.ToListAsync(); var model = list.ToIndexViewModelList(); return View(model); } public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(CreateViewModel model) { if (ModelState.IsValid) { ApiResource entity = model.ToApiResource(); _context.Add(entity); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } return View(model); } public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var apiResource = await _context.ApiResources.SingleOrDefaultAsync(m => m.Id == id); if (apiResource == null) { return NotFound(); } return View(apiResource.ToDeleteViewModel()); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var apiResource = await _context.ApiResources.SingleOrDefaultAsync(m => m.Id == id); _context.ApiResources.Remove(apiResource); await _context.SaveChangesAsync(); return RedirectToAction("Index"); } } }
tafo/Bade
Bade.IdentityServer/Controllers/ApiResourceController.cs
C#
mit
2,177
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> {% include _head.html %} </head> <body class="home"> {% include _browser-upgrade.html %} {% include _navigation.html %} {% if page.image.feature %} <div class="image-wrap"> <img src= {% if page.image.feature contains 'http' %} "{{ page.image.feature }}" {% else %} "{{ site.url }}/images/{{ page.image.feature }}" {% endif %} alt="{{ page.title }} feature image"> {% if page.image.credit %} <span class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a></span> {% endif %} </div><!-- /.image-wrap --> {% endif %} <div id="main" role="main"> <div class="article-author-side"> {% include _author-bio.html %} </div> <div id="index"> <h3><a href="{{ site.url}}/posts/">Recent Posts</a></h3> {% assign posts = site.posts | where:"indexed","true" %} {% for post in posts limit:5 %} <article> {% if post.link %} <h2 class="link-post"><a href="{{ site.url }}{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a> <a href="{{ post.link }}" target="_blank" title="{{ post.title }}"><i class="fa fa-link"></i></h2> {% else %} <h2><a href="{{ site.url }}{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a></h2> <p>{{ post.excerpt | strip_html | truncate: 160 }}</p> {% endif %} </article> {% endfor %} <br/> <h3><a href="{{ site.url}}/talks/">Recent Talks</a></h3> {% assign talks = site.talks | sort:"date" %} {% for talk in talks limit:3 %} <article> <h2><a href="{{ site.url }}{{ talk.url }}" title="{{ talk.title }}">{{ talk.title }}</a></h2> </article> {% endfor %} </div><!-- /#index --> </div><!-- /#main --> <div class="footer-wrap"> <footer> {% include _footer.html %} </footer> </div><!-- /.footer-wrap --> {% include _scripts.html %} </body> </html>
mpraglowski/mpraglowski.github.com
_layouts/home.html
HTML
mit
2,216
<div class="body-top"> <div class="alert" role=""> <span class="">小标题</span> </div> </div>
accccc/shuyi
application/views/common/body_top.html
HTML
mit
100
<!DOCTYPE html> <html> <head> <title>Error No Private Key Found.</title> <link href="https://fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; color: rgba(27, 109, 133, 1); display: table; font-weight: 100; font-family: 'Lato', sans-serif; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 72px; margin-bottom: 40px; } </style> </head> <body> <div class="container"> <div class="content"> <div class="title">No Private Key has been found!.</div> <H3 class="text-danger"><strong>There is no Private Key in DB. This is probably becouse they have been generated in another device and signed by This CA.</strong></H3> <p class="btn btn-default btn-bg"><a href='{{ URL('dashboard/index') }}'>Go to Dashboard</a></p> </div> </div> </body> </html>
lopeaa/Certificate-Authority
resources/views/errors/noKeyFound.blade.php
PHP
mit
1,726
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-12-08 21:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0021_auto_20161208_1214'), ] operations = [ migrations.AlterField( model_name='tournamentteam', name='name', field=models.CharField(max_length=255, verbose_name='holdnavn'), ), migrations.AlterField( model_name='tournamentteam', name='profiles', field=models.ManyToManyField(to='main.Profile', verbose_name='medlemmer'), ), ]
bomjacob/htxaarhuslan
main/migrations/0022_auto_20161208_2216.py
Python
mit
679
--- title: avk38 type: products image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png heading: k38 description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj main: heading: Foo Bar BAz description: |- ***This is i a thing***kjh hjk kj # Blah Blah ## Blah![undefined](undefined) ### Baah image1: alt: kkkk ---
pblack/kaldi-hugo-cms-template
site/content/pages2/avk38.md
Markdown
mit
339
/* * The MIT License * * Copyright 2016 enlo. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package info.naiv.lab.java.jmt.infrastructure.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Target; /** * 優先度. 値が小さいほど優先度が高い. * * @author enlo */ @Retention(RUNTIME) @Target(ElementType.TYPE) public @interface ServicePriority { /** * * @return */ int value(); }
enlo/jmt-projects
jmt-core/src/main/java/info/naiv/lab/java/jmt/infrastructure/annotation/ServicePriority.java
Java
mit
1,631
// // AppDelegate.h // FWPageControl // // Created by Chin on 15/3/16. // Copyright (c) 2015年 Chin. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
howenis/FWPageControl
FWPageControl/AppDelegate.h
C
mit
274
<textarea class="form-control richTextBox" data-name="{{ $row->display_name }}" name="{{ $row->field }}" id="richtext{{ $row->field }}"> @if(isset($dataTypeContent->{$row->field})) {{ old($row->field, $dataTypeContent->{$row->field}) }} @else {{old($row->field)}} @endif </textarea>
laraveladminpanel/admin
resources/views/formfields/rich_text_box.blade.php
PHP
mit
312
<!DOCTYPE html> <html lang="en-ca"> <head> <meta charset="utf-8"> <title>Typography</title> <link href="../css/typography.css" rel="stylesheet"> <link href="../../inclass-ecommerce/css/buttons.css" rel="stylesheet"> <link href="../../inclass-ecommerce/css/list-group.css" rel="stylesheet"> <link href="../../inclass-ecommerce/css/media-object.css" rel="stylesheet"> <link href="../../inclass-ecommerce/css/product.css" rel="stylesheet"> <link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300,300italic,400italic,700italic' rel='stylesheet' type='text/css'> </head> <body> <h1>Heading Level 1 <a href="#">Linked</a></h1> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <h2>Heading Level 2 <a href="#">Linked</a></h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <h3>Heading Level 3 <a href="#">Linked</a></h3> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <h4>Heading Level 4 <a href="#">Linked</a></h4> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <h5>Heading Level 5 <a href="#">Linked</a></h5> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <h6>Heading Level 6 <a href="#">Linked</a></h6> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <h1 class="yotta">Yotta Size <a href="#">Linked</a></h1> <p class="tera">Lorem ipsum dolor sit amet, <a href="#">consectetuer adipiscing elit.</a></p> <h1 class="zetta">Zetta Size <a href="#">Linked</a></h1> <p class="giga">Lorem ipsum dolor sit amet, <a href="#">consectetuer adipiscing elit.</a></p> <hr class="fade"> <h2>Lists</h2> <ul> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li><a href="#">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</a></li> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> </ul> <ol> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li><a href="#">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</a></li> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li> </ol> <dl> <dt>Lorem Ipsum</dt> <dd>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</dd> <dt><a href="#">Lorem Ipsum</a></dt> <dd>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</dd> <dt>Lorem Ipsum</dt> <dd>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</dd> </dl> <hr class="fade"> <h2>Blockquotes</h2> <blockquote> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.</p> <footer>—<cite>The Person</cite></footer> </blockquote> <hr class="fade"> <h2>Text Level</h2> <p><strong>Lorem</strong> ipsum <em>dolor</em> sit amet<sub>2</sub>, consectetuer<sup>2</sup> adipiscing <a href="#">elit</a>. Aenean <a href="#">commodo ligula eget</a> dolor. <i>Aenean massa.</i> Cum <b>sociis</b> natoque <ins>penatibus</ins> et <del>magnis</del> dis <s>parturient</s> montes, <time datetime="2014-01-01">nascetur</time> ridiculus <abbr title="Hypertext Markup Language">HTML</abbr>. Donec <q>“quam”</q> felis, <mark>ultricies</mark> nec, <data>pellentesque</data> eu, <dfn>pretium quis</dfn>, sem.</p> <hr class="fade"> <h2>Smaller Text</h2> <p><small>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</small></p> <p class="milli">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> <p class="micro">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p> <hr class="fade"> <h2>Tables</h2> <table> <caption>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</caption> <thead> <tr> <th></th> <th scope="col">Lorem</th> <th scope="col">Ipsum</th> <th scope="col">Dolor</th> </tr> </thead> <tbody> <tr> <th>Sit</th> <td>1 × 1</td> <td>2 × 1</td> <td>3 × 1</td> </tr> <tr> <th>Amet</th> <td>1 × 2</td> <td>2 × 2</td> <td>3 × 2</td> </tr> <tr> <th>Elit</th> <td>1 × 3</td> <td>2 × 3</td> <td>3 × 3</td> </tr> <tr> <th>Eget</th> <td>1 × 4</td> <td>2 × 4</td> <td>3 × 4</td> </tr> </tbody> </body> </html>
Hasan-Yavuz/ecommerce-website
styleguide/typography.html
HTML
mit
6,670
/** * Created by 勇 on 2015/7/3. */
fflskh/yundd
src/lib/qnode.js
JavaScript
mit
39
from functools import wraps def retry_task(f): @wraps(f) def decorated_function(*args, **kwargs): retry = kwargs.get('retry', False) if retry == 0: return f(*args, **kwargs) elif retry > 0: for x in range(0, retry): result = f(*args, **kwargs) if result['status'] != 500: return result return f(*args, **kwargs) elif retry == -1: while retry: result = f(*args, **kwargs) if result['status'] != 500: return result return decorated_function
JR--Chen/flasky
app/spider/decorators.py
Python
mit
641
#------------------------------------------------------------------------------ # Copyright (C) 2009 Richard W. Lincoln # # 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. #------------------------------------------------------------------------------ """ Defines an action for moving the workspace to the parent directory. """ #------------------------------------------------------------------------------ # Imports: #------------------------------------------------------------------------------ from os.path import dirname from enthought.traits.api import Bool, Instance from enthought.pyface.api import ImageResource from enthought.pyface.action.api import Action from enthought.envisage.ui.workbench.api import WorkbenchWindow from puddle.resource.resource_view import RESOURCE_VIEW from common import IMAGE_LOCATION #------------------------------------------------------------------------------ # "UpAction" class: #------------------------------------------------------------------------------ class UpAction(Action): """ Defines an action for moving the workspace to the parent directory. """ #-------------------------------------------------------------------------- # "Action" interface: #-------------------------------------------------------------------------- # A longer description of the action: description = "Move workspace to the parent directory" # The action"s name (displayed on menus/tool bar tools etc): name = "&Up" # A short description of the action used for tooltip text etc: tooltip = "Open parent directory" # Keyboard accelerator: accelerator = "Alt+Up" # The action's image (displayed on tool bar tools etc): image = ImageResource("up", search_path=[IMAGE_LOCATION]) #-------------------------------------------------------------------------- # "UpAction" interface: #-------------------------------------------------------------------------- window = Instance(WorkbenchWindow) #-------------------------------------------------------------------------- # "Action" interface: #-------------------------------------------------------------------------- def perform(self, event): """ Perform the action. """ # Note that we always offer the service via its name, but look it up # via the actual protocol. from puddle.resource.i_workspace import IWorkspace workspace = self.window.application.get_service(IWorkspace) workspace.path = dirname(workspace.absolute_path) view = self.window.get_view_by_id(RESOURCE_VIEW) if view is not None: workspace = self.window.application.get_service(IWorkspace) view.tree_viewer.refresh(workspace) # EOF -------------------------------------------------------------------------
rwl/puddle
puddle/resource/action/up_action.py
Python
mit
3,878
/* Pretty printing styles. Used with prettify.js. */ pre.prettyprint .str { color: #080; } pre.prettyprint .kwd { color: #008; } pre.prettyprint .com { color: #800; } pre.prettyprint .typ { color: #606; } pre.prettyprint .lit { color: #066; } pre.prettyprint .pun { color: #660; } pre.prettyprint .pln { color: #000; } pre.prettyprint .tag { color: #008; } pre.prettyprint .atn { color: #606; } pre.prettyprint .atv { color: #080; } pre.prettyprint .dec { color: #606; } pre.prettyprint { max-width: 580px;border:solid 1px #888;border-left-width: 5px;padding:10px;overflow: auto } @media print { pre.prettyprint .str { color: #060; } pre.prettyprint .kwd { color: #006; font-weight: bold; } pre.prettyprint .com { color: #600; font-style: italic; } pre.prettyprint .typ { color: #404; font-weight: bold; } pre.prettyprint .lit { color: #044; } pre.prettyprint .pun { color: #440; } pre.prettyprint .pln { color: #000; } pre.prettyprint .tag { color: #006; font-weight: bold; } pre.prettyprint .atn { color: #404; } pre.prettyprint .atv { color: #060; } }
leveille/blog.v1
wurdig/public/css/prettify.css
CSS
mit
1,077
package authorization import ( "net" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/authelia/authelia/v4/internal/configuration/schema" ) type AuthorizerSuite struct { suite.Suite } type AuthorizerTester struct { *Authorizer } func NewAuthorizerTester(config schema.AccessControlConfiguration) *AuthorizerTester { fullConfig := &schema.Configuration{ AccessControl: config, } return &AuthorizerTester{ NewAuthorizer(fullConfig), } } func (s *AuthorizerTester) CheckAuthorizations(t *testing.T, subject Subject, requestURI, method string, expectedLevel Level) { url, _ := url.ParseRequestURI(requestURI) object := Object{ Scheme: url.Scheme, Domain: url.Hostname(), Path: url.Path, Method: method, } level := s.GetRequiredLevel(subject, object) assert.Equal(t, expectedLevel, level) } type AuthorizerTesterBuilder struct { config schema.AccessControlConfiguration } func NewAuthorizerBuilder() *AuthorizerTesterBuilder { return &AuthorizerTesterBuilder{} } func (b *AuthorizerTesterBuilder) WithDefaultPolicy(policy string) *AuthorizerTesterBuilder { b.config.DefaultPolicy = policy return b } func (b *AuthorizerTesterBuilder) WithRule(rule schema.ACLRule) *AuthorizerTesterBuilder { b.config.Rules = append(b.config.Rules, rule) return b } func (b *AuthorizerTesterBuilder) Build() *AuthorizerTester { return NewAuthorizerTester(b.config) } var AnonymousUser = Subject{ Username: "", Groups: []string{}, IP: net.ParseIP("127.0.0.1"), } var UserWithGroups = Subject{ Username: "john", Groups: []string{"dev", "admins"}, IP: net.ParseIP("10.0.0.8"), } var John = UserWithGroups var UserWithoutGroups = Subject{ Username: "bob", Groups: []string{}, IP: net.ParseIP("10.0.0.7"), } var Bob = UserWithoutGroups var UserWithIPv6Address = Subject{ Username: "sam", Groups: []string{}, IP: net.ParseIP("fec0::1"), } var Sam = UserWithIPv6Address var UserWithIPv6AddressAndGroups = Subject{ Username: "sam", Groups: []string{"dev", "admins"}, IP: net.ParseIP("fec0::2"), } var Sally = UserWithIPv6AddressAndGroups func (s *AuthorizerSuite) TestShouldCheckDefaultBypassConfig() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(bypass).Build() tester.CheckAuthorizations(s.T(), AnonymousUser, "https://public.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithoutGroups, "https://public.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithoutGroups, "https://public.example.com/elsewhere", "GET", Bypass) } func (s *AuthorizerSuite) TestShouldCheckDefaultDeniedConfig() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny).Build() tester.CheckAuthorizations(s.T(), AnonymousUser, "https://public.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithoutGroups, "https://public.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithoutGroups, "https://public.example.com/elsewhere", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckMultiDomainRule() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"*.example.com"}, Policy: bypass, }). Build() tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://private.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/elsewhere", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com.c/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.co/", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckDynamicDomainRules() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"{user}.example.com"}, Policy: bypass, }). WithRule(schema.ACLRule{ Domains: []string{"{group}.example.com"}, Policy: bypass, }). Build() tester.CheckAuthorizations(s.T(), UserWithGroups, "https://john.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://dev.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://admins.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://othergroup.example.com/", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckMultipleDomainRule() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"*.example.com", "other.com"}, Policy: bypass, }). Build() tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://private.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/elsewhere", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com.c/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.co/", "GET", Denied) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://other.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://other.com/elsewhere", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://private.other.com/", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckFactorsPolicy() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"single.example.com"}, Policy: oneFactor, }). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: twoFactor, }). WithRule(schema.ACLRule{ Domains: []string{"public.example.com"}, Policy: bypass, }). Build() tester.CheckAuthorizations(s.T(), UserWithGroups, "https://public.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://protected.example.com/", "GET", TwoFactor) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://single.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), UserWithGroups, "https://example.com/", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckRulePrecedence() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: bypass, Subjects: [][]string{{"user:john"}}, }). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, }). WithRule(schema.ACLRule{ Domains: []string{"*.example.com"}, Policy: twoFactor, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), John, "https://public.example.com/", "GET", TwoFactor) } func (s *AuthorizerSuite) TestShouldCheckUserMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, Subjects: [][]string{{"user:john"}}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckGroupMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, Subjects: [][]string{{"group:admins"}}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "GET", Denied) } func (s *AuthorizerSuite) TestShouldCheckSubjectsMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, Subjects: [][]string{{"group:admins"}, {"user:bob"}}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), Sam, "https://protected.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://protected.example.com/", "GET", OneFactor) } func (s *AuthorizerSuite) TestShouldCheckMultipleSubjectsMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, Subjects: [][]string{{"group:admins", "user:bob"}, {"group:admins", "group:dev"}}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://protected.example.com/", "GET", OneFactor) } func (s *AuthorizerSuite) TestShouldCheckIPMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: bypass, Networks: []string{"192.168.1.8", "10.0.0.8"}, }). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, Networks: []string{"10.0.0.7"}, }). WithRule(schema.ACLRule{ Domains: []string{"net.example.com"}, Policy: twoFactor, Networks: []string{"10.0.0.0/8"}, }). WithRule(schema.ACLRule{ Domains: []string{"ipv6.example.com"}, Policy: twoFactor, Networks: []string{"fec0::1/64"}, }). WithRule(schema.ACLRule{ Domains: []string{"ipv6-alt.example.com"}, Policy: twoFactor, Networks: []string{"fec0::1"}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "GET", OneFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://protected.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), John, "https://net.example.com/", "GET", TwoFactor) tester.CheckAuthorizations(s.T(), Bob, "https://net.example.com/", "GET", TwoFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://net.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), Sally, "https://ipv6-alt.example.com/", "GET", Denied) tester.CheckAuthorizations(s.T(), Sam, "https://ipv6-alt.example.com/", "GET", TwoFactor) tester.CheckAuthorizations(s.T(), Sally, "https://ipv6.example.com/", "GET", TwoFactor) tester.CheckAuthorizations(s.T(), Sam, "https://ipv6.example.com/", "GET", TwoFactor) } func (s *AuthorizerSuite) TestShouldCheckMethodMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: bypass, Methods: []string{"OPTIONS", "HEAD", "GET", "CONNECT", "TRACE"}, }). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: oneFactor, Methods: []string{"PUT", "PATCH", "POST"}, }). WithRule(schema.ACLRule{ Domains: []string{"protected.example.com"}, Policy: twoFactor, Methods: []string{"DELETE"}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "OPTIONS", Bypass) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://protected.example.com/", "HEAD", Bypass) tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "CONNECT", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "TRACE", Bypass) tester.CheckAuthorizations(s.T(), John, "https://protected.example.com/", "PUT", OneFactor) tester.CheckAuthorizations(s.T(), Bob, "https://protected.example.com/", "PATCH", OneFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://protected.example.com/", "POST", OneFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://protected.example.com/", "DELETE", TwoFactor) } func (s *AuthorizerSuite) TestShouldCheckResourceMatching() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"resource.example.com"}, Policy: bypass, Resources: []string{"^/bypass/[a-z]+$", "^/$", "embedded"}, }). WithRule(schema.ACLRule{ Domains: []string{"resource.example.com"}, Policy: oneFactor, Resources: []string{"^/one_factor/[a-z]+$"}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://resource.example.com/", "GET", Bypass) tester.CheckAuthorizations(s.T(), John, "https://resource.example.com/bypass/abc", "GET", Bypass) tester.CheckAuthorizations(s.T(), John, "https://resource.example.com/bypass/", "GET", Denied) tester.CheckAuthorizations(s.T(), John, "https://resource.example.com/bypass/ABC", "GET", Denied) tester.CheckAuthorizations(s.T(), John, "https://resource.example.com/one_factor/abc", "GET", OneFactor) tester.CheckAuthorizations(s.T(), John, "https://resource.example.com/xyz/embedded/abc", "GET", Bypass) } // This test assures that rules without domains (not allowed by schema validator at this time) will pass validation correctly. func (s *AuthorizerSuite) TestShouldMatchAnyDomainIfBlank() { tester := NewAuthorizerBuilder(). WithRule(schema.ACLRule{ Policy: bypass, Methods: []string{"OPTIONS", "HEAD", "GET", "CONNECT", "TRACE"}, }). WithRule(schema.ACLRule{ Policy: oneFactor, Methods: []string{"PUT", "PATCH"}, }). WithRule(schema.ACLRule{ Policy: twoFactor, Methods: []string{"DELETE"}, }). Build() tester.CheckAuthorizations(s.T(), John, "https://one.domain-four.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-three.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-two.com", "OPTIONS", Bypass) tester.CheckAuthorizations(s.T(), John, "https://one.domain-four.com", "PUT", OneFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-three.com", "PATCH", OneFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-two.com", "PUT", OneFactor) tester.CheckAuthorizations(s.T(), John, "https://one.domain-four.com", "DELETE", TwoFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-three.com", "DELETE", TwoFactor) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-two.com", "DELETE", TwoFactor) tester.CheckAuthorizations(s.T(), John, "https://one.domain-four.com", "POST", Denied) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-three.com", "POST", Denied) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://one.domain-two.com", "POST", Denied) } func (s *AuthorizerSuite) TestShouldMatchResourceWithSubjectRules() { tester := NewAuthorizerBuilder(). WithDefaultPolicy(deny). WithRule(schema.ACLRule{ Domains: []string{"public.example.com"}, Resources: []string{"^/admin/.*$"}, Subjects: [][]string{{"group:admins"}}, Policy: oneFactor, }). WithRule(schema.ACLRule{ Domains: []string{"public.example.com"}, Resources: []string{"^/admin/.*$"}, Policy: deny, }). WithRule(schema.ACLRule{ Domains: []string{"public.example.com"}, Policy: bypass, }). WithRule(schema.ACLRule{ Domains: []string{"public2.example.com"}, Resources: []string{"^/admin/.*$"}, Subjects: [][]string{{"group:admins"}}, Policy: bypass, }). WithRule(schema.ACLRule{ Domains: []string{"public2.example.com"}, Resources: []string{"^/admin/.*$"}, Policy: deny, }). WithRule(schema.ACLRule{ Domains: []string{"public2.example.com"}, Policy: bypass, }). WithRule(schema.ACLRule{ Domains: []string{"private.example.com"}, Subjects: [][]string{{"group:admins"}}, Policy: twoFactor, }). Build() tester.CheckAuthorizations(s.T(), John, "https://public.example.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://public.example.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://public.example.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), John, "https://public.example.com/admin/index.html", "GET", OneFactor) tester.CheckAuthorizations(s.T(), Bob, "https://public.example.com/admin/index.html", "GET", Denied) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://public.example.com/admin/index.html", "GET", OneFactor) tester.CheckAuthorizations(s.T(), John, "https://public2.example.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://public2.example.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://public2.example.com", "GET", Bypass) tester.CheckAuthorizations(s.T(), John, "https://public2.example.com/admin/index.html", "GET", Bypass) tester.CheckAuthorizations(s.T(), Bob, "https://public2.example.com/admin/index.html", "GET", Denied) // This test returns this result since we validate the schema instead of validating it in code. tester.CheckAuthorizations(s.T(), AnonymousUser, "https://public2.example.com/admin/index.html", "GET", Bypass) tester.CheckAuthorizations(s.T(), John, "https://private.example.com", "GET", TwoFactor) tester.CheckAuthorizations(s.T(), Bob, "https://private.example.com", "GET", Denied) tester.CheckAuthorizations(s.T(), AnonymousUser, "https://private.example.com", "GET", TwoFactor) } func (s *AuthorizerSuite) TestPolicyToLevel() { s.Assert().Equal(Bypass, PolicyToLevel(bypass)) s.Assert().Equal(OneFactor, PolicyToLevel(oneFactor)) s.Assert().Equal(TwoFactor, PolicyToLevel(twoFactor)) s.Assert().Equal(Denied, PolicyToLevel(deny)) s.Assert().Equal(Denied, PolicyToLevel("whatever")) } func TestRunSuite(t *testing.T) { s := AuthorizerSuite{} suite.Run(t, &s) } func TestNewAuthorizer(t *testing.T) { config := &schema.Configuration{ AccessControl: schema.AccessControlConfiguration{ DefaultPolicy: deny, Rules: []schema.ACLRule{ { Domains: []string{"example.com"}, Policy: twoFactor, Subjects: [][]string{ { "user:admin", }, { "group:admins", }, }, }, }, }, } authorizer := NewAuthorizer(config) assert.Equal(t, Denied, authorizer.defaultPolicy) assert.Equal(t, TwoFactor, authorizer.rules[0].Policy) user, ok := authorizer.rules[0].Subjects[0].Subjects[0].(AccessControlUser) require.True(t, ok) assert.Equal(t, "admin", user.Name) group, ok := authorizer.rules[0].Subjects[1].Subjects[0].(AccessControlGroup) require.True(t, ok) assert.Equal(t, "admins", group.Name) } func TestAuthorizerIsSecondFactorEnabledRuleWithNoOIDC(t *testing.T) { config := &schema.Configuration{ AccessControl: schema.AccessControlConfiguration{ DefaultPolicy: deny, Rules: []schema.ACLRule{ { Domains: []string{"example.com"}, Policy: oneFactor, }, }, }, } authorizer := NewAuthorizer(config) assert.False(t, authorizer.IsSecondFactorEnabled()) authorizer.rules[0].Policy = TwoFactor assert.True(t, authorizer.IsSecondFactorEnabled()) } func TestAuthorizerIsSecondFactorEnabledRuleWithOIDC(t *testing.T) { config := &schema.Configuration{ AccessControl: schema.AccessControlConfiguration{ DefaultPolicy: deny, Rules: []schema.ACLRule{ { Domains: []string{"example.com"}, Policy: oneFactor, }, }, }, IdentityProviders: schema.IdentityProvidersConfiguration{ OIDC: &schema.OpenIDConnectConfiguration{ Clients: []schema.OpenIDConnectClientConfiguration{ { Policy: oneFactor, }, }, }, }, } authorizer := NewAuthorizer(config) assert.False(t, authorizer.IsSecondFactorEnabled()) authorizer.rules[0].Policy = TwoFactor assert.True(t, authorizer.IsSecondFactorEnabled()) authorizer.rules[0].Policy = OneFactor assert.False(t, authorizer.IsSecondFactorEnabled()) config.IdentityProviders.OIDC.Clients[0].Policy = twoFactor assert.True(t, authorizer.IsSecondFactorEnabled()) authorizer.rules[0].Policy = OneFactor config.IdentityProviders.OIDC.Clients[0].Policy = oneFactor assert.False(t, authorizer.IsSecondFactorEnabled()) authorizer.defaultPolicy = TwoFactor assert.True(t, authorizer.IsSecondFactorEnabled()) }
clems4ever/two-factor-auth-server
internal/authorization/authorizer_test.go
GO
mit
21,224
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using ForumSystem.Services.Models; namespace ForumSystem.Services.Providers { using ForumSystem.Models; public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider { private readonly string _publicClientId; public ApplicationOAuthProvider(string publicClientId) { if (publicClientId == null) { throw new ArgumentNullException("publicClientId"); } _publicClientId = publicClientId; } public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); User user = await userManager.FindAsync(context.UserName, context.Password); if (user == null) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.UserName); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); } public override Task TokenEndpoint(OAuthTokenEndpointContext context) { foreach (KeyValuePair<string, string> property in context.Properties.Dictionary) { context.AdditionalResponseParameters.Add(property.Key, property.Value); } return Task.FromResult<object>(null); } public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { // Resource owner password credentials does not provide a client ID. if (context.ClientId == null) { context.Validated(); } return Task.FromResult<object>(null); } public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == _publicClientId) { Uri expectedRootUri = new Uri(context.Request.Uri, "/"); if (expectedRootUri.AbsoluteUri == context.RedirectUri) { context.Validated(); } } return Task.FromResult<object>(null); } public static AuthenticationProperties CreateProperties(string userName) { IDictionary<string, string> data = new Dictionary<string, string> { { "userName", userName } }; return new AuthenticationProperties(data); } } }
StefanSinapov/TelerikAcademy
13. Web Services and Cloud/10. Exam Preparation/Sample Exam - 2014/ForumSystem.Services/Providers/ApplicationOAuthProvider.cs
C#
mit
3,477
Rails.application.routes.draw do root 'badge#new' get '' => 'badge#new' # create new badge-url for given parameters post '' => 'badge#create' # request badge get ':id.png' => 'badge#show', as: :badge end
pkubiak/waymarking-badge
config/routes.rb
Ruby
mit
219
using System; using UnityEngine; using System.Collections; public abstract class Opponent : MonoBehaviour { public float MoveTime = 0.1f; //Time it will take object to move, in seconds. public LayerMask BlockingLayer; //Layer on which collision will be checked. public float ScoredDelay = 0.5f; public GameObject OpponentGameObject; public int Gold = 100; public int GoldEachTurn = 100; public int Health; private BoxCollider2D boxCollider; //The BoxCollider2D component attached to this object. private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object. private float inverseMoveTime; //Used to make movement more efficient. private Renderer objectRenderer; protected GameObject opponent; //states protected bool isMoving; protected abstract bool IsUnitsTurn { get; set; } protected bool InitialUnitPlacingSet { get { return objectRenderer.enabled; } set { objectRenderer.enabled = value; } } protected bool fogOfWarReset { get; set; } protected bool boardPlacementPerformed { get; set; } //unit specific config protected abstract int StartColumn { get; } protected abstract int UnitAdvanceDirection { get; } protected abstract int EndColumn { get; } protected abstract bool DesiredFogOfWarState { get; } protected abstract bool ShouldAct { get; } // Use this for initialization protected virtual void Start() { boxCollider = GetComponent<BoxCollider2D>(); rb2D = GetComponent<Rigidbody2D>(); inverseMoveTime = 1f / MoveTime; objectRenderer = GetComponent<Renderer>(); InitialUnitPlacingSet = false; opponent = GameObject.Find(OpponentGameObject.name); } protected virtual void Update() { if (!ShouldAct) return; //opponent sets the board if (!boardPlacementPerformed) WaitForOpponentBoardPlacement(); //set fog of war if (!fogOfWarReset) ResetFogOfWar(); OpponentUpdate(); } protected abstract void OpponentUpdate(); protected void Move(Vector2 targetDestination) { // Debug.Log("Moving to " + targetDestination.x + "," + targetDestination.y); isMoving = true; if (!InitialUnitPlacingSet) { transform.position = targetDestination; isMoving = false; InitialUnitPlacingSet = true; return; } // Vector2 start = transform.position; //Disable the boxCollider so that linecast doesn't hit this object's own collider. // boxCollider.enabled = false; //Cast a line from start point to end point checking collision on blockingLayer. // hit = Physics2D.Linecast(start, end, blockingLayer); //Re-enable boxCollider after linecast // boxCollider.enabled = true; //Check if anything was hit // if (hit.transform == null) // { //If nothing was hit, start SmoothMovement co-routine passing in the Vector2 end as destination StartCoroutine(SmoothMovement(targetDestination)); //Return true to say that Move was successful // return true; // } //If something was hit, return false, Move was unsuccesful. // return false; } //Co-routine for moving units from one space to next, takes a parameter end to specify where to move to. protected IEnumerator SmoothMovement(Vector3 end) { // Debug.Log(end.x + "," + end.y); var sqrRemainingDistance = (transform.position - end).sqrMagnitude; while (sqrRemainingDistance > float.Epsilon) { var newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime); rb2D.MovePosition(newPostion); sqrRemainingDistance = (transform.position - end).sqrMagnitude; yield return null; } //reached other side if (Math.Abs(end.x - EndColumn) < float.Epsilon) { Invoke("Scored", ScoredDelay); } else { isMoving = false; GameManager.Instance.BoardManager.ActivateItemAtPosition(end, this); } } void Scored() { CleanUpOpponentTurn(); } private void CleanUpOpponentTurn() { isMoving = false; IsUnitsTurn = false; InitialUnitPlacingSet = false; fogOfWarReset = false; boardPlacementPerformed = false; GameManager.Instance.BoardManager.ClearItems(); Gold += GoldEachTurn; } protected void ResetFogOfWar() { GameManager.Instance.BoardManager.SetAllFogOfWar(DesiredFogOfWarState); fogOfWarReset = true; } //board placing protected void WaitForOpponentBoardPlacement() { opponent.GetComponent<Opponent>().PlaceBoardForOpponent(); boardPlacementPerformed = true; } protected abstract void PlaceBoardForOpponent(); }
odedw/ponglike
ponglike/Assets/Scripts/Opponent.cs
C#
mit
5,105
/** * \file blas/blas_vector.h * * \brief Dense vector arithmetic using BLAS. * */ #ifndef BLAS_BLAS_VECTOR_H #define BLAS_BLAS_VECTOR_H #include "invlib/dense/vector_data.h" #include "invlib/sparse/sparse_data.h" #include "invlib/blas/blas_generic.h" namespace invlib { // -------------------- // // Forward Declarations // // -------------------- // template <typename SType, template <typename> typename VData> class BlasVector; template <typename SType, template <typename> typename MData> class BlasMatrix; template <typename SType, template <typename> typename VData> SType dot(const BlasVector<SType, VData>&, const BlasVector<SType, VData>&); // ------------------- // // Blas Vector Class // // ------------------- // /** * \brief Dense Vector Arithmetic using BLAS * * Implements a dense vector class that uses BLAS level 1 functions for vector * arithmetic. In addition to that the vector type provides functions for scaling * and addition of a constant, which are necessary for use with the CG solver. * * \tparam SType Floating point type used for the representation of * the vector elements. */ template < typename SType, template <typename> typename VData = VectorData > class BlasVector : public VData<SType> { public: // -------------- // // Type Aliases // // -------------- // using RealType = SType; using VectorType = BlasVector; using MatrixType = BlasVector; using ResultType = BlasVector; // ------------------------------- // // Constructors and Destructors // // ------------------------------- // BlasVector() = default; /*! Performs a shallow copy of the BlasVector object. */ BlasVector(const BlasVector &) = default; BlasVector(BlasVector &&) = default; /*! Performs a shallow copy of the BlasVector object. */ BlasVector & operator=(const BlasVector & ) = default; BlasVector & operator=( BlasVector &&) = default; /*! Construct BlasVector object from given VData object. * * Simply forwards the copy constructor call to that of the super class. * Its behavior thus depends on the VData class. */ BlasVector(const VData<SType> & v); /*! Construct BlasVector object from given VData object. * * Forwards the move constructor call to that of the super class. * Its behavior thus depends on the VData class. */ BlasVector(VData<SType> &&v); // ------------ // // Data access // // ------------ // SType * get_element_pointer() { return elements.get(); } const SType * get_element_pointer() const { return elements.get(); } // ------------ // // Arithmetic // // ------------ // void accumulate(const BlasVector &v); void accumulate(SType c); void subtract(const BlasVector &v); void scale(SType c); SType norm() const; friend SType dot<>(const BlasVector&, const BlasVector&); protected: // ------------------- // // Base Class Members // // ------------------- // using VData<SType>::elements; using VData<SType>::n; }; #include "blas_vector.cpp" } // namespace invlib #endif // BLAS_BLAS_VECTOR_H
simonpf/invlib
src/invlib/blas/blas_vector.h
C
mit
3,301
--- name: learn-teach-code title: "Learn Teach Code: Documenting My Journey" --- My main projects for 2017 all revolve around **<a href="http://learnteachcode.org/">Learn Teach Code</a>**, the meetup group I started in 2015. This is by far the most ambitious, scary, but also rewarding and fulfilling project I've ever worked on! So I figured I'd better share the journey. I want to openly share my own learning process and all the ups and downs along the way. For **March 2017**, my newest (and craziest!) project is to start **my own programming bootcamp**, first with a four-week part-time pilot program introducing full-stack JavaScript development. I want to create a truly valuable experience for my future students and dedicate myself to this full-time! But I'm also still struggling with my own personal challenges. So I want to share what happens, whether this ends up a spectacular success or a spectacular failure. Either way, it will be a great learning experience! **Here are all my blog posts and video blogs for this project so far:** <div class="tiles"> {% for post in site.posts %} {% if post.cats contains page.name %} {% include post-list.html %} {% endif %} {% endfor %} </div><!-- /.tiles -->
LearningNerd/learningnerd.github.io
_cats/learn-teach-code.md
Markdown
mit
1,235
<?php namespace Pterodactyl\Exceptions\Repository; use Pterodactyl\Exceptions\DisplayException; class DuplicateDatabaseNameException extends DisplayException { }
Pterodactyl/Panel
app/Exceptions/Repository/DuplicateDatabaseNameException.php
PHP
mit
165
@extends($master) @section('page', trans('panichd::admin.category-edit-title', ['name' => ucwords($category->name)])) @include('panichd::shared.common') @include('panichd::shared.colorpicker', [ 'include_colorpickerplus_script' => true, 'input_color' => $category->color ]) @section('panichd_assets') <style type="text/css"> #tag-panel .fa { color: #777; } #jquery_popup_tag_input { border: transparent; box-shadow: none; } </style> @append @section('content') <div class="card bg-light"> <div class="card-body"> {!! CollectiveForm::model($category, [ 'route' => [$setting->grab('admin_route').'.category.update', $category->id], 'method' => 'PATCH' ]) !!} <legend>{{ trans('panichd::admin.category-edit-title', ['name' => ucwords($category->name)]) }}</legend> @include('panichd::admin.category.form', ['update', true]) @include('panichd::admin.category.modal-email') {!! CollectiveForm::close() !!} </div> </div> @include('panichd::admin.category.modal-reason') @append @section('footer') @include('panichd::admin.category.scripts-create-edit') @include('panichd::shared.grouped_check_list') @append @include('panichd::shared.tag_create_edit')
panichelpdesk/panichd
src/Views/admin/category/edit.blade.php
PHP
mit
1,210
export const data = [ { id: 549731, name: 'Beautiful Lies', artist: 'Birdy', release: '2016.03.26', type: 'Deluxe', typeCode: '1', genre: 'Pop', genreCode: '1', grade: '4', price: 10000, downloadCount: 1000, listenCount: 5000 }, { id: 436461, name: 'X', artist: 'Ed Sheeran', release: '2014.06.24', type: 'Deluxe', typeCode: '1', genre: 'Pop', genreCode: '1', grade: '5', price: 20000, downloadCount: 1000, listenCount: 5000 }, { id: 295651, name: 'Moves Like Jagger', release: '2011.08.08', artist: 'Maroon5', type: 'Single', typeCode: '3', genre: 'Pop,Rock', genreCode: '1,2', grade: '2', price: 7000, downloadCount: 1000, listenCount: 5000 }, { id: 541713, name: 'A Head Full Of Dreams', artist: 'Coldplay', release: '2015.12.04', type: 'Deluxe', typeCode: '1', genre: 'Rock', genreCode: '2', grade: '3', price: 25000, downloadCount: 200, listenCount: 5000 }, { id: 265289, name: '21', artist: 'Adele', release: '2011.01.21', type: 'Deluxe', typeCode: '1', genre: 'Pop,R&B', genreCode: '1,3', grade: '5', price: 15000, downloadCount: 1000, listenCount: 5000 }, { id: 555871, name: 'Warm On A Cold Night', artist: 'HONNE', release: '2016.07.22', type: 'EP', typeCode: '1', genre: 'R&B,Electronic', genreCode: '3,4', grade: '4', price: 11000, downloadCount: 34000, listenCount: 5000 }, { id: 550571, name: 'Take Me To The Alley', artist: 'Gregory Porter', release: '2016.09.02', type: 'Deluxe', typeCode: '1', genre: 'Jazz', genreCode: '5', grade: '3', price: 30000, downloadCount: 1000, listenCount: 5000 }, { id: 544128, name: 'Make Out', artist: 'LANY', release: '2015.12.11', type: 'EP', typeCode: '2', genre: 'Electronic', genreCode: '4', grade: '2', price: 12000, downloadCount: 1200, listenCount: 5000 }, { id: 366374, name: 'Get Lucky', artist: 'Daft Punk', release: '2013.04.23', type: 'Single', typeCode: '3', genre: 'Pop,Funk', genreCode: '1,5', grade: '3', price: 9000, downloadCount: 1000, listenCount: 5000 }, { id: 8012747, name: 'Valtari', artist: 'Sigur Rós', release: '2012.05.31', type: 'EP', typeCode: '3', genre: 'Rock', genreCode: '2', grade: '5', price: 10000, downloadCount: 1040, listenCount: 5000 }, { id: 502792, name: 'Bush', artist: 'Snoop Dogg', release: '2015.05.12', type: 'EP', typeCode: '2', genre: 'Hiphop', genreCode: '5', grade: '5', price: 18000, downloadCount: 2000, listenCount: 5000 }, { id: 294574, name: '4', artist: 'Beyoncé', release: '2011.07.26', type: 'Deluxe', typeCode: '1', genre: 'Pop', genreCode: '1', grade: '3', price: 12000, downloadCount: 1000, listenCount: 5000 }, { id: 317659, name: "I Won't Give Up", artist: 'Jason Mraz', release: '2012.01.03', type: 'Single', typeCode: '3', genre: 'Pop', genreCode: '1', grade: '2', price: 7000, downloadCount: 1000, listenCount: 5000 }, { id: 583551, name: 'Following My Intuition', artist: 'Craig David', release: '2016.10.01', type: 'Deluxe', typeCode: '1', genre: 'R&B,Electronic', genreCode: '3,4', grade: '5', price: 15000, downloadCount: 1000, listenCount: 5000 }, { id: 490500, name: 'Blue Skies', release: '2015.03.18', artist: 'Lenka', type: 'Single', typeCode: '3', genre: 'Pop,Rock', genreCode: '1,2', grade: '5', price: 6000, downloadCount: 2000, listenCount: 5000 }, { id: 587871, name: 'This Is Acting', artist: 'Sia', release: '2016.10.22', type: 'EP', typeCode: '2', genre: 'Pop', genreCode: '1', grade: '3', price: 20000, downloadCount: 1400, listenCount: 5000 }, { id: 504288, name: 'Blurryface', artist: 'Twenty One Pilots', release: '2015.05.19', type: 'EP', typeCode: '2', genre: 'Rock', genreCode: '2', grade: '1', price: 13000, downloadCount: 3000, listenCount: 5000 }, { id: 450720, name: "I'm Not The Only One", artist: 'Sam Smith', release: '2014.09.15', type: 'Single', typeCode: '3', genre: 'Pop,R&B', genreCode: '1,3', grade: '4', price: 8000, downloadCount: 2000, listenCount: 5000 }, { id: 498896, name: 'The Magic Whip', artist: 'Blur', release: '2015.04.27', type: 'EP', typeCode: '2', genre: 'Rock', genreCode: '2', grade: '3', price: 15000, downloadCount: 1200, listenCount: 5000 }, { id: 491379, name: 'Chaos And The Calm', artist: 'James Bay', release: '2015.03.23', type: 'EP', typeCode: '2', genre: 'Pop,Rock', genreCode: '1,2', grade: '5', price: 12000, downloadCount: 1000, listenCount: 5100 } ]; export const sortData = [ { alphabetA: 'BCA', alphabetB: 'B', alphabetC: 'ACC', numberA: 2, stringNumberA: '2', mixedValue: 'A' }, { alphabetA: 'A', alphabetB: 'A', alphabetC: 'ACC', numberA: 1, stringNumberA: '1', mixedValue: 'C' }, { alphabetA: 'C', alphabetB: 'A', alphabetC: 'C', numberA: 1, stringNumberA: '100', mixedValue: 'EA' }, { alphabetA: 'A', alphabetB: 'B', alphabetC: 'ACA', numberA: 1, stringNumberA: '101', mixedValue: 'AK' }, { alphabetA: 'A', alphabetB: 'B', alphabetC: 'C', numberA: 10, stringNumberA: '11', mixedValue: '121' }, { alphabetA: 'D', alphabetB: 'E', alphabetC: 'CDD', numberA: 1, stringNumberA: '201', mixedValue: '2' }, { alphabetA: 'BAA', alphabetB: 'C', alphabetC: 'C', numberA: 20, stringNumberA: '202', mixedValue: '30' }, { alphabetA: 'A', alphabetB: 'A', alphabetC: 'A', numberA: 24, stringNumberA: '211', mixedValue: '1' }, { alphabetA: 'FGA', alphabetB: 'F', alphabetC: 'FGA', numberA: 25, stringNumberA: '301', mixedValue: 'O' } ];
nhnent/tui.grid
packages/toast-ui.grid/samples/basic.ts
TypeScript
mit
6,507
var express = require('express'); var hsv = require("hsv-rgb"); var fs = require('fs'); var profile = require('../modules/profile'); var milight = require('../modules/milight-controller.js'); var harmony = require('../modules/harmony-controller.js'); var tplink = require('../modules/hs100-controller'); var blinkstick = require('blinkstick'); var led = blinkstick.findFirst(); if(led != undefined) { led.setMode(1); } var router = express.Router(); // a middleware function with no mount path. This code is executed for every request to the router router.use(function (req, res, next) { console.log(JSON.stringify(req.body, null, 4)); var event = req.body; var token = event.directive.payload.scope ? event.directive.payload.scope.token : event.directive.endpoint.scope.token; profile.getProfile(token, function(error, user) { if(error) { console.log(error); } // Only the authorised user can call this if (user === null || user.email !== process.env.authorised_email) { res.status(403).send('Not allowed!'); } res.user = user; next(); }); }); router.post('/alexa', function(req, res){ var event = req.body; var header = event.directive ? event.directive.header : event.header; switch (header.namespace) { case 'Alexa.Discovery': handleDiscovery(req, res); break; case 'Alexa.PowerController': powerController(req, res); break; case 'Alexa.BrightnessController': brightnessController(req, res); break; case 'Alexa.ColorController': colorController(req, res); break; case 'Alexa': stateController(req, res); break; /** * We received an unexpected message */ default: log('Err', 'No supported namespace: ' + header.namespace); res.setHeader('Content-Type', 'application/json'); res.json(constructError(event)); break; } }); var handleDiscovery = function (req, res) { var event = req.body; var payload = JSON.parse(fs.readFileSync(__dirname + '/../devices.json', 'utf8')); var headers = { messageId: event.directive.header.messageId, name: "Discover.Response", namespace: "Alexa.Discovery", payloadVersion: "3" }; var result = { event: { header: headers, payload: payload } }; res.setHeader('Content-Type', 'application/json'); res.json(result); }; var powerController = function(req, res) { var event = req.body; var endpoint = event.directive.endpoint.endpointId; if(endpoint === 'everything') { controlEverything(event); } if(endpoint === 'milights') { milight.setIp(event.directive.endpoint.cookie.ip); event.directive.header.name === "TurnOff" ? milight.off() : milight.on(); } if(endpoint === 'ikea-led') { if(event.directive.header.name === "TurnOn") { led.setColor('#FFFFFF', function() { /* called when color is changed */ }); } else { led.turnOff(); } } if(endpoint === 'heater') { harmony.heatingOn(event.directive.endpoint.cookie.harmonyIP, event.directive.endpoint.cookie.harmonyId); } var response = constructResponse(event, "powerState", event.directive.header.name === "TurnOff" ? "OFF": "ON"); res.setHeader('Content-Type', 'application/json'); res.json(response); }; var brightnessController = function(req, res) { var event = req.body; // default to error var response = constructError(event); var endpoint = event.directive.endpoint.endpointId; if(endpoint === 'milights') { milight.setIp(event.directive.endpoint.cookie.ip); if(event.directive.header.name === "SetBrightness") { var brightnessPercentage = event.directive.payload.brightness; milight.brightness(brightnessPercentage, 0); response = constructResponse(event, "brightness", brightnessPercentage); } else { var brightnessDelta = event.directive.payload.brightnessDelta < 0 ? 20 : 100; milight.brightness(brightnessDelta, 0); response = constructResponse(event, "brightness", brightnessDelta); } } res.setHeader('Content-Type', 'application/json'); res.json(response); }; var colorController = function(req, res) { var event = req.body; // default to error var response = constructError(event); var endpoint = event.directive.endpoint.endpointId; if(endpoint === 'milights') { milight.setIp(event.directive.endpoint.cookie.ip); if(event.directive.header.name === "SetColor") { var color = event.directive.payload.color; if(color.hue === 0 && color.saturation === 0) { // Set to White milight.on(0); } else { // Set to provided Colour milight.colorHsv([color.hue, color.saturation, color.brightness]); } response = constructResponse(event, "color", color); } } if(endpoint === 'ikea-led') { var color = event.directive.payload.color; var h = color.hue; var s = Math.floor(color.saturation * 100); var b = Math.floor(color.brightness * 100); var rgb = hsv(h, s, b); led.setColor(rgb[0], rgb[1], rgb[2]); response = constructResponse(event, "color", color); } res.setHeader('Content-Type', 'application/json'); res.json(response); }; var stateController = function(req, res){ var event = req.body; // default to error var response = constructError(event); var exampleResponse = { "context": { "properties":[ { "namespace":"Alexa.PowerController", "name":"powerState", "value":"ON" }, { "namespace":"Alexa.BrightnessController", "name":"brightness", "value":100 }, { "namespace":"Alexa.ColorController", "name":"color", "value":{ "hue": 0, "saturation": 0, "brightness": 1 } } ] }, "event":{ "header":{ "messageId":event.directive.header.messageId, "correlationToken":event.directive.header.correlationToken, "namespace":"Alexa", "name":"StateReport", "payloadVersion":"3" }, "endpoint":event.directive.endpoint, "payload":{ } } } if(event.directive.endpoint.endpointId === 'milights'){ response = exampleResponse; } res.setHeader('Content-Type', 'application/json'); res.json(response); }; var controlEverything = function(event) { if(event.directive.header.name === "TurnOff") { milight.off(); led.turnOff(); tplink.off(event.directive.endpoint.cookie.ip, event.directive.endpoint.cookie.port); harmony.tvOff(); } else { milight.on(); led.setColor('#FFFFFF', function() { /* called when color is changed */ }); tplink.on(event.directive.endpoint.cookie.ip, event.directive.endpoint.cookie.port); harmony.tvOn(); } } var constructResponse = function(event, name, value) { var response = { "context": { "properties": [ { "namespace": event.directive.header.namespace, "name": name, "value": value, //"timeOfSample": "2017-02-03T16:20:50.52Z", //"uncertaintyInMilliseconds": 500 } ] }, "event": { "header": { "namespace": "Alexa", "name": "Response", "payloadVersion": "3", "messageId": event.directive.header.messageId, "correlationToken": event.directive.header.correlationToken }, "endpoint": event.directive.endpoint, "payload": {} } } return response; } var constructError = function(event) { return { "event": { "header": { "namespace": "Alexa", "name": "ErrorResponse", "messageId": event.directive.header.messageId, "correlationToken": event.directive.header.correlationToken, "payloadVersion": "3" }, "endpoint":{ "endpointId":event.directive.endpoint.endpointId }, "payload": { "type": "ENDPOINT_UNREACHABLE", "message": "Unable to reach device because it appears to be offline" } } } } module.exports = router;
leafuk/milight-web
src/routes/smartHomeV3.js
JavaScript
mit
8,291
namespace Games { using System; using System.Collections.Generic; using System.Linq; using Games.Interfaces; using Games.IOEngines; public class MinesGame { private const int Rows = 5; private const int Cols = 10; private const int RankListCapacity = 6; private const int MaxPoints = 35; private const char InitialPlaygroundCellSign = '?'; private const char EmptyPlaygroundCellSign = '-'; private const char BombCellSign = '*'; private readonly List<Winner> rankList = new List<Winner>(RankListCapacity); private readonly IWriter consoleWriter = new ConsoleWriter(); private readonly IReader consoleReader = new ConsoleReader(); private char[,] playground; private char[,] bombs; private bool isDead, isWinner; private int pointsCount = 0; public MinesGame() { this.playground = this.CreateNewPlayground(Rows, Cols, InitialPlaygroundCellSign); this.bombs = this.CreatePlaygroundWithBombs(); } public void Start() { this.consoleWriter.ShowCommands(); this.consoleWriter.ShowPlayground(this.playground); string inputCommand = string.Empty; do { int row = 0, col = 0; this.consoleWriter.ShowMessage("Enter row and col (or command): "); inputCommand = this.consoleReader.ReadCommand(); if (this.TryParseCoords(ref row, ref col, inputCommand)) { inputCommand = "turn"; } switch (inputCommand) { case "turn": { this.ExecuteTurnCommand(row, col); break; } case "top": { this.consoleWriter.ShowRankList(this.rankList); break; } case "restart": { this.ExecuteRestartCommand(); break; } case "exit": { this.consoleWriter.ShowMessage("\nYou have left the game!"); break; } default: { this.consoleWriter.ShowMessage("\n - Error! Invalid input command!\n\n"); break; } } if (this.IsGameEnd(this.pointsCount)) { this.pointsCount = 0; this.isWinner = false; this.isDead = false; } } while (inputCommand != "exit"); this.consoleReader.ReadCommand(); } private void ExecuteTurnCommand(int row, int col) { if (this.bombs[row, col] != BombCellSign) { if (this.bombs[row, col] == EmptyPlaygroundCellSign) { this.PlaceBombsCountNearToCell(this.playground, this.bombs, row, col); this.pointsCount++; } if (MaxPoints == this.pointsCount) { this.isWinner = true; } else { this.consoleWriter.ShowPlayground(this.playground); } } else { this.isDead = true; } } private void ExecuteRestartCommand() { this.playground = this.CreateNewPlayground(Rows, Cols, InitialPlaygroundCellSign); this.bombs = this.CreatePlaygroundWithBombs(); this.consoleWriter.ShowPlayground(this.playground); } private char[,] CreateNewPlayground(int rows, int cols, char cellSign) { char[,] playground = new char[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { playground[i, j] = cellSign; } } return playground; } private char[,] CreatePlaygroundWithBombs() { char[,] playground = this.CreateNewPlayground(Rows, Cols, EmptyPlaygroundCellSign); IList<int> randomIntegers = new List<int>(); while (randomIntegers.Count < 15) { Random randomGenerator = new Random(); int randomInteger = randomGenerator.Next(50); if (!randomIntegers.Contains(randomInteger)) { randomIntegers.Add(randomInteger); } } foreach (int randomNumber in randomIntegers) { int row = randomNumber / Cols; int col = randomNumber % Cols; if (col == 0 && randomNumber != 0) { row--; col = Cols; } else { col++; } playground[row, col - 1] = BombCellSign; } return playground; } private bool TryParseCoords(ref int row, ref int col, string inputCommand) { if (inputCommand.Length >= 3) { if (int.TryParse(inputCommand[0].ToString(), out row) && int.TryParse(inputCommand[2].ToString(), out col)) { if (row <= this.playground.GetLength(0) && col <= this.playground.GetLength(1)) { return true; } } } return false; } private bool IsGameEnd(int pointsCount) { if (this.isDead) { this.consoleWriter.ShowMessage("\nGAME OVER!\n"); this.consoleWriter.ShowMessage(string.Format("You win {0} points!\n\n", pointsCount)); this.GetWinnerInformation(pointsCount); this.ExecuteRestartCommand(); return true; } if (this.isWinner) { this.consoleWriter.ShowMessage("\nCongratulations!\n"); this.consoleWriter.ShowMessage(string.Format("You have opened all the {0} cells!\n", pointsCount)); this.GetWinnerInformation(pointsCount); this.ExecuteRestartCommand(); return true; } return false; } private int GetBombsCount(char[,] playground, int row, int col) { int bombsCount = 0; int rows = playground.GetLength(0); int cols = playground.GetLength(1); if (row - 1 >= 0) { if (playground[row - 1, col] == BombCellSign) { bombsCount++; } if (col - 1 >= 0) { if (playground[row - 1, col - 1] == BombCellSign) { bombsCount++; } } if (col + 1 < cols) { if (playground[row - 1, col + 1] == BombCellSign) { bombsCount++; } } } if (row + 1 < rows) { if (playground[row + 1, col] == BombCellSign) { bombsCount++; } if (col - 1 >= 0) { if (playground[row + 1, col - 1] == BombCellSign) { bombsCount++; } } if (col + 1 < cols) { if (playground[row + 1, col + 1] == BombCellSign) { bombsCount++; } } } if (col - 1 >= 0) { if (playground[row, col - 1] == BombCellSign) { bombsCount++; } } if (col + 1 < cols) { if (playground[row, col + 1] == BombCellSign) { bombsCount++; } } return bombsCount; } private void PlaceBombsCountNearToCell(char[,] playground, char[,] bombs, int row, int col) { int bombsCount = this.GetBombsCount(bombs, row, col); char bombsCountToChar = char.Parse(bombsCount.ToString()); bombs[row, col] = bombsCountToChar; playground[row, col] = bombsCountToChar; } private void GetWinnerInformation(int pointsCount) { this.consoleWriter.ShowMessage("Enter your nickname: "); string nickname = this.consoleReader.ReadCommand(); Winner winner = new Winner(nickname, pointsCount); this.AddWinnerToRankList(winner); } private void AddWinnerToRankList(Winner winner) { if (this.rankList.Count < RankListCapacity) { this.rankList.Add(winner); } else { for (int i = 0; i < this.rankList.Count; i++) { if (this.rankList[i].Points < winner.Points) { this.rankList.Insert(i, winner); this.rankList.RemoveAt(this.rankList.Count - 1); break; } } } this.rankList.Sort((Winner w1, Winner w2) => w2.Name.CompareTo(w1.Name)); this.rankList.Sort((Winner w1, Winner w2) => w2.Points.CompareTo(w1.Points)); } } }
StefanSinapov/TelerikAcademy
07. High-Quality Code/Homework/02. Naming Identifiers/04. Code improvements/MinesGame.cs
C#
mit
10,329