code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#region License Information (GPL v3) /* ShareX - A program that allows you to take screenshots and share any file type Copyright (c) 2007-2016 ShareX Team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Optionally you can also view the license at <http://www.gnu.org/licenses/>. */ #endregion License Information (GPL v3) using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Cache; using System.Text; using Newtonsoft.Json; namespace puush_installer.ShareX.HelpersLib { public class GitHubUpdateChecker : UpdateChecker { public string Owner { get; private set; } public string Repo { get; private set; } public bool IncludePreRelease { get; set; } private const string APIURL = "https://api.github.com"; private string ReleasesURL => $"{APIURL}/repos/{Owner}/{Repo}/releases"; public GitHubUpdateChecker(string owner, string repo) { Owner = owner; Repo = repo; } public override void CheckUpdate() { } public string GetLatestDownloadURL(bool includePreRelease, bool isPortable, bool isBrowserDownloadURL) { try { GitHubRelease latestRelease = GetLatestRelease(includePreRelease); if (UpdateReleaseInfo(latestRelease, isPortable, isBrowserDownloadURL)) { return DownloadURL; } } catch (Exception) { //DebugHelper.WriteException(e); } return null; } public string GetDownloadCounts() { StringBuilder sb = new StringBuilder(); foreach (GitHubRelease release in GetReleases().Where(x => x.assets != null && x.assets.Count > 0)) { sb.AppendFormat("{0} ({1}): {2}{3}", release.name, DateTime.Parse(release.published_at), release.assets.Sum(x => x.download_count), Environment.NewLine); } return sb.ToString().Trim(); } private List<GitHubRelease> GetReleases() { using (WebClient wc = new WebClient()) { wc.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); wc.Headers.Add("user-agent", "ShareX"); wc.Proxy = Proxy; string response = wc.DownloadString(ReleasesURL); if (!string.IsNullOrEmpty(response)) { return JsonConvert.DeserializeObject<List<GitHubRelease>>(response); } } return null; } private GitHubRelease GetLatestRelease(bool includePreRelease) { GitHubRelease latestRelease = null; List<GitHubRelease> releases = GetReleases(); if (releases != null && releases.Count > 0) { if (includePreRelease) { latestRelease = releases[0]; } else { latestRelease = releases.FirstOrDefault(x => !x.prerelease); } } return latestRelease; } public bool UpdateReleaseInfo(GitHubRelease release, bool isPortable, bool isBrowserDownloadURL) { if (release != null && !string.IsNullOrEmpty(release.tag_name) && release.tag_name.Length > 1 && release.tag_name[0] == 'v') { LatestVersion = new Version(release.tag_name.Substring(1)); if (release.assets != null && release.assets.Count > 0) { string endsWith; if (isPortable) { endsWith = "portable.zip"; } else { endsWith = ".exe"; } foreach (GitHubAsset asset in release.assets) { if (asset != null && !string.IsNullOrEmpty(asset.name) && asset.name.EndsWith(endsWith, StringComparison.InvariantCultureIgnoreCase)) { Filename = asset.name; if (isBrowserDownloadURL) { DownloadURL = asset.browser_download_url; } else { DownloadURL = asset.url; } return true; } } } } return false; } } [System.Reflection.ObfuscationAttribute(Feature = "renaming", ApplyToMembers = true)] [Serializable] public class GitHubRelease { public string url { get; set; } public string assets_url { get; set; } public string upload_url { get; set; } public string html_url { get; set; } public int id { get; set; } public string tag_name { get; set; } public string target_commitish { get; set; } public string name { get; set; } public string body { get; set; } public bool draft { get; set; } public bool prerelease { get; set; } public string created_at { get; set; } public string published_at { get; set; } public List<GitHubAsset> assets { get; set; } public string tarball_url { get; set; } public string zipball_url { get; set; } } [System.Reflection.ObfuscationAttribute(Feature = "renaming", ApplyToMembers = true)] [Serializable] public class GitHubAsset { public string url { get; set; } public int id { get; set; } public string name { get; set; } public string label { get; set; } public string content_type { get; set; } public string state { get; set; } public int size { get; set; } public int download_count { get; set; } public string created_at { get; set; } public string updated_at { get; set; } public string browser_download_url { get; set; } } }
Jaex/puush-installer
puush-installer/ShareX.HelpersLib/GitHubUpdateChecker.cs
C#
mit
7,044
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace FancyAsyncMagic { public class AsyncWriter { private readonly Stream _Stream; public AsyncWriter(Stream stream) { _Stream = stream; } private Task WriteBytes(byte[] data, CancellationToken token) { return _Stream.WriteAsync(data, 0, data.Length, token); } private async Task WriteBytesAndType(byte[] data, ElementType type, CancellationToken token, byte[] dataPrefix = null) { await WriteBytes(new byte[] { (byte)type }, token); if (dataPrefix != null) await WriteBytes(dataPrefix, token); await WriteBytes(data, token); } public Task Write(byte b, CancellationToken token) { return WriteBytesAndType(new byte[] { b }, ElementType.Byte, token); } public Task Write(Int32 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.Int32, token); } public Task Write(Int64 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.Int64, token); } public Task Write(UInt32 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.UInt32, token); } public Task Write(UInt64 i, CancellationToken token) { return WriteBytesAndType(BitConverter.GetBytes(i), ElementType.UInt64, token); } public Task Write(byte[] data, CancellationToken token) { return WriteBytesAndType(data, ElementType.ByteArray, token, BitConverter.GetBytes(data.Length)); } public Task Write(string s, CancellationToken token) { return WriteBytesAndType(Encoding.UTF8.GetBytes(s), ElementType.String, token, BitConverter.GetBytes(Encoding.UTF8.GetByteCount(s))); } } }
main--/FancyAsyncMagic
FancyAsyncMagic/AsyncWriter.cs
C#
mit
2,141
<?php /* * This file is part of KoolKode BPMN. * * (c) Martin Schröder <m.schroeder2007@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types = 1); namespace KoolKode\BPMN\Task\Command; use KoolKode\BPMN\Engine\AbstractBusinessCommand; use KoolKode\BPMN\Engine\ProcessEngine; use KoolKode\BPMN\Task\Event\UserTaskUnclaimedEvent; use KoolKode\Util\UUID; /** * Removes the current assignee from a user task. * * @author Martin Schröder */ class UnclaimUserTaskCommand extends AbstractBusinessCommand { protected $taskId; public function __construct(UUID $taskId) { $this->taskId = $taskId; } /** * {@inheritdoc} * * @codeCoverageIgnore */ public function isSerializable(): bool { return true; } /** * {@inheritdoc} */ public function executeCommand(ProcessEngine $engine): void { $task = $engine->getTaskService()->createTaskQuery()->taskId($this->taskId)->findOne(); if (!$task->isClaimed()) { throw new \RuntimeException(\sprintf('User task %s is not claimed', $task->getId())); } $sql = " UPDATE `#__bpmn_user_task` SET `claimed_at` = :time, `claimed_by` = :assignee WHERE `id` = :id "; $stmt = $engine->prepareQuery($sql); $stmt->bindValue('time', null); $stmt->bindValue('assignee', null); $stmt->bindValue('id', $task->getId()); $stmt->execute(); $task = $engine->getTaskService()->createTaskQuery()->taskId($this->taskId)->findOne(); $engine->notify(new UserTaskUnclaimedEvent($task, $engine)); $engine->debug('User task "{task}" unclaimed', [ 'task' => $task->getName() ]); } }
koolkode/bpmn
src/Task/Command/UnclaimUserTaskCommand.php
PHP
mit
1,946
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) from folium.plugins.marker_cluster import MarkerCluster from folium.utilities import _validate_coordinates from jinja2 import Template class FastMarkerCluster(MarkerCluster): """ Add marker clusters to a map using in-browser rendering. Using FastMarkerCluster it is possible to render 000's of points far quicker than the MarkerCluster class. Be aware that the FastMarkerCluster class passes an empty list to the parent class' __init__ method during initialisation. This means that the add_child method is never called, and no reference to any marker data are retained. Methods such as get_bounds() are therefore not available when using it. Parameters ---------- data: list List of list of shape [[], []]. Data points should be of the form [[lat, lng]]. callback: string, default None A string representation of a valid Javascript function that will be passed a lat, lon coordinate pair. See the FasterMarkerCluster for an example of a custom callback. name : string, default None The name of the Layer, as it will appear in LayerControls. overlay : bool, default True Adds the layer as an optional overlay (True) or the base layer (False). control : bool, default True Whether the Layer will be included in LayerControls. show: bool, default True Whether the layer will be shown on opening (only for overlays). options : dict, default None A dictionary with options for Leaflet.markercluster. See https://github.com/Leaflet/Leaflet.markercluster for options. """ _template = Template(u""" {% macro script(this, kwargs) %} var {{ this.get_name() }} = (function(){ {{this._callback}} var data = {{ this._data }}; var cluster = L.markerClusterGroup({{ this.options }}); for (var i = 0; i < data.length; i++) { var row = data[i]; var marker = callback(row); marker.addTo(cluster); } cluster.addTo({{ this._parent.get_name() }}); return cluster; })(); {% endmacro %}""") def __init__(self, data, callback=None, options=None, name=None, overlay=True, control=True, show=True): super(FastMarkerCluster, self).__init__(name=name, overlay=overlay, control=control, show=show, options=options) self._name = 'FastMarkerCluster' self._data = _validate_coordinates(data) if callback is None: self._callback = """ var callback = function (row) { var icon = L.AwesomeMarkers.icon(); var marker = L.marker(new L.LatLng(row[0], row[1])); marker.setIcon(icon); return marker; };""" else: self._callback = 'var callback = {};'.format(callback)
QuLogic/folium
folium/plugins/fast_marker_cluster.py
Python
mit
3,213
namespace OggVorbisEncoder.Setup.Templates.FloorBooks { public class Line256X7_0Sub3 : IStaticCodeBook { public int Dimensions { get; } = 1; public byte[] LengthList { get; } = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3, 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9, 10, 9, 11, 13, 11, 13, 10, 10, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12 }; public CodeBookMapType MapType { get; } = CodeBookMapType.None; public int QuantMin { get; } = 0; public int QuantDelta { get; } = 0; public int Quant { get; } = 0; public int QuantSequenceP { get; } = 0; public int[] QuantList { get; } = null; } }
vr-the-feedback/vr-the-feedback-unity
Assets/VRTheFeedback/Scripts/OggVorbisEncoder/Setup/Templates/FloorBooks/Line256X7_0Sub3.cs
C#
mit
775
#include "SumUnique.cc" #include <algorithm> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <sys/time.h> #include <vector> const static double __EPSILON = 1e-9; static double __time = 0.0; static void __timer_start() { struct timeval tv; if (gettimeofday(&tv, NULL) == 0) { __time = double(tv.tv_sec) * 1000.0 + double(tv.tv_usec) * 0.001; } } static double __timer_stop() { double start = __time; __timer_start(); return __time - start; } static void __eat_whitespace(std::istream& in) { while (in.good() && std::isspace(in.peek())) in.get(); } std::ostream& operator << (std::ostream& out, const std::string& str) { out << '"' << str.c_str() << '"'; return out; } template <class T> std::ostream& operator << (std::ostream& out, const std::vector<T>& vec) { out << '{'; if (0 < vec.size()) { out << vec[0]; for (size_t i = 1; i < vec.size(); ++i) out << ", " << vec[i]; } out << '}'; return out; } std::istream& operator >> (std::istream& in, std::string& str) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '"') { std::ostringstream s; while (in.good() && (c = in.get()) != '"') { s.put(char(c)); } str = s.str(); } return in; } template <class T> std::istream& operator >> (std::istream& in, std::vector<T>& vec) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '{') { __eat_whitespace(in); vec.clear(); while (in.good() && (c = in.get()) != '}') { if (c != ',') in.putback(c); T t; in >> t; __eat_whitespace(in); vec.push_back(t); } } return in; } template <class T> bool __equals(const T& actual, const T& expected) { return actual == expected; } bool __equals(double actual, double expected) { if (std::abs(actual - expected) < __EPSILON) { return true; } else { double minimum = std::min(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); double maximum = std::max(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); return actual > minimum && actual < maximum; } } bool __equals(const std::vector<double>& actual, const std::vector<double>& expected) { if (actual.size() != expected.size()) { return false; } for (size_t i = 0; i < actual.size(); ++i) { if (!__equals(actual[i], expected[i])) { return false; } } return true; } int main(int argc, char* argv[]) { bool __abort_on_fail = false; int __pass = 0; int __fail = 0; if (1 < argc) __abort_on_fail = true; std::cout << "TAP version 13" << std::endl; std::cout.flush(); std::ifstream __in("testcases.txt"); for(;;) { int __testnum = __pass + __fail + 1; int __expected; vector <int> values; __in >> __expected >> values; if (!__in.good()) break; std::cout << "# input for test " << __testnum << ": " << values << std::endl; std::cout.flush(); __timer_start(); SumUnique __object; int __actual = __object.getSum(values); double __t = __timer_stop(); std::cout << "# test completed in " << __t << "ms" << std::endl; std::cout.flush(); if (__equals(__actual, __expected)) { std::cout << "ok"; ++__pass; } else { std::cout << "not ok"; ++__fail; } std::cout << " " << __testnum << " - " << __actual << " must equal " << __expected << std::endl; std::cout.flush(); if (__abort_on_fail && 0 < __fail) std::abort(); } std::cout << "1.." << (__pass + __fail) << std::endl << "# passed: " << __pass << std::endl << "# failed: " << __fail << std::endl; if (__fail == 0) { std::cout << std::endl << "# Nice! Don't forget to compile remotely before submitting." << std::endl; } return __fail; } // vim:ft=cpp:noet:ts=8
mathemage/CompetitiveProgramming
topcoder/SRM/Rookie-SRM-7-DIV-1/500/driver.cc
C++
mit
3,736
var gulp = require('gulp'), sass = require('gulp-sass'), scsslint = require('gulp-scss-lint'); gulp.task('sass', function () { gulp.src('./_sass/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('./css')); }); gulp.task('scsslint', function () { gulp.src('./_sass/**/*.scss') .pipe(scsslint()) }); gulp.task('sass:watch', function () { gulp.watch('./_sass/**/*.scss', ['sass']); }); gulp.task('sass:watch:lint', function () { gulp.watch(['./_sass/**/*.scss', './_sass/**/_*.scss'], ['sass','scsslint']); });
rogeralbinoi/html5-boilerplate-sass-lint
Gulpfile.js
JavaScript
mit
557
<?php require_once __DIR__ . '/vendor/autoload.php'; use Chadicus\Marvel\Api\Client; use Chadicus\Marvel\Api\Entities\ImageVariant; use DominionEnterprises\Util\Arrays; $nameStartsWith = Arrays::get($_POST, 'nameStartsWith'); ?> <html> <head> <style> label { display: inline-block; width: 140px; text-align: right; } img { max-width:800px; } </style> </head> <body> <form method="POST" action="/"> <fieldset> <legend>Search Characters</legend> <br /> <label for="nameStartsWith">Name</label> <input type="text" name="nameStartsWith" size="32" value="<?=$nameStartsWith?>" /> <br /> <input type="Submit" value="Search" /> </fieldset> </form> <?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?> <?php $client = new Client(getenv('PRIVATE_KEY'), getenv('PUBLIC_KEY')); $dataWrapper = $client->search('characters', ['nameStartsWith' => $nameStartsWith]); $count = 0; ?> <h3><?=$dataWrapper->getData()->getTotal()?> characters found</h3> <table border="1"> <tbody> <tr> <?php foreach ($dataWrapper->getData()->getResults() as $character): ?> <?php if ($count++ % 5 === 0): ?> </tr><tr> <?php endif; ?> <td> <p><?=$character->getName()?></p> <a href="<?=$character->getUrls()[0]->getUrl()?>"> <img src="<?=$character->getThumbnail()->getUrl(ImageVariant::PORTRAIT_XLARGE())?>" /> </a> </td> <?php endforeach; ?> </tr> </tbody> </table> <center><?=$dataWrapper->getAttributionHTML()?></center> <?php endif; ?> </body> </html>
chadicus/marvel-api-client
examples/gallery/index.php
PHP
mit
2,104
<?php /******************************************************************* * Glype is copyright and trademark 2007-2015 UpsideOut, Inc. d/b/a Glype * and/or its licensors, successors and assigners. All rights reserved. * * Use of Glype is subject to the terms of the Software License Agreement. * http://www.glype.com/license.php ******************************************************************* * This is the parser for the proxy - changes the original 'raw' * document so that everything (images, links, etc.) is rerouted to * be downloaded via the proxy script instead of directly. ******************************************************************/ class parser { # State of javascript parser - null for parse everything, false # for parse all non-standard overrides, or (array) with specifics private $jsFlagState; # Browsing options (Remove Scripts, etc.) private $htmlOptions; # Constructor accepts options and saves them in the object function __construct($htmlOptions, $jsFlags) { $this->jsFlagState = $jsFlags; $this->htmlOptions = $htmlOptions; } /***************************************************************** * HTML parsers - main parsing function splits up document into * component parts ('normal' HTML, scripts and styles) ******************************************************************/ function HTMLDocument($input, $insert='', $inject=false, $footer='') { if (strlen($input)>65536) { if (version_compare(PHP_VERSION, '5.3.7')<=0) { ini_set('pcre.backtrack_limit', 1000000); } } # # Apply parsing that only needs to be done once.. # # Record the charset global $charset; if (!isset($charset)) { $meta_equiv = preg_match('#(<meta[^>]*http\-equiv\s*=[^>]*>)#is', $input, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[0][0] : null; if (isset($meta_equiv)) { $charset = preg_match('#charset\s*=\s*["\']+([^"\'\s>]*)#is', $meta_equiv, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[1][0] : null; } } if (!isset($charset)) { $meta_charset = preg_match('#<meta[^>]*charset\s*=\s*["\']+([^"\'\s>]*)#is', $input, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[1][0] : null; if (isset($meta_charset)) { $charset = $meta_charset; } } # Remove empty script comments $input = preg_replace('#/\*\s*\*/#s', '', $input); # Remove conditional comments $input = preg_replace('#<\!\-\-\[if \!IE\]>\s*\-\->(.*?)<\!\[endif\]\-\->#s','$1',$input); $input = preg_replace('#<\!\-\-\[if.*?<\!\[endif\]\-\->#s','',$input); # Prevent websites from calling disableOverride() $input = preg_replace('#disableOverride#s', 'disabled___disableOverride', $input); # Remove titles if option is enabled if ( $this->htmlOptions['stripTitle'] || $this->htmlOptions['encodePage'] ) { $input = preg_replace('#<title.*?</title>#is', '', $input, 1); $input = preg_replace('#<meta[^>]*name=["\'](title|description|keywords)["\'][^>]*>#is', '', $input, 3); $input = preg_replace('#<link[^>]*rel=["\'](icon|shortcut icon)["\'][^>]*>#is', '', $input, 2); } # Remove and record a <base> href $input = preg_replace_callback('#<base href\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)[^>]*>#i', 'html_stripBase', $input, 1); # Proxy url= values in meta redirects $input = preg_replace_callback('#content\s*=\s*(["\\\'])?[0-9]+\s*;\s*url=([\\\'"]|&\#39;)?((?(?<=")[^"]+|(?(?<=\\\')[^\\\']+|[^\\\'" >]+)))(?(2)\\2|)(?(1)\\1|)#i', 'html_metaRefresh', $input, 1); # Process forms $input = preg_replace_callback('#<form([^>]*)>(.*?)</form>#is', 'html_form', $input); # Remove scripts blocks (avoids individual processing below) if ( $this->htmlOptions['stripJS'] ) { $input = preg_replace('#<script[^>]*>.*?</script>#is', '', $input); } # # Split up the document into its different types and parse them # # Build up new document into this var $new = ''; $offset = 0; # Find instances of script or style blocks while ( preg_match('#<(s(?:cript|tyle))[^>]*>#i', $input, $match, PREG_OFFSET_CAPTURE, $offset) ) { # What type of block is this? $block = strtolower($match[1][0]); # Start position of content $outerStart = $match[0][1]; $innerStart = $outerStart + strlen($match[0][0]); # Determine type of end tag and find it's position $endTag = "</$block>"; $innerEnd = stripos($input, $endTag, $innerStart); if ($innerEnd===false) { $endTag = "</"; $innerEnd = stripos($input, $endTag, $innerStart); if ($innerEnd===false) { $input = preg_replace('#<script[^>]*>.*?$#is', '', $input); break; } } $outerEnd = $innerEnd + strlen($endTag); # Parse everything up till here and add to the new document $new .= $this->HTML(substr($input, $offset, $innerStart - $offset)); # Find parsing function $parseFunction = $block == 'style' ? 'CSS' : 'JS' ; # Add the parsed block $new .= $this->$parseFunction(substr($input, $innerStart, $innerEnd - $innerStart)); # Move offset to new position $offset = $innerEnd; } # And add the final chunk (between last script/style block and end of doc) $new .= $this->HTML(substr($input, $offset)); # Replace input with the updated document $input = $new; global $foundPlugin; if ( $foundPlugin && function_exists('postParse') ) { $input = postParse($input, 'html'); $foundPlugin=false; } # Make URLs relative $input = preg_replace('#=\s*(["\'])?\s*https?://[^"\'>/]*/#i', '=$1/', $input); # Encode the page if ( $this->htmlOptions['encodePage'] ) { $input = encodePage($input); } # # Now add our own code bits # # Insert our mini form after the <body> if ( $insert !== false ) { # Check for a frameset if ( ( $useFrames = stripos($input, '<frameset') ) !== false ) { # Flag the frames so only first displays mini-form $input = preg_replace_callback('#<frame[^>]+src\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', 'html_flagFrames', $input); } # Attempt to add after body $input = preg_replace('#(<body[^>]*>)#i', '$1' . $insert, $input, 1, $tmp); # Check it inserted and append (if not a frameset) if ( ! $tmp && ! $useFrames ) { $input = $insert . $input; } } # Insert our javascript library if ( $inject ) { # Generate javascript to insert $inject = injectionJS(); # Add our proxy javascript after <head> $input = preg_replace('#(<head[^>]*>)#i', '$1' . $inject, $input, 1, $tmp); # If no <head>, just prepend if ( ! $tmp ) { $input = $inject . $input; } } # Add anything to the footer? if ( $footer ) { $input = preg_replace('#(</body[^>]*>)#i', $footer . '$1', $input, 1, $tmp); # If no </body>, just append the footer if ( ! $tmp ){ $input .= $footer; } } # Return new document return $input; } # Parse HTML sections function HTML($input) { # Removing objects? Follow spec and display inner content of object tags instead. if ( $this->htmlOptions['stripObjects'] ) { # Remove all object tags (including those deprecated but still common) $input = preg_replace('#<(?>object|applet|param|embed)[^>]*>#i', '', $input, -1, $tmp); # Found any? Remove the corresponding end tags if ( $tmp ) { $input = preg_replace('#</(?>object|applet|param|embed)>#i', '', $input, $tmp); } } else { # Parse <param name="movie" value="URL"> tags $input = preg_replace_callback('#<param[^>]+value\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)[^>]*>#i', 'html_paramValue', $input); # To do: proxy object related URLs } # Show content within <noscript> tags # (preg_ seems to be faster than 2 str_ireplace() calls) if ( $this->htmlOptions['stripJS'] ) { $input = preg_replace('#</?noscript>#i', '', $input); } # remove srcset attribute for now $input = preg_replace('#srcset\s*=\s*[\\\'"][^"]*[\\\'"]#i', '', $input); # Parse onX events $input = preg_replace_callback('#\b(on(?<!\.on)[a-z]{2,20})\s*=\s*([\\\'"])?((?(2)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(2)\\2|)#i', array(&$this, 'html_eventJS'), $input); # Parse style attributes $input = preg_replace_callback('#style\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', array(&$this, 'html_elementCSS'), $input); # Proxy URL attributes - this is the bottleneck but optimized as much as possible $input = preg_replace_callback('#(?><[A-Z0-9]{1,15})(?>\s+[^>\s]+)*?\s*(?>(href|src|background|poster)\s*=(?!\\\\)\s*)(?>([\\\'"])?)((?(2)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^ >]{1,2048}))(?(2)\\2|)#i', 'html_attribute', $input); # Return changed input return $input; } # Proxy an onX javascript event function html_eventJS($input) { return $this->htmlOptions['stripJS'] ? '' : $input[1] . '=' . $input[2] . $this->JS($input[3]) . $input[2]; } # Proxy a style="CSS" attribute function html_elementCSS($input) { return 'style=' . $input[1] . $this->CSS($input[2]) . $input[1]; } /***************************************************************** * CSS parser - main parsing function * CSS parsing is a complicated by the caching of CSS files. We need * to consider (A) cross-domain caching and (B) the unique URLs option. * A) If possible, use a relative URL so the saved URLs do not explictly * point to a single domain. * B) There is a second set of callback functions with "_unique" suffixed * and these return the original URL to be reparesed. ******************************************************************/ # The URLs depend on the unique and path info settings. The type parameter allows # us to specify the unique callbacks. function CSS($input, $storeUnique=false) { # What type of parsing is this? Normally we parse any URLs to redirect # back through the proxy but not when storing a cache with unique URLs. $type = $storeUnique ? '_unique' : ''; # CSS needs proxying the calls to url(), @import and src='' $input = preg_replace_callback('#\burl\s*\(\s*[\\\'"]?([^\\\'"\)]+)[\\\'"]?\s*\)#i', 'css_URL' . $type, $input); $input = preg_replace_callback('#@import\s*[\\\'"]([^\\\'"\(\)]+)[\\\'"]#i', 'css_import' . $type, $input); $input = preg_replace_callback('#\bsrc\s*=\s*([\\\'"])?([^)\\\'"]+)(?(1)\\1|)#i', 'css_src' . $type, $input); # Make URLs relative $input = preg_replace('#https?://[^"\'>/]*/#i', '/', $input); # Return changed return $input; } /***************************************************************** * Javascript parser - main parsing function * * The specific parts that need proxying depends on which javascript * functions we've been able to override. On first page load, the browser * capabilities are tested to see what we can do client-side and the results * sent back to us. This allows us to parse only what we have to. * If $CONFIG['override_javascript'] is disabled, all commands are parsed * server-side. This will use much more CPU! * * Commands to proxy only if no override at all: * document.write() * document.writeln() * window.open() * eval() * * Commands to proxy, regardless of browser capabilities: * location.replace() * .innerHTML= * * Commands to proxy if the extra "watch" flag is set * (the browser doesn't support the .watch() method): * location= * x.location= * location.href= * * Commands to proxy if the extra "setters" flag is set * (the browser doesn't support the __defineSetter__() method): * .src= * .href= * .background= * .action= * * Commands to proxy if the extra "ajax" flag is set * (the browser failed to override the .open() method): * XMLHttpRequest.open() ******************************************************************/ function JS($input) { # Stripping? if ( $this->htmlOptions['stripJS'] ) { return ''; } # Get our flags $flags = $this->jsFlagState; # Unless we know we don't need to, apply all the browser-specific flags if ( ! is_array($this->jsFlagState) ) { $flags = array('ajax', 'watch', 'setters'); } # If override is disabled, add a "base" flag if ( $this->jsFlagState === null ) { $flags[] = 'base'; } # Start parsing! $search = array(); # Create shortcuts to various search patterns: # "before" - matches preceeding character (string of single char) [ignoring whitespace] # "after" - matches next character (string of single char) [ignoring whitespace] # "id" - key for identifying the original match (e.g. if we have >1 of the same key) $assignmentPattern = array('before' => '.', 'after' => '='); $methodPattern = array('before' => '.', 'after' => '('); $functionPattern = array('after' => '('); # Configure strings to search for, starting with always replaced commands $search['innerHTML'][] = $assignmentPattern; $search['location'][] = array('after' => '.', 'id' => 'replace()'); # ^ This is only for location.replace() - other forms are handled later # Look for attribute assignments if ( in_array('setters', $flags) ) { $search['src'][] = $assignmentPattern; $search['href'][] = $assignmentPattern; $search['action'][] = $assignmentPattern; $search['background'][] = $assignmentPattern; $search['poster'][] = $assignmentPattern; } # Look for location changes # location.href will be handled above, location= is handled here if ( in_array('watch', $flags) ) { $search['location'][] = array('after' => '=', 'id' => 'assignment'); } # Look for .open() if either AJAX (XMLHttpRequest.open) or # base (window.open) flags are present if ( in_array('ajax', $flags) || in_array('base', $flags) ) { $search['open'][] = $methodPattern; } # Add the basic code if no override if ( in_array('base', $flags) ) { $search['eval'][] = $functionPattern; $search['writeln'][] = $methodPattern; $search['write'][] = $methodPattern; } # Set up starting parameters $offset = 0; $length = strlen($input); $searchStrings = array_keys($search); while ( $offset < $length ) { # Start off by assuming no more items (i.e. the next position # of interest is the end of the document) $commandPos = $length; # Loop through the search subjects foreach ( $searchStrings as $item ) { # Any more instances of this? if ( ( $tmp = strpos($input, $item, $offset) ) === false ) { # Nope, skip to next item continue; } # If $item is whole word? if ( ( $input[$tmp-1] == '_' ) || ctype_alpha($input[$tmp-1]) ) { # No continue; } # Closer to the currently held 'next' position? if ( $tmp < $commandPos ) { $commandPos = $tmp; $command = $item; } } # No matches found? Finish parsing. if ( $commandPos == $length ) { break; } # We've found the main point of interest; now use the # search parameters to check the surrounding chars to validate # the match. $valid = false; foreach ( $search[$command] as $pattern ) { # Check the preceeding chars if ( isset($pattern['before']) && str_checkprev($input, $pattern['before'], $commandPos-1) === false ) { continue; } # Check next chars if ( isset($pattern['after']) && ( $charPos = str_checknext($input, $pattern['after'], $commandPos + strlen($command), false, false) ) === false ) { continue; } $postCharPos = ($charPos + 1) + strspn($input, " \t\r\n", $charPos + 1); # Still here? Match must be OK so generate a match ID if ( isset($pattern['id']) ) { $valid = $command . $pattern['id']; } else { $valid = $command; } break; } # What we do next depends on which match (if any) we've found... switch ( $valid ) { # Assigment case 'src': case 'href': case 'background': case 'poster': case 'action': case 'locationassignment': case 'innerHTML': # Check our post-char position for = as well (could be equality # test rather than assignment, i.e. == ) if ( ! isset($input[$postCharPos]) || $input[$postCharPos] == '=' ) { break; } # Find the end of this statement $endPos = analyzeAssign_js($input, $charPos); $valueLength = $endPos - $postCharPos; # Produce replacement command $replacement = sprintf('parse%s(%s)', $command=='innerHTML' ? 'HTML' : 'URL', substr($input, $postCharPos, $valueLength)); # Adjust total document length as appropriate $length += strlen($replacement); # Make the replacement $input = substr_replace($input, $replacement, $postCharPos, $valueLength); # Move offset up to new position $offset = $endPos + 10; # Go get next match continue 2; # Function calls - we don't know for certain if these are in fact members of the # appropriate objects (window/XMLHttpRequest for .open(), document for .write() and # .writeln) so we won't change anything. Main.js still overrides these functions but # does nothing with them by default. We add an extra parameter to tell our override # to kick in. case 'open': case 'write': case 'writeln': # Find the end position (the closing ")" for the function call) $endPos = analyze_js($input, $charPos); # Insert our additional argument just before that $glStr=',"gl"'; if (strspn($input, ";\n\r\+{}()[]", $charPos) >= ($endPos - $charPos)) { $glStr='"gl"'; } $input = substr_replace($input, $glStr, $endPos - 1, 0); # Adjust the document length $length += strlen($glStr); # And move the offset $offset = $endPos + strlen($glStr); # Get next match continue 2; # Eval() is a just as easy since we can just wrap the entire thing in parseJS(). case 'eval': # Ensure this is a call to eval(), not anotherfunctionendingineval() if ( isset($input[$commandPos-1]) && strpos('abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_', $input[$commandPos-1]) !== false ) { break; } # Find the end position (the closing ")" for the function call) $endPos = analyze_js($input, $charPos); $valueLength = $endPos - $postCharPos; # Generate our replacement $replacement = sprintf('parseJS(%s)', substr($input, $postCharPos, $valueLength)); # Make the replacement $input = substr_replace($input, $replacement, $postCharPos, $valueLength); # Adjust the document length $length += 9; # And move the offset $offset = $endPos + 9; continue 2; # location.replace() is a tricky one. We have the position of the char # after . as $postCharPos and need to ensure we're calling replace(), # then parse the entire URL case 'locationreplace()': # Validate the match if ( ! preg_match('#\Greplace\s*\(#', $input, $tmp, 0, $postCharPos) ) { break; } # Move $postCharPos to inside the brackets of .replace() $postCharPos += strlen($tmp[0]); # Find the end position (the closing ")" for the function call) $endPos = analyze_js($input, $postCharPos); $valueLength = $endPos - $postCharPos; # Generate our replacement $replacement = sprintf('parseURL(%s)', substr($input, $postCharPos, $valueLength)); # Make the replacement $input = substr_replace($input, $replacement, $postCharPos, $valueLength); # Adjust the document length $length += 9; # And move the offset $offset = $endPos + 9; continue 2; } # Still here? A match didn't validate so adjust offset to just after # current position $offset = $commandPos + 1; } # Ignore document.domain $input = str_replace('document.domain', 'ignore', $input); # Return changed return $input; } } /***************************************************************** * HTML callbacks ******************************************************************/ # Remove and record the <base> href function html_stripBase($input) { global $base; $base = $input[2]; return ''; } # Proxy the location of a meta refresh function html_metaRefresh($input) { return str_replace($input[3], proxyURL($input[3]), $input[0]); } # Proxy URL in <param name="movie" value="URL"> function html_paramValue($input) { # Check for a name="movie" tag if ( stripos($input[0], 'movie') === false ) { return $input[0]; } return str_replace($input[2], proxyURL($input[2]), $input[0]); } # Process forms - the query string is used by the proxy script # and GET data needs to be encoded anyway. We convert all GET # forms to POST and then the proxy script will forward it properly. function html_form($input) { # Check for a given method if ( preg_match('#\bmethod\s*=\s*["\\\']?(get|post)["\\\']?#i', $input[1], $tmp) ) { # Not POST? if ( strtolower($tmp[1]) != 'post' ) { # Convert to post and flag as a conversion $input[1] = str_replace($tmp[0], 'method="post"', $input[1]); $converted = true; } } else { # Append a POST method (no method given and GET is default) $input[1] .= ' method="post"'; $converted = true; } # Prepare the extra input to insert $add = empty($converted) ? '' : '<input type="hidden" name="convertGET" value="1">'; # To do: javascript onsubmit event to immediately redirect to the appropriate # location using GET data, without an intermediate POST to the proxy script. # Proxy the form action $input[1] = preg_replace_callback('#\baction\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', 'html_formAction', $input[1]); # What type of form is this? Due to register_globals support, PHP converts # a number of characters to _ in incoming variable names. To get around this, # we can use the raw post data from php://input but this is not available # for multipart forms. Instead we must encode the input names in these forms. if ( stripos($input[1], 'multipart/form-data') ) { $input[2] = preg_replace_callback('#name\s*=\s*([\\\'"])?((?(1)(?(?<=")[^"]{1,2048}|[^\\\']{1,2048})|[^\s"\\\'>]{1,2048}))(?(1)\\1|)#i', 'html_inputName', $input[2]); } # Return updated form return '<form' . $input[1] . '>' . $add . $input[2] . '</form>'; } # Proxy the action="URL" value in forms function html_formAction($input) { return 'action=' . $input[1] . proxyURL($input[2]) . $input[1]; } # Encode input names function html_inputName($input) { return 'name=' . $input[1] . inputEncode($input[2]) . $input[1]; } # Proxy URL values in attributes function html_attribute($input) { # Is this an iframe? $flag = stripos($input[0], 'iframe') === 1 ? 'frame' : ''; # URL occurred as value of an attribute and should have been htmlspecialchar()ed # We need to do the job of the browser and decode before proxying. return str_replace($input[3], htmlspecialchars(proxyURL(htmlspecialchars_decode($input[3]), $flag)), $input[0]); } # Flag frames in a frameset so only the first one shows the mini-form. # This could be done in the above callback but adds extra processing # when 99% of the time, it won't be needed. function html_flagFrames($input) { static $addFlag; # If it's the first frame, leave it but set the flag var if ( ! isset($addFlag) ) { $addFlag = true; return $input[0]; } # Add the frame flag $newURL = $input[2] . ( strpos($input[2], '?') ? '&amp;f=frame' : 'fframe/'); return str_replace($input[2], $newURL, $input[0]); } /***************************************************************** * CSS callbacks ******************************************************************/ # Proxy CSS url(LOCATION) function css_URL($input) { return 'url(' . proxyURL(trim($input[1])) . ')'; } # Proxy CSS @import "URL" function css_import($input) { return '@import "' . proxyURL($input[1]) . '"'; } # Proxy CSS src= function css_src($input) { return 'src=' . $input[1] . proxyURL($input[2]) . $input[1]; } # Callbacks for use with unique URLs and cached CSS # The <UNIQUE[]URL> acts as a marker for quick and easy processing later # Unique CSS url(LOCATION) function css_URL_unique($input) { return 'url(<UNIQUE[' . absoluteURL($input[1],'') . ']URL>)'; } # Unique CSS @import "URL" function css_import_unique($input) { return '@import "<UNIQUE[' . absoluteURL($input[1]) . ']URL>"'; } # Unique CSS src= function css_src_unique($input) { return 'src=' . $input[1] . '<UNIQUE[' . absoluteURL($input[2]) . ']URL>' . $input[1]; } /***************************************************************** * Helper functions ******************************************************************/ # Take a string, and check that the next non-whitespace char is the # passed in char (X). Return false if non-whitespace and non-X char is # found. Otherwise, return the position of X. # If $inverse is true, the next non-whitespace char must NOT be in $char # If $pastChar is true, ignore whitespace after finding X and return # the position of the last post-X whitespace char. function str_checknext($input, $char, $offset, $inverse = false, $pastChar = false) { for ( $i = $offset, $length = strlen($input); $i < $length; ++$i ) { # Examine char switch ( $input[$i] ) { # Ignore whitespace case ' ': case "\t": case "\r": case "\n": break; # Found the passed char case $char: # $inverse means we do NOT want this char if ( $inverse ) { return false; } # Move past this to the next non-whitespace? if ( $pastChar ) { ++$i; return $i + strspn($input, " \t\r\n", $i); } # Found desired char, no $pastChar, just return X offset return $i; # Found non-$char non-whitespace default: # This is the desired result if $inverse if ( $inverse ) { return $i; } # No $inverse, found a non-$char, return false return false; } } return false; } # Same as above but go backwards function str_checkprev($input, $char, $offset, $inverse = false) { for ( $i = $offset; $i > 0; --$i ) { # Examine char switch ( $input[$i] ) { # Ignore whitespace case ' ': case "\t": case "\r": case "\n": break; # Found char case $char: return $inverse ? false : $i; # Found non-$char char default: return $inverse ? $i : false; } } return $inverse; } # Analyze javascript and return offset positions. # Default is to find the end of the statement, indicated by: # (1) ; while not in string # (2) newline which, if not there, would create invalid syntax # (3) a closing bracket (object, language construct or function call) for which # no corresponding opening bracket was detected AFTER the passed offset # If (int) $argPos is true, we return an array of the start and end position # for the nth argument, where n = $argPos. The $start position must be just inside # the parenthesis of the function call we're interested in. function analyze_js($input, $start, $argPos = false) { # Add , if looking for an argument position if ( $argPos ) { $currentArg = 1; } # Loop through the input, stopping only at special chars for ( $i = $start, $length = strlen($input), $end = false, $openObjects = $openBrackets = $openArrays = 0; $end === false && $i < $length; ++$i ) { $char = $input[$i]; switch ( $char ) { # Starting string delimiters case '"': case "'": if ( $input[$i-1] == '\\' ) { break; } # Skip straight to end of string # Find the corresponding end delimiter and ensure it's not escaped while ( ( $i = strpos($input, $char, $i+1) ) && $input[$i-1] == '\\' ); # Check for false, in which case we assume the end is the end of the doc if ( $i === false ) { break 2; } break; # End of operation? case ';': $end = $i; break; # New lines case "\n": case "\r": # Newlines are OK if occuring within an open brackets, arrays or objects. if ( $openObjects || $openBrackets || $openArrays || $argPos ) { break; } # Newlines are also OK if followed by an opening function OR concatenation # e.g. someFunc\n(params) or someVar \n + anotherVar # Find next non-whitespace char position $tmp = $i + strspn($input, " \t\r\n", $i+1); # And compare to allowed chars if ( isset($input[$tmp+1]) && ( $input[$tmp+1] == '(' || $input[$tmp+1] == '+' ) ) { $i = $tmp; break; } # Newline not indicated as OK, set the end to here $end = $i; break; # Concatenation case '+': # Our interest in the + operator is it's use in allowing an expression # to span multiple lines. If we come across a +, move past all whitespace, # including newlines (which would otherwise indicate end of expression). $i += strspn($input, " \t\r\n", $i+1); break; # Opening chars (objects, parenthesis and arrays) case '{': ++$openObjects; break; case '(': ++$openBrackets; break; case '[': ++$openArrays; break; # Closing chars - is there a corresponding open char? # Yes = reduce stored count. No = end of statement. case '}': $openObjects ? --$openObjects : $end = $i; break; case ')': $openBrackets ? --$openBrackets : $end = $i; break; case ']': $openArrays ? --$openArrays : $end = $i; break; # Commas - tell us which argument it is case ',': # Ignore commas inside other functions or whatnot if ( $openObjects || $openBrackets || $openArrays ) { break; } # End now if ( $currentArg == $argPos ) { $end = $i; } # Increase the current argument number ++$currentArg; # If we're not after the first arg, start now? if ( $currentArg == $argPos ) { $start = $i+1; } break; } } # End not found? Use end of document if ( $end === false ) { $end = $length; } # Return array of start/end if ( $argPos ) { return array($start, $end); } # Return end return $end; } function analyzeAssign_js($input, $start) { # Loop through the input, stopping only at special chars for ( $i = $start, $length = strlen($input), $end = false, $openObjects = $openBrackets = $openArrays = 0; $end === false && $i < $length; ++$i ) { $char = $input[$i]; switch ( $char ) { # Starting string delimiters case '"': case "'": if ( $input[$i-1] == '\\' ) { break; } # Skip straight to end of string # Find the corresponding end delimiter and ensure it's not escaped while ( ( $i = strpos($input, $char, $i+1) ) && $input[$i-1] == '\\' ); # Check for false, in which case we assume the end is the end of the doc if ( $i === false ) { break 2; } break; # End of operation? case ';': $end = $i; break; # New lines case "\n": case "\r": # Newlines are OK if occuring within an open brackets, arrays or objects. if ( $openObjects || $openBrackets || $openArrays ) { break; } break; # Concatenation case '+': # Our interest in the + operator is it's use in allowing an expression # to span multiple lines. If we come across a +, move past all whitespace, # including newlines (which would otherwise indicate end of expression). $i += strspn($input, " \t\r\n", $i+1); break; # Opening chars (objects, parenthesis and arrays) case '{': ++$openObjects; break; case '(': ++$openBrackets; break; case '[': ++$openArrays; break; # Closing chars - is there a corresponding open char? # Yes = reduce stored count. No = end of statement. case '}': $openObjects ? --$openObjects : $end = $i; break; case ')': $openBrackets ? --$openBrackets : $end = $i; break; case ']': $openArrays ? --$openArrays : $end = $i; break; # Commas - tell us which argument it is case ',': # Ignore commas inside other functions or whatnot if ( $openObjects || $openBrackets || $openArrays ) { break; } # End now $end = $i; break; } } # End not found? Use end of document if ( $end === false ) { $end = $length; } # Return end return $end; } /***************************************************************** * Page encoding functions ******************************************************************/ # Encode page - splits into HTML/script sections and encodes HTML function encodePage($input) { # Look for script blocks # if ( preg_match_all('#<(?:script|style).*?</(?:script|style)>#is', $input, $scripts, PREG_OFFSET_CAPTURE) ) { # not working if ( preg_match_all('#<script.*?</script>#is', $input, $scripts, PREG_OFFSET_CAPTURE) ) { # Create starting offset - only start encoding after the <head> # as this seems to help browsers cope! $offset = preg_match('#<body[^>]*>(.)#is', $input, $tmp, PREG_OFFSET_CAPTURE) ? $tmp[1][1] : 0; $new = $offset ? substr($input, 0, $offset) : ''; # Go through all the matches foreach ( $scripts[0] as $id => $match ) { # Determine position of the preceeding non-script block $end = $match[1] ? $match[1]-1 : 0; $start = $offset; $length = $end - $start; # Add encoded block to page if there is one if ($length && $length>0) { $new .= "\n\n\n<!--start encode block-->\n"; $new .= encodeBlock(substr($input, $start, $length)); $new .= "\n<!--end encode block-->\n\n\n"; } # Add unencoded script to page $new .= "\n\n\n<!--start unencoded block-->\n"; $new .= $match[0]; $new .= "\n<!--end unencoded block-->\n\n\n"; # Move offset up $offset = $match[1] + strlen($match[0]); } # Add final block if ( $remainder = substr($input, $offset) ) { $new .= encodeBlock($remainder); } # Update input with new $input = $new; } else { # No scripts is easy - just encode the lot $input = encodeBlock($input); } # Return the encoded page return $input; } # Encode block - applies the actual encoding # note - intended to obfustate URLs and HTML source code. Does not provide security. Use SSL for actual security. function encodeBlock($input) { global $charset; $new=''; if (isset($charset)) { $charset=strtolower($charset); if (function_exists('mb_convert_encoding')) { $input=mb_convert_encoding($input, 'HTML-ENTITIES', $charset); } } # Return javascript decoder return '<script type="text/javascript">document.write(arcfour(ginf.enc.u,base64_decode(\'' . arcfour('encrypt',$GLOBALS['unique_salt'],$input) . '\')));</script>'; }
selecterskyphp/glype_chs
includes/parser.php
PHP
mit
34,604
namespace NorthwindWindowsStore.DAL.Model.Interface { public interface ITerritory { } }
krzysztofkolek/NorthwindWindowsStore
NorthwindWindowsStoreService/NorthwindWindowsStore.DAL.Model/Interface/ITerritory.cs
C#
mit
99
/* Project : 4-9 Math Tutor Author : Mohammad Al-Husseini Description : Displays two random numbers to be added then waits for the user to solve it. The user can type their result in and the program tells them if they are correct. Knowns : 2x Random Numbers - Int Inputs : Answer - Int Display : 2x Radnom Numbers - Int Answer - Int */ /////////////////////////////////////////////////////////////////////////////////////////////////// #include <iostream> // cout and cin objects for command line output/input #include <cstdlib> // random numbers #include <ctime> // time to seed the random numbers using namespace std; int main() { // Create variables to hold the random numbers int num1, num2; // Variable for User Input int result; // Seed the random number unsigned seed = time(0); // 0 indicates current time at run-time srand(seed); // Generate the random numbers num1 = rand(); num2 = rand(); // Display the numbers cout << " " << num1 << endl; cout << "+ " << num2 << endl; cout << "__________" << endl; cout << " "; // Wait for user input cin >> result; // Determine if answer was correct if (result == num1 + num2) cout << "Congratulations! That is correct, good job!"; else cout << " " << num1 + num2; return 0; }
menarus/C-Course
Solutions/Ch4/4-09 Math Tutor.cpp
C++
mit
1,339
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- try: from ._models_py3 import AlertRuleResource from ._models_py3 import AlertRuleResourceCollection from ._models_py3 import AlertRuleResourcePatch from ._models_py3 import AutoscaleNotification from ._models_py3 import AutoscaleProfile from ._models_py3 import AutoscaleSettingResource from ._models_py3 import AutoscaleSettingResourceCollection from ._models_py3 import AutoscaleSettingResourcePatch from ._models_py3 import EmailNotification from ._models_py3 import ErrorResponse from ._models_py3 import EventCategoryCollection from ._models_py3 import EventData from ._models_py3 import EventDataCollection from ._models_py3 import HttpRequestInfo from ._models_py3 import LocalizableString from ._models_py3 import LocationThresholdRuleCondition from ._models_py3 import ManagementEventAggregationCondition from ._models_py3 import ManagementEventRuleCondition from ._models_py3 import MetricTrigger from ._models_py3 import Operation from ._models_py3 import OperationDisplay from ._models_py3 import OperationListResult from ._models_py3 import Recurrence from ._models_py3 import RecurrentSchedule from ._models_py3 import Resource from ._models_py3 import RuleAction from ._models_py3 import RuleCondition from ._models_py3 import RuleDataSource from ._models_py3 import RuleEmailAction from ._models_py3 import RuleManagementEventClaimsDataSource from ._models_py3 import RuleManagementEventDataSource from ._models_py3 import RuleMetricDataSource from ._models_py3 import RuleWebhookAction from ._models_py3 import ScaleAction from ._models_py3 import ScaleCapacity from ._models_py3 import ScaleRule from ._models_py3 import ScaleRuleMetricDimension from ._models_py3 import SenderAuthorization from ._models_py3 import ThresholdRuleCondition from ._models_py3 import TimeWindow from ._models_py3 import WebhookNotification except (SyntaxError, ImportError): from ._models import AlertRuleResource # type: ignore from ._models import AlertRuleResourceCollection # type: ignore from ._models import AlertRuleResourcePatch # type: ignore from ._models import AutoscaleNotification # type: ignore from ._models import AutoscaleProfile # type: ignore from ._models import AutoscaleSettingResource # type: ignore from ._models import AutoscaleSettingResourceCollection # type: ignore from ._models import AutoscaleSettingResourcePatch # type: ignore from ._models import EmailNotification # type: ignore from ._models import ErrorResponse # type: ignore from ._models import EventCategoryCollection # type: ignore from ._models import EventData # type: ignore from ._models import EventDataCollection # type: ignore from ._models import HttpRequestInfo # type: ignore from ._models import LocalizableString # type: ignore from ._models import LocationThresholdRuleCondition # type: ignore from ._models import ManagementEventAggregationCondition # type: ignore from ._models import ManagementEventRuleCondition # type: ignore from ._models import MetricTrigger # type: ignore from ._models import Operation # type: ignore from ._models import OperationDisplay # type: ignore from ._models import OperationListResult # type: ignore from ._models import Recurrence # type: ignore from ._models import RecurrentSchedule # type: ignore from ._models import Resource # type: ignore from ._models import RuleAction # type: ignore from ._models import RuleCondition # type: ignore from ._models import RuleDataSource # type: ignore from ._models import RuleEmailAction # type: ignore from ._models import RuleManagementEventClaimsDataSource # type: ignore from ._models import RuleManagementEventDataSource # type: ignore from ._models import RuleMetricDataSource # type: ignore from ._models import RuleWebhookAction # type: ignore from ._models import ScaleAction # type: ignore from ._models import ScaleCapacity # type: ignore from ._models import ScaleRule # type: ignore from ._models import ScaleRuleMetricDimension # type: ignore from ._models import SenderAuthorization # type: ignore from ._models import ThresholdRuleCondition # type: ignore from ._models import TimeWindow # type: ignore from ._models import WebhookNotification # type: ignore from ._monitor_management_client_enums import ( ComparisonOperationType, ConditionOperator, EventLevel, MetricStatisticType, RecurrenceFrequency, ScaleDirection, ScaleRuleMetricDimensionOperationType, ScaleType, TimeAggregationOperator, TimeAggregationType, ) __all__ = [ 'AlertRuleResource', 'AlertRuleResourceCollection', 'AlertRuleResourcePatch', 'AutoscaleNotification', 'AutoscaleProfile', 'AutoscaleSettingResource', 'AutoscaleSettingResourceCollection', 'AutoscaleSettingResourcePatch', 'EmailNotification', 'ErrorResponse', 'EventCategoryCollection', 'EventData', 'EventDataCollection', 'HttpRequestInfo', 'LocalizableString', 'LocationThresholdRuleCondition', 'ManagementEventAggregationCondition', 'ManagementEventRuleCondition', 'MetricTrigger', 'Operation', 'OperationDisplay', 'OperationListResult', 'Recurrence', 'RecurrentSchedule', 'Resource', 'RuleAction', 'RuleCondition', 'RuleDataSource', 'RuleEmailAction', 'RuleManagementEventClaimsDataSource', 'RuleManagementEventDataSource', 'RuleMetricDataSource', 'RuleWebhookAction', 'ScaleAction', 'ScaleCapacity', 'ScaleRule', 'ScaleRuleMetricDimension', 'SenderAuthorization', 'ThresholdRuleCondition', 'TimeWindow', 'WebhookNotification', 'ComparisonOperationType', 'ConditionOperator', 'EventLevel', 'MetricStatisticType', 'RecurrenceFrequency', 'ScaleDirection', 'ScaleRuleMetricDimensionOperationType', 'ScaleType', 'TimeAggregationOperator', 'TimeAggregationType', ]
Azure/azure-sdk-for-python
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/models/__init__.py
Python
mit
6,678
<?php require_once __DIR__ . '/../../lib/DoublyLinkedListNode.php'; class SumListNoConvertReversed { public static function sum(Node $n1, Node $n2) { $head = $tail = null; $n1Length = self::getLinkedListSize($n1); $n2Length = self::getLinkedListSize($n2); $maxLength = max($n1Length, $n2Length); $n1Offset = $maxLength - $n1Length; $n2Offset = $maxLength - $n2Length; while ($n1 !== null || $n2 !== null) { $sum = 0; if ($n1Offset > 0) { $n1Offset--; } else { $sum += $n1->getData(); $n1 = $n1->getNext(); } if ($n2Offset > 0) { $n2Offset--; } else { $sum += $n2->getData(); $n2 = $n2->getNext(); } self::addDigitToLinkedList($head, $tail, $sum); } return $head; } public static function addDigitToLinkedList( DoublyLinkedListNode &$head = null, DoublyLinkedListNode &$tail = null, $number) { $digit = $number % 10; if ($number >= 10) { $carry = ($number - $digit) / 10; if ($tail !== null) { $previousDigit = $tail->getData(); $tail = $tail->getPrevious(); if ($tail !== null) { $tail->setNext(null); } else { $head = null; } } else { $previousDigit = 0; } self::addDigitToLinkedList($head, $tail, $previousDigit + $carry); } $node = new DoublyLinkedListNode($digit); if ($tail !== null) { $tail->setNext($node); $node->setPrevious($tail); $tail = $node; } else { $head = $tail = $node; } } public static function getLinkedListSize(Node $node) { $size = 0; while ($node !== null) { $size++; $node = $node->getNext(); } return $size; } }
Kiandr/CrackingCodingInterview
php/src/chapter02/question2.5/SumListNoConvertReversed.php
PHP
mit
2,104
#!/usr/bin/env node import {cd, exec, rm, set} from 'shelljs'; import * as fs from 'fs'; // Fail on first error set('-e'); // Install Angular packages that are built locally from HEAD. // This also gets around the bug whereby yarn caches local `file://` urls. // See https://github.com/yarnpkg/yarn/issues/2165 // The below packages are all required in a default CLI project. const ngPackages = [ 'animations', 'core', 'common', 'compiler', 'forms', 'platform-browser', 'platform-browser-dynamic', 'router', 'compiler-cli', 'language-service', ]; // Keep typescript, tslib, and @types/node versions in sync with the ones used in this repo const nodePackages = [ '@types/node', 'tslib', 'typescript', ]; // Under Bazel integration tests are sand-boxed and cannot reference // reference `../../dist/*` packages and should not do so as these are not // inputs to the test. The npm_integeration_test rule instead provides a manifest // file that contains all of the npm package mappings available to the test. const bazelMappings: { [key: string]: string } = fs.existsSync('NPM_PACKAGE_MANIFEST.json') ? require('./NPM_PACKAGE_MANIFEST.json') : {}; const packages: { [key: string]: string } = {}; for (let p of ngPackages) { const n = `@angular/${p}`; packages[n] = `file:${bazelMappings[n]}` || `file:${__dirname}/../../dist/packages-dist/${p}`; } for (let p of nodePackages) { packages[p] = `file:${bazelMappings[p]}` || `file:${__dirname}/../../node_modules/${p}`; } // Clean up previously run test cd(__dirname); rm('-rf', `demo`); // Set up demo project exec('ng version'); exec('ng new demo --skip-git --skip-install --style=css --no-interactive'); cd('demo'); // Use a local yarn cache folder so we don't access the global yarn cache exec('mkdir .yarn_local_cache'); // Install Angular packages that are built locally from HEAD and npm packages // from root node modules that are to be kept in sync const packageList = Object.keys(packages).map(p => `${p}@${packages[p]}`).join(' '); exec(`yarn add --ignore-scripts --silent ${packageList} --cache-folder ./.yarn_local_cache`); // Add @angular/elements const schematicPath = bazelMappings ? `${bazelMappings['@angular/elements']}` : `${__dirname}/../../dist/packages-dist/elements`; exec(`ng add "${schematicPath}" --skip-confirmation`); // Test that build is successful after adding elements exec('ng build --no-source-map --configuration=development');
mgechev/angular
integration/ng_elements_schematics/test.ts
TypeScript
mit
2,456
<?php class Pilotes extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Pilote_model'); } public function index() { $data['title'] = 'Gestion des pilotes'; $this->load->view('header', $data); // Critères sur les pilotes à afficher $champs = $this->Pilote_model->getFields(); $data['champsLike'] = null; $data['champsEqual'] = null; foreach ($champs as $champ) { if (isset($_GET[$champ])) { if (($champ == 'id') OR ($_GET[$champ] == 'true' OR $_GET[$champ] == 'false') OR strtotime(str_replace('/', '-', $_GET[$champ]))) { $data['champsEqual'][$champ] = $_GET[$champ]; } else { $data['champsLike'][$champ] = $_GET[$champ]; } $data['old_data'][$champ] = $_GET[$champ]; } } $this->load->view('formRecherchePilote', $data); $this->display_pilotes($data); $this->load->view('footer', $data); } public function display_pilotes($data) { $data['title'] = 'Pilotes'; // Critère de tri if (isset($_GET['o'])) { $o = $_GET['o']; } else { $o = 'id'; } // Récupération des données $data['array_data'] = $this->Pilote_model->get($o, $data['champsEqual'], $data['champsLike'])->result_array(); $data['fields_metadata'] = $this->Pilote_model->getFieldsMetaData(); $data['array_headings'] = $this->perso->get_headings('pilote'); $data['miscInfos'] = $this->Pilote_model->getMisc(); $this->perso->set_data_for_display('pilote', $data['array_data']); // Traitement des lignes /*foreach($data['array_data'] as $num_row => $row) { }*/ $data['btnNouveau'] = true; $data['btnModif'] = true; $data['btnInfos'] = true; $data['object'] = 'pilote'; $data['miscInfos'] = $this->Pilote_model->getMisc(); $this->load->view('table', $data); } public function ajouter() { $data['title'] = 'Ajouter un pilote'; if (isset($_POST['nom'])) { if (!isset($_POST['qualification_biplace'])) { $_POST['qualification_biplace'] = false; } $_POST['nom'] = strtolower($_POST['nom']); $_POST['prenom'] = strtolower($_POST['prenom']); try { $this->Pilote_model->add($_POST); redirect('/pilotes', 'location', 301); } catch (Exception $e) { $data['error_message'] = $e.getMessage(); redirect('/pilotes', 'location', 400); } } else { $this->load->view('header', $data); $data['function'] = 'ajouter'; $this->load->view('formPilote', $data); $this->load->view('footer', $data); } } public function modifier($id) { $data['title'] = 'Modifier un pilote'; if (isset($_POST['nom'])) { if (!isset($_POST['qualification_biplace'])) { $_POST['qualification_biplace'] = false; } $_POST['nom'] = strtolower($_POST['nom']); $_POST['prenom'] = strtolower($_POST['prenom']); try { $this->Pilote_model->update($id, $_POST); redirect('/pilotes', 'location', 301); } catch (Exception $e) { $data['error_message'] = $e.getMessage(); redirect('/pilotes', 'location', 400); } } else { $this->load->view('header', $data); $data['function'] = 'modifier/'.$id; $data['old_data'] = $this->Pilote_model->get('id', array('id' => $id), null)->result_array()[0]; $this->load->view('formPilote', $data); $this->load->view('footer', $data); } } }
Sayomul/GestionParapente
application/controllers/Pilotes.php
PHP
mit
3,292
<?php namespace SEC\SolicitudesBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ProcesoType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('tipo', 'entity', array( 'class' => 'SECSolicitudesBundle:Tipo', 'property' => 'descripcion', 'empty_value' => 'Seleccione...' )) ->add('fechaRecSDA', 'date', array( 'label' => 'Fecha Recepción SDA : ', 'widget' => 'single_text', )) ->add('fechaRecSER', 'date', array( 'label' => 'Fecha Recepción SER : ', 'widget' => 'single_text', )) ->add('titulo') ->add('resumen', 'textarea', array( 'label' => 'Resumen' )) ->add('infoadicional') ->add('noradicado') ->add('entecontrol', 'entity', array( 'class' => 'SECSolicitudesBundle:EnteControl', 'property' => 'nombre', 'empty_value' => 'Seleccione...' )) ->add('diasrespuesta') ->add('fechamaxrespuesta', 'date', array( 'label' => 'Fecha Maxima : ', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'read_only' => true )) ->add('alerta1', 'date', array( 'label' => 'Alerta 1 : ', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'read_only' => true )) ->add('alerta2', 'date', array( 'label' => 'Alerta 2 : ', 'widget' => 'single_text', 'format' => 'dd/MM/yyyy', 'read_only' => true )) ->add('asignaciones', 'collection', array( 'type' => new AsignacionType(), 'label' => 'Responsables', 'by_reference' => false, //'prototype_data' => new Asignacion(), 'allow_delete' => true, 'allow_add' => true, )) ; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'SEC\SolicitudesBundle\Entity\Proceso' )); } public function getName() { return 'proceso_asignaciones'; } } ?>
miguelplazasr/sec
src/SEC/SolicitudesBundle/Form/ProcesoType.php
PHP
mit
2,796
require 'rails_helper' describe UserImportResult do #pending "add some examples to (or delete) #{__FILE__}" end # == Schema Information # # Table name: user_import_results # # id :bigint not null, primary key # user_import_file_id :bigint # user_id :bigint # body :text # created_at :datetime not null # updated_at :datetime not null # error_message :text #
next-l/enju_library
spec/models/user_import_result_spec.rb
Ruby
mit
464
package com.example.alexeyglushkov.uimodulesandclasses.activitymodule.presenter; import com.example.alexeyglushkov.uimodulesandclasses.activitymodule.view.ActivityModuleItemView; import com.example.alexeyglushkov.uimodulesandclasses.activitymodule.view.ActivityModuleView; /** * Created by alexeyglushkov on 02.04.17. */ public interface ActivityModuleItem { ActivityModuleItemView getActivityModuleItemView(); }
soniccat/android-taskmanager
ui/src/main/java/com/example/alexeyglushkov/uimodulesandclasses/activitymodule/presenter/ActivityModuleItem.java
Java
mit
422
@extends('adminlte::page') @section('title', 'Redirects') @section('content_header') <h1>Redirects</h1> @stop @section('content') <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-body"> @include('admin.redirects._form', [ 'route' => ['admin.redirects.store'] ]) </div> </div> </div> </div> @stop
patrykwozinski/shared-flat
resources/views/admin/redirects/create.blade.php
PHP
mit
474
namespace EngineOverflow.Web.ViewModels.Manage { using System.ComponentModel.DataAnnotations; public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone Number")] public string Number { get; set; } } }
delyan-nikolov-1992/EngineOverflow
Source/Web/EngineOverflow.Web/ViewModels/Manage/AddPhoneNumberViewModel.cs
C#
mit
276
var Articles = require("../articles"); var summarize = require("../summarize"); var translate = require("../translate"); var pipeline = require("../pipeline"); var veoozInterface = require("./veoozInterface.js"); module.exports = function (socketEnsureLoggedIn, socket) { function handleError(err) { return Promise.reject(err); } function throwError(err) { console.log(socket.id, "Throwing error:", err); socket.emit('new error', err); } function ensureArticleFactory(source) { if (!socket.articleFactory) { socket.articleFactory = new Articles(socket.id, source); } } socket.on('get article list', function (options, callback) { ensureArticleFactory(socket.handshake.query.articleSource); socket.articleFactory.fetchList(options).then(callback, throwError); }); socket.on('access article', function (articleId, langs, options, callback) { ensureArticleFactory(socket.handshake.query.articleSource); var authPromise; if (options.requireAuth) { authPromise = socketEnsureLoggedIn(socket); } else { authPromise = Promise.resolve(); } authPromise .then(function () { return socket.articleFactory.fetchOne(articleId); }, handleError) .then(function (article) { return pipeline.accessArticle(article, langs, options); }, handleError) .then(function (articles) { if (options.initializeLog) { var loggerPromises = []; articles.forEach(function (article) { loggerPromises.push( socket.articleFactory.initializeLogger(article) .then(function (loggerId) { if (!("_meta" in article)) { article._meta = {}; } article._meta.loggerId = loggerId; }, handleError) ); }); return Promise.all(loggerPromises).then(function () { return articles; }, handleError); } else { return articles; } }) .then(callback, handleError) .catch(throwError); }); socket.on('insert logs', function (loggerId, logs, callback) { ensureArticleFactory(socket.handshake.query.articleSource); // Client should ensure that no parallel request for the same loggerId are made. socketEnsureLoggedIn(socket) .then(function () { socket.articleFactory.insertLogs(loggerId, logs) .then(callback, function (err) { console.log(socket.id, "Ignoring error:", err); }); }, function (err) { console.log(socket.id, "Ignoring error:", err); }); }); socket.on('publish article', function (article, callback) { ensureArticleFactory(socket.handshake.query.articleSource); socketEnsureLoggedIn(socket) .then(function (user) { if (!article._meta) { article._meta = {}; } article._meta.username = user.username; return article; }, handleError) .then(function (article) { socket.articleFactory.storeEdited(article) .then(callback, throwError); if (article._meta.rawId) { console.log(socket.id, "Pushing accessible article to Veooz:", article.id); return veoozInterface.pushArticle(article).catch(function (err) { console.log(socket.id, "Error pushing article:", err); }); } }, throwError); }); socket.on('translate text', function (text, from, to, method, callback) { translate.translateText(text, from, to, method) .then(callback, throwError); }); };
nisargjhaveri/news-access
server/handleSocket.js
JavaScript
mit
4,291
module Fog module OpenStack class Compute class Real def list_os_interfaces(server_id) request( :expects => [200, 203], :method => 'GET', :path => "servers/#{server_id}/os-interface" ) end end class Mock def list_os_interfaces(server_id) Excon::Response.new( :body => {'interfaceAttachments' => data[:os_interfaces]}, :status => 200 ) end end end end end
fog/fog-openstack
lib/fog/openstack/compute/requests/list_os_interfaces.rb
Ruby
mit
530
'use strict'; var _ = require('lodash'); var moment = require('moment'); var util = require('util'); var articleService = require('../../services/article'); var listOrSingle = require('./lib/listOrSingle'); function parse (params) { var formats = ['YYYY', 'MM', 'DD']; var parts = _.values(params); var len = parts.length; var input = parts.join('-'); var inputFormat = formats.slice(0, len).join('-'); var unit; var textual; if (params.day) { textual = 'MMMM Do, YYYY'; unit = 'day'; } else if (params.month) { textual = 'MMMM, YYYY'; unit = 'month'; } else { textual = 'YYYY'; unit = 'year'; } var when = moment(input, inputFormat); var text = when.format(textual); return { start: when.startOf(unit).toDate(), end: when.clone().endOf(unit).toDate(), text: text }; } function slug (params) { var fmt = 'YYYY/MM/DD'; var keys = Object.keys(params).length; var parts = [params.year, params.month, params.day].splice(0, keys.length); return moment(parts.join('/'), fmt).format(fmt); } module.exports = function (req, res, next) { var parsed = parse(req.params); var handle = listOrSingle(res, { skip: false }, next); var titleFormat = 'Articles published on %s'; var title = util.format(titleFormat, parsed.text); res.viewModel = { model: { title: title, meta: { canonical: '/articles/' + slug(req.params), description: 'This search results page contains all of the ' + title.toLowerCase() } } }; var query = { status: 'published', publication: { $gte: parsed.start, $lt: parsed.end } }; articleService.find(query, handle); };
cshum/ponyfoo
controllers/articles/dated.js
JavaScript
mit
1,693
using Android.App; using Android.Content; using Android.Content.PM; using Android.OS; using Android.Support.V7.App; using System; using System.IO; namespace Teaching.Skills.Droid.Activities { [Activity(Label = "@string/app_title", Icon = "@drawable/icon", Theme = "@style/App.Default", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)] public class BaseActivity : AppCompatActivity { public BaseActivity() { } protected override void OnPause() { base.OnPause(); MainApplication.LastUseTime = DateTime.UtcNow; } protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); if (toolbar != null) { SetSupportActionBar(toolbar); SupportActionBar.Title = this.Title; SupportActionBar.SetDisplayHomeAsUpEnabled(true); SupportActionBar.SetHomeButtonEnabled(true); } } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { Permissions.Verify(grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } public static Intent CreateIntent<T>(object model = null) where T : Activity { var intent = new Intent(Application.Context, typeof(T)); if (model != null) { var serializer = new System.Xml.Serialization.XmlSerializer(model.GetType()); var modelStream = new MemoryStream(); serializer.Serialize(modelStream, model); intent.PutExtra("Model", modelStream.ToArray()); } return intent; } public override bool OnOptionsItemSelected(Android.Views.IMenuItem item) { if (item.ItemId == Android.Resource.Id.Home) Finish(); return base.OnOptionsItemSelected(item); } } }
ennerperez/teaching-skills
teaching.skills.droid/Activities/BaseActivity.cs
C#
mit
2,260
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; namespace CodeTiger.CodeAnalysis.Analyzers.Readability { /// <summary> /// Analyzes general readability issues. /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class GeneralReadabilityAnalyzer : DiagnosticAnalyzer { internal static readonly DiagnosticDescriptor EmptyStatementsShouldNotBeUsedDescriptor = new DiagnosticDescriptor("CT3100", "Empty statements should not be used.", "Empty statements should not be used.", "CodeTiger.Readability", DiagnosticSeverity.Warning, true); /// <summary> /// Gets a set of descriptors for the diagnostics that this analyzer is capable of producing. /// </summary> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(EmptyStatementsShouldNotBeUsedDescriptor); /// <summary> /// Registers actions in an analysis context. /// </summary> /// <param name="context">The context to register actions in.</param> /// <remarks>This method should only be called once, at the start of a session.</remarks> public override void Initialize(AnalysisContext context) { Guard.ArgumentIsNotNull(nameof(context), context); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.EnableConcurrentExecution(); context.RegisterSyntaxNodeAction(AnalyzeEmptyStatements, SyntaxKind.EmptyStatement); } private static void AnalyzeEmptyStatements(SyntaxNodeAnalysisContext context) { context.ReportDiagnostic(Diagnostic.Create(EmptyStatementsShouldNotBeUsedDescriptor, context.Node.GetLocation())); } } }
csdahlberg/CodeTiger.CodeAnalysis
CodeTiger.CodeAnalysis/Analyzers/Readability/GeneralReadabilityAnalyzer.cs
C#
mit
1,931
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); ui->capsLabel->clear(); //Setup Keyboard keyboard = new VirtualKeyboard(this); ui->keyboardLayout->addWidget(keyboard); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->keyboardToggle, SIGNAL(clicked()), keyboard, SLOT(toggleKeyboard())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR RCoinUSAS</b>!\nAre you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), tr("RCoinUSA will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your RCoinUSAs from being stolen by malware infecting your computer.")); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was succesfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when accepable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on.")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on.")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } else if (event->type() == QEvent::FocusIn) { if (object->inherits("QLineEdit")) { keyboard->setInput(object); } } return false; }
rcoinwallet/RCoinUSA
src/qt/askpassphrasedialog.cpp
C++
mit
9,309
namespace Mirage.Urbanization.ZoneStatisticsQuerying { public interface IQueryCrimeResult : IQueryCellValueResult { } }
Miragecoder/Urbanization
src/Mirage.Urbanization/ZoneStatisticsQuerying/IQueryCrimeResult.cs
C#
mit
123
# frozen_string_literal: true require 'spec_helper' require 'vk/api/ads/targ_suggestions_regions' RSpec.describe Vk::API::Ads::TargSuggestionsRegions do subject(:model) { described_class } it { is_expected.to be < Dry::Struct } it { is_expected.to be < Vk::Schema::Object } describe 'attributes' do subject(:attributes) { model.instance_methods(false) } it { is_expected.to include :id } it { is_expected.to include :name } it { is_expected.to include :type } end end
alsemyonov/vk
spec/vk/api/ads/targ_suggestions_regions_spec.rb
Ruby
mit
497
package percolate; /****************************************************************************** * Compilation: javac InteractivePercolationVisualizer.java * Execution: java InteractivePercolationVisualizer N * Dependencies: PercolationVisualizer.java Percolation.java * * This program takes the grid size N as a command-line argument. * Then, the user repeatedly clicks sites to open with the mouse. * After each site is opened, it draws full sites in light blue, * open sites (that aren't full) in white, and blocked sites in black. * ******************************************************************************/ import edu.princeton.cs.algs4.StdDraw; public class InteractivePercolationVisualizer { private static final int DELAY = 20; public static void main(String[] args) { // N-by-N percolation system (read from command-line, default = 10) int N = 10; if (args.length == 1) N = Integer.parseInt(args[0]); // turn on animation mode StdDraw.show(0); // repeatedly open site specified my mouse click and draw resulting system //StdOut.println(N); Percolation perc = new Percolation(N); PercolationVisualizer.draw(perc, N); StdDraw.show(DELAY); while (true) { // detected mouse click if (StdDraw.mousePressed()) { // screen coordinates double x = StdDraw.mouseX(); double y = StdDraw.mouseY(); // convert to row i, column j int i = (int) (N - Math.floor(y) - 1); int j = (int) (Math.floor(x)); // open site (i, j) provided it's in bounds if (i >= 0 && i < N && j >= 0 && j < N) { if (!perc.isOpen(i, j)) { //StdOut.println(i + " " + j); perc.open(i, j); } } // draw N-by-N percolation system PercolationVisualizer.draw(perc, N); } StdDraw.show(DELAY); } } }
TicknorN/B8-CSC301
Percolate/src/percolate/InteractivePercolationVisualizer.java
Java
mit
2,166
/*! \file */ /* ************************************************************************ * Copyright (c) 2019-2022 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ************************************************************************ */ #include "auto_testing_bad_arg.hpp" #include "testing.hpp" template <typename T> void testing_gthr_bad_arg(const Arguments& arg) { static const size_t safe_size = 100; // Create rocsparse handle rocsparse_local_handle handle; // Allocate memory on device device_vector<rocsparse_int> dx_ind(safe_size); device_vector<T> dx_val(safe_size); device_vector<T> dy(safe_size); if(!dx_ind || !dx_val || !dy) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } // Test rocsparse_gthr() EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(nullptr, safe_size, dy, dx_val, dx_ind, rocsparse_index_base_zero), rocsparse_status_invalid_handle); EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(handle, safe_size, nullptr, dx_val, dx_ind, rocsparse_index_base_zero), rocsparse_status_invalid_pointer); EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(handle, safe_size, dy, nullptr, dx_ind, rocsparse_index_base_zero), rocsparse_status_invalid_pointer); EXPECT_ROCSPARSE_STATUS( rocsparse_gthr<T>(handle, safe_size, dy, dx_val, nullptr, rocsparse_index_base_zero), rocsparse_status_invalid_pointer); } template <typename T> void testing_gthr(const Arguments& arg) { rocsparse_int M = arg.M; rocsparse_int nnz = arg.nnz; rocsparse_index_base base = arg.baseA; // Create rocsparse handle rocsparse_local_handle handle; // Argument sanity check before allocating invalid memory if(nnz <= 0) { static const size_t safe_size = 100; // Allocate memory on device device_vector<rocsparse_int> dx_ind(safe_size); device_vector<T> dx_val(safe_size); device_vector<T> dy(safe_size); if(!dx_ind || !dx_val || !dy) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); EXPECT_ROCSPARSE_STATUS(rocsparse_gthr<T>(handle, nnz, dy, dx_val, dx_ind, base), nnz < 0 ? rocsparse_status_invalid_size : rocsparse_status_success); return; } // Allocate host memory host_vector<rocsparse_int> hx_ind(nnz); host_vector<T> hx_val_gold(nnz); host_vector<T> hy(M); // Initialize data on CPU rocsparse_seedrand(); rocsparse_init_index(hx_ind, nnz, 1, M); rocsparse_init<T>(hy, 1, M, 1); // Allocate device memory device_vector<rocsparse_int> dx_ind(nnz); device_vector<T> dx_val_1(nnz); device_vector<T> dx_val_2(nnz); device_vector<T> dy(M); if(!dx_ind || !dx_val_1 || !dx_val_2 || !dy) { CHECK_HIP_ERROR(hipErrorOutOfMemory); return; } // Copy data from CPU to device CHECK_HIP_ERROR(hipMemcpy(dx_ind, hx_ind, sizeof(rocsparse_int) * nnz, hipMemcpyHostToDevice)); CHECK_HIP_ERROR(hipMemcpy(dy, hy, sizeof(T) * M, hipMemcpyHostToDevice)); if(arg.unit_check) { // Pointer mode host CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_1, dx_ind, base)); // Pointer mode device CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_device)); CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_2, dx_ind, base)); // Copy output to host // CPU gthr host_gthr<rocsparse_int, T>(nnz, hy, hx_val_gold, hx_ind, base); hx_val_gold.unit_check(dx_val_1); hx_val_gold.unit_check(dx_val_2); } if(arg.timing) { int number_cold_calls = 2; int number_hot_calls = arg.iters; CHECK_ROCSPARSE_ERROR(rocsparse_set_pointer_mode(handle, rocsparse_pointer_mode_host)); // Warm up for(int iter = 0; iter < number_cold_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_1, dx_ind, base)); } double gpu_time_used = get_time_us(); // Performance run for(int iter = 0; iter < number_hot_calls; ++iter) { CHECK_ROCSPARSE_ERROR(rocsparse_gthr<T>(handle, nnz, dy, dx_val_1, dx_ind, base)); } gpu_time_used = (get_time_us() - gpu_time_used) / number_hot_calls; double gbyte_count = gthr_gbyte_count<T>(nnz); double gpu_gbyte = get_gpu_gbyte(gpu_time_used, gbyte_count); display_timing_info("nnz", nnz, s_timing_info_bandwidth, gpu_gbyte, s_timing_info_time, get_gpu_time_msec(gpu_time_used)); } } #define INSTANTIATE(TYPE) \ template void testing_gthr_bad_arg<TYPE>(const Arguments& arg); \ template void testing_gthr<TYPE>(const Arguments& arg) INSTANTIATE(float); INSTANTIATE(double); INSTANTIATE(rocsparse_float_complex); INSTANTIATE(rocsparse_double_complex);
ROCmSoftwarePlatform/rocSPARSE
clients/testings/testing_gthr.cpp
C++
mit
6,546
<?php /** * @package start */ ?> <h1>integration</h1> <div class="content-section-b"> <div class="container"> <h1 class="title">Carreiras</h1> <div class="sidebar col-md-3"> <div> <h4 class='col-md-6'>total (<span id="total_vagas99">0</span>)</h4> <!--<div class="col-md-6 progress"> <div class="progress-bar" id="stream_progress" style="width: 0%;">0%</div> </div>--> </div> <div> <label class="sr-only" for="searchbox">Filtrar</label> <input type="text" class="form-control" id="searchbox" placeholder="Filtrar &hellip;" autocomplete="off"> <span class="glyphicon glyphicon-search search-icon"></span> </div> <br> <!--selects --> <div class="well"> <fieldset id="times_criteria"> <legend>Times</legend> <select class="form-control" id="times_filter" multiple="multiple"> </select> </fieldset> </div> <div class="well"> <fieldset id="local_criteria"> <legend>Localização</legend> <select class="form-control" id="local_filter" multiple="multiple"> </select> </fieldset> </div> <div class="well"> <fieldset id="tipo_criteria"> <legend>Tipo</legend> <select class="form-control" id="tipo_filter" multiple="multiple"> </select> </fieldset> </div> </div> <!-- /.col-md-3 --> <div class="col-md-9"> <div class="row"> <div class="content col-md-12"> <div id="pagination" class="vagas99-pagination col-md-9"></div> <div class="col-md-3 content"> Por Página: <span id="per_page" class="content"></span> </div> </div> </div> <!--teams and vagas--> <div class="row"> <div class="totalvagasteams"></div> </div> <div class="vagas99 row" id="vagas99"> </div> </div> <!-- /.col-md-9 --> </div> </div> <!-- /.container --> <script id="vagas99-template" type="text/html"> <div class="col-md-4 portfolio-item"> <div class="clearfix"></div> <a href="#"> <img class="img-responsive" src="http://placehold.it/700x400" alt=""> </a> <h3> <h4><a href="vaga.html?vagaid=<%= id %>"><%= _fid %> - <%= text %></a></h4> </h3> <h4><%= categories.team %></h4> <p><%= text %></p> </div> </script>
deigmaranderson/99carreiras
99carreiras/template-parts/integration.php
PHP
mit
2,732
<?php /* TwigBundle:Exception:traces.txt.twig */ class __TwigTemplate_39f631a2eb2e29d9f4069821c7f3afd5beaf2ed87b37023f3fdd2045c6e3f438 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 if (twig_length_filter($this->env, $this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array()))) { // line 2 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["exception"]) ? $context["exception"] : $this->getContext($context, "exception")), "trace", array())); foreach ($context['_seq'] as $context["_key"] => $context["trace"]) { // line 3 $this->env->loadTemplate("TwigBundle:Exception:trace.txt.twig")->display(array("trace" => $context["trace"])); // line 4 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } } public function getTemplateName() { return "TwigBundle:Exception:traces.txt.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 27 => 4, 25 => 3, 21 => 2, 19 => 1,); } }
spvernet/symfony_2
app/cache/dev/twig/39/f6/31a2eb2e29d9f4069821c7f3afd5beaf2ed87b37023f3fdd2045c6e3f438.php
PHP
mit
1,750
using Jobber.Core; using Jobber.Sample.Contract; namespace Jobber.Sample.JobProducer { class TodoJob : Job<Todo> { } }
GokGokalp/Jobber
Jobber.Sample.JobProducer/TodoJob.cs
C#
mit
134
function onInitSchema(schema, className) { schema.helpers = {}; }; export default onInitSchema;
jagi/meteor-astronomy
lib/modules/helpers/hooks/onInitSchema.js
JavaScript
mit
98
module Adman # Indicates this service is a web application WEB_APPLICATION = "_web_app" # Announces services on a network or other venue. class Campaign attr_reader :message attr_reader :venues # Create a new Campaign to advertize the given service. # # If the service given isn't already a Service (a String perhaps?) then the # Campaign will try to turn it into one. def initialize(service) # If this isn't yet a service try to turn it into one unless service.kind_of?(Service) service = Service.new(service) end @message = service @venues = [] end def add_venue(venue) @venues << venue self end # Start advertising this service def launch @venues.each do |venue| venue.register(message) end self end end # A Service which is announced by the announcer. # # A service is a general term and can be a web application, # mail server, or anything that can described in terms of a # service name, type, and port. class Service DEFAULT_PORT = 3000 DEFAULT_TYPE = "_web_app" include Comparable attr_reader :name attr_reader :port attr_reader :type # Compare this Service to another def <=>(other) if self.name < other.name return -1 elsif self.name > other.name return 1 elsif self.port < other.port return -1 elsif self.port > other.port return 1 elsif self.type < other.type return -1 elsif self.type > other.type return 1 else return 0 end end def initialize(service_name) @name = service_name # Set some defaults @port = 3000 @type = WEB_APPLICATION end end def self.announce(service_name) announcer = Announcer.new(service_name) announcer end end
MarkBennett/announcer
lib/announcer.rb
Ruby
mit
1,899
using System.Collections; using UnityEngine; [RequireComponent (typeof(Animator))] public class SpriteDestruction : MonoBehaviour { private SpriteBuilder m_spriteBuilder; private Animator m_animator; public float TimeToDestroy = 1; public int DestroySquarePixelSize = 10; public int DestroySquareCount = 5; void Awake () { m_animator = GetComponent<Animator> (); m_spriteBuilder = GetComponent<SpriteBuilder> (); } public IEnumerator DestroySprite () { m_animator.enabled = false; m_spriteBuilder.Build (); var rect = m_spriteBuilder.Sprite.rect; var minX = (int)rect.x; var maxX = (int)rect.xMax + 1 - DestroySquarePixelSize; var minY = (int)rect.y; var maxY = (int)rect.yMax + 1 - DestroySquarePixelSize; var interval = TimeToDestroy / DestroySquareCount; // Destroy any squares on Alien. for (int i = 0; i < DestroySquareCount; i++) { // Get random points to square. var beginX = Random.Range (minX, maxX); var endX = beginX + DestroySquarePixelSize; var beginY = Random.Range (minY, maxY); var endy = beginY + DestroySquarePixelSize; // Draw the square. for (var x = beginX; x <= endX; x++) { for (var y = beginY; y < endy; y++) { m_spriteBuilder.ClearColor (x, y); } } m_spriteBuilder.Rebuild (); yield return new WaitForSeconds (interval); } m_spriteBuilder.Build (); SendMessageUpwards ("OnSpriteDestructionEnd"); } }
skahal/SpaceInvadersRemake
src/SpaceInvadersRemake/Assets/Scripts/SpriteDestruction.cs
C#
mit
1,423
var angular = require('angular'); angular.module('rsInfiniteScrollDemo', [require('rs-infinite-scroll').default]) /*@ngInject*/ .controller('RsDemoController', ['$q', '$timeout', function($q, $timeout) { var ctrl = this; ctrl.scrollProxy = { loadPrevious, loadFollowing }; ctrl.dummyList = []; let init = function() { $timeout(function() { ctrl.dummyList = [ {index: 1}, {index: 2}, {index: 3}, {index: 4}, {index: 5}, {index: 6}, {index: 7}, {index: 8}, {index: 9}, {index: 10} ]; loadFollowing(); }, 5000); }; init(); function loadPrevious() { let first = ctrl.dummyList[0]; return addBefore(first); } function loadFollowing() { let last = ctrl.dummyList[ctrl.dummyList.length-1]; // should be safe after initialization if (!last) { var deferred = $q.defer(); deferred.resolve(); return deferred.promise; } return addAfter(last); } function addAfter(last) { var deferred = $q.defer(); deferred.resolve(); $timeout(() => { if (last.index > 1000) { deferred.resolve(); return; } for (let i = last.index+1; i < last.index+10; i++) { ctrl.dummyList.push({index: i}); } deferred.resolve(); }, 200); return deferred.promise; } function addBefore(first) { var deferred = $q.defer(); deferred.resolve(); $timeout(() => { if (first.index < -1000) { deferred.resolve(); return; } for (let i = first.index-1; i > first.index-10; i--) { ctrl.dummyList.unshift({index: i}); } deferred.resolve(); }, 200); return deferred.promise; } }]);
RetroSquareGroup/rs-infinite-scroll
demo/demo.js
JavaScript
mit
1,907
<?php /* * This file is part of the json-schema bundle. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace HadesArchitect\JsonSchemaBundle\Exception; use HadesArchitect\JsonSchemaBundle\Error\Error; class ViolationException extends JsonSchemaException { /** * @var Error[] */ protected $errors = array(); /** * @param Error[] $errors */ public function __construct(array $errors) { $message = ''; foreach ($errors as $error) { $message .= (string) $error . '. '; $this->addError($error); } parent::__construct(rtrim($message)); } public function addError(Error $error) { $this->errors[] = $error; } public function getErrors() { return $this->errors; } }
HadesArchitect/JsonSchemaBundle
Exception/ViolationException.php
PHP
mit
898
/*************************************** ** Tsunagari Tile Engine ** ** window.cpp ** ** Copyright 2011-2014 PariahSoft LLC ** ***************************************/ // ********** // 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. // ********** #include <stdlib.h> #include "window.h" #include "world.h" GameWindow::GameWindow() : keysDown(KB_SIZE) { } GameWindow::~GameWindow() { } void GameWindow::emitKeyDown(KeyboardKey key) { keysDown[key]++; if (keysDown[KBEscape] && (keysDown[KBLeftShift] || keysDown[KBRightShift])) { exit(0); } if (keysDown[key]) World::instance().buttonDown(key); } void GameWindow::emitKeyUp(KeyboardKey key) { keysDown[key]--; if (!keysDown[key]) World::instance().buttonUp(key); } bool GameWindow::isKeyDown(KeyboardKey key) { return keysDown[key] != false; } BitRecord GameWindow::getKeysDown() { return keysDown; }
pariahsoft/TsunagariC
src/window.cpp
C++
mit
1,938
class MagicDictionary { public: map<int, vector<string>> m; /** Initialize your data structure here. */ MagicDictionary() { } /** Build a dictionary through a list of words */ void buildDict(vector<string> dict) { for (auto &i : dict) { m[i.length()].push_back(i); } } /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */ bool search(string word) { int len = word.length(); for (auto &i : m[len]) { int count = 0; for (int k = 0; k < len; k++) { if (i[k] == word[k]) { count++; } } if (count + 1 == len) { return true; } } return false; } }; /** * Your MagicDictionary object will be instantiated and called as such: * MagicDictionary obj = new MagicDictionary(); * obj.buildDict(dict); * bool param_2 = obj.search(word); */
MegaShow/college-programming
OJ/LeetCode/676 Implement Magic Dictionary.cpp
C++
mit
1,046
<?php return array ( 'id' => 'zte_z750c_ver1', 'fallback' => 'generic_android_ver4_1', 'capabilities' => array ( 'model_name' => 'Z750C', 'brand_name' => 'ZTE', 'marketing_name' => 'Savvy', 'physical_screen_height' => '88', 'physical_screen_width' => '53', 'resolution_width' => '480', 'resolution_height' => '800', ), );
cuckata23/wurfl-data
data/zte_z750c_ver1.php
PHP
mit
361
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. */ package com.microsoft.o365_android_onenote_rest; import com.microsoft.AzureADModule; import com.microsoft.AzureAppCompatActivity; import com.microsoft.live.LiveAuthClient; import com.microsoft.o365_android_onenote_rest.application.SnippetApp; import com.microsoft.o365_android_onenote_rest.conf.ServiceConstants; import com.microsoft.o365_android_onenote_rest.inject.AzureModule; import com.microsoft.o365_android_onenote_rest.inject.ObjectGraphInjector; import com.microsoft.o365_android_onenote_rest.model.Scope; import java.util.ArrayList; import javax.inject.Inject; import dagger.ObjectGraph; import timber.log.Timber; public abstract class BaseActivity extends AzureAppCompatActivity implements ObjectGraphInjector { @Inject protected LiveAuthClient mLiveAuthClient; public static final Iterable<String> sSCOPES = new ArrayList<String>() {{ for (Scope.wl scope : Scope.wl.values()) { Timber.i("Adding scope: " + scope); add(scope.getScope()); } for (Scope.office scope : Scope.office.values()) { Timber.i("Adding scope: " + scope); add(scope.getScope()); } }}; @Override protected AzureADModule getAzureADModule() { AzureADModule.Builder builder = new AzureADModule.Builder(this); builder.validateAuthority(true) .skipBroker(true) .authenticationResourceId(ServiceConstants.AUTHENTICATION_RESOURCE_ID) .authorityUrl(ServiceConstants.AUTHORITY_URL) .redirectUri(ServiceConstants.REDIRECT_URI) .clientId(ServiceConstants.CLIENT_ID); return builder.build(); } @Override protected Object[] getModules() { return new Object[]{new AzureModule()}; } @Override protected ObjectGraph getRootGraph() { return SnippetApp.getApp().mObjectGraph; } @Override public void inject(Object target) { mObjectGraph.inject(target); } } // ********************************************************* // // Android-REST-API-Explorer, https://github.com/OneNoteDev/Android-REST-API-Explorer // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // *********************************************************
OneNoteDev/Android-REST-API-Explorer
app/src/main/java/com/microsoft/o365_android_onenote_rest/BaseActivity.java
Java
mit
3,525
<?php namespace Domora\TvGuide\Data; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use JMS\Serializer\Annotation as Serializer; /** * @ORM\Entity * @ORM\Table(name="service") */ class Service { /** * @ORM\Id * @ORM\Column(type="string") * @Serializer\Groups({"list", "service"}) */ private $id; /** * @ORM\Column(type="string") * @Serializer\Groups({"list", "service"}) */ private $name; /** * @ORM\Column(type="string") * @Serializer\Groups({"list", "service"}) */ private $country; /** * @ORM\OneToMany(targetEntity="ServiceChannelAssociation", mappedBy="service") * @Serializer\Type("array<Domora\TvGuide\Data\ServiceChannelAssociation>") * @Serializer\Groups({"service"}) */ private $channels; public function __construct() { $this->channels = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set id * * @param string id * @return Channel */ public function setId($id) { $this->id = $id; return $this; } /** * Set name * * @param string $name * @return Channel */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set country * * @param string $country * @return Channel */ public function setCountry($country) { $this->country = $country; return $this; } /** * Get country * * @return string */ public function getCountry() { return $this->country; } /** * Add channels * * @param \Domora\TvGuide\Data\ServiceChannelAssociation $channels * * @return Service */ public function addChannel(\Domora\TvGuide\Data\ServiceChannelAssociation $channels) { $this->channels[] = $channels; return $this; } /** * Remove channels * * @param \Domora\TvGuide\Data\ServiceChannelAssociation $channels */ public function removeChannel(\Domora\TvGuide\Data\ServiceChannelAssociation $channels) { $this->channels->removeElement($channels); } /** * Get channels * * @return \Doctrine\Common\Collections\Collection */ public function getChannels() { return $this->channels; } }
domora/tvguide
src/Domora/TvGuide/Data/Service.php
PHP
mit
2,698
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("NotificationSenderUtility")] [assembly: AssemblyDescription("Class Library to communicate with the Push Notification Service")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corp.")] [assembly: AssemblyProduct("Using Push Notifications Hands-on Lab")] [assembly: AssemblyCopyright("Copyright © Microsoft 2010")] [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("4cb73b37-8cd0-456a-8c69-ea3e6622582b")] // 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")]
DDReaper/XNAGameStudio
Samples/PushRecipe_WP7_SL/Source/WindowsPhone.Recipes.Push.Messasges/Properties/AssemblyInfo.cs
C#
mit
1,525
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { reddit: { userAgent: 'USER_AGENT', clientId: 'CLIENT ID', clientSecret: 'CLIENT SECRET', username: 'BOT USERNAME', password: 'BOT PASSWORD' }, mods: ['MODERATOR_1', 'MODERATOR_2'] };
cmhoc/fuckmwbot
dist/config.js
JavaScript
mit
308
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Powder_Plastic_Coat_Model extends CI_Model { private $powder_plastic_coatTable = 'powder_plastic_coat'; private $powder_plastic_coatColumn = 'powder_plastic_coat_id'; public function __construct() { parent::__construct(); } public function form_input_attributes($data, $id) { if(isset($id) && !empty($id)) { $data_split = explode('_', $data); $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach ($query->result() as $row) { $value = $row->$data; } if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } else { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } } else { $data_split = explode('_', $data); if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3]).' here' ); } else { $attributes = array( 'name' => $data_split[3], 'id' => $data_split[3], 'type' => 'text', 'class' => 'form-control input-md', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3]).' here' ); } } return $attributes; } public function form_textarea_attributes($data, $id) { if(isset($id) && !empty($id)) { $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach ($query->result() as $row) { $value = $row->$data; } $attributes = array( 'name' => $data, 'id' => $data, 'rows' => '5', 'value' => $value, 'class' => 'auto-size form-control', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } else { $attributes = array( 'name' => $data, 'id' => $data, 'rows' => '5', 'class' => 'auto-size form-control', 'placeholder' => 'insert '.str_replace('_', ' ', $data).' here' ); } return $attributes; } public function form_input_numeric_attributes($data, $id) { if(isset($id) && !empty($id)) { $data_split = explode('_', $data); $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach ($query->result() as $row) { $value = $row->$data; } if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } else { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'value' => $value, 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } } else { $data_split = explode('_', $data); if(count($data_split) > 2) { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } else { $attributes = array( 'name' => $data_split[3].'_'.$data_split[4], 'id' => $data_split[3].'_'.$data_split[4], 'type' => 'text', 'class' => 'form-control input-md numeric', 'placeholder' => 'insert '.str_replace('_', ' ', $data_split[3].' '.$data_split[4]).' here' ); } } return $attributes; } public function find($id) { $this->db->select('*'); $this->db->from('powder_plastic_coat as dep'); $this->db->join('created as cre','dep.powder_plastic_coat_id = cre.created_table_id'); $this->db->where('cre.created_table','powder_plastic_coat'); $this->db->where('dep.powder_plastic_coat_id', $id); $query = $this->db->get(); foreach ($query->result() as $row) { $arr[] = array( 'powder_plastic_coat_id' => $row->powder_plastic_coat_id, 'powder_plastic_coat_code' => $row->powder_plastic_coat_code, 'derpartment_name' => $row->powder_plastic_coat_name, 'powder_plastic_coat_description' => $row->powder_plastic_coat_description ); } return $arr; } public function insert($data) { $this->db->insert($this->powder_plastic_coatTable, $data); return $this->db->insert_id(); } public function modify($data, $id) { $this->db->where($this->powder_plastic_coatColumn, $id); $this->db->update($this->powder_plastic_coatTable, $data); return true; } public function get_all_powder_plastic_coat($start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function get_alls_powder_plastic_coat() { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function like_powder_plastic_coat($wildcard='', $start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function likes_powder_plastic_coat($wildcard='') { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 1); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function get_all_archived_powder_plastic_coat($start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as dep'); $this->db->join('status as stat','dep.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->order_by('dep.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function get_alls_archived_powder_plastic_coat() { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as dep'); $this->db->join('status as stat','dep.powder_plastic_coat_id = stat.status_table_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->order_by('dep.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function like_archived_powder_plastic_coat($wildcard='', $start_from=0, $limit=0) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->limit( $limit, $start_from )->get(); return $query; } public function likes_archived_powder_plastic_coat($wildcard='') { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable.' as pow'); $this->db->join('status as stat','pow.powder_plastic_coat_id = stat.status_table_id'); $this->db->join('unit_of_measurement as uom','pow.unit_of_measurement_id = uom.unit_of_measurement_id'); $this->db->where('stat.status_table', $this->powder_plastic_coatTable); $this->db->where('stat.status_code', 0); $this->db->group_start(); $this->db->or_where('pow.powder_plastic_coat_id LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_code LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_name LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_description LIKE', '%' . $wildcard . '%'); $this->db->or_where('pow.powder_plastic_coat_weighted_ave LIKE', '%' . $wildcard . '%'); $this->db->or_where('uom.unit_of_measurement_name LIKE', '%' . $wildcard . '%'); $this->db->group_end(); $this->db->order_by('pow.'.$this->powder_plastic_coatColumn, 'DESC'); $query = $this->db->get(); return $query; } public function get_powder_plastic_coat_name_by_id($id) { $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get($this->powder_plastic_coatTable); foreach($query->result() as $row) { $id = $row->powder_plastic_coat_name; } return $id; } public function form_select_attributes($data) { $attributes = array( 'name' => $data, 'id' => $data, 'class' => 'selectpicker', 'data-live-search' => 'true' ); return $attributes; } public function form_select_options($data) { $query = $this->db->get($this->powder_plastic_coatTable); $arr[] = array( '0' => 'select '.str_replace('_', ' ', $data).' here', ); foreach ($query->result() as $row) { $arr[] = array( $row->powder_plastic_coat_id => $row->powder_plastic_coat_name ); } $array = array(); foreach($arr as $arrs) foreach($arrs as $key => $val) $array[$key] = $val; return $array; } public function form_selected_options($id) { $this->db->select('*'); $this->db->from($this->powder_plastic_coatTable); $this->db->where($this->powder_plastic_coatColumn, $id); $query = $this->db->get(); if($query->num_rows() > 0) { foreach ($query->result() as $row) { $id = $row->powder_plastic_coat_id; } return $id; } else { return $id = '0'; } } }
aliudin-ftc/just-in-time-version-2
application/models/Powder_Plastic_Coat_Model.php
PHP
mit
16,688
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Ci::Pipeline::Seed::Environment do let_it_be(:project) { create(:project) } let(:job) { build(:ci_build, project: project) } let(:seed) { described_class.new(job) } let(:attributes) { {} } before do job.assign_attributes(**attributes) end describe '#to_resource' do subject { seed.to_resource } context 'when job has environment attribute' do let(:attributes) do { environment: 'production', options: { environment: { name: 'production' } } } end it 'returns a persisted environment object' do expect(subject).to be_a(Environment) expect(subject).to be_persisted expect(subject.project).to eq(project) expect(subject.name).to eq('production') end context 'when environment has already existed' do let!(:environment) { create(:environment, project: project, name: 'production') } it 'returns the existing environment object' do expect(subject).to be_persisted expect(subject).to eq(environment) end end end end end
stoplightio/gitlabhq
spec/lib/gitlab/ci/pipeline/seed/environment_spec.rb
Ruby
mit
1,171
using Naxis.Core.Components; namespace Naxis.Core.Security { public class AuthedUser { /// <summary> /// 授权服务 /// </summary> private static readonly IAuthenticationService Service = ObjectContainer.Resolve<IAuthenticationService>(); /// <summary> /// 获取当前用户信息 /// </summary> public static AuthUser Current { get { return Service.GetAuthenticatedUser(); } } } }
swpudp/Naxis
Naxis.Common/Security/AuthedUser.cs
C#
mit
494
<?php $pageTitle = "News Feed"; require('includes/header.php'); $my_friends=$mysqli->query("SELECT friendArray FROM profile WHERE userID=$userID"); $myfriends=mysqli_fetch_row($my_friends); $myfriends=implode("",$myfriends); $my_friends_array=explode(",",$myfriends); //echo $my_friends_array; ?> <link href="css/4Inst.css" rel="stylesheet"> <div class="container"> <h3>News Feed</h3> <div class="SetCenterImage"> <?php $query_image = $mysqli->query("SELECT * FROM PhotoUpload WHERE circleShared='' ORDER BY datestamp DESC"); while($query_image_row=mysqli_fetch_array($query_image)){ $photoUserID = $query_image_row['userID']; $photoTime=$query_image_row['datestamp']; if(in_array($photoUserID,$my_friends_array)){ $photoURL = $query_image_row['photo']; $photoID = $query_image_row['photoID']; //get photo uploader name $getuserNames = $mysqli->query("SELECT firstname, lastname FROM Profile WHERE userID=$photoUserID"); $getuserNamesrow = mysqli_fetch_array($getuserNames); $photoUserFname = $getuserNamesrow['firstname']; $photoUserLname = $getuserNamesrow['lastname']; echo '<div class="col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-body"> <a href="photoInfo.php?photoid='.$photoID.'"class="thumbnail"> <img src="'.$photoURL.'"> </a> </div> <div class="panel-footer"> <h4>'.$photoUserFname.' '.$photoUserLname.' <small>on '.$photoTime.'</small></h4> </div> </div> </div>'; } else { } } ?> </div> </div> <?php require('includes/footer.php');?>
mgander/4inst
home.php
PHP
mit
1,563
using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Security.Cryptography; namespace Radical.Windows.Bootstrap { //courtesy of NServiceBus https://github.com/Particular/NServiceBus/blob/4954af83fad81cc80769c8ed161ee4a37812d443/src/NServiceBus.Core/Hosting/Helpers/AssemblyValidator.cs class AssemblyValidator { public static void ValidateAssemblyFile(string assemblyPath, out bool shouldLoad, out string reason) { using (var stream = File.OpenRead(assemblyPath)) using (var file = new PEReader(stream)) { var hasMetadata = false; try { hasMetadata = file.HasMetadata; } catch (BadImageFormatException) { } if (!hasMetadata) { shouldLoad = false; reason = "File is not a .NET assembly."; return; } var reader = file.GetMetadataReader(); var assemblyDefinition = reader.GetAssemblyDefinition(); if (!assemblyDefinition.PublicKey.IsNil) { var publicKey = reader.GetBlobBytes(assemblyDefinition.PublicKey); var publicKeyToken = GetPublicKeyToken(publicKey); if (IsRuntimeAssembly(publicKeyToken)) { shouldLoad = false; reason = "File is a .NET runtime assembly."; return; } } shouldLoad = true; reason = "File is a .NET assembly."; } } static byte[] GetPublicKeyToken(byte[] publicKey) { using (var sha1 = SHA1.Create()) { var hash = sha1.ComputeHash(publicKey); var publicKeyToken = new byte[8]; for (var i = 0; i < 8; i++) { publicKeyToken[i] = hash[hash.Length - (i + 1)]; } return publicKeyToken; } } public static bool IsRuntimeAssembly(byte[] publicKeyToken) { var tokenString = BitConverter.ToString(publicKeyToken).Replace("-", string.Empty).ToLowerInvariant(); //Compare token to known Microsoft tokens switch (tokenString) { case "b77a5c561934e089": case "7cec85d7bea7798e": case "b03f5f7f11d50a3a": case "31bf3856ad364e35": case "cc7b13ffcd2ddd51": case "adb9793829ddae60": return true; default: return false; } } } }
RadicalFx/Radical.Windows
src/Radical.Windows/Bootstrap/AssemblyValidator.cs
C#
mit
2,902
var amqp=require("amqplib"); amqp.connect('amqp://localhost').then(function(connection){ return connection.createChannel().then(function(ch){ var ex="logs"; ch.assertExchange(ex,'fanout',{durable:true}); var ok=ch.assertQueue('',{exclusive:true}) .then(function(q){ console.log("[x]Waiting for message in '%s' ",q.queue); return ch.bindQueue(q.queue,ex,''); }).then(function(q){ return ch.consume(q.queue,function(msg){ console.log("[x]Receiving message:'%s'",msg.content.toString()); },{noAck:true}); }); }) }).then(null,console.warn);
zhangmingkai4315/RabbitMQ-Nodejs
pub_sub/receive_logs.js
JavaScript
mit
569
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // NovaCoin: check prefix if(uri.scheme() != QString("testfaucetcoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert testfaucetcoin:// to testfaucetcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("testfaucetcoin://")) { uri.replace(0, 12, "testfaucetcoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "<qt/>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "testfaucetcoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "testfaucetcoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=testfaucetcoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("testfaucetcoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " testfaucetcoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("testfaucetcoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
testfaucetcoin/testfaucetcoin
src/qt/guiutil.cpp
C++
mit
13,417
<?php namespace Tests\App; use App\VCS\Git; use App\VCS\Tagged; use Illuminate\Filesystem\Filesystem; use Mockery; use App\VCS\Repository; use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Process; class GitTest extends \TestCase { /** @var Mockery\MockInterface */ protected $repository; /** @var Mockery\MockInterface */ protected $filesystem; /** @var Mockery\MockInterface */ protected $version; /** @var Git */ protected $git; public function setUp() { parent::setUp(); $this->repository = Mockery::mock(Repository::class); $this->filesystem = Mockery::mock(Filesystem::class); $this->version = Mockery::mock(Tagged::class)->shouldIgnoreMissing(); $this->git = new Git($this->filesystem); } /** * @test */ public function canCloneRepository() { $path = uniqid(); $this->git = Mockery::mock(Git::class.'[temporaryPath]', [$this->filesystem]); $this->git->shouldAllowMockingProtectedMethods(); $this->git->shouldReceive('temporaryPath')->andReturn($path); $this->repository->shouldReceive('path')->andReturn($path); $this->repository->shouldReceive('setPath')->with($path)->once(); $this->repository->shouldReceive('sshUrl')->andReturn(uniqid()); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[setWorkingDirectory,run,isSuccessful]', ['']); $process->shouldReceive('setWorkingDirectory')->with($path)->once(); $process->shouldReceive('run')->once(); $process->shouldReceive('isSuccessful')->andReturnTrue(); app()->instance(Process::class, $process); $this->assertEquals($this->repository, $this->git->clone($this->repository, $this->version)); } /** * @test */ public function cloneRepositoryComplainsWhenFails() { $this->expectException(ProcessFailedException::class); $this->filesystem->shouldReceive('makeDirectory')->once(); $this->repository->shouldIgnoreMissing(); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[isSuccessful]', ['']); $process->shouldReceive('isSuccessful')->andReturnFalse(); $process->shouldIgnoreMissing(); app()->instance(Process::class, $process); $this->assertEquals($this->repository, $this->git->clone($this->repository, $this->version)); } /** * @test */ public function canCheckoutTag() { $path = uniqid(); $this->repository->shouldReceive('path')->andReturn($path); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[setWorkingDirectory,run,isSuccessful]', ['']); $process->shouldReceive('setWorkingDirectory')->with($path)->once(); $process->shouldReceive('run')->once(); $process->shouldReceive('isSuccessful')->andReturnTrue(); app()->instance(Process::class, $process); $this->assertTrue($this->git->checkoutTag($this->repository, $this->version)); } /** * @test */ public function checkoutTagComplainsWhenFails() { $this->expectException(ProcessFailedException::class); $this->repository->shouldIgnoreMissing(); // passing an empty string in place of a "command" that's normally passed $process = Mockery::mock(Process::class.'[isSuccessful]', ['']); $process->shouldReceive('isSuccessful')->andReturnFalse(); $process->shouldIgnoreMissing(); app()->instance(Process::class, $process); $this->assertTrue($this->git->checkoutTag($this->repository, $this->version)); } }
realpage/asset-publisher
tests/unit/VCS/GitTest.php
PHP
mit
3,894
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Topics.Radical.Model { /// <summary> /// Applied to properties asks that models skip this property when notifying property changes. /// </summary> [AttributeUsage( AttributeTargets.Property )] public sealed class SkipPropertyValidationAttribute : Attribute { } }
micdenny/radical
src/net35/Radical/Model/SkipPropertyValidationAttribute.cs
C#
mit
392
/* * SonarLint for Visual Studio * Copyright (C) 2016-2021 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Collections.Generic; using System.IO.Abstractions.TestingHelpers; using System.Linq; using FluentAssertions; using Microsoft.VisualStudio.CodeAnalysis.RuleSets; namespace SonarLint.VisualStudio.Integration.UnitTests { internal class ConfigurableRuleSetSerializer : IRuleSetSerializer { private readonly Dictionary<string, RuleSet> savedRuleSets = new Dictionary<string, RuleSet>(StringComparer.OrdinalIgnoreCase); private readonly MockFileSystem fileSystem; private readonly Dictionary<string, int> ruleSetLoaded = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); public ConfigurableRuleSetSerializer(MockFileSystem fileSystem) { this.fileSystem = fileSystem; } #region IRuleSetFileSystem RuleSet IRuleSetSerializer.LoadRuleSet(string path) { this.savedRuleSets.TryGetValue(path, out RuleSet rs); this.ruleSetLoaded.TryGetValue(path, out int counter); this.ruleSetLoaded[path] = ++counter; rs?.Validate(); return rs; } void IRuleSetSerializer.WriteRuleSetFile(RuleSet ruleSet, string path) { if (!this.savedRuleSets.TryGetValue(path, out _)) { this.savedRuleSets[path] = ruleSet; } this.fileSystem.AddFile(path, new MockFileData("")); } #endregion IRuleSetFileSystem #region Test Helpers public IEnumerable<string> RegisteredRuleSets { get { return this.savedRuleSets.Keys; } } public void RegisterRuleSet(RuleSet ruleSet) { this.RegisterRuleSet(ruleSet, ruleSet.FilePath); } public void RegisterRuleSet(RuleSet ruleSet, string path) { this.savedRuleSets[path] = ruleSet; this.fileSystem.AddFile(path, new MockFileData("")); } public void ClearRuleSets() { foreach (var filePath in fileSystem.AllFiles) { fileSystem.RemoveFile(filePath); } savedRuleSets.Clear(); } public void AssertRuleSetExists(string path) { fileSystem.GetFile(path).Should().NotBe(null); } public void AssertRuleSetNotExists(string path) { fileSystem.GetFile(path).Should().Be(null); } public void AssertRuleSetsAreEqual(string ruleSetPath, RuleSet expectedRuleSet) { this.AssertRuleSetExists(ruleSetPath); RuleSet actualRuleSet = this.savedRuleSets[ruleSetPath]; actualRuleSet.Should().NotBeNull("Expected rule set to be written"); RuleSetAssert.AreEqual(expectedRuleSet, actualRuleSet); } public void AssertRuleSetsAreSame(string ruleSetPath, RuleSet expectedRuleSet) { this.AssertRuleSetExists(ruleSetPath); RuleSet actualRuleSet = this.savedRuleSets[ruleSetPath]; actualRuleSet.Should().Be(expectedRuleSet); } public void AssertRuleSetLoaded(string ruleSet, int expectedNumberOfTimes) { this.ruleSetLoaded.TryGetValue(ruleSet, out int actual); actual.Should().Be(expectedNumberOfTimes, "RuleSet {0} was loaded unexpected number of times", ruleSet); } #endregion Test Helpers } }
SonarSource-VisualStudio/sonarlint-visualstudio
src/TestInfrastructure/Framework/ConfigurableRuleSetSerializer.cs
C#
mit
4,356
<?php class updatePitchDeck_m extends CI_Model{ function __construct(){ parent::__construct(); } function updateIdeaGen($data){ $sql = "update idea_genboard set problem = ? , people = ? , behavior = ? , solution = ? where idea_id = ?"; $query = $this->db->query($sql,array($data['problem'],$data['people'],$data['behavior'],$data['solution'],$data['idea_id'])); if($query){ $sql1 = "select * from ungen_pitchdeck where idea_id = ? "; $query1 = $this->db->query($sql1,array($data['idea_id'])); if($query1->num_rows()>0){ $row = $query1->row(); $session = array( 'ungen_id'=>$row->ungen_id ); $this->session->set_userdata($session); return true; } } } function updateBMC($data){ $sql = "update bmc set cust_segment = ? , cust_relationship = ? , channels = ? , value_proposition = ? , key_activities = ? , key_sources = ? , key_partners = ? , cost_structures = ? , revenue_streams = ? where bmc_id = ? "; $query = $this->db->query($sql,array($data['segment'],$data['relationship'],$data['channels'],$data['proposition'],$data['activities'],$data['resources'],$data['partners'],$data['structure'],$data['streams'],$data['bmc_id'])); if($query){ $session = array( 'bmcid'=>$data['bmc_id'] ); $this->session->set_tempdata($session); return true; } } function updateValueProp($data){ $sql = "update value_prop set wants = ? , needs = ? , fears = ? , benefits = ? , experience = ? , features = ? , company = ? , product = ? , ideal_cust = ? , substitutes = ? where valueprop_id = ? "; $query = $this->db->query($sql,array($data['wants'],$data['needs'],$data['fears'],$data['benefits'],$data['experience'],$data['features'],$data['company'],$data['product'],$data['ideal_cust'],$data['substitutes'],$data['valueprop_id'])); if($query){ $sql1 = "select * from ungen_pitchdeck where valueprop_id = ? "; $query1 = $this->db->query($sql1,array($data['valueprop_id'])); if($query1->num_rows()>0){ $row = $query1->row(); $session = array( 'ungen_id'=>$row->ungen_id ); $this->session->set_userdata($session); return true; } } } function updateValidationBoard($data){ $sql = "update validation_board set stage= ? , customer = ? , problem = ? , solution = ? , risk_assumpt = ? , solution_criteria = ? , results = ? , learnings = ? , customer2 = ? , problem2 = ? , solution2 = ? , risk_assumpt2 = ? , solution_criteria2 = ? , results2 = ? , learnings2 = ? , customer3 = ? , problem3 = ? , solution3 = ? , risk_assumpt3 = ? , solution_criteria3 = ? , results3 = ? , learnings3 = ? where valid_id = ?"; $query = $this->db->query($sql,array($data['stage'],$data['customer'],$data['problem'],$data['solution'],$data['risk_assumpt'],$data['solution_criteria'],$data['results'],$data['learnings'],$data['customer2'],$data['problem2'],$data['solution2'],$data['risk_assumpt2'],$data['solution_criteria2'],$data['results2'],$data['learnings2'],$data['customer3'],$data['problem3'],$data['solution3'],$data['risk_assumpt3'],$data['solution_criteria3'],$data['results3'],$data['learnings3'],$data['valid_id'])); if($query){ $sql1 = "select * from ungen_pitchdeck where valid_id = ? "; $query1 = $this->db->query($sql1,array($data['valid_id'])); if($query1->num_rows()>0){ $row = $query1->row(); $session = array( 'ungen_id'=>$row->ungen_id ); $this->session->set_userdata($session); return true; } } } } ?>
jLKisni/PitchItUp
application/modules/Web/models/updatePitchDeck_m.php
PHP
mit
3,710
#ifndef M3D_RANDOM_UTILS_H #define M3D_RANDOM_UTILS_H #include <stdlib.h> #include <math.h> namespace m3D { namespace utils { float ranf() { return ((float) rand()) / ((float) RAND_MAX); } float box_muller(float m, float s) { float x1, x2, w, y1; static float y2; static int use_last = 0; static int initialized_rand = 0; if (!initialized_rand) { #if BSD srandomdev(); #endif initialized_rand = 1; } if (use_last) /* use value from previous call */ { y1 = y2; use_last = 0; } else { do { x1 = 2.0 * ranf() - 1.0; x2 = 2.0 * ranf() - 1.0; w = x1 * x1 + x2 * x2; } while (w >= 1.0); w = sqrt((-2.0 * log(w)) / w); y1 = x1 * w; y2 = x2 * w; use_last = 1; } return ( m + y1 * s); } } } #endif
meteo-ubonn/meanie3D
src/utils/rand_utils.cpp
C++
mit
1,159
package co.navdeep.popmovies.tmdb.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Genre { @SerializedName("id") @Expose private Integer id; @SerializedName("name") @Expose private String name; /** * * @return * The id */ public Integer getId() { return id; } /** * * @param id * The id */ public void setId(Integer id) { this.id = id; } /** * * @return * The name */ public String getName() { return name; } /** * * @param name * The name */ public void setName(String name) { this.name = name; } }
navdeepsekhon/PopMovies
app/src/main/java/co/navdeep/popmovies/tmdb/model/Genre.java
Java
mit
778
#include <cstring> #include <occa/types/bits.hpp> #include <occa/types/primitive.hpp> #include <occa/internal/io.hpp> #include <occa/internal/utils/lex.hpp> #include <occa/internal/utils/string.hpp> namespace occa { primitive::primitive(const char *c) { *this = load(c); } primitive::primitive(const std::string &s) { const char *c = s.c_str(); *this = load(c); } primitive primitive::load(const char *&c, const bool includeSign) { bool loadedFormattedValue = false; bool unsigned_ = false; bool negative = false; bool decimal = false; bool float_ = false; int longs = 0; int digits = 0; const char *c0 = c; primitive p; const int cLength = strlen(c); if(cLength >= 4){ if (strncmp(c, "true", 4) == 0) { p = true; p.source = "true"; c += 4; return p; } } if(cLength >= 5){ if (strncmp(c, "false", 5) == 0) { p = false; p.source = "false"; c += 5; return p; } } if ((*c == '+') || (*c == '-')) { if (!includeSign) { return primitive(); } negative = (*c == '-'); ++c; lex::skipWhitespace(c); } if (*c == '0') { ++digits; ++c; const char C = uppercase(*c); if ((C == 'B') || (C == 'X')) { loadedFormattedValue = true; if (C == 'B') { p = primitive::loadBinary(++c, negative); } else if (C == 'X') { p = primitive::loadHex(++c, negative); } if (p.type & primitiveType::none) { c = c0; return primitive(); } } else { --c; } } if (!loadedFormattedValue) { while (true) { if (('0' <= *c) && (*c <= '9')) { ++digits; } else if (*c == '.') { decimal = true; } else { break; } ++c; } } if (!loadedFormattedValue && !digits) { c = c0; p.source = std::string(c0, c - c0); return p; } while(*c != '\0') { const char C = uppercase(*c); if (C == 'L') { ++longs; ++c; } else if (C == 'U') { unsigned_ = true; ++c; } else if (!loadedFormattedValue) { if (C == 'E') { primitive exp = primitive::load(++c); // Check if there was an 'F' in exp decimal = true; float_ = (exp.type & primitiveType::isFloat); break; } else if (C == 'F') { float_ = true; ++c; } else { break; } } else { break; } } if (loadedFormattedValue) { // Hex and binary only handle U, L, and LL if (longs == 0) { if (unsigned_) { p = p.to<uint32_t>(); } else { p = p.to<int32_t>(); } } else if (longs >= 1) { if (unsigned_) { p = p.to<uint64_t>(); } else { p = p.to<int64_t>(); } } } else { // Handle the multiple other formats with normal digits if (decimal || float_) { if (float_) { p = (float) occa::parseFloat(std::string(c0, c - c0)); } else { p = (double) occa::parseDouble(std::string(c0, c - c0)); } } else { uint64_t value_ = parseInt(std::string(c0, c - c0)); if (longs == 0) { if (unsigned_) { p = (uint32_t) value_; } else { p = (int32_t) value_; } } else if (longs >= 1) { if (unsigned_) { p = (uint64_t) value_; } else { p = (int64_t) value_; } } } } p.source = std::string(c0, c - c0); return p; } primitive primitive::load(const std::string &s, const bool includeSign) { const char *c = s.c_str(); return load(c, includeSign); } primitive primitive::loadBinary(const char *&c, const bool isNegative) { const char *c0 = c; uint64_t value_ = 0; while (*c == '0' || *c == '1') { value_ = (value_ << 1) | (*c - '0'); ++c; } if (c == c0) { return primitive(); } const int bits = c - c0 + isNegative; if (bits < 8) { return isNegative ? primitive((int8_t) -value_) : primitive((uint8_t) value_); } else if (bits < 16) { return isNegative ? primitive((int16_t) -value_) : primitive((uint16_t) value_); } else if (bits < 32) { return isNegative ? primitive((int32_t) -value_) : primitive((uint32_t) value_); } else { return isNegative ? primitive((int64_t) -value_) : primitive((uint64_t) value_); } } primitive primitive::loadHex(const char *&c, const bool isNegative) { const char *c0 = c; uint64_t value_ = 0; while (true) { const char C = uppercase(*c); if (('0' <= C) && (C <= '9')) { value_ = (value_ << 4) | (C - '0'); } else if (('A' <= C) && (C <= 'F')) { value_ = (value_ << 4) | (10 + C - 'A'); } else { break; } ++c; } if (c == c0) { return primitive(); } const int bits = 4*(c - c0) + isNegative; if (bits < 8) { return isNegative ? primitive((int8_t) -value_) : primitive((uint8_t) value_); } else if (bits < 16) { return isNegative ? primitive((int16_t) -value_) : primitive((uint16_t) value_); } else if (bits < 32) { return isNegative ? primitive((int32_t) -value_) : primitive((uint32_t) value_); } else { return isNegative ? primitive((int64_t) -value_) : primitive((uint64_t) value_); } } std::string primitive::toString() const { if (source.size()) { return source; } std::string str; switch (type) { case primitiveType::bool_ : str = (value.bool_ ? "true" : "false"); break; case primitiveType::uint8_ : str = occa::toString((uint64_t) value.uint8_); break; case primitiveType::uint16_ : str = occa::toString((uint64_t) value.uint16_); break; case primitiveType::uint32_ : str = occa::toString((uint64_t) value.uint32_); break; case primitiveType::uint64_ : str = occa::toString((uint64_t) value.uint64_); break; case primitiveType::int8_ : str = occa::toString((int64_t) value.int8_); break; case primitiveType::int16_ : str = occa::toString((int64_t) value.int16_); break; case primitiveType::int32_ : str = occa::toString((int64_t) value.int32_); break; case primitiveType::int64_ : str = occa::toString((int64_t) value.int64_); break; case primitiveType::float_ : str = occa::toString(value.float_); break; case primitiveType::double_ : str = occa::toString(value.double_); break; case primitiveType::none : default: return ""; break; } if (type & (primitiveType::uint64_ | primitiveType::int64_)) { str += 'L'; } return str; } //---[ Misc Methods ]----------------- uint64_t primitive::sizeof_() const { switch(type) { case primitiveType::bool_ : return sizeof(bool); case primitiveType::uint8_ : return sizeof(uint8_t); case primitiveType::uint16_ : return sizeof(uint16_t); case primitiveType::uint32_ : return sizeof(uint32_t); case primitiveType::uint64_ : return sizeof(uint64_t); case primitiveType::int8_ : return sizeof(int8_t); case primitiveType::int16_ : return sizeof(int16_t); case primitiveType::int32_ : return sizeof(int32_t); case primitiveType::int64_ : return sizeof(int64_t); case primitiveType::float_ : return sizeof(float); case primitiveType::double_ : return sizeof(double); case primitiveType::ptr : return sizeof(void*); default: return 0; } } //==================================== //---[ Unary Operators ]-------------- primitive primitive::not_(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(!p.value.bool_); case primitiveType::int8_ : return primitive(!p.value.int8_); case primitiveType::uint8_ : return primitive(!p.value.uint8_); case primitiveType::int16_ : return primitive(!p.value.int16_); case primitiveType::uint16_ : return primitive(!p.value.uint16_); case primitiveType::int32_ : return primitive(!p.value.int32_); case primitiveType::uint32_ : return primitive(!p.value.uint32_); case primitiveType::int64_ : return primitive(!p.value.int64_); case primitiveType::uint64_ : return primitive(!p.value.uint64_); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ! to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ! to double type"); break; default: ; } return primitive(); } primitive primitive::positive(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(+p.value.bool_); case primitiveType::int8_ : return primitive(+p.value.int8_); case primitiveType::uint8_ : return primitive(+p.value.uint8_); case primitiveType::int16_ : return primitive(+p.value.int16_); case primitiveType::uint16_ : return primitive(+p.value.uint16_); case primitiveType::int32_ : return primitive(+p.value.int32_); case primitiveType::uint32_ : return primitive(+p.value.uint32_); case primitiveType::int64_ : return primitive(+p.value.int64_); case primitiveType::uint64_ : return primitive(+p.value.uint64_); case primitiveType::float_ : return primitive(+p.value.float_); case primitiveType::double_ : return primitive(+p.value.double_); default: ; } return primitive(); } primitive primitive::negative(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(-p.value.bool_); case primitiveType::int8_ : return primitive(-p.value.int8_); case primitiveType::uint8_ : return primitive(-p.value.uint8_); case primitiveType::int16_ : return primitive(-p.value.int16_); case primitiveType::uint16_ : return primitive(-p.value.uint16_); case primitiveType::int32_ : return primitive(-p.value.int32_); case primitiveType::uint32_ : return primitive(-p.value.uint32_); case primitiveType::int64_ : return primitive(-p.value.int64_); case primitiveType::uint64_ : return primitive(-p.value.uint64_); case primitiveType::float_ : return primitive(-p.value.float_); case primitiveType::double_ : return primitive(-p.value.double_); default: ; } return primitive(); } primitive primitive::tilde(const primitive &p) { switch(p.type) { case primitiveType::bool_ : return primitive(!p.value.bool_); case primitiveType::int8_ : return primitive(~p.value.int8_); case primitiveType::uint8_ : return primitive(~p.value.uint8_); case primitiveType::int16_ : return primitive(~p.value.int16_); case primitiveType::uint16_ : return primitive(~p.value.uint16_); case primitiveType::int32_ : return primitive(~p.value.int32_); case primitiveType::uint32_ : return primitive(~p.value.uint32_); case primitiveType::int64_ : return primitive(~p.value.int64_); case primitiveType::uint64_ : return primitive(~p.value.uint64_); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ~ to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ~ to double type"); break; default: ; } return primitive(); } primitive& primitive::leftIncrement(primitive &p) { switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator ++ to bool type"); break; case primitiveType::int8_ : ++p.value.int8_; return p; case primitiveType::uint8_ : ++p.value.uint8_; return p; case primitiveType::int16_ : ++p.value.int16_; return p; case primitiveType::uint16_ : ++p.value.uint16_; return p; case primitiveType::int32_ : ++p.value.int32_; return p; case primitiveType::uint32_ : ++p.value.uint32_; return p; case primitiveType::int64_ : ++p.value.int64_; return p; case primitiveType::uint64_ : ++p.value.uint64_; return p; case primitiveType::float_ : ++p.value.float_; return p; case primitiveType::double_ : ++p.value.double_; return p; default: ; } return p; } primitive& primitive::leftDecrement(primitive &p) { switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator -- to bool type"); break; case primitiveType::int8_ : --p.value.int8_; return p; case primitiveType::uint8_ : --p.value.uint8_; return p; case primitiveType::int16_ : --p.value.int16_; return p; case primitiveType::uint16_ : --p.value.uint16_; return p; case primitiveType::int32_ : --p.value.int32_; return p; case primitiveType::uint32_ : --p.value.uint32_; return p; case primitiveType::int64_ : --p.value.int64_; return p; case primitiveType::uint64_ : --p.value.uint64_; return p; case primitiveType::float_ : --p.value.float_; return p; case primitiveType::double_ : --p.value.double_; return p; default: ; } return p; } primitive primitive::rightIncrement(primitive &p) { primitive oldP = p; switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator ++ to bool type"); break; case primitiveType::int8_ : p.value.int8_++; return oldP; case primitiveType::uint8_ : p.value.uint8_++; return oldP; case primitiveType::int16_ : p.value.int16_++; return oldP; case primitiveType::uint16_ : p.value.uint16_++; return oldP; case primitiveType::int32_ : p.value.int32_++; return oldP; case primitiveType::uint32_ : p.value.uint32_++; return oldP; case primitiveType::int64_ : p.value.int64_++; return oldP; case primitiveType::uint64_ : p.value.uint64_++; return oldP; case primitiveType::float_ : p.value.float_++; return oldP; case primitiveType::double_ : p.value.double_++; return oldP; default: ; } return oldP; } primitive primitive::rightDecrement(primitive &p) { primitive oldP = p; switch(p.type) { case primitiveType::bool_ : OCCA_FORCE_ERROR("Cannot apply operator -- to bool type"); break; case primitiveType::int8_ : p.value.int8_--; return oldP; case primitiveType::uint8_ : p.value.uint8_--; return oldP; case primitiveType::int16_ : p.value.int16_--; return oldP; case primitiveType::uint16_ : p.value.uint16_--; return oldP; case primitiveType::int32_ : p.value.int32_--; return oldP; case primitiveType::uint32_ : p.value.uint32_--; return oldP; case primitiveType::int64_ : p.value.int64_--; return oldP; case primitiveType::uint64_ : p.value.uint64_--; return oldP; case primitiveType::float_ : p.value.float_--; return oldP; case primitiveType::double_ : p.value.double_--; return oldP; default: ; } return oldP; } //==================================== //---[ Boolean Operators ]------------ primitive primitive::lessThan(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() < b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() < b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() < b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() < b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() < b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() < b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() < b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() < b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() < b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() < b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() < b.to<double>()); default: ; } return primitive(); } primitive primitive::lessThanEq(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() <= b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() <= b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() <= b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() <= b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() <= b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() <= b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() <= b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() <= b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() <= b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() <= b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() <= b.to<double>()); default: ; } return primitive(); } primitive primitive::equal(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() == b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() == b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() == b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() == b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() == b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() == b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() == b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() == b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() == b.to<uint64_t>()); case primitiveType::float_ : return primitive(areBitwiseEqual(a.value.float_, b.value.float_)); case primitiveType::double_ : return primitive(areBitwiseEqual(a.value.double_, b.value.double_)); default: ; } return primitive(); } primitive primitive::compare(const primitive &a, const primitive &b) { if (lessThan(a, b)) { return -1; } return greaterThan(a, b) ? 1 : 0; } primitive primitive::notEqual(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() != b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() != b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() != b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() != b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() != b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() != b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() != b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() != b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() != b.to<uint64_t>()); case primitiveType::float_ : return primitive(!areBitwiseEqual(a.value.float_, b.value.float_)); case primitiveType::double_ : return primitive(!areBitwiseEqual(a.value.double_, b.value.double_)); default: ; } return primitive(); } primitive primitive::greaterThanEq(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() >= b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() >= b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() >= b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() >= b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() >= b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() >= b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() >= b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() >= b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() >= b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() >= b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() >= b.to<double>()); default: ; } return primitive(); } primitive primitive::greaterThan(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() > b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() > b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() > b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() > b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() > b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() > b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() > b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() > b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() > b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() > b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() > b.to<double>()); default: ; } return primitive(); } primitive primitive::and_(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() && b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() && b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() && b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() && b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() && b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() && b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() && b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() && b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() && b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator && to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator && to double type"); break; default: ; } return primitive(); } primitive primitive::or_(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() || b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() || b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() || b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() || b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() || b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() || b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() || b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() || b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() || b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator || to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator || to double type"); break; default: ; } return primitive(); } //==================================== //---[ Binary Operators ]------------- primitive primitive::mult(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() * b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() * b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() * b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() * b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() * b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() * b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() * b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() * b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() * b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() * b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() * b.to<double>()); default: ; } return primitive(); } primitive primitive::add(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() + b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() + b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() + b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() + b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() + b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() + b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() + b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() + b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() + b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() + b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() + b.to<double>()); default: ; } return primitive(); } primitive primitive::sub(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() - b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() - b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() - b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() - b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() - b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() - b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() - b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() - b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() - b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() - b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() - b.to<double>()); default: ; } return primitive(); } primitive primitive::div(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() / b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() / b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() / b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() / b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() / b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() / b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() / b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() / b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() / b.to<uint64_t>()); case primitiveType::float_ : return primitive(a.to<float>() / b.to<float>()); case primitiveType::double_ : return primitive(a.to<double>() / b.to<double>()); default: ; } return primitive(); } primitive primitive::mod(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() % b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() % b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() % b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() % b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() % b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() % b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() % b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() % b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() % b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator % to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator % to double type"); break; default: ; } return primitive(); } primitive primitive::bitAnd(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() & b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() & b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() & b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() & b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() & b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() & b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() & b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() & b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() & b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator & to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator & to double type"); break; default: ; } return primitive(); } primitive primitive::bitOr(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() | b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() | b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() | b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() | b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() | b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() | b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() | b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() | b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() | b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator | to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator | to double type"); break; default: ; } return primitive(); } primitive primitive::xor_(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() ^ b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() ^ b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() ^ b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() ^ b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() ^ b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() ^ b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() ^ b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() ^ b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() ^ b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to double type"); break; default: ; } return primitive(); } primitive primitive::rightShift(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() >> b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() >> b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() >> b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() >> b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() >> b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() >> b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() >> b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() >> b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() >> b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator >> to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator >> to double type"); break; default: ; } return primitive(); } primitive primitive::leftShift(const primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : return primitive(a.to<bool>() << b.to<bool>()); case primitiveType::int8_ : return primitive(a.to<int8_t>() << b.to<int8_t>()); case primitiveType::uint8_ : return primitive(a.to<uint8_t>() << b.to<uint8_t>()); case primitiveType::int16_ : return primitive(a.to<int16_t>() << b.to<int16_t>()); case primitiveType::uint16_ : return primitive(a.to<uint16_t>() << b.to<uint16_t>()); case primitiveType::int32_ : return primitive(a.to<int32_t>() << b.to<int32_t>()); case primitiveType::uint32_ : return primitive(a.to<uint32_t>() << b.to<uint32_t>()); case primitiveType::int64_ : return primitive(a.to<int64_t>() << b.to<int64_t>()); case primitiveType::uint64_ : return primitive(a.to<uint64_t>() << b.to<uint64_t>()); case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator << to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator << to double type"); break; default: ; } return primitive(); } //==================================== //---[ Assignment Operators ]--------- primitive& primitive::assign(primitive &a, const primitive &b) { a = b; return a; } primitive& primitive::multEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() * b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() * b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() * b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() * b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() * b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() * b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() * b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() * b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() * b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() * b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() * b.to<double>()); break; default: ; } return a; } primitive& primitive::addEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() + b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() + b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() + b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() + b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() + b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() + b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() + b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() + b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() + b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() + b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() + b.to<double>()); break; default: ; } return a; } primitive& primitive::subEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() - b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() - b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() - b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() - b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() - b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() - b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() - b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() - b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() - b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() - b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() - b.to<double>()); break; default: ; } return a; } primitive& primitive::divEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() / b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() / b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() / b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() / b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() / b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() / b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() / b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() / b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() / b.to<uint64_t>()); break; case primitiveType::float_ : a = (a.to<float>() / b.to<float>()); break; case primitiveType::double_ : a = (a.to<double>() / b.to<double>()); break; default: ; } return a; } primitive& primitive::modEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() % b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() % b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() % b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() % b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() % b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() % b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() % b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() % b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() % b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator % to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator % to double type"); break; default: ; } return a; } primitive& primitive::bitAndEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() & b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() & b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() & b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() & b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() & b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() & b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() & b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() & b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() & b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator & to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator & to double type"); break; default: ; } return a; } primitive& primitive::bitOrEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() | b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() | b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() | b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() | b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() | b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() | b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() | b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() | b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() | b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator | to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator | to double type"); break; default: ; } return a; } primitive& primitive::xorEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() ^ b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() ^ b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() ^ b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() ^ b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() ^ b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() ^ b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() ^ b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() ^ b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() ^ b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator ^ to double type"); break; default: ; } return a; } primitive& primitive::rightShiftEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() >> b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() >> b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() >> b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() >> b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() >> b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() >> b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() >> b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() >> b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() >> b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator >> to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator >> to double type"); break; default: ; } return a; } primitive& primitive::leftShiftEq(primitive &a, const primitive &b) { const int retType = (a.type > b.type) ? a.type : b.type; switch(retType) { case primitiveType::bool_ : a = (a.to<bool>() << b.to<bool>()); break; case primitiveType::int8_ : a = (a.to<int8_t>() << b.to<int8_t>()); break; case primitiveType::uint8_ : a = (a.to<uint8_t>() << b.to<uint8_t>()); break; case primitiveType::int16_ : a = (a.to<int16_t>() << b.to<int16_t>()); break; case primitiveType::uint16_ : a = (a.to<uint16_t>() << b.to<uint16_t>()); break; case primitiveType::int32_ : a = (a.to<int32_t>() << b.to<int32_t>()); break; case primitiveType::uint32_ : a = (a.to<uint32_t>() << b.to<uint32_t>()); break; case primitiveType::int64_ : a = (a.to<int64_t>() << b.to<int64_t>()); break; case primitiveType::uint64_ : a = (a.to<uint64_t>() << b.to<uint64_t>()); break; case primitiveType::float_ : OCCA_FORCE_ERROR("Cannot apply operator << to float type"); break; case primitiveType::double_ : OCCA_FORCE_ERROR("Cannot apply operator << to double type"); break; default: ; } return a; } //==================================== io::output& operator << (io::output &out, const primitive &p) { out << p.toString(); return out; } }
libocca/occa
src/types/primitive.cpp
C++
mit
49,514
/** * pax * https://github.com/reekoheek/pax * * Copyright (c) 2013 PT Sagara Xinix Solusitama * Licensed under the MIT license. * https://github.com/reekoheek/pax/blob/master/LICENSE * * Composer command * */ var spawn = require('child_process').spawn, d = require('simply-deferred'); module.exports = function(pax, args, opts) { var deferred = d.Deferred(), packageFile = 'package.json'; var found = require('matchdep').filterDev('grunt-' + args[0], process.cwd() + '/' + packageFile); if (found.length <= 0) { var insDep = spawn('npm', ['install', 'grunt-' + args[0], '--save-dev'], {stdio: 'inherit'}); insDep.on('close', function(code) { if (code > 0) { deferred.reject(new Error('NPM error occured.')); } else { deferred.resolve(); } }); } else { pax.log.info(args[0], 'already exists.'); deferred.resolve(); } return deferred.promise(); };
krisanalfa/pax
lib/commands/grunt/add.js
JavaScript
mit
1,004
/* globals require module */ const modelRegistrator = require("./utils/model-registrator"); module.exports = modelRegistrator.register("Superhero", { name: { type: String, required: true }, secretIdentity: { type: String, required: true }, alignment: { type: String, required: true }, story: { type: String, required: true }, imageUrl: { type: String, required: true }, fractions: [{}], powers: [{}], city: {}, country: {}, planet: {}, user: {} });
Minkov/Superheroes-Universe
models/superhero-model.js
JavaScript
mit
594
var engine = require('../data.js'); var collection = engine.getCollection('posts'); var requiredKeys = ['title', 'markdown', 'body', 'slug', 'createdAt']; var requiredMessage = 'You must provide at least these keys: ' + requiredKeys.join(', '); function _dummyIndex(err, indexName) { if (err) { throw new Error(err); } console.log('Created', indexName); } collection.ensureIndex('slug', {unique: true}, _dummyIndex); collection.ensureIndex({createdAt: -1}, {w: 1}, _dummyIndex); collection.ensureIndex({tags: 1}, {_tiarr: true}, _dummyIndex); module.exports.list = listPosts; module.exports.listByDate = listPostsByDate; module.exports.listByTag = listPostsByTag; module.exports.get = getPost; module.exports.upsert = upsertPost; module.exports.create = createPost; module.exports.update = updatePost; module.exports.remove = removePost; module.exports.addComment = addComment; function dateLimit(year, month) { var MIN_MONTH = 1; var MAX_MONTH = 12; var currDate = new Date(); var hasMonth = Number.isFinite(month); var upper, lower; year = year || currDate.getFullYear(); month = month || currDate.getMonth(); if (hasMonth) { lower = year + '-' + month + '-1'; if (month + 1 > MAX_MONTH) { upper = (year + 1) + '-1-1'; } else { upper = year + '-' + (month + 1) + '-1'; } } else { lower = year + '-1-1'; upper = (year + 1) + '-1-1'; } return [new Date(Date.parse(lower)), new Date(Date.parse(upper))]; } function clone(original, edited) { var properties = ['title', 'body', 'markdown', 'tags']; properties.forEach(function (key) { original[key] = edited[key]; }); return original; } function validate(data) { var dataKeys = Object.keys(data); var hasKeys = requiredKeys.map(function (key) { return dataKeys.indexOf(key) > -1; }).reduce(function (accum, value) { return accum && value; }); return hasKeys; } function listPosts(options) { var page = options.page || 0; // posts per page var limit = options.limit || 5; // skip how many posts var skip = limit * page; collection.find( {}, { limit: limit, skip: skip, sort: {createdAt: -1} }, options.callback ); } function listPostsByTag(options) { collection.find( {tags: options.tag}, options.callback ); } function listPostsByDate(options) { var limits = dateLimit(options.year, options.month); collection.find( {publishAt: {$gt: limits[0], $lt: limits[1]}}, options.callback ); } function getPost(options) { collection.findOne({slug: options.slug}, options.callback); } function upsertPost(options) { collection.update( {slug: options.slug}, options.data, {upsert: true}, options.callback ); } function createPost(options) { if (!validate(options.data)) { return options.callback(new Error(requiredMessage)); } collection.insert(options.data, options.callback); } function updatePost(options) { getPost({ slug: options.slug, callback: function retrieved(err, item) { collection.update( {slug: options.slug}, clone(item, options.data), options.callback ); } }); } function removePost(options) { collection.remove({slug: options.slug}, options.callback); } function addComment(options) { getPost({ slug: options.slug, callback: function retrieved(err, item) { if (!item.comments) { item.comments = []; } item.comments.push(options.comment); item.comments = item.comments.sort(function sortByDate(a, b) { return b.createdAt.valueOf() - a.createdAt.valueOf(); }); collection.update( {slug: options.slug}, item, options.callback ); } }); }
joaodubas/blog
lib/data-post/index.js
JavaScript
mit
3,760
package edu.psu.sweng500.emrms.service; import edu.psu.sweng500.emrms.application.ApplicationSessionHelper; import edu.psu.sweng500.emrms.mappers.ChartingMapper; import edu.psu.sweng500.emrms.model.HAuditRecord; import edu.psu.sweng500.emrms.model.HProblem; import edu.psu.sweng500.emrms.util.PersonPatientUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("manageProblemService") public class ManageProblemServiceImpl implements ManageProblemService{ @Autowired private ChartingMapper chartingMapper; @Autowired private AuditEventService auditEventService; @Autowired private PersonPatientUtils patientUtils; @Autowired private ApplicationSessionHelper sessionHelper; public void setChartingMapper(ChartingMapper chartingMapper) { this.chartingMapper = chartingMapper; } @Override public int AddProblem(HProblem problem) { chartingMapper.addProblem(problem); HAuditRecord auditRecord = new HAuditRecord(); auditRecord.setEventName("Add Problem"); auditRecord.setUserId(sessionHelper.getPhysicianName()); auditRecord.setPolicyId(17); auditRecord.setPatient_ObjectID(problem.getPatientID()); auditRecord.setPatientName(patientUtils.getPatientName(problem.getPatientID())); auditRecord.setEncounter_ObjectID(problem.getEncObjectId()); auditEventService.auditEvent(auditRecord); return 0; } @Override public int ReviseProblem(HProblem problem) { chartingMapper.reviseProblem(problem); HAuditRecord auditRecord = new HAuditRecord(); auditRecord.setEventName("Revise Problem"); auditRecord.setUserId(sessionHelper.getPhysicianName()); auditRecord.setPolicyId(18); auditRecord.setPatient_ObjectID(problem.getPatientID()); auditRecord.setPatientName(patientUtils.getPatientName(problem.getPatientID())); auditRecord.setEncounter_ObjectID(problem.getEncObjectId()); auditEventService.auditEvent(auditRecord); return 0; } @Override public int DeleteProblem(HProblem problem) { chartingMapper.deleteProblem(problem); HAuditRecord auditRecord = new HAuditRecord(); auditRecord.setEventName("Delete Problem"); auditRecord.setUserId(sessionHelper.getPhysicianName()); auditRecord.setPolicyId(22); auditRecord.setPatient_ObjectID(problem.getPatientID()); auditRecord.setPatientName(patientUtils.getPatientName(problem.getPatientID())); auditRecord.setEncounter_ObjectID(problem.getEncObjectId()); auditEventService.auditEvent(auditRecord); return 0; } @Override public List<HProblem> GetProblemsList(int patientObjId, int encObjId) { return chartingMapper.getPatientProblemList(patientObjId,encObjId); } }
Nilbog21/EMRMS
src/main/java/edu/psu/sweng500/emrms/service/ManageProblemServiceImpl.java
Java
mit
2,947
#include "world/Obstacle.h" #include <math.h> using namespace manip_core; using namespace matrices; using namespace Eigen; Obstacle::Obstacle(const Vector3& p1, const Vector3& p2, const Vector3& p3, bool donttouch) : p1_(p1) , p2_(p2) , p3_(p3) , p4_(p1+ (p3 - p2)) , u_(p3-p1) , v_(p2-p1) , n_(u_.cross(v_)) , donttouch_(donttouch) ,onlyThreePoints_(true) { InitObstacle(); } Obstacle::Obstacle(const Vector3& p1, const Vector3& p2, const Vector3& p3, const Vector3& p4, bool donttouch) : p1_(p1) , p2_(p2) , p3_(p3) , p4_(p4) , u_(p3-p4) , v_(p1-p4) , n_(u_.cross(v_)) , donttouch_(donttouch) , onlyThreePoints_(false) { InitObstacle(); } void Obstacle::InitObstacle() { Vector3 normal = n_; a_ = (float)(normal.x()); b_ = (float)(normal.y()); c_ = (float)(normal.z()); //if (c_ < 0) c_ = -c_; norm_ = (float)(normal.norm()); normsquare_ = norm_ * norm_; d_ = (float)(-(a_ * p1_.x() + b_ * p1_.y() + c_ * p1_.z())); center_ = p1_ + ((p4_ - p1_) + (p2_ - p1_)) / 2 ; basis_ = Matrix4::Zero(); Vector3 x = (p3_ - p4_); x.normalize(); Vector3 y = (p1_ - p4_); y.normalize(); normal.normalize(); basis_.block(0,0,3,1) = x; basis_.block(0,1,3,1) = y; basis_.block(0,2,3,1) = normal; basis_.block(0,3,3,1) = p4_; basis_(3,3) = 1; basisInverse_ = basis_.inverse(); w_ = (float)((p3_ - p4_).norm()); h_ = (float)((p1_ - p4_).norm()); /*triangle1_ = tree::MakeTriangle(p1, p2, p3); triangle2_ = tree::MakeTriangle(p1, p4, p3);*/ } Obstacle::~Obstacle() { // NOTHING } numeric Obstacle::Distance(const Vector3& point, Vector3& getCoordinates) const { // http://fr.wikipedia.org/wiki/Distance_d%27un_point_%C3%A0_un_plan numeric lambda = - ((a_ * point.x() + b_ * point.y() + c_ * point.z() + d_) / normsquare_); getCoordinates(0) = lambda * a_ + point.x(); getCoordinates(1) = lambda * b_ + point.y(); getCoordinates(2) = lambda * c_ + point.z(); return (abs(lambda) * norm_); } bool Obstacle::IsAbove(const matrices::Vector3& point) const { Vector3 nNormal = n_; nNormal.normalize(); Vector3 projection; numeric distance = Distance(point, projection); return (point - ( projection + distance * nNormal )).norm() < 0.000000001; } const matrices::Vector3 Obstacle::ProjectUp(const matrices::Vector3& point) const// projects a points onto obstacle plan and rises it up a little { matrices::Vector3 res = matrices::matrix4TimesVect3(basisInverse_, point); matrices::Vector3 nNormal = n_; nNormal.normalize(); res(2) = nNormal(2) * 0.1; return matrices::matrix4TimesVect3(basis_, res); } //bool Obstacle::ContainsPlanar(const Vector3& point) const //{ // double xc, yc, zc; // xc = point(0); yc = point(1); // return ((xc > 0 && xc < w_) && // (yc > 0 && yc < h_) ; //}
stonneau/manipulabilityreduced
src/world/Obstacle.cpp
C++
mit
2,741
package com.hps.wizard.sample.states; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.TextView; import com.hps.wizard.StateFragment; import com.hps.wizard.AbstractWizardActivity; import com.hps.wizard.sample.R; /** * This fragment is a state fragment which accepts two possible next states and a label. It then moves forward to the appropriate state based on user selection. */ public class AreYouSure extends StateFragment { public static final String ARE_YOU_SURE_TEXT = "text"; public static final String YES_STATE = "yesState"; public static final String NO_STATE = "noState"; private static final String CHECKED_BUTTON_ID = "checkedId"; private RadioButton yes, no; private RadioGroup choiceGroup; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_state_are_your_sure, container, false); Bundle args = getArguments(); String message = args.getString(ARE_YOU_SURE_TEXT); TextView tv = (TextView) v.findViewById(R.id.textView); tv.setText(message); yes = (RadioButton) v.findViewById(R.id.yes); no = (RadioButton) v.findViewById(R.id.no); choiceGroup = (RadioGroup) v.findViewById(R.id.choiceGroup); /** * Set up a listener to enable or disable the next button. */ OnCheckedChangeListener thingListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (getWizardActivity() != null) { getWizardActivity().enableButton(AbstractWizardActivity.NEXT_BUTTON, group.getCheckedRadioButtonId() != -1, AreYouSure.this); } } }; choiceGroup.setOnCheckedChangeListener(thingListener); /** * Check the correct radio button if we're rebuilding the screen after orientation change. */ if (getArguments() != null) { int checkedId = getArguments().getInt(CHECKED_BUTTON_ID, -1); if (checkedId != -1) { choiceGroup.check(checkedId); } } return v; } @Override public String getTitle() { return "Are You Sure?"; } @Override public String getPreviousButtonLabel() { return getWizardActivity().getString(R.string.wizard_previous); } @Override public boolean canGoForward() { /** * We can go forward only if the fragment has been created and the user has selected yes or no. */ return yes != null && (yes.isChecked() || no.isChecked()); } @SuppressWarnings("unchecked") @Override public StateDefinition getNextState() { Bundle args = getArguments(); Class<? extends StateFragment> nextState; /** * Select the correct state based on which radio button is checked. */ if (yes.isChecked()) { nextState = (Class<? extends StateFragment>) args.getSerializable(YES_STATE); } else { nextState = (Class<? extends StateFragment>) args.getSerializable(NO_STATE); } return new StateDefinition(nextState, null); } @Override public Bundle getSavedInstanceState() { Bundle bundle = getBundleToSave(); /** * Store off which radio button was checked (if any). */ if (choiceGroup != null) { bundle.putInt(CHECKED_BUTTON_ID, choiceGroup.getCheckedRadioButtonId()); } return bundle; } }
HeartlandPaymentSystems/Android-Wizard-Framework
WizardSample/src/com/hps/wizard/sample/states/AreYouSure.java
Java
mit
3,465
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.aspose.imaging.examples; /** * * @author mfazi */ public final class Assert { public static void areEqual(Object left, Object right) { if (!left.equals(right)) throw new AssertionError(left + " != " + right); } public static void areEqual(Object left, Object right, String msg) { if (!left.equals(right)) throw new AssertionError(msg); } public static void areEqual(long left, long right, String msg) { if (left != right) throw new AssertionError(left + " != " + right); } public static void areEqual(float left, float right, float epsilon) { assert Math.abs(left - right) < epsilon; } public static void areNotEqual(Object left, Object right) { assert !left.equals(right); } public static void assertTrue(boolean value) { if (!value) throw new AssertionError("value is false"); } public static void assertTrue(boolean value, String msg) { assert value : msg; } }
aspose-imaging/Aspose.Imaging-for-Java
Examples/src/main/java/com/aspose/imaging/examples/Assert.java
Java
mit
1,281
<?php $navbar = [ "config" => [ "navbar-class" => "navbar" ], "items" => [ "start" => [ "text" => "Start", "route" => "", ], "about" => [ "text" => "About", "route" => "about", ], "report" => [ "text" => "Report", "route" => "report", ], ] ]; $navHtml = ""; $navClass = $navbar["config"]["navbar-class"]; // Create url using $app->url->create(); foreach ($navbar["items"] as $items => $item) { $nav = $item["route"]; $url = $app->url->create("$nav"); $navHtml .= '<li><a href="' . $url . '">' . $item["text"] . '</a></li>'; } ?> <nav class="<?= $navClass ?>"> <ul> <?= $navHtml ?> </ul> </nav>
Marv2/anax-lite
view/navbar1/navbar.php
PHP
mit
772
'use strict'; angular.module('nav', ['playlist']) .controller('NavController', function ($scope, $mdDialog, $location, webRTC, socket) { $scope.showPlaylist = function(ev) { $mdDialog.show({ controller: 'PlaylistController', templateUrl: 'app/components/playlist/playlist.html', parent: angular.element(document.body), targetEvent: ev, clickOutsideToClose:true }) .then(function(answer) { $scope.status = 'You said the information was "' + answer + '".'; }, function() { $scope.status = 'You cancelled the dialog.'; }); }; $scope.joinRoom = function() { //assumes that we are in #/room/:id var ioRoom = $location.path().split('/')[2] webRTC.joinRoom(ioRoom); // Room.getRoom($location.path()) // .then(function (data) { // socket.init(data.id) // }) // .catch(function(err) { // console.error(err); // }) }; //join on nav init $scope.joinRoom(); });
nickfujita/WhiteBoard
public/app/components/nav/nav.js
JavaScript
mit
978
var gulp = require('gulp'); var less = require('gulp-less'); var browserSync = require('browser-sync').create(); var header = require('gulp-header'); var cleanCSS = require('gulp-clean-css'); var rename = require("gulp-rename"); var uglify = require('gulp-uglify'); var filter = require('gulp-filter'); var pkg = require('./package.json'); // Set the banner content var banner = ['/*!\n', ' * Max Rohrer - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n', ' * Copyright 2017-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n', ' */\n', '' ].join(''); // Compile LESS files from /less into /css gulp.task('less', function() { var f = filter(['*', '!mixins.less', '!variables.less']); return gulp.src('less/*.less') .pipe(f) .pipe(less()) .pipe(header(banner, { pkg: pkg })) .pipe(gulp.dest('css')) .pipe(browserSync.reload({ stream: true })) }); // Minify compiled CSS gulp.task('minify-css', ['less'], function() { return gulp.src('css/freelancer.css') .pipe(cleanCSS({ compatibility: 'ie8' })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('css')) .pipe(browserSync.reload({ stream: true })) }); // Minify JS gulp.task('minify-js', function() { return gulp.src('js/freelancer.js') .pipe(uglify()) .pipe(header(banner, { pkg: pkg })) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('js')) .pipe(browserSync.reload({ stream: true })) }); // Copy vendor libraries from /node_modules into /vendor gulp.task('copy', function() { gulp.src(['node_modules/bootstrap/dist/**/*', '!**/npm.js', '!**/bootstrap-theme.*', '!**/*.map']) .pipe(gulp.dest('vendor/bootstrap')) gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js']) .pipe(gulp.dest('vendor/jquery')) gulp.src([ 'node_modules/font-awesome/**', '!node_modules/font-awesome/**/*.map', '!node_modules/font-awesome/.npmignore', '!node_modules/font-awesome/*.txt', '!node_modules/font-awesome/*.md', '!node_modules/font-awesome/*.json' ]) .pipe(gulp.dest('vendor/font-awesome')) }) // Run everything gulp.task('default', ['less', 'minify-css', 'minify-js', 'copy']); // Configure the browserSync task gulp.task('browserSync', function() { browserSync.init({ server: { baseDir: '' }, }) }) // Dev task with browserSync gulp.task('dev', ['browserSync', 'less', 'minify-css', 'minify-js'], function() { gulp.watch('less/*.less', ['less']); gulp.watch('css/*.css', ['minify-css']); gulp.watch('js/*.js', ['minify-js']); // Reloads the browser whenever HTML or JS files change gulp.watch('*.html', browserSync.reload); gulp.watch('js/**/*.js', browserSync.reload); });
maxroar/maxroar.github.io
gulpfile.js
JavaScript
mit
2,957
import React from 'react'; import PropTypes from 'prop-types'; import DatePicker from './DatePicker'; import Cell from './Cell'; import { View } from 'react-native'; class CellDatePicker extends React.Component { static defaultProps = { mode: 'datetime', date: new Date() } static proptTypes = { ...Cell.propTypes, onShow: PropTypes.func, onDateSelected: PropTypes.func.isRequired, mode: PropTypes.string.isRequired, date: PropTypes.object, cancelText: PropTypes.string } handleOnDateSelected = (date) => { this.props.onDateSelected(date); } handleDateOnPress = () => { if (this.props.onPress) this.props.onPress(); this._datePicker.open(); } render() { return ( <View> <DatePicker ref={component => this._datePicker = component} date={this.props.date} mode={this.props.mode} onDateSelected={this.handleOnDateSelected} cancelText={this.props.cancelText} /> <Cell onPress={this.handleDateOnPress} {...this.props} /> </View> ); } } export default CellDatePicker;
lodev09/react-native-cell-components
components/CellDatePicker.js
JavaScript
mit
1,159
using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace ChromeRuntimeDownloader.Models { public class NugetInfo { public NugetInfo(PackageType packageType, string name, string version, CopyPath[] copyPaths) { PackageType = packageType; Name = name; Version = version; CopyPaths = copyPaths; } [JsonConverter(typeof(StringEnumConverter))] public PackageType PackageType { get; } public string Name { get; set; } public string Version { get; set; } public CopyPath[] CopyPaths { get; } } }
pkudrel/ChromeRuntimeDownloader
src/ChromeRuntimeDownloader/Models/NugetInfo.cs
C#
mit
626
using UnityEngine; namespace Atlas.Examples { public sealed class Example_Range { // generic character class public class Character { public void ApplyDamage( float damage ) { /* ... */ } } public void OnCharacterHit( Character hitCharacter ) { // get randomized damage amount float damageAmount = m_damageRange.GetRandomValue(); // apply damage hitCharacter.ApplyDamage( damageAmount ); } // range declaration [SerializeField] private Range m_damageRange = new Range( 6f, 20f ); } }
david-knopp/Atlas
Assets/Examples/Scripts/Runtime/Math/Example_Range.cs
C#
mit
635
/* * Copyright (C) 2009 University of Washington * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.mamasdelrio.android.views; import org.mamasdelrio.android.logic.HierarchyElement; import org.mamasdelrio.android.utilities.TextUtils; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.Gravity; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import org.mamasdelrio.android.widgets.QuestionWidget; public class HierarchyElementView extends RelativeLayout { private TextView mPrimaryTextView; private TextView mSecondaryTextView; private ImageView mIcon; public HierarchyElementView(Context context, HierarchyElement it) { super(context); setColor(it.getColor()); mIcon = new ImageView(context); mIcon.setImageDrawable(it.getIcon()); mIcon.setId(QuestionWidget.newUniqueId()); mIcon.setPadding(0, 0, dipToPx(4), 0); addView(mIcon, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mPrimaryTextView = new TextView(context); mPrimaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Large); setPrimaryText(it.getPrimaryText()); mPrimaryTextView.setId(QuestionWidget.newUniqueId()); mPrimaryTextView.setGravity(Gravity.CENTER_VERTICAL); LayoutParams l = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); l.addRule(RelativeLayout.RIGHT_OF, mIcon.getId()); addView(mPrimaryTextView, l); mSecondaryTextView = new TextView(context); mSecondaryTextView.setText(it.getSecondaryText()); mSecondaryTextView.setTextAppearance(context, android.R.style.TextAppearance_Small); mSecondaryTextView.setGravity(Gravity.CENTER_VERTICAL); LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.BELOW, mPrimaryTextView.getId()); lp.addRule(RelativeLayout.RIGHT_OF, mIcon.getId()); addView(mSecondaryTextView, lp); setPadding(dipToPx(8), dipToPx(4), dipToPx(8), dipToPx(8)); } public void setPrimaryText(String text) { mPrimaryTextView.setText(TextUtils.textToHtml(text)); } public void setSecondaryText(String text) { mSecondaryTextView.setText(TextUtils.textToHtml(text)); } public void setIcon(Drawable icon) { mIcon.setImageDrawable(icon); } public void setColor(int color) { setBackgroundColor(color); } public void showSecondary(boolean bool) { if (bool) { mSecondaryTextView.setVisibility(VISIBLE); setMinimumHeight(dipToPx(64)); } else { mSecondaryTextView.setVisibility(GONE); setMinimumHeight(dipToPx(32)); } } public int dipToPx(int dip) { return (int) (dip * getResources().getDisplayMetrics().density + 0.5f); } }
srsudar/MamasDelRioAndroid
app/src/main/java/org/mamasdelrio/android/views/HierarchyElementView.java
Java
mit
3,631
package render import ( "image" "image/draw" //import png _ "image/png" "os" ) type LevelSheet struct { width int height int filePath string PixelArray []byte encoding string } //Constructor for LevelSheet func NewLevelSheet(filePath string) (LevelSheet, int, int) { reader, err := os.Open(filePath) if err != nil { panic(err) } defer reader.Close() img, str, err := image.Decode(reader) rect := img.Bounds() rgba := image.NewRGBA(rect) draw.Draw(rgba, rect, img, rect.Min, draw.Src) width := rect.Max.X - rect.Min.X height := rect.Max.Y - rect.Min.Y return LevelSheet{ width: width, height: height, filePath: filePath, PixelArray: rgba.Pix, encoding: str, }, width, height }
LokiTheMango/jatdg
game/render/levelsheet.go
GO
mit
740
import java.util.Scanner; /* * @author https://github.com/Hoenn * Happy St. Patrick's Day! Write a program that accepts a year as input and outputs what day St. Patrick's Day falls on. */ public class Challenge_27 { public static final int spMonth=3; public static final int spDay=17; public static final String[] daysOfWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; public static final int[] monthsTable = { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 }; public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Enter year: "); int year = input.nextInt(); int day = findDayOfWeek(year); System.out.println("St. Patrick's Day is on a "+daysOfWeek[day]); } public static int findDayOfWeek(int year) { int tempYear=year; int secondHalf = 0; if(tempYear>1000) { tempYear/=100; secondHalf= year%1000; } else { tempYear/=10; secondHalf=year%100; } int c = tempYear%4; return ((spDay+monthsTable[spMonth-1]+secondHalf+(secondHalf/4)+c)-1)%7; }
FreddieV4/DailyProgrammerChallenges
Intermediate Challenges/Challenge 0027 Intermediate/solutions/solution.java
Java
mit
1,136
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/EngineLog.hpp> # include <Siv3D/Windows.hpp> # include <Siv3D/DLL.hpp> # include <ShellScalingApi.h> # include "HighDPI.hpp" namespace s3d { // 高 DPI ディスプレイで、フルスクリーン使用時に High DPI Aware を有効にしないと、 // Windows の互換性マネージャーによって // HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/AppCompatFlags/Layers // に高 DPI が既定の設定として登録されてしまう。 void SetHighDPIAwareness(const bool aware) { LOG_TRACE(U"SetHighDPIAwareness(aware = {})"_fmt(aware)); if (HMODULE user32 = DLL::LoadSystemLibrary(L"user32.dll")) { decltype(SetThreadDpiAwarenessContext)* p_SetThreadDpiAwarenessContext = DLL::GetFunctionNoThrow(user32, "SetThreadDpiAwarenessContext"); if (p_SetThreadDpiAwarenessContext) { p_SetThreadDpiAwarenessContext(aware ? DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 : DPI_AWARENESS_CONTEXT_UNAWARE); ::FreeLibrary(user32); return; } ::FreeLibrary(user32); } if (HINSTANCE shcore = DLL::LoadSystemLibrary(L"shcore.dll")) { decltype(SetProcessDpiAwareness)* p_SetProcessDpiAwareness = DLL::GetFunctionNoThrow(shcore, "SetProcessDpiAwareness"); if (p_SetProcessDpiAwareness) { p_SetProcessDpiAwareness(aware ? PROCESS_PER_MONITOR_DPI_AWARE : PROCESS_DPI_UNAWARE); ::FreeLibrary(shcore); return; } ::FreeLibrary(shcore); } if (aware) { ::SetProcessDPIAware(); } } }
wynd2608/OpenSiv3D
Siv3D/src/Siv3D-Platform/WindowsDesktop/Window/HighDPI.cpp
C++
mit
1,768
var outputType = 'ARRAY'; var input = null; var output = null; var fs = require('fs'); var scriptName = process.argv[1].split('/'); scriptName = scriptName[ scriptName.length - 1 ]; function get_usage() { var usage = "\n"; usage += "Usage: " + scriptName + ' <options> <input markdown file>\n'; usage += "options:\n"; usage += get_options('\t') + '\n'; return usage; } function get_options(prefix) { var options = ""; options += prefix + '--array (to output as an array : DEFAULT)\n'; options += prefix + '--string (to output as a flat string)\n'; options += prefix + '--help (to display this output and exit)\n'; return options } function print_usage(exit, code) { console.log(get_usage()); if (exit) { process.exit(code); } } function toString(text) { return '"'+text.replace(/\n/g, '\\n').replace(/"/g, "\\\"") + '"'; } function toArray(text) { var arrayText = ""; arrayText += "[\n"; text = text.replace(/"/g, "\\\""); text.split('\n').map(function(line) { arrayText += '"' + line + '",\n'; }); arrayText += "]"; return arrayText; } // now the main code if (process.argv.length == 4) { if (process.argv[2] == '--array') { outputType = 'ARRAY'; } else if (process.argv[2] == '--string') { outputType = 'STRING'; } else { print_usage(true, -1); } input = process.argv[3]; output = input + '.converted.json'; } else if (process.argv.length == 3) { if (process.argv[2] == '--help') { print_usage(true, 0); } else { input = process.argv[2]; output = input + '.converted.json'; } } else { console.error('Incorrect arguments!'); print_usage(true, -1); } // load the file fs.readFile(input, function(err, data) { if (err) { throw err; } // make it a string data = new String(data); // now convert var outputData = ''; if (outputType == 'ARRAY') { outputData = toArray(data); } else if (outputType == 'STRING') { outputData = toString(data); } // write output fs.writeFile(output, outputData, 'utf8', (err) => { if (err) { throw err; } process.exit(0); }); });
finger563/webgme-codeeditor
tools/docStringConverter.js
JavaScript
mit
2,300
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using BizHawk.Emulation.Cores.Nintendo.NES; using BizHawk.Common; using BizHawk.Client.Common; using BizHawk.Emulation.Common; namespace BizHawk.Client.EmuHawk { public partial class BarcodeEntry : Form, IToolForm { [RequiredService] private DatachBarcode reader { get; set; } public BarcodeEntry() { InitializeComponent(); } #region IToolForm public void NewUpdate(ToolFormUpdateType type) { } public void UpdateValues() { } public void FastUpdate() { } public void Restart() { textBox1_TextChanged(null, null); } public bool AskSaveChanges() { return true; } public bool UpdateBefore { get { return false; } } #endregion private void textBox1_TextChanged(object sender, EventArgs e) { string why; if (!DatachBarcode.ValidString(textBox1.Text, out why)) { label3.Text = $"Invalid: {why}"; label3.Visible = true; button1.Enabled = false; } else { label3.Visible = false; button1.Enabled = true; } } private void button1_Click(object sender, EventArgs e) { reader.Transfer(textBox1.Text); } } }
ircluzar/RTC3
Real-Time Corruptor/BizHawk_RTC/BizHawk.Client.EmuHawk/tools/NES/BarcodeEntry.cs
C#
mit
1,310
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; // Include the required modules var {assert, expect} = require("../../../../lib/assertions"); var prefs = require("../../../../lib/prefs"); var tabs = require("../../../lib/tabs"); var utils = require("../../../../lib/utils"); var prefWindow = require("../../../lib/ui/pref-window"); const BASE_URL = collector.addHttpResource("../../../../data/"); const TEST_DATA = BASE_URL + "layout/mozilla.html"; const PREF_BROWSER_IN_CONTENT = "browser.preferences.inContent"; const PREF_BROWSER_INSTANT_APPLY = "browser.preferences.instantApply"; var setupModule = function(aModule) { aModule.controller = mozmill.getBrowserController(); prefs.setPref(PREF_BROWSER_IN_CONTENT, false); if (mozmill.isWindows) { prefs.setPref(PREF_BROWSER_INSTANT_APPLY, false); } tabs.closeAllTabs(aModule.controller); } var teardownModule = function(aModule) { prefs.clearUserPref(PREF_BROWSER_IN_CONTENT); prefs.clearUserPref(PREF_BROWSER_INSTANT_APPLY); prefs.clearUserPref("browser.startup.homepage"); } /** * Restore home page to default */ var testRestoreHomeToDefault = function() { // Open a web page for the temporary home page controller.open(TEST_DATA); controller.waitForPageLoad(); var link = new elementslib.Link(controller.tabs.activeTab, "Organization"); assert.ok(link.exists(), "'Organization' link has been found"); // Call Preferences dialog and set home page prefWindow.openPreferencesDialog(controller, prefDialogHomePageCallback); // Go to the saved home page and verify it's the correct page controller.click(new elementslib.ID(controller.window.document, "home-button")); controller.waitForPageLoad(); link = new elementslib.Link(controller.tabs.activeTab, "Organization"); assert.ok(link.exists(), "'Organization' link has been found"); // Open Preferences dialog and reset home page to default prefWindow.openPreferencesDialog(controller, prefDialogDefHomePageCallback); // Check that the current homepage is set to the default homepage - about:home var currentHomepage = prefs.getPref("browser.startup.homepage", ""); var defaultHomepage = utils.getDefaultHomepage(); assert.equal(currentHomepage, defaultHomepage, "Default homepage restored"); } /** * Set the current page as home page via the preferences dialog * * @param {MozMillController} aController * MozMillController of the window to operate on */ var prefDialogHomePageCallback = function(aController) { var prefDialog = new prefWindow.preferencesDialog(aController); prefDialog.paneId = 'paneMain'; // Set home page to the current page var useCurrent = new elementslib.ID(aController.window.document, "useCurrent"); aController.waitThenClick(useCurrent); aController.sleep(100); prefDialog.close(true); } var prefDialogDefHomePageCallback = function(aController) { var prefDialog = new prefWindow.preferencesDialog(aController); // Reset home page to the default page var useDefault = new elementslib.ID(aController.window.document, "restoreDefaultHomePage"); aController.waitForElement(useDefault); aController.click(useDefault); // Check that the homepage field has the default placeholder text var dtds = ["chrome://browser/locale/aboutHome.dtd"]; var defaultHomepageTitle = utils.getEntity(dtds, "abouthome.pageTitle"); var browserHomepageField = new elementslib.ID(aController.window.document, "browserHomePage"); var browserHomepagePlaceholderText = browserHomepageField.getNode().placeholder; expect.equal(browserHomepagePlaceholderText, defaultHomepageTitle, "Default homepage title"); prefDialog.close(true); }
lucashmorais/x-Bench
mozmill-env/msys/firefox/tests/functional/testPreferences/testRestoreHomepageToDefault.js
JavaScript
mit
3,833
namespace ArgentPonyWarcraftClient; /// <summary> /// A character associated with a World of Warcraft account. /// </summary> public record AccountCharacter { /// <summary> /// Gets a link to the character. /// </summary> [JsonPropertyName("character")] public Self Character { get; init; } /// <summary> /// Gets a link to the protected character information. /// </summary> [JsonPropertyName("protected_character")] public Self ProtectedCharacter { get; init; } /// <summary> /// Gets the name of the character. /// </summary> [JsonPropertyName("name")] public string Name { get; init; } /// <summary> /// Gets the ID of the character. /// </summary> [JsonPropertyName("id")] public int Id { get; init; } /// <summary> /// Gets a reference to the character's realm. /// </summary> [JsonPropertyName("realm")] public RealmReference Realm { get; init; } /// <summary> /// Gets a reference to the character's class. /// </summary> [JsonPropertyName("playable_class")] public PlayableClassReference PlayableClass { get; init; } /// <summary> /// Gets a reference to the character's race. /// </summary> [JsonPropertyName("playable_race")] public PlayableClassReference PlayableRace { get; init; } /// <summary> /// Gets the gender of the character. /// </summary> [JsonPropertyName("gender")] public EnumType Gender { get; init; } /// <summary> /// Gets the faction of the character (Alliance or Horde). /// </summary> [JsonPropertyName("faction")] public EnumType Faction { get; init; } /// <summary> /// Gets the level of the character. /// </summary> [JsonPropertyName("level")] public int Level { get; init; } }
danjagnow/ArgentPonyWarcraftClient
src/ArgentPonyWarcraftClient/Models/ProfileApi/AccountProfile/AccountCharacter.cs
C#
mit
1,827
/* NormalBatteryProfileTestCase.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.profile.intent.test; import android.content.Intent; import android.os.Bundle; import android.support.test.runner.AndroidJUnit4; import org.deviceconnect.android.test.plugin.profile.TestBatteryProfileConstants; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.deviceconnect.profile.BatteryProfileConstants; import org.junit.Test; import org.junit.runner.RunWith; /** * Batteryプロファイルの正常系テスト. * @author NTT DOCOMO, INC. */ @RunWith(AndroidJUnit4.class) public class NormalBatteryProfileTestCase extends IntentDConnectTestCase { /** * バッテリー全属性取得テストを行う. * <pre> * 【Intent通信】 * Action: GET * Profile: battery * Interface: なし * Attribute: なし * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・chargingがfalseで返ってくること。 * ・chargingtimeが50000.0で返ってくること。 * ・dischargingtimeが10000.0で返ってくること。 * ・levelが0.5で返ってくること。 * </pre> */ @Test public void testBattery() { Intent request = new Intent(IntentDConnectMessage.ACTION_GET); String serviceId = getServiceId(); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, serviceId); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); Intent response = sendRequest(request); assertResultOK(response); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING)); assertEquals(TestBatteryProfileConstants.CHARGING, response.getBooleanExtra(BatteryProfileConstants.PARAM_CHARGING, false)); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING_TIME)); assertEquals(TestBatteryProfileConstants.CHARGING_TIME, response.getDoubleExtra(BatteryProfileConstants.PARAM_CHARGING_TIME, 0)); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME)); assertEquals(TestBatteryProfileConstants.DISCHARGING_TIME, response.getDoubleExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME, 0)); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_LEVEL)); assertEquals(TestBatteryProfileConstants.LEVEL, response.getDoubleExtra(BatteryProfileConstants.PARAM_LEVEL, 0.0d)); } /** * charging属性取得テストを行う. * <pre> * 【Intent通信】 * Action: GET * Profile: battery * Interface: なし * Attribute: charging * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・chargingがfalseで返ってくること。 * </pre> */ @Test public void testBatteryCharging() { Intent request = new Intent(IntentDConnectMessage.ACTION_GET); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_CHARGING); Intent response = sendRequest(request); assertResultOK(response); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING)); assertEquals(TestBatteryProfileConstants.CHARGING, response.getBooleanExtra(BatteryProfileConstants.PARAM_CHARGING, false)); } /** * chargingTime属性取得テストを行う. * <pre> * 【Intent通信】 * Action: GET * Profile: battery * Interface: なし * Attribute: なし * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・chargingTimeが50000.0で返ってくること。 * </pre> */ @Test public void testBatteryChargingTime() { Intent request = new Intent(IntentDConnectMessage.ACTION_GET); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_CHARGING_TIME); Intent response = sendRequest(request); assertResultOK(response); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_CHARGING_TIME)); assertEquals(TestBatteryProfileConstants.CHARGING_TIME, response.getDoubleExtra(BatteryProfileConstants.PARAM_CHARGING_TIME, 0)); } /** * dischargingTime属性取得テストを行う. * <pre> * 【Intent通信】 * Action: GET * Profile: battery * Interface: なし * Attribute: dischargingTime * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・dischargingTimeが10000.0で返ってくること。 * </pre> */ @Test public void testBatteryDischargingTime() { Intent request = new Intent(IntentDConnectMessage.ACTION_GET); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_DISCHARGING_TIME); Intent response = sendRequest(request); assertResultOK(response); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME)); assertEquals(TestBatteryProfileConstants.DISCHARGING_TIME, response.getDoubleExtra(BatteryProfileConstants.PARAM_DISCHARGING_TIME, 0)); } /** * level属性取得テストを行う. * <pre> * 【Intent通信】 * Action: GET * Profile: battery * Interface: なし * Attribute: なし * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・levelが0.5で返ってくること。 * </pre> */ @Test public void testBatteryLevel() { Intent request = new Intent(IntentDConnectMessage.ACTION_GET); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_LEVEL); Intent response = sendRequest(request); assertResultOK(response); assertTrue(response.hasExtra(BatteryProfileConstants.PARAM_LEVEL)); assertEquals(TestBatteryProfileConstants.LEVEL, response.getDoubleExtra(BatteryProfileConstants.PARAM_LEVEL, 0.0d)); } /** * onchargingchange属性のコールバック登録テストを行う. * <pre> * 【Intent通信】 * Action: PUT * Profile: battery * Interface: なし * Attribute: onchargingchange * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・コールバック登録後にイベントを受信すること。 * </pre> */ @Test public void testBatteryOnChargingChange01() { Intent request = new Intent(IntentDConnectMessage.ACTION_PUT); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_CHARGING_CHANGE); Intent response = sendRequest(request); assertResultOK(response); Intent event = waitForEvent(); assertNotNull(event); assertEquals(BatteryProfileConstants.PROFILE_NAME, event.getStringExtra(DConnectMessage.EXTRA_PROFILE)); assertEquals(BatteryProfileConstants.ATTRIBUTE_ON_CHARGING_CHANGE, event.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE)); Bundle battery = event.getBundleExtra(BatteryProfileConstants.PROFILE_NAME); assertEquals(false, battery.getBoolean(BatteryProfileConstants.PARAM_CHARGING)); } /** * onchargingchange属性のコールバック解除テストを行う. * <pre> * 【Intent通信】 * Action: DELETE * Profile: battery * Interface: なし * Attribute: onchargingchange * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * </pre> */ @Test public void testBatteryOnChargingChange02() { Intent request = new Intent(IntentDConnectMessage.ACTION_DELETE); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_CHARGING_CHANGE); Intent response = sendRequest(request); assertResultOK(response); } /** * onbatterychange属性のコールバック登録テストを行う. * <pre> * 【Intent通信】 * Action: PUT * Profile: battery * Interface: なし * Attribute: onbatterychange * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・コールバック登録後にイベントを受信すること。 * </pre> */ @Test public void testBatteryOnBatteryChange01() { Intent request = new Intent(IntentDConnectMessage.ACTION_PUT); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_BATTERY_CHANGE); Intent response = sendRequest(request); assertResultOK(response); Intent event = waitForEvent(); assertNotNull(event); assertEquals(BatteryProfileConstants.PROFILE_NAME, event.getStringExtra(DConnectMessage.EXTRA_PROFILE)); assertEquals(BatteryProfileConstants.ATTRIBUTE_ON_BATTERY_CHANGE, event.getStringExtra(DConnectMessage.EXTRA_ATTRIBUTE)); Bundle battery = event.getBundleExtra(BatteryProfileConstants.PARAM_BATTERY); assertEquals(TestBatteryProfileConstants.CHARGING_TIME, battery.getDouble(BatteryProfileConstants.PARAM_CHARGING_TIME)); assertEquals(TestBatteryProfileConstants.DISCHARGING_TIME, battery.getDouble(BatteryProfileConstants.PARAM_DISCHARGING_TIME)); assertEquals(TestBatteryProfileConstants.LEVEL, battery.getDouble(BatteryProfileConstants.PARAM_LEVEL)); } /** * onbatterychange属性のコールバック解除テストを行う. * <pre> * 【Intent通信】 * Action: DELETE * Profile: battery * Interface: なし * Attribute: onbatterychange * </pre> * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * </pre> */ @Test public void testBatteryOnBatteryChange02() { Intent request = new Intent(IntentDConnectMessage.ACTION_DELETE); request.putExtra(DConnectMessage.EXTRA_SERVICE_ID, getServiceId()); request.putExtra(DConnectMessage.EXTRA_SESSION_KEY, TEST_SESSION_KEY); request.putExtra(DConnectMessage.EXTRA_PROFILE, BatteryProfileConstants.PROFILE_NAME); request.putExtra(DConnectMessage.EXTRA_ATTRIBUTE, BatteryProfileConstants.ATTRIBUTE_ON_BATTERY_CHANGE); Intent response = sendRequest(request); assertResultOK(response); } }
Onuzimoyr/dAndroid
dConnectManager/dConnectManager/app/src/androidTest/java/org/deviceconnect/android/profile/intent/test/NormalBatteryProfileTestCase.java
Java
mit
12,808
package net.bingyan.campass.greendao; // THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit. /** * Entity mapped to table ELECTRIC_RECORD. */ public class ElectricRecord { private Long id; private String area; private Integer building; private Integer dorm; private Float remain; private java.util.Date date; public ElectricRecord() { } public ElectricRecord(Long id) { this.id = id; } public ElectricRecord(Long id, String area, Integer building, Integer dorm, Float remain, java.util.Date date) { this.id = id; this.area = area; this.building = building; this.dorm = dorm; this.remain = remain; this.date = date; } public ElectricRecord(String area, Integer building, Integer dorm, Float remain, java.util.Date date) { this.area = area; this.building = building; this.dorm = dorm; this.remain = remain; this.date = date; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public Integer getBuilding() { return building; } public void setBuilding(Integer building) { this.building = building; } public Integer getDorm() { return dorm; } public void setDorm(Integer dorm) { this.dorm = dorm; } public Float getRemain() { return remain; } public void setRemain(Float remain) { this.remain = remain; } public java.util.Date getDate() { return date; } public void setDate(java.util.Date date) { this.date = date; } }
BingyanStudio/CamPass-Android
app/src-gen/net/bingyan/campass/greendao/ElectricRecord.java
Java
mit
1,848
/** * Unittest file for led. In this example the timer module is faked also * */ #include "catch.hpp" #include "Arduino.h" #include "led.h" // include the unit under test #include "mock_stimer.h" // include the faked module (so we can set the return values) void run_loop( StatusToLed* led ) { for ( int loop = 0; loop < 100; loop ++ ) { led->loop(); } } TEST_CASE( "Led blinking works", "[led]" ) { StatusToLed led; ARDUINO_TEST.hookup(); led.setup( 10 ); STimer__check_fake.return_val = false; SECTION("It runs") { run_loop(&led); REQUIRE( digitalWrite_fake.call_count == 1); digitalWrite_fake.call_count = 0; STimer__check_fake.return_val = true; // after this it will appear to module as the time would be changing always run_loop(&led); REQUIRE( digitalWrite_fake.call_count == 100); } }
susundberg/arduino-simple-unittest
examples/example_blink_led/tests/test_led.cpp
C++
mit
894
# -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # Author: Mauro Soria class Path(object): def __init__(self, path=None, status=None, response=None): self.path = path self.status = status self.response = response def __str__(self): return self.path
Yukinoshita47/Yuki-Chan-The-Auto-Pentest
Module/dirsearch/lib/core/Path.py
Python
mit
987
<?php namespace eBussola\Feedback\Components; use Cms\Classes\ComponentBase; use Cms\Classes\Page; use eBussola\Feedback\Models\Channel; use Lang; use October\Rain\Exception\AjaxException; class Feedback extends ComponentBase { /** * @var Channel */ public $channel; public function componentDetails() { return [ 'name' => Lang::get('ebussola.feedback::lang.component.feedback.name'), 'description' => Lang::get('ebussola.feedback::lang.component.feedback.description') ]; } public function defineProperties() { return [ 'channelCode' => [ 'title' => Lang::get('ebussola.feedback::lang.channel.one'), 'description' => Lang::get('ebussola.feedback::lang.component.feedback.channelCode.description'), 'type' => 'dropdown', 'required' => true ], 'successMessage' => [ 'title' => Lang::get('ebussola.feedback::lang.component.feedback.successMessage.title'), 'description' => Lang::get('ebussola.feedback::lang.component.feedback.successMessage.description') ], 'redirectTo' => [ 'title' => Lang::get('ebussola.feedback::lang.component.feedback.redirectTo.title'), 'description' => Lang::get('ebussola.feedback::lang.component.feedback.redirectTo.description'), 'type' => 'dropdown', 'default' => 0 ] ]; } /** * @throws \October\Rain\Database\ModelException */ public function onSend() { try { $data = post('feedback'); $channel = Channel::getByCode($this->property('channelCode')); if ($channel) { $channel->send($data); } else { $this->sendAdminEmail('Error on Feedback plugin', 'This message was generated by OctoberCMS\'s plugin Feedback. This message is send when you forget to configure your component. Please, check all your pages to find any Feedback component misconfigured.'); } $message = $this->property('successMessage', Lang::get('ebussola.feedback::lang.component.onSend.success')); \Flash::success($message); if ($this->property('redirectTo', false)) { return redirect(url($this->property('redirectTo'))); } else { return $message; } } catch (\Exception $e) { \Flash::error($e->getMessage()); throw new AjaxException($e->getMessage()); } } public function onRun() { $this->channel = Channel::getByCode($this->property('channelCode')); } public function getRedirectToOptions() { return array_merge([0 => '- none -'], Page::sortBy('baseFileName')->lists('fileName', 'url')); } public function getChannelCodeOptions() { return Channel::all()->lists('name', 'code'); } private function sendAdminEmail($subject, $message) { $channel = new Channel([ 'method' => 'email', 'method_data' => [ 'email_destination' => null, 'subject' => $subject, 'template' => $message ], 'prevent_save_database' => true ]); $channel->send([ 'email' => 'foo@bar.com', 'message' => 'loremipsum' ]); } }
ebussola/octobercms-feedback
components/Feedback.php
PHP
mit
3,549
require 'spec_helper' describe Cardiac::ResourceAdapter do let(:base_url) { 'http://localhost/prefix/segment?q=foobar' } let(:base_uri) { URI(base_url) } let(:resource) { Cardiac::Resource.new(base_uri) } let(:adapter) { Cardiac::ResourceAdapter.new(nil, resource) } include_context 'Client responses' subject { adapter } describe '#http_verb' do subject { super().http_verb } it { is_expected.to be_nil } end describe '#payload' do subject { super().payload } it { is_expected.to be_nil } end describe '#response' do subject { super().response } it { is_expected.to be_nil } end describe '#result' do subject { super().result } it { is_expected.to be_nil } end describe '#resource' do subject { super().resource } it { is_expected.to eq(resource) } end it { is_expected.to be_resolved } describe '#call!()' do describe 'successful responses' do include_context 'Client execution', :get, :success before :example do resource.http_method(:get) expect { @retval = adapter.call! }.not_to raise_error end describe '#response' do subject { adapter.response } it { is_expected.to be_present } end describe '#result' do subject { adapter.result } it { is_expected.to be_present } end it('returns true') { expect(@retval).to be_a(TrueClass) } end describe 'failed responses' do include_context 'Client execution', :get, :failure before :example do resource.http_method(:get) expect { @retval = adapter.call! }.to raise_error end describe '#response' do subject { adapter.response } it { is_expected.not_to be_present } end describe '#result' do subject { adapter.result } it { is_expected.not_to be_present } end end end end
joekhoobyar/cardiac
spec/shared/cardiac/resource/adapter_spec.rb
Ruby
mit
1,981
using System; class CheckPointInCircle { static void Main() { /* Problem 7. Point in a Circle Write an expression that checks if given point (x, y) is inside a circle K({0, 0}, 2). */ Console.WriteLine("Check if given point (x,y) is within K((0,0),2)"); Console.Write("Insert x: "); decimal x = Convert.ToDecimal(Console.ReadLine()); Console.Write("Insert y: "); decimal y = Convert.ToDecimal(Console.ReadLine()); bool checkPoint = (x * x) + (y * y) <= (2 * 2); Console.WriteLine("Is the point ({0},{1}) within a circle K(0,2)?\nIt's {2}.", x, y, checkPoint); } }
TeeeeeC/TelerikAcademy2015-2016
01. C# part 1/03. Operators and Statements/CheckPointInCircle/CheckPointInCircle.cs
C#
mit
676
/* * ImageChangedEvent.java * -- documented * * After a change, such an object is created and passed to the listener * */ package oj.processor.events; public class ImageChangedEventOJ { public static final int IMAGE_ADDED = 1; public static final int IMAGE_EDITED = 2; public static final int IMAGE_DELETED = 3; public static final int IMAGES_SWAP = 4; public static final int IMAGES_SORT = 5; private String firstImageName; private String secondImageName; private int operation; /** Creates a new instance of ImageChangedEvent */ public ImageChangedEventOJ(String firstImageName, String secondImageName, int operation) { this.operation = operation; this.firstImageName = firstImageName; this.secondImageName = secondImageName; } public ImageChangedEventOJ(String name, int operation) { this.firstImageName = name; this.secondImageName = name; this.operation = operation; } public ImageChangedEventOJ(int operation) { this.operation = operation; } public String getName() { return firstImageName; } public String getFirstImageName() { return firstImageName; } public String getSecondImageName() { return secondImageName; } public String getNewImageName() { return firstImageName; } public String getOldImageName() { return secondImageName; } public int getOperation() { return operation; } }
steliann/objectj
src/oj/processor/events/ImageChangedEventOJ.java
Java
mit
1,584
<?php require('HeadAndHeader.php'); ?> <hr id="header-horizontal-line"/> <div id="content"> <div id="current-path"> <p id="current-path-paragraph">Startsait > Settings</p> </div> <fieldset> <legend id="fieldset-title">Settings</legend> <div class="settingsDivs" id="firstSettingsDiv"> <div class="box"> <?php echo form_open('settings/change_password'); ?> <?php echo form_label('Old Password:', 'old_password'); ?> <?php echo form_input(array( 'name' => 'old_password', 'id' => 'old_password', 'placeholder' => 'Enter your current password', )); ?> <?php echo form_label('New Password:', 'password'); ?> <?php echo form_input(array( 'name' => 'password', 'id' => 'password', 'placeholder' => 'New password', )); ?> <?php echo form_label('Repeat Password:', 'password_again'); ?> <?php echo form_input(array( 'name' => 'password_again', 'id' => 'password_again', 'placeholder' => 'New password again', )); ?> <?php echo form_hidden('user_id', $user->id);?> <?php echo form_submit('submit', 'Change password'); ?> <?php echo form_close(); ?> </div> <div class="box"> <?php echo form_open('settings/change_email'); ?> <?php echo form_label('Current Email:', 'current_email'); ?> <?php echo form_input(array( 'name' => 'current_email', 'id' => 'current_email', 'value' => $user->email, 'disabled' => '' )); ?> <?php echo form_label('New Email:', 'email'); ?> <?php echo form_input(array( 'name' => 'email', 'id' => 'email', 'placeholder' => 'Enter the new email', )); ?> <?php echo form_hidden('user_id', $user->id);?> <?php echo form_submit('submit', 'Change Email'); ?> <?php echo form_close(); ?> </div> </div> <div class="settingsDivs" id="secondSettingsDiv" > <div class="box"> <?php echo form_open('settings/add_address'); echo form_label('Full name:', 'full_name'); echo form_input(array( 'name' => 'full_name', 'id' => 'full_name', 'placeholder' => ' Enter your full name' )); echo form_label('Address:', 'address'); echo form_input(array( 'name' => 'address', 'id' => 'address_settings', 'placeholder' => 'Enter your address' )); echo form_label('City:', 'city'); echo form_input(array( 'name' => 'city', 'id' => 'city', 'placeholder' => 'Enter your City' )); echo form_label('State/Province/Region', 'state'); echo form_input(array( 'name' => 'state', 'id' => 'state', 'placeholder' => ' Enter your state/province/region' )); echo form_label('ZIP/Postal code', 'zip_code'); echo form_input(array( 'name' => 'zip_code', 'id' => 'zip_code', 'placeholder' => ' Enter your ZIP/Postal code' )); echo form_label('Country:', 'country'); echo country_dropdown('country', 'cont', 'dropdown', 'BG', array('US', 'CA', 'GB'), ''); echo form_label('Phone', 'phone'); echo form_input(array( 'name' => 'phone', 'id' => 'phone', 'placeholder' => ' Enter your phone number' )); echo form_hidden('user_id', $user->id); echo form_submit('submit' ,'Add address'); echo form_close(); ?> </div> </div> <div class="settingsDivs" id="thirdSettingsDiv" > <?php if ($addresses): ?> <p>Added shipping addresses:</p> <table class="addresses"> <thead> <tr> <th>Full name</th> <th>Address</th> <th>City</th> <th>Country</th> <th>State</th> <th>Zip code</th> <th>Phone</th> </tr> </thead> <tbody> <?php foreach ($addresses as $address): ?> <tr> <td><?php echo $address->full_name; ?></td> <td><?php echo $address->address; ?></td> <td><?php echo $address->city; ?></td> <td><?php echo $address->country; ?></td> <td><?php echo $address->state; ?></td> <td><?php echo $address->zip_code; ?></td> <td><?php echo $address->phone; ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> <p>No addresses added!</p> <?php endif; ?> </div> </div> </fieldset> </div> <?php require('Footer.php'); ?>
kbuglow/intshop
application/views/shop/settings.php
PHP
mit
6,625
<?php return [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session", "token" | */ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => false, ], ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => ALttP\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ], ];
sporchia/alttp_vt_randomizer
config/auth.php
PHP
mit
3,280
class TwitterHandle < ActiveRecord::Base belongs_to :topic has_many :tweets validates :twitter_handle, presence: true end
tweet-squared/Tweets-Squared-App
app/models/twitter_handle.rb
Ruby
mit
132
$(document).ready(function () { var svgContainer = document.getElementById('svgContainer'); if (svgContainer) { var mama = new bodymovin.loadAnimation({ wrapper: svgContainer, autoplay: false, animType: 'svg', loop: false, name: 'test', animationData: JSON.parse(animationData) }); mama.play('test'); mama.setSpeed(1.5, 'test'); mama.setDirection(1, 'test'); $("#svgContainer").mouseenter(function () { mama.stop(); mama.play('test'); mama.setSpeed(1.5, 'test'); mama.setDirection(1, 'test'); }); } });
soywod/MAD
public/js/index.js
JavaScript
mit
697
"use strict" // String interpolation: supports string interpolation via template literals let first = 'Jon'; let last = 'Smith'; console.log(`Hello ${first} ${last}!`); // Hello Jon Smith // Multi-line string const multiLine = ` This is a string with four lines`; console.log (multiLine); // This is // a string // with four // lines
dlinaz/Simple-es6
src/stringFeatures.js
JavaScript
mit
350
namespace DemoForum.Data.Migrations { using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<DemoForum.Data.MsSqlDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(MsSqlDbContext context) { const string AdministratorUserName = "info@telerikacademy.com"; const string AdministratorPassword = "123456"; this.SeedAdmin(context, AdministratorUserName, AdministratorPassword); this.SampleData(context, AdministratorUserName); } private void SeedAdmin(MsSqlDbContext context, string AdministratorUserName, string AdministratorPassword) { if (!context.Roles.Any()) { var roleName = "Admin"; var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var role = new IdentityRole { Name = roleName }; roleManager.Create(role); var userStore = new UserStore<User>(context); var userManager = new UserManager<User>(userStore); var user = new User { UserName = AdministratorUserName, Email = AdministratorUserName, EmailConfirmed = true, CreatedOn = DateTime.Now }; userManager.Create(user, AdministratorPassword); userManager.AddToRole(user.Id, roleName); } } private void SampleData(MsSqlDbContext context, string userName) { if (!context.Posts.Any()) { for (int i = 0; i < 5; i++) { var post = new Post() { Title = "Post " + i, Content = "Bacon ipsum dolor amet brisket jowl shankle meatloaf salami biltong jerky shoulder drumstick, ball tip bresaola prosciutto ham hock venison. Swine tail prosciutto meatloaf, sausage pork belly kevin pork chop.", Author = context.Users.First(x => x.Email == userName), CreatedOn = DateTime.Now }; context.Posts.Add(post); } } } } }
zachdimitrov/Learning_2017
ASP.NET-MVC/DemoForum/DemoForum.Data/Migrations/Configuration.cs
C#
mit
2,643
<?php return [ '@class' => 'Grav\\Common\\File\\CompiledYamlFile', 'filename' => '/Users/kenrickkelly/Sites/hokui/user/plugins/admin/languages/eu.yaml', 'modified' => 1527231007, 'data' => [ 'PLUGIN_ADMIN' => [ 'ADMIN_BETA_MSG' => 'Beta bertsio bat da hau! Produkzioan erabili ezazu zure ardurapean...', 'ADMIN_REPORT_ISSUE' => 'Arazoren bat topatu duzu? Mesedez, horren berri eman GitHub-en.', 'EMAIL_FOOTER' => '<a href="http://getgrav.org">Grav-ekin eginda</a> - Fitxategi lauzko CMS modernoa', 'LOGIN_BTN' => 'Sartu', 'LOGIN_BTN_FORGOT' => 'Ahaztu', 'LOGIN_BTN_RESET' => 'Berrezarri pasahitza', 'LOGIN_BTN_SEND_INSTRUCTIONS' => 'Bidali reset egiteko argibideak', 'LOGIN_BTN_CLEAR' => 'Garbitu inprimakia', 'LOGIN_BTN_CREATE_USER' => 'Sortu erabiltzailea', 'LOGIN_LOGGED_IN' => 'Saioa arrakastaz hastea lortu duzu', 'LOGIN_FAILED' => 'Akatsa sartzerakoan', 'LOGGED_OUT' => 'Saiotik irten zara', 'RESET_NEW_PASSWORD' => 'Mesedez sartu pasahitz berri bat &hellip;', 'RESET_LINK_EXPIRED' => 'Reset egiteko esteka iraungi da, mesedez saiatu berriro', 'RESET_PASSWORD_RESET' => 'Pasahitza berrezarri da', 'RESET_INVALID_LINK' => 'Reset egiteko esteka baliogabea, mesedez saiatu berriro', 'FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL' => 'Zure pasahitza berriz ezartzeko argibideak zure helbide elektronikora bidali dira', 'FORGOT_FAILED_TO_EMAIL' => 'Akatsa argibideak posta elektroniko bidez bidaltzean, mesedez saiatu berriro beranduago', 'FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL' => 'Ezinezkoa da pasahitza berriro ezartzea %s-rentzat, ez da helbide elektronikorik ezarri', 'FORGOT_USERNAME_DOES_NOT_EXIST' => '<b>%s</b> erabiltzailea ez da existitzen', 'FORGOT_EMAIL_NOT_CONFIGURED' => 'Ezin da pasahitza berrezarri. Gune hau ez dago konfiguratuta mezu elektronikoak bidaltzeko', 'FORGOT_EMAIL_SUBJECT' => '%s Pasahitza Berrezartzeko Eskaera', 'FORGOT_EMAIL_BODY' => '<h1>Pazahitza berrezarketa</h1><p>%1$s estimatua,</p><p>Eskaera egin da <b>%4$s</b> zure pasahitza berrezartzeko.</p><p><br /><a href="%2$s" class="btn-primary">Klik egin hemen zure pasahitza berrezartzeko</a><br /><br /></p><p>Edo bestela kopiatu hurrengo URLa zure nabigatzailearen helbide barran</p> <p>%2$s</p><p><br />Begirunez,<br /><br />%3$s</p>', 'MANAGE_PAGES' => 'Orrialdeak Kudeatu', 'CONFIGURATION' => 'Konfigurazioa', 'PAGES' => 'Orrialdeak', 'PLUGINS' => 'Pluginak', 'PLUGIN' => 'Plugina', 'THEMES' => 'Itxurak', 'LOGOUT' => 'Irten', 'BACK' => 'Itzuli', 'ADD_PAGE' => 'Gehitu orrialdea', 'ADD_MODULAR' => 'Gehitu modulua', 'MOVE' => 'Mugitu', 'DELETE' => 'Ezabatu', 'SAVE' => 'Gorde', 'NORMAL' => 'Normala', 'EXPERT' => 'Aditua', 'EXPAND_ALL' => 'Guztia Zabaldu', 'COLLAPSE_ALL' => 'Tolestu dena', 'ERROR' => 'Errorea', 'CLOSE' => 'Itxi', 'CANCEL' => 'Utzi', 'CONTINUE' => 'Jarraitu', 'MODAL_DELETE_PAGE_CONFIRMATION_REQUIRED_TITLE' => 'Egiaztapena Beharrezkoa da', 'MODAL_CHANGED_DETECTED_TITLE' => 'Aldaketak Aurkituta', 'MODAL_CHANGED_DETECTED_DESC' => 'Gorde gabeko aldaketak dauzkazu. Ziur al zaude irten nahi duzula?', 'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_TITLE' => 'Egiaztapena Beharrezkoa da', 'MODAL_DELETE_FILE_CONFIRMATION_REQUIRED_DESC' => 'Ziur al zaude fitxategi hau ezabatu nahi duzula? Ekintza hau ezingo da desegin.', 'ADD_FILTERS' => 'Iragazkiak gehitu', 'SEARCH_PAGES' => 'Orrialdeak Bilatu', 'VERSION' => 'Bertsioa', 'UPDATE_THEME' => 'Itxura Eguneratu', 'UPDATE_PLUGIN' => 'Plugina Eguneratu', 'AUTHOR' => 'Egilea', 'HOMEPAGE' => 'Hasiera Orrialdea', 'DEMO' => 'Demo', 'BUG_TRACKER' => 'Akatsen Jarraitzailea', 'KEYWORDS' => 'Hitz gakoak', 'LICENSE' => 'Lizentzia', 'DESCRIPTION' => 'Deskribapena', 'README' => 'Irakur nazazu', 'REMOVE_THEME' => 'Itxura Ezabatu', 'INSTALL_THEME' => 'Itxura instalatu', 'THEME' => 'Itxura', 'BACK_TO_THEMES' => 'Itxuretara Itzuli', 'BACK_TO_PLUGINS' => 'Pluginetara Itzuli', 'CHECK_FOR_UPDATES' => 'Begiratu Eguneraketak', 'ADD' => 'Gehitu', 'CLEAR_CACHE' => 'Garbitu Katxea', 'CLEAR_CACHE_ALL_CACHE' => 'Katxe Guztia', 'CLEAR_CACHE_ASSETS_ONLY' => 'Asset-ak Bakarrik', 'CLEAR_CACHE_IMAGES_ONLY' => 'Irudiak Bakarrik', 'CLEAR_CACHE_CACHE_ONLY' => 'Katxea Bakarrik', 'CLEAR_CACHE_TMP_ONLY' => 'Tmp Bakarrik', 'DASHBOARD' => 'Arbela', 'UPDATES_AVAILABLE' => 'Eguneraketak Eskuragarri', 'DAYS' => 'Egun', 'UPDATE' => 'Eguneratu', 'BACKUP' => 'Segurtasun kopia', 'STATISTICS' => 'Estatistikak', 'TODAY' => 'Gaur', 'WEEK' => 'Astea', 'MONTH' => 'Hilabetea', 'LATEST_PAGE_UPDATES' => 'Eguneratutako Azken Orrialdeak', 'MAINTENANCE' => 'Mantenua', 'UPDATED' => 'Eguneratuta', 'MON' => 'Al.', 'TUE' => 'Ar.', 'WED' => 'Az.', 'THU' => 'Og.', 'FRI' => 'Ol.', 'SAT' => 'Lr.', 'SUN' => 'Ig.', 'COPY' => 'Kopiatu', 'EDIT' => 'Editatu', 'CREATE' => 'Sortu', 'GRAV_ADMIN' => 'Grav Admin', 'GRAV_OFFICIAL_PLUGIN' => 'Grav-en Plugin Ofiziala', 'GRAV_OFFICIAL_THEME' => 'Grav-en Itxura Ofiziala', 'PLUGIN_SYMBOLICALLY_LINKED' => 'Plugin hau sinbolikoki estekatuta dago. Eguneraketak ezingo dira aurkitu.', 'THEME_SYMBOLICALLY_LINKED' => 'Plugin hau sinbolikoki estekatuta dago. Eguneraketak ezingo dira aurkitu', 'REMOVE_PLUGIN' => 'Plugina Ezabatu', 'INSTALL_PLUGIN' => 'Plugina instalatu', 'AVAILABLE' => 'Eskuragarri', 'INSTALLED' => 'Instalatuta', 'INSTALL' => 'Instalatu', 'ACTIVE_THEME' => 'Itxura Aktiboa', 'SWITCHING_TO_DESCRIPTION' => 'Itxura ezberdin batera aldatuz gero, ezingo da ziurtatu orrialdeen egiturak ondo eutsiko dutenik, potentzialki erroreak eragingo dituzte orrialdeak kargatzen saiatzean.', 'SWITCHING_TO_CONFIRMATION' => 'Jarraitu eta Itxura aldatu nahi al duzu', 'CREATE_NEW_USER' => 'Erabiltzaile Berri Bat Sortu', 'REMOVE_USER' => 'Erabiltzailea Ezabatu', 'ACCESS_DENIED' => 'Sarbide debekatua', 'ACCOUNT_NOT_ADMIN' => 'zure kontuak ez dauka administratzaile baimenik', 'PHP_INFO' => 'PHP Info', 'INSTALLER' => 'Instalatzaile', 'AVAILABLE_THEMES' => 'Eskuragarri Dauden Itxurak', 'AVAILABLE_PLUGINS' => 'Eskuragarri Dauden Pluginak', 'INSTALLED_THEMES' => 'Instalatutako Itxurak', 'INSTALLED_PLUGINS' => 'Instalatutako Pluginak', 'BROWSE_ERROR_LOGS' => 'Begiratu Errore Erregistroa', 'SITE' => 'Gunea', 'INFO' => 'Info', 'SYSTEM' => 'Sistema', 'USER' => 'Erabiltzailea', 'ADD_ACCOUNT' => 'Gehitu Kontua', 'SWITCH_LANGUAGE' => 'Aldatu Hizkuntza', 'SUCCESSFULLY_ENABLED_PLUGIN' => 'Plugina ondo gaitu da', 'SUCCESSFULLY_DISABLED_PLUGIN' => 'Plugina ondo desgaitu da', 'SUCCESSFULLY_CHANGED_THEME' => 'Itxura lehenetsia ondo aldatu da', 'INSTALLATION_FAILED' => 'Instalazioak huts egin du', 'INSTALLATION_SUCCESSFUL' => 'Instalazioa ondo egin da', 'UNINSTALL_FAILED' => 'Desinstalazioak huts egin du', 'UNINSTALL_SUCCESSFUL' => 'Desinstalazioa ondo egin da', 'SUCCESSFULLY_SAVED' => 'Ondo gorde da', 'SUCCESSFULLY_COPIED' => 'Ondo kopiatu da', 'REORDERING_WAS_SUCCESSFUL' => 'Ordenaren aldaketa ondo egin da', 'SUCCESSFULLY_DELETED' => 'Ondo ezabatu da', 'SUCCESSFULLY_SWITCHED_LANGUAGE' => 'Hizkuntza ondo aldatu da', 'INSUFFICIENT_PERMISSIONS_FOR_TASK' => 'Ez daukazu bahimen nahikorik zereginerako', 'CACHE_CLEARED' => 'Katxea garbituta', 'METHOD' => 'Metodoa', 'ERROR_CLEARING_CACHE' => 'Errorea katxea garbitzean', 'AN_ERROR_OCCURRED' => 'Errore bat gertatu da', 'YOUR_BACKUP_IS_READY_FOR_DOWNLOAD' => 'Zure segurtasun kopia deskargatzeko prest dago', 'DOWNLOAD_BACKUP' => 'Segurtasun kopia deskargatu', 'PAGES_FILTERED' => 'Orrialdeak iragazita', 'NO_PAGE_FOUND' => 'Ez da Orrialderik aurkitu', 'INVALID_PARAMETERS' => 'Baliogabeko Parametroak', 'NO_FILES_SENT' => 'Fitxategirik ez da bidali', 'EXCEEDED_FILESIZE_LIMIT' => 'PHP konfigurazio fitxategiaren tamainaren muga gainditu da', 'UNKNOWN_ERRORS' => 'Errore ezezagunak', 'EXCEEDED_GRAV_FILESIZE_LIMIT' => 'Grav konfigurazio fitxategiaren tamainaren muga gainditu da', 'UNSUPPORTED_FILE_TYPE' => 'Fitxategi mota bateraezina', 'FAILED_TO_MOVE_UPLOADED_FILE' => 'Akatsa igotako fitxategia mugitzean', 'FILE_UPLOADED_SUCCESSFULLY' => 'Fitxategia ondo igo da', 'FILE_DELETED' => 'Fitxategia ezabatuta', 'FILE_COULD_NOT_BE_DELETED' => 'Fitxategia ezin da ezabatu', 'FILE_NOT_FOUND' => 'Fitxategia ez da aurkitu', 'NO_FILE_FOUND' => 'Fitxategirik ez da aurkitu', 'GRAV_UPDATE_FAILED' => 'Grav eguneraketak huts egin du', 'EVERYTHING_UPDATED' => 'Dena eguneratuta', 'UPDATES_FAILED' => 'Eguneraketek huts egin dute', 'LAST_BACKUP' => 'Azkenengo babes kopia', 'FULL_NAME' => 'Izen osoa', 'USERNAME' => 'Erabiltzaile izena', 'EMAIL' => 'Helbide Elektronikoa', 'USERNAME_EMAIL' => 'Erabiltzaile izena edo helbide elektronikoa', 'PASSWORD' => 'Pasahitza', 'PASSWORD_CONFIRM' => 'Pasahitza egiaztatu', 'TITLE' => 'Izenburua', 'LANGUAGE' => 'Hizkuntza', 'ACCOUNT' => 'Kontua', 'EMAIL_VALIDATION_MESSAGE' => 'Benetako helbide elektroniko bat izan behar da', 'PASSWORD_VALIDATION_MESSAGE' => 'Pasahitzak zenbaki bat eta letra maiuskula eta minuskula bat eduki eduki behar du gutxienez, eta 8 edo karaktere gehiago', 'LANGUAGE_HELP' => 'Gogoko hizkuntza ezarri', 'MEDIA' => 'Media', 'DEFAULTS' => 'Lehenetsitakoak', 'SITE_TITLE' => 'Gunearen Izenburua', 'SITE_TITLE_PLACEHOLDER' => 'Gune osoko izenburua' ] ] ];
h0kui/hokui
cache/compiled/files/f9471ea96fca48eee43207f0cb30d8d6.yaml.php
PHP
mit
11,189
package us.grahn.trojanow.presentation.feed; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import us.grahn.trojanow.R; /** * An interface to display to display the default feed for the user. This will contain posts which * are made by pals and posts which are made by strangers. * * @us.grahn.class FeedInterface * @us.grahn.component FeedInterface * @us.grahn.tier Presentation */ public class FeedActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_feed); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_feed, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
dgrahn/csci578
client/app/src/main/java/us/grahn/trojanow/presentation/feed/FeedActivity.java
Java
mit
1,442
<?php namespace Library\WhatsApp\Connection\WhatsAPI; class rc4 { private $s; private $i; private $j; public function __construct($key, $drop) { $this->s = range(0, 255); for ($i = 0, $j = 0; $i < 256; $i++) { $k = ord($key{$i % strlen($key)}); $j = ($j + $k + $this->s[$i]) & 255; $this->swap($i, $j); } $this->i = 0; $this->j = 0; $this->cipher(range(0, $drop), 0, $drop); } public function cipher($data, $offset, $length) { $r = ''; for ($n = $length; $n > 0; $n--) { $this->i = ($this->i + 1) & 255; $this->j = ($this->j + $this->s[$this->i]) & 255; $this->swap($this->i, $this->j); $d = ord($data{$offset++}); $r .= chr($d ^ $this->s[($this->s[$this->i] + $this->s[$this->j]) & 255]); } return $r; } protected function swap($i, $j) { $c = $this->s[$i]; $this->s[$i] = $this->s[$j]; $this->s[$j] = $c; } }
flolas/WhatsAppZorron
Classes/Library/WhatsApp/Connection/WhatsAPI/RC4.php
PHP
mit
1,065
<?php /** * This file is part of the Loops framework. * * @author Lukas <lukas@loopsframework.com> * @license https://raw.githubusercontent.com/loopsframework/base/master/LICENSE * @link https://github.com/loopsframework/base * @link https://loopsframework.com/ * @version 0.1 */ namespace Loops; use IteratorAggregate; use Serializable; use Loops; use Loops\Renderer\CacheInterface; use Loops\Misc\AccessTrait; use Loops\Annotations\Access\ReadOnly; use Loops\Annotations\Access\ReadWrite; use Loops\Annotations\Access\Expose; /** * An element that can be structured in hierarical trees * * Instances of the Loops\Element class largely define how Loops processes requests. The Loops\ElementInterface is implemented * and parent/name values are automatically updated. * The action method of the Loops\Element class implements the (recommended) way of how Loops processes request urls that have * been split into parameter. * * Loops\Element inherits from Loops\Object and implements all its magic Loops behaviour. It also implements the * Loops\Renderer\CacheInterface. The behaviour of this interface is quickly configurable by settings default properties or * overriding methods. * */ abstract class Element extends Object implements ElementInterface, CacheInterface { /** * @var string|FALSE Used by the action method to determine a default offset where a request may be forwarded to. * * @ReadOnly */ protected $delegate_action = FALSE; /** * @var bool Used by the action method to specify if the element accepts the request on default. * * See method action for details. */ protected $direct_access = FALSE; /** * @var bool Used by the action method to specify if the element accepts the request on default during an ajax request. * * See method action for details. */ protected $ajax_access = FALSE; /** * @var integer The renderer cache lifetime of this object in seconds. * @ReadWrite * * A negative value disabled the renderer cache. * 0 defines that the cache never expires. */ protected $cache_lifetime = -1; /** * @var string Magic access to ->getLoopsId() * @Expose * @ReadOnly("getLoopsId") */ protected $loopsid; /** * @var string Magic access to ->getPagePath() * @Expose * @ReadOnly("getPagePath") */ protected $pagepath; /** * @var mixed The creation context (see constructor) * @ReadOnly */ protected $context; /** * Can be returned from action methods for convinience */ const NO_OUTPUT = -1; private $__name = NULL; private $__parent = NULL; /** * The contructror * * A creation context can be passed to the constructor. It can be any value but should * be set to the object which is responsible of creating this instance. This is done * automatically when creating elements via loops annotations. * Usually this value will be the same as the parent object of this element. * * @param mixed $context The creation context * @param Loops\Context $loops The context that is used to resolve services. * * The content will default to the last Loops context. */ public function __construct($context = NULL, Loops $loops = NULL) { $this->context = $context; parent::__construct($loops); } /** * Generate the Loops id of this object. * * If the object has no parent use its hash as the Loops id. * Otherwise add its name to the parents Loops id separated with a dash * * @param string|NULL $refkey Defines the offset of a child which is requesting the Loops id * @return string The Loops id */ protected function __getLoopsId($refkey = NULL) { if($this->__parent) { return $this->__parent->__getLoopsId($this->__name)."-".$this->__name; } return spl_object_hash($this); } /** * Returns if the object is cacheable based on the cache_lifetime property. * * @return bool TRUE if the renderer chache should be used for this object. */ public function isCacheable() { return $this->cache_lifetime >= 0; } /** * Return the cacheid * * By default, the elements Loops ID is going to be used. * This method should be overridden if the appearance changes based on other factors. * * @return string The Cache ID */ public function getCacheId() { return $this->getLoopsId(); } /** * Returns the cache lifetime in seconds (=property cache_lifetime) * * @return integer The cache lifetime in seconds */ public function getCacheLifetime() { return $this->cache_lifetime; } /** * {@inheritdoc} */ public function getLoopsId() { return $this->__getLoopsId(); } /** * Adds an element into the hierarchy. * * This function is a simple wrapper for offsetSet but introduces type checking. * * @param string $name The name of the child element * @param Loops\Element $child The child element */ public function addChild($name, Element $child) { $this->offsetSet($name, $child); } /** * Internal use, an Element instances __parent and __name property are automatically updated * * @param string $name The name of the property where the Loops\Element is stored * @param mixed $child The value that is going to be checked and adjusted if it is a Loops\Element * @param bool $detacht Detach the element from its old parent if exists. * @return mixed The passed $child value */ protected function initChild($name, $child, $detach = FALSE) { if($child instanceof Element) { if($detach && $child->__parent && $child->__parent !== $this) { $child->detach(); } if(!$child->__parent) { $child->__parent = $this; $child->__name = $name; } } return $child; } /** * Automatically initializes child elements in case they were not initialized yet * * @param string $offset The element offset */ public function offsetGet($offset) { $value = parent::offsetGet($offset); return $offset === "context" ? $value : $this->initChild($offset, $value); } /** * Automatically initailizes child elements in case they were not initialized yet * * If a element was already set on another element object, it will be detached. * * @param string $offset The offset * @param mixed $value The value to be set at offset */ public function offsetSet($offset, $value) { parent::offsetSet($offset, $value); $this->initChild($offset, $value, TRUE); } /** * Automatically detaches child elements if they belong to this element * * @param string The offset */ public function offsetUnset($offset) { $detach = NULL; if(parent::offsetExists($offset)) { $child = parent::offsetGet($offset); if($child instanceof Element && $child->__parent === $this) { $detach = $child; } } parent::offsetUnset($offset); if($detach) { $detach->detach(); } } /** * A class internal way of iterating over class properties. * * Wrapper to the AccessTrait getGenerator method. * * @param bool $include_readonly Include values that have been marked with the {\@}ReadOnly or {\@}ReadWrite annotations. * @param bool $include_protected Also include protected values without annotations. * @param array Only include values with keys that are specified in this array. * @param array Exclude values with keys that are specified in this array. * @return Generator A generator that traverses over the requested values of this object. */ protected function getGenerator($include_readonly = FALSE, $include_protected = FALSE, $include = FALSE, $exclude = FALSE) { foreach(parent::getGenerator($include_readonly, $include_protected, $include, $exclude) as $key => $value) { yield $key => ($key === "context") ? $value : $this->initChild($key, $value); } } /** * Default action processing * * The default behaviour of an element is to not accept a request. * An element only accepts requests on default, when no parameter were passed and direct_access has been set to TRUE. * In an ajax call, it is also possible to set ajax_access to TRUE for accepting the request. The service request will * be checked if this currently is an ajax call. * The action method will return itself (rather than TRUE) when accepting a request. This makes it possible to determine * which (sub) element actually accepted the request. * * If parameters are given, the following logic can be used to determine if a request should be accepted: * 1. Take the first parameter and check for a method named "{param}Action", pass all parameters to it and use the resulting value. * If such a method does not exist or the value is NULL or FALSE do not accept the request, continue. * 2. Take the first parameter and check if there is another Loops\Element instance at the offset defined by the parameter (->offsetExists($param) & ->offsetGet($param)) * If such object exists execute that objects action, pass the rest of the parameter and use its return value, continue if it was NULL or FALSE. * 3. Check if the element defines a property delegate_action and, prepend it to the action parameters and apply step 2. * * @param array $parameter The action parameter. * @return mixed The processed value */ public function action($parameter) { $result = FALSE; if($parameter) { $name = $parameter[0]; $method_name = $name."Action"; if(method_exists($this, $method_name)) { $result = $this->$method_name(array_slice($parameter, 1)); } if(in_array($result, [FALSE, NULL], TRUE)) { if($parameter && $this->offsetExists($name)) { $child = $this->offsetGet($name); if($child instanceof ElementInterface) { $result = $child->action(array_slice($parameter, 1)); } } } } if(in_array($result, [FALSE, NULL], TRUE)) { if($this->delegate_action) { if($this->offsetExists($this->delegate_action)) { $child = $this->offsetGet($this->delegate_action); if($child instanceof ElementInterface) { $result = $child->action($parameter); } } } } if(in_array($result, [FALSE, NULL], TRUE)) { if(!$parameter) { if($this->direct_access) { $result = TRUE; } else { $loops = $this->getLoops(); if($loops->hasService("request") && $loops->getService("request")->isAjax() && $this->ajax_access) { $result = TRUE; } } } } if($result === TRUE) { $result = $this; } return $result; } /** * Reset the internal caching mechanism of the parent element and name. * This may be needed if you want to assign the element on a different object. * * @return Loops\Element Returns $this for method chaining. */ public function detach() { if($this->__parent) { $this->__parent->offsetUnset($this->__name); } $this->__parent = NULL; $this->__name = NULL; return $this; } /** * Returns the parent elemenet * * @return Loops\Element The parent object or FALSE if the element has no parent. */ public function getParent() { return $this->__parent ?: FALSE; } /** * Returns the offset name with which this object can be accessed from its parent object. * * @return string|FALSE Returns FALSE if the element has no parent. */ public function getName() { return $this->__parent ? $this->__name : FALSE; } /** * Returns the page path of this object. (See documentation of Loops\ElementInterface for details) * * If the element has no parent or is not present in a hierachy with a page element at the top, no * page path can be generated and FALSE is returned. * * @return string */ public function getPagePath() { if(!$this->__parent) { return FALSE; } $pagepath = $this->__parent->getPagePath(); if($pagepath === FALSE) { return FALSE; } if($this->__parent->delegate_action == $this->__name) { return $pagepath; } return ltrim(rtrim($pagepath, "/")."/".$this->__name, "/"); } /** * Returns FALSE on default * * @return false */ public static function isPage() { return FALSE; } }
loopsframework/base
src/Loops/Element.php
PHP
mit
13,526
namespace More.Windows.Controls { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Windows.Controls; /// <summary> /// Represents a mediator that can coordinate columns between a /// <see cref="DataGrid">data grid</see> and a <see cref="IList">list</see>. /// </summary> sealed class ColumnsMediator : IDisposable { volatile bool disposed; volatile bool suppressCollectionChanged; volatile bool suppressColumnsChanged; DataGrid dataGrid; ICollection<DataGridColumn> columns; INotifyCollectionChanged columnEvents; #pragma warning disable SA1401 // Fields should be private internal readonly long Key; #pragma warning restore SA1401 // Fields should be private internal ColumnsMediator( DataGrid dataGrid, IEnumerable<DataGridColumn> sequence, INotifyCollectionChanged columnEvents ) { Contract.Requires( dataGrid != null ); Contract.Requires( sequence != null ); Contract.Requires( columnEvents != null ); Key = CreateKey( dataGrid, sequence ); columns = sequence as ICollection<DataGridColumn>; this.columnEvents = columnEvents; this.columnEvents.CollectionChanged += OnCollectionChanged; this.dataGrid = dataGrid; // if the provided sequence isn't a collection, then mediation is one-way. // the sequence can notify the data grid, but not the other way around. if ( columns != null ) { this.dataGrid.Columns.CollectionChanged += OnColumnsChanged; } } bool IsSuppressingEvents => suppressColumnsChanged || suppressCollectionChanged; void Dispose( bool disposing ) { if ( disposed ) { return; } disposed = true; if ( !disposing ) { return; } if ( dataGrid != null ) { dataGrid.Columns.CollectionChanged -= OnColumnsChanged; dataGrid = null; } if ( columnEvents != null ) { columnEvents.CollectionChanged -= OnCollectionChanged; columnEvents = null; } columns = null; } internal static long CreateKey( DataGrid dataGrid, object items ) { Contract.Requires( dataGrid != null ); var hash = ( dataGrid.GetHashCode() << 32 ) | ( items == null ? 0 : items.GetHashCode() ); return hash; } static void SynchronizeCollection( ICollection<DataGridColumn> columns, NotifyCollectionChangedEventArgs e, bool fastClear ) { Contract.Requires( columns != null ); Contract.Requires( e != null ); if ( e.Action == NotifyCollectionChangedAction.Reset ) { if ( fastClear ) { columns.Clear(); } else { // HACK: yet another blunder in the DataGrid (at least for Silverlight). I'm assuming this will hold true in WPF // as well. Calling Clear() on the DataGrid.Columns property does not correctly calculate it's internal indexes. An // ArgumentOutOfRangeException is thrown from an internal List<T>, but it's difficult to say what the exact problem is. // Through trial and error, removing columns one at a time proved to produce reliable results; therefore, this branch of // the code uses Remove() or RemoveAt() instead of Clear(). if ( columns is IList<DataGridColumn> list ) { for ( var i = list.Count - 1; i > -1; i-- ) { list.RemoveAt( i ); } } else { list = new List<DataGridColumn>( columns ); for ( var i = list.Count - 1; i > -1; i-- ) { columns.Remove( list[i] ); } } } return; } if ( e.OldItems != null ) { foreach ( DataGridColumn column in e.OldItems ) { columns.Remove( column ); } } if ( e.NewItems != null ) { foreach ( DataGridColumn column in e.NewItems ) { if ( !columns.Contains( column ) ) { columns.Add( column ); } } } } void OnColumnsChanged( object sender, NotifyCollectionChangedEventArgs e ) { if ( IsSuppressingEvents ) { return; } suppressCollectionChanged = true; SynchronizeCollection( columns, e, true ); suppressCollectionChanged = false; } void OnCollectionChanged( object sender, NotifyCollectionChangedEventArgs e ) { if ( IsSuppressingEvents ) { return; } suppressColumnsChanged = true; SynchronizeCollection( dataGrid.Columns, e, false ); suppressColumnsChanged = false; } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } } }
commonsensesoftware/More
src/More.UI.Presentation/Platforms/net45/More/Windows.Controls/ColumnsMediator.cs
C#
mit
5,912
<form method="POST" action="<?= URL ;?>users/update/<?= $data['news']->id;?>"> <div class="modal-content"> <h4>Modifier l'utilisateur : <?= $data['user']->pseudo; ?></h4> <input type="hidden" name="user_id" value="<?= $data['user']->id; ?>"> <div class="row"> <div class="input-field col s12"> <input id="pseudo" type="text" name="pseudo" value="<?= $data['user']->pseudo; ?>"> <label class="active" for="pseudo">Pseudo</label> </div> </div> <div class="row"> <div class="input-field col s6"> <input id="first_name" type="text" name="first_name" value="<?= $data['user']->prenom; ?>"> <label class="active" for="first_name">Prénom</label> </div> <div class="input-field col s6"> <input id="last_name" type="text" name="last_name" value="<?= $data['user']->nom; ?>"> <label class="active" for="last_name">Nom</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input id="email" type="email" name="email" class="validate" value="<?= $data['user']->mail; ?>"> <label class="active" for="email">Email</label> </div> </div> <div class="row"> Admin : <div class="switch"> <label> Off <?php $checked = ''; if($data['user']->admin == 1) { $checked = 'checked'; } ?> <input type="checkbox" name="admin" <?= $checked;?>> <span class="lever"></span> On </label> </div> </div> </div> <div class="modal-footer"> <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </div> </form>
HelleboidQ/projetphpgghq
app/views/admin/edit_user.php
PHP
mit
2,071