repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
lajosbencz/phalcon-hint-generator | phalcon-ide/2.0.5.4/Phalcon/Debug/Dump.php | 2409 | <?php
namespace Phalcon\Debug;
class Dump
{
protected $_detailed = false;
public function getDetailed() {
return $this->_detailed;
}
public function setDetailed($value) {
$this->_detailed = $value;
}
protected $_methods = null;
protected $_styles;
/**
* Phalcon\Debug\Dump constructor
*
* @param array $styles
* @param boolean $detailed
* @param \boolean detailed debug $object
*
*/
public function __construct(array $styles=null, $detailed=false) {}
/**
* Alias of variables() method
*
* @param mixed variable
* @param ...
*
* @return string
*/
public function all() {}
/**
* Get style for type
*
* @param string $type
*
* @return string
*/
protected function getStyle($type) {}
/**
* Set styles for vars type
*
* @param mixed $styles
*
* @return array
*/
public function setStyles($styles=null) {}
/**
* Alias of variable() method
*
* @param mixed $variable
* @param string $name
*
* @return string
*/
public function one($variable, $name=null) {}
/**
* Prepare an HTML string of information about a single variable.
*
* @param mixed $variable
* @param string $name
* @param int $tab
*
* @return string
*/
protected function output($variable, $name=null, $tab=1) {}
/**
* Returns an HTML string of information about a single variable.
*
* <code>
* echo (new \Phalcon\Debug\Dump())->variable($foo, "foo");
* </code>
*
* @param mixed $variable
* @param string $name
*
* @return string
*/
public function variable($variable, $name=null) {}
/**
* Returns an HTML string of debugging information about any number of
* variables, each wrapped in a "pre" tag.
*
* <code>
* $foo = "string";
* $bar = ["key" => "value"];
* $baz = new stdClass();
* echo (new \Phalcon\Debug\Dump())->variables($foo, $bar, $baz);
*</code>
*
* @param mixed variable
* @param ...
*
* @return string
*/
public function variables() {}
/**
* Returns an JSON string of information about a single variable.
*
* <code>
* $foo = ["key" => "value"];
* echo (new \Phalcon\Debug\Dump())->toJson($foo);
* $foo = new stdClass();
* $foo->bar = 'buz';
* echo (new \Phalcon\Debug\Dump())->toJson($foo);
* </code>
*
* @param mixed $variable
*
*
* @return string
*/
public function toJson($variable) {}
}
| mit |
nico01f/z-pec | ZimbraClient/src/java/com/zimbra/client/event/ZModifyVoiceMailItemEvent.java | 1504 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2007, 2008, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.client.event;
import com.zimbra.common.service.ServiceException;
public class ZModifyVoiceMailItemEvent implements ZModifyItemEvent {
private String mId;
private boolean mIsHeard;
private boolean mMadeChange;
public ZModifyVoiceMailItemEvent(String id, boolean isHeard) throws ServiceException {
mId = id;
mIsHeard = isHeard;
mMadeChange = false;
}
/**
* @return id
*/
public String getId() throws ServiceException {
return mId;
}
/**
* @return true if item has been heard
*/
public boolean getIsHeard() {
return mIsHeard;
}
/**
* Makes note that something actually changed. Used when marking (un)heard
* so that we can try to keep track of the folder's unheard count,
* which is never updated by the server.
*/
public void setMadeChange() {
mMadeChange = true;
}
/**
* Returns true if something actually changed.
*/
public boolean getMadeChange() {
return mMadeChange;
}
}
| mit |
BathnesDevelopment/Public-Art-Website | scripts/map.js | 8967 | ////////////////////////////////////////////////////////////
// Site.js: Handles general page loading and functionality
// Created: 17th Feb 2016.
////////////////////////////////////////////////////////////
$(function () {
//////////////////
// MAP setup
// Uses CartoDB positron
//////////////////
var layer = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: '© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://cartodb.com/attributions">CartoDB</a>'
});
var map = L.map('map', {
scrollWheelZoom: false,
center: [51.38, -2.35],
zoom: 13
});
map.addLayer(layer);
///////////////////////////////////////////////////////////
// Load: GetFilteredData
// On loading the page
///////////////////////////////////////////////////////////
PublicArt.getFiltered(function () {
var uniqueCategories = {};
var uniqueArtists = {};
var markerArray = [];
$.each(PublicArt.dataset, function (key, value) {
var catList = '';
if (value.categories) {
$.each(value.categories, function (idx, cat) {
if (!uniqueCategories[cat.replace(/ /g, '')]) uniqueCategories[cat.replace(/ /g, '')] = { name: cat, count: 0 };
uniqueCategories[cat.replace(/ /g, '')]['count']++;
});
catList = value.categories.join('","');
}
var artistList = '';
if (value.artists) {
$.each(value.artists, function (idx, artist) {
if (!uniqueArtists[artist.name.replace(/ /g, '')]) uniqueArtists[artist.name.replace(/ /g, '')] = artist;
artistList += ',"' + artist.name + '"';
});
}
var photosLinks = '';
$.each(value.images, function (key, image) {
if (key == 0) photosLinks += '<a href="' + PublicArt.imageFullLocation + image.filename + '" id="btnImg1' + value.reference + '" class="btn btn-link btn-images" data-id="' + value.reference + '" data-gallery="' + value.reference + '" data-toggle="lightbox" data-title="' + value.title + '" data-footer="Image ' + (key + 1) + ' of ' + value.images.length + '<br>' + (image.caption ? image.caption : '') + '" data-target="#itemImages">View Photos</a>'
if (key != 0) photosLinks += '<a href="' + PublicArt.imageFullLocation + image.filename + '" class="btn btn-link" data-id="' + value.reference + '" data-gallery="' + value.reference + '" data-toggle="lightbox" data-title="' + value.title + '" data-footer="Image ' + (key + 1) + ' of ' + value.images.length + '<br>' + (image.caption ? image.caption : '') + '" data-target="#itemImages" style="display: none;">View Photos</a>'
});
var markerPopup = '<p class="lead">' + value.title + '</p>';
markerPopup += '<p>';
markerPopup += $.map(value.artists, function (i, a) {
return i.name
}).join(', ');
markerPopup += '</p>';
markerPopup += '<p>' + photosLinks + '</p>';
var markerStyle = ['red','cloud']
if (value.categories && value.categories[0]) markerStyle = getMarkerStyle(value.categories[0]);
var marker = L.AwesomeMarkers.icon({
icon: '',
markerColor: markerStyle[0]
});
if (value.lat && value.lng) markerArray.push(L.marker([value.lat, value.lng], { icon: marker }).bindPopup(markerPopup));
});
var group = L.featureGroup(markerArray).addTo(map);
// map.fitBounds(group.getBounds());
///////////////////////////////////////////////////////////
// Event: Show modal.
// On clicking the item it should launch the item modal
// and call the datastore to get the item detail.
///////////////////////////////////////////////////////////
$('#itemDetails').on('show.bs.modal', function (e) {
// Clear the existing modal
$('.modal-title').not('.modal-loading').text('');
$('#divTabContent #details').empty();
$('#divTabContent #measurements').empty();
$('#ulArtists').empty();
$('#divCategories').empty();
$('#divTabContent div[id^=artist]').remove();
$('#divTabContent #hLocation').text();
// Show the loader
$('.modal-loading').show();
$('a[href="#details"]').tab('show');
var id = $(e.relatedTarget).data('id');
PublicArt.getItem(id, function () {
// The artists display
if (PublicArt.dataset[id].artists) {
$.each(PublicArt.dataset[id].artists, function (key, val) {
$('#ulArtists').append('<li><a href="#artist' + key + '" data-toggle="tab">' + val.name + '</a></li><li class="divider></li>');
$('#divTabContent').append('<div class="tab-pane fade" id="artist' + key + '"><h5>' + (val.name ? val.name : '') + (val.startdate ? ' (' + val.startdate + '-' : '') + (val.enddate ? val.enddate + ' )' : '') + '</h5>' + (val.website ? '<p><a target="_blank" href=' + val.website + '>' + val.website + '</a></p>' : '') + '<p>' + (val.biography ? val.biography : '') + '</p></div>');
});
}
// The title (incl date).
$('.modal-title').not('.modal-loading').text((PublicArt.dataset[id].date ? PublicArt.dataset[id].date + ' - ' : '') + PublicArt.dataset[id].title);
// The categories labels
if (PublicArt.dataset[id].categories) {
$.each(PublicArt.dataset[id].categories, function (key, cat) {
$('#divCategories').append('<span class="label label-' + getBootstrapColour(cat) + '">' + cat + '</span> ');
});
}
// The main details tab.
if (PublicArt.dataset[id].description) $('#divTabContent #details').append('<h5>Description</h5><p>' + PublicArt.dataset[id].description + '</p>');
if (PublicArt.dataset[id].history) $('#divTabContent #details').append('<h5>History</h5><p>' + PublicArt.dataset[id].history + '</p>');
if (PublicArt.dataset[id].unveilingyear) $('#divTabContent #details').append('<h5>Unveiling</h5><p>' + PublicArt.dataset[id].unveilingyear + (PublicArt.dataset[id].unveilingdetails ? ', ' + PublicArt.dataset[id].unveilingdetails : '') + '</p>');
if (PublicArt.dataset[id].statement) $('#divTabContent #details').append('<h5>Artist statement</h5><p>' + PublicArt.dataset[id].statement + '</p>');
// The location tab.
if (PublicArt.dataset[id].address) $('#divTabContent #location #pLocation').text(PublicArt.dataset[id].address);
// The physical details tab.
if (PublicArt.dataset[id].inscription) $('#divTabContent #measurements').append('<h5>Inscription</h5><p>' + PublicArt.dataset[id].inscription + '</p>');
if (PublicArt.dataset[id].material) $('#divTabContent #measurements').append('<h5>Material</h5><p>' + PublicArt.dataset[id].material + '</p>');
// The measurements
var dimensionsTable = '<table class="table"><thead><tr><th>Height (cm)</th><th>Width (cm)</th><th>Depth (cm)</th><th>Diameter (cm)</th></tr></thead><tbody><tr><td>' + PublicArt.dataset[id].height + '</td><td>' + (PublicArt.dataset[id].width ? PublicArt.dataset[id].width : '') + '</td><td>' + (PublicArt.dataset[id].depth ? PublicArt.dataset[id].depth : '') + '</td><td>' + (PublicArt.dataset[id].diameter ? PublicArt.dataset[id].diameter : '') + '</td></tr></tbody></table>';
$('#divTabContent #measurements').append('<h5>Measurements</h5>' + dimensionsTable);
// To do: would quite like to do some graphical representation showing the dimensions
$('.modal-loading').hide();
});
});
///////////////////////////////////////////////////////////
// OnLoad: Show modal.
///////////////////////////////////////////////////////////
var getParameterByName = function (name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
};
if (window.location.href.indexOf('id') != -1) {
$('[data-ref=' + getParameterByName('id') + ']').click();
}
});
}); | mit |
Grimace1975/bclcontrib-web | System.WebEx/Web+Routing/Routing+Dynamic/DynamicRoute.cs | 7769 | #region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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.
*/
#endregion
using System.Linq;
using System.Collections.Generic;
namespace System.Web.Routing
{
/// <summary>
/// DynamicRoute
/// </summary>
public class DynamicRoute : Route
{
private readonly IDynamicRoutingContext _routingContextAsFixed;
private Func<DynamicRoute, IDynamicRoutingContext> _routingContext;
public DynamicRoute()
: this(new SiteMapDynamicRoutingContext((ISiteMapProvider)SiteMap.Provider)) { }
public DynamicRoute(ISiteMapProvider siteMapProvider)
: this(new SiteMapDynamicRoutingContext(siteMapProvider)) { }
public DynamicRoute(SiteMapProvider siteMapProvider)
: this((ISiteMapProvider)siteMapProvider) { }
public DynamicRoute(IDynamicRoutingContext routingContext)
: base(null, null)
{
_routingContextAsFixed = routingContext;
RoutingContext = (r => _routingContextAsFixed);
}
public DynamicRoute(Func<DynamicRoute, IDynamicRoutingContext> routingContext)
: base(null, null)
{
RoutingContext = routingContext;
}
public static void SetRouteDefaults(IEnumerable<Route> routes, IDynamicNode node)
{
var id = node.Key;
foreach (var route in routes)
{
route.DataTokens["dynamicID"] = id;
route.DataTokens["dynamicNode"] = node;
route.Defaults["dynamicID"] = id;
}
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
var httpRequest = httpContext.Request;
// virtualPath modeled from Route::GetRouteData
var virtualPath = httpRequest.AppRelativeCurrentExecutionFilePath.Substring(1) + httpRequest.PathInfo;
//var requestUri = _siteMapExRouteContext.GetRequestUri(httpContext);
var node = GetNode(_routingContext(this), virtualPath);
if (node != null)
{
// func
var func = node.Get<Func<IDynamicNode, RouteData>>();
if (func != null)
return func(node);
// single
var route = node.Get<Route>();
if (route != null)
return route.GetRouteData(httpContext);
// many
var multiRoutes = node.GetMany<Route>();
if (multiRoutes != null)
foreach (var multiRoute in multiRoutes)
{
var data = multiRoute.GetRouteData(httpContext);
if (data != null)
return data;
}
}
return null;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
if (requestContext == null)
throw new ArgumentNullException("requestContext");
var node = GetNode(_routingContext(this), values, true);
if (node != null)
{
// func
var func = node.Get<Func<IDynamicNode, VirtualPathData>>();
if (func != null)
return func(node);
// single
var route = node.Get<Route>();
if (route != null)
return route.GetVirtualPath(requestContext, values);
// many
var multiRoutes = node.GetMany<Route>();
if (multiRoutes != null)
foreach (var multiRoute in multiRoutes)
{
var path = multiRoute.GetVirtualPath(requestContext, values);
if (path != null)
return path;
}
}
return null;
}
public Func<DynamicRoute, IDynamicRoutingContext> RoutingContext
{
get { return _routingContext; }
set
{
if (value == null)
throw new ArgumentNullException("value");
_routingContext = value;
}
}
private static IDynamicNode GetNode(IDynamicRoutingContext routingContext, string path) { return routingContext.FindNode(path); }
private static IDynamicNode GetNode(IDynamicRoutingContext routingContext, RouteValueDictionary values, bool removeDynamicID)
{
object value;
string valueAsString;
if (values.TryGetValue("controller", out value) && (valueAsString = (value as string)) != null && valueAsString.StartsWith("#"))
{
var node = routingContext.FindNodeByID(valueAsString.Substring(1));
if (node != null)
{
values["controller"] = GetControllerNameFromNode(node);
if (removeDynamicID)
values.Remove("dynamicID");
}
return node;
}
if (values.TryGetValue("dynamicID", out value) && (valueAsString = (value as string)) != null)
{
var node = routingContext.FindNodeByID(valueAsString);
if (node != null)
{
values["controller"] = GetControllerNameFromNode(node);
if (removeDynamicID)
values.Remove("dynamicID");
}
return node;
}
return null;
}
private static string GetControllerNameFromNode(IDynamicNode node)
{
// func
var func = node.Get<Func<IDynamicNode, RouteData>>();
if (func != null)
throw new InvalidOperationException("Controller name: Func not allowed");
// single | many
var route = node.Get<Route>();
if (route == null)
{
var multiRoutes = node.GetMany<Route>();
if (multiRoutes != null)
route = multiRoutes.FirstOrDefault();
}
if (route != null)
return (string)route.Defaults["controller"];
throw new InvalidOperationException("No controller set for node");
}
}
}
| mit |
HMNikolova/Telerik_Academy | WebDesign/homework js/1. JavaScript Fundamentals/3. Conditional Statements/05.DigitAsWord/DigitAsWord.js | 1643 | /* Problem 5. Digit as word
Write a script that asks for a digit (0-9), and depending on the input, shows the digit as a word (in English).
Print “not a digit” in case of invalid input.
Use a switch statement.
Examples:
digit result
2 two
1 one
0 zero
5 five
-0.1 not a digit
hi not a digit
9 nine
10 not a digit
*/
//Feel free to add or remove numbers
var numbers = [2, 1, 0, 5, -0.1, 'hi', 9, 10],
loops = numbers.length,
i;
for (i = 0; i < loops; i += 1) {
LogDigit(numbers[i]);
}
function LogDigit(number) {
switch (number) {
case 0:
console.log('Digit in ' + number + ' is Zero');
break;
case 1:
console.log('Digit in ' + number + ' is One');
break;
case 2:
console.log('Digit in ' + number + ' is Two');
break;
case 3:
console.log('Digit in ' + number + ' is Three');
break;
case 4:
console.log('Digit in ' + number + ' is Four');
break;
case 5:
console.log('Digit in ' + number + ' is Five');
break;
case 6:
console.log('Digit in ' + number + ' is Six');
break;
case 7:
console.log('Digit in ' + number + ' is Seven');
break;
case 8:
console.log('Digit in ' + number + ' is Eigth');
break;
case 9:
console.log('Digit in ' + number + ' is Nine');
break;
default:
console.log('Digit in ' + number + ' is Not a Digit!');
break;
}
} | mit |
ambagasdowa/kml | cake/console/controllers/secure_presenters_controller.php | 2224 | <?php
class SecurePresentersController extends AppController {
var $name = 'SecurePresenters';
function index() {
$this->SecurePresenter->recursive = 0;
$this->set('securePresenters', $this->paginate());
}
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid secure presenter', true));
$this->redirect(array('action' => 'index'));
}
$this->set('securePresenter', $this->SecurePresenter->read(null, $id));
}
function add() {
if (!empty($this->data)) {
$this->SecurePresenter->create();
if ($this->SecurePresenter->save($this->data)) {
$this->Session->setFlash(__('The secure presenter has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The secure presenter could not be saved. Please, try again.', true));
}
}
$groups = $this->SecurePresenter->Group->find('list');
$users = $this->SecurePresenter->User->find('list');
$this->set(compact('groups', 'users'));
}
function edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid secure presenter', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->SecurePresenter->save($this->data)) {
$this->Session->setFlash(__('The secure presenter has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The secure presenter could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->SecurePresenter->read(null, $id);
}
$groups = $this->SecurePresenter->Group->find('list');
$users = $this->SecurePresenter->User->find('list');
$this->set(compact('groups', 'users'));
}
function delete($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for secure presenter', true));
$this->redirect(array('action'=>'index'));
}
if ($this->SecurePresenter->delete($id)) {
$this->Session->setFlash(__('Secure presenter deleted', true));
$this->redirect(array('action'=>'index'));
}
$this->Session->setFlash(__('Secure presenter was not deleted', true));
$this->redirect(array('action' => 'index'));
}
}
| mit |
AmrSaber/XC2 | Util/GUIServer.java | 558 | /*
* 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 Util;
/**
*
* @author amr
*/
public interface GUIServer {
public void connect();
public void disconnect();
public void setTime(String server_time, String duration);
public void addProblem(String id, String title);
public void removeProblems()throws Exception;
public void setStandingUrl(String url);
}
| mit |
billdueber/searchparser | lib/searchparser/boolean_skeleton.rb | 1942 | require 'searchparser/basics'
module SearchParser
# A simple little parser that defines AND/OR/NOT
# as the and_op, or_op, and not_op, respectively,
# surrounded by whitespace
class UppercaseEnglishOps < Parslet::Parser
include Basics
rule(:and_op) { space? >> str('AND') >> space? }
rule(:or_op) { space? >> str('OR') >> space? }
rule(:not_op) { space? >> str('NOT') >> space? }
end
# A partial parser that does correct operator precedence for AND/OR/NOT
# Set up as a module, so you can include it in another parser and
# just define a rule for :base and everything will work
#
# :base is the "thing" that is subjected to parenthesizing and
# boolean operations
module BooleanSkeleton
include Parslet
include Basics
DEFAULT_OP_PARSER = UppercaseEnglishOps.new
# By default, we use capitalized strings for AND OR NOT,
# but you can change this by passing in a parser that
# defines rules for :and_op, :or_op, and :not_op
# (so, for example, you could use '&&' and '||' if you want)
def setup_operators(op_parser: DEFAULT_OP_PARSER)
define_singleton_method(:and_op) { op_parser.and_op }
define_singleton_method(:or_op) { op_parser.or_op }
define_singleton_method(:not_op) { op_parser.not_op }
self
end
# But until you call setup_operators, use the defaults
rule(:and_op) { DEFAULT_OP_PARSER.and_op }
rule(:or_op) { DEFAULT_OP_PARSER.or_op }
rule(:not_op) { DEFAULT_OP_PARSER.not_op }
rule(:any_op) { not_op | or_op | and_op }
rule(:parens) { lp >> or_expr >> rp | base }
rule(:not_expr) { not_op >> parens.as(:not) | parens }
rule(:and_expr) { (not_expr.as(:left) >> and_op >> and_expr.as(:right)).as(:and) | not_expr }
rule(:or_expr) { (and_expr.as(:left) >> or_op >> or_expr.as(:right)).as(:or) | and_expr }
rule(:expr) { (or_expr >> not_expr.repeat(0)).as(:search) }
end
end
| mit |
yfeldblum/mongo-lock | lib/mongo/lock/version.rb | 59 | module Mongo
module Lock
VERSION = "0.0.1"
end
end
| mit |
BUCTdarkness/jedis | src/main/java/redis/clients/jedis/HostAndPort.java | 982 | package redis.clients.jedis;
public class HostAndPort {
public static final String LOCALHOST_STR = "localhost";
private String host;
private int port;
public HostAndPort(String host, int port) {
this.host = host;
this.port = port;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof HostAndPort) {
HostAndPort hp = (HostAndPort) obj;
String thisHost = convertHost(host);
String hpHost = convertHost(hp.host);
return port == hp.port &&
thisHost.equals(hpHost);
}
return false;
}
@Override
public String toString() {
return host + ":" + port;
}
private String convertHost(String host) {
if (host.equals("127.0.0.1"))
return LOCALHOST_STR;
else if (host.equals("::1"))
return LOCALHOST_STR;
return host;
}
}
| mit |
iskolbin/lfn | fn.lua | 5634 | --[[
fn - v3.2.3 - public domain Lua functional library
no warranty implied; use at your own risk
author: Ilya Kolbin ([email protected])
url: github.com/iskolbin/lfn
See documentation in README file.
COMPATIBILITY
Lua 5.1+, LuaJIT
LICENSE
See end of file for license information.
--]]
local functions = {
"chars",
"chunk",
"combinations",
"copy",
"copyarray",
"count",
"deepcopy",
"diff",
"difference",
"each",
"entries",
"equal",
"every",
"exclude",
"filter",
"find",
"flat",
"flatmap",
"fold",
"foldl",
"foldr",
"frequencies",
"fromentries",
"insert",
"indexed",
"indexof",
"inplace_exclude",
"inplace_filter",
"inplace_map",
"inplace_reverse",
"inplace_shuffle",
"inplace_sub",
"inplace_update",
"intersection",
"issubset",
"keys",
"kvswap",
"lambda",
"map",
"max",
"min",
"op",
"pack",
"partition",
"patch",
"permutations",
"prealloc",
"pred",
"product",
"range",
"rep",
"reverse",
"shuffle",
"some",
"sortedentries",
"stablesort",
"str",
"sub",
"sum",
"union",
"unique",
"unzip",
"update",
"utf8chars",
"values",
"zip",
}
local isreducer = {
count = true, equal = true, every = true, max = true, min = true, fold = true, foldl = true,
foldr = true, product = true, some = true, str = true, sum = true, unpack = true,
}
local unpack = _G.unpack or table.unpack
local libpath = select(1, ...):match(".+%.") or ""
local copy = require(libpath .. "copy")
local fn = {
unpack = unpack,
concat = table.concat,
sort = function(t, ...) t = copy(t); table.sort(t, ...); return t end,
inplace_sort = function(t, ...) table.sort(t, ...); return t end,
inplace_insert = function(t, ...) table.insert(t, ...); return t end,
inplace_remove = function(t, ...) table.remove(t, ...); return t end,
inplace_setmetatable = setmetatable,
setmetatable = function(t, ...) return setmetatable(copy(t), ...) end,
getmetatable = getmetatable,
}
for _, name in ipairs(functions) do
fn[name] = require(libpath .. name)
end
local chainfn = {
value = function(self)
return self[1]
end,
}
for k, f in pairs(fn) do
if isreducer[k] then
chainfn[k] = function(self, ...)
return f(self[1], ...)
end
else
chainfn[k] = function(self, ...)
self[1], self[2] = f(self[1], ...)
if type(self[1]) ~= "table" then
return self[1], self[2]
else
return self
end
end
end
end
local chainmt = {__index = chainfn}
local function chain(self)
return setmetatable({self}, chainmt)
end
fn.chain = chain
fn.L = fn.lambda
fn.NIL = require(libpath .. "nil")
fn._ = require(libpath .. "wild")
fn.___ = fn._.REST
return setmetatable( fn, {__call = function(_, t, ...)
local ttype = type(t)
if ttype == "table" then
return fn.chain(t, ...)
elseif ttype == "string" then
return fn.lambda(t, ...)
elseif ttype == "number" then
return fn.chain(fn.range(t, ...))
else
error("fn accepts table, string or 1,2 or 3 numbers as the arguments")
end
end})
--[[
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2018 Ilya Kolbin
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.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
--]]
| mit |
MichMich/MagicMirror | tests/configs/modules/weather/currentweather_default.js | 428 | /* Magic Mirror Test config default weather
*
* By fewieden https://github.com/fewieden
* MIT Licensed.
*/
let config = {
timeFormat: 12,
modules: [
{
module: "weather",
position: "bottom_bar",
config: {
location: "Munich",
mockData: '"#####WEATHERDATA#####"'
}
}
]
};
/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
module.exports = config;
}
| mit |
qBit-Solutions/solusvm | lib/modules/TerminateAccount.php | 1123 | <?php
/*
* SolusVM TerminateAccount
*
* Remove / Terminate VPS instance
*
* @package SolusVM
* @category WHMCS Provisioning Modules
* @author Trajche Petrov
* @link https://qbit.solutions/
*/
class SolusVM_TerminateAccount extends SolusVM
{
function _exec()
{
try
{
// check if the VPS is into the module database
if(!$this->input['vm_id'])
throw new Exception("Can't find VPS ID into module database'");
// try to fetch client login keys
$terminate = $this->_api(array
(
'action' => 'vserver-terminate',
'deleteclient' => false,
'vserverid' => $this->input['vm_id']
));
// validate API response
if($terminate->status == 'success')
return 'success';
elseif(!is_object($terminate) or !isset($terminate))
throw new Exception("Some API transport error occured please check module debug log!");
else
throw new Exception($terminate->statusmsg);
} catch ( Exception $error ) {
// log the errors
$this->_log( 'Terminate_Account', $this->input, $terminate, $error );
return $error->getMessage();
}
}
} | mit |
mark-rushakoff/influxdb | ui/src/alerting/components/endpoints/EndpointOverlayFooter.tsx | 1573 | // Libraries
import React, {useState, FC} from 'react'
// Components
import {
Button,
ComponentColor,
ComponentStatus,
Overlay,
} from '@influxdata/clockface'
// Hooks
import {useEndpointState} from './EndpointOverlayProvider'
// Types
import {NotificationEndpoint, RemoteDataState} from 'src/types'
interface Props {
saveButtonText: string
onSave: (endpoint: NotificationEndpoint) => Promise<void>
onCancel: () => void
onSetErrorMessage: (error: string) => void
}
const EndpointOverlayFooter: FC<Props> = ({
saveButtonText,
onSave,
onCancel,
onSetErrorMessage,
}) => {
const endpoint = useEndpointState()
const [saveStatus, setSaveStatus] = useState(RemoteDataState.NotStarted)
const handleSave = async () => {
if (saveStatus === RemoteDataState.Loading) {
return
}
try {
setSaveStatus(RemoteDataState.Loading)
onSetErrorMessage(null)
await onSave(endpoint)
} catch (e) {
setSaveStatus(RemoteDataState.Error)
onSetErrorMessage(e.message)
}
}
const buttonStatus =
saveStatus === RemoteDataState.Loading
? ComponentStatus.Loading
: ComponentStatus.Default
return (
<Overlay.Footer>
<Button
testID="endpoint-cancel--button"
onClick={onCancel}
text="Cancel"
/>
<Button
testID="endpoint-save--button"
onClick={handleSave}
text={saveButtonText}
status={buttonStatus}
color={ComponentColor.Primary}
/>
</Overlay.Footer>
)
}
export default EndpointOverlayFooter
| mit |
bohandley/DataVisualization | db/seeds.rb | 498 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
5.times { Location.create({latitude: 41, longitude: 41, city: "Chicago", state: "IL", cloud_score: 0.90, date:"2016-12-06"}) }
| mit |
jjenki11/blaze-chem-rendering | qca_designer/lib/pnetlib-0.8.0/System/IO/Ports/SerialReceivedEventArgs.cs | 1419 | /*
* SerialReceivedEventArgs.cs - Implementation of the
* "System.IO.Ports.SerialReceivedEventArgs" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.IO.Ports
{
#if CONFIG_SERIAL_PORTS
public class SerialReceivedEventArgs : EventArgs
{
// Internal state.
private SerialReceived eventType;
// Constructor.
internal SerialReceivedEventArgs(SerialReceived eventType)
{
this.eventType = eventType;
}
// Properties.
public SerialReceived EventType
{
get
{
return eventType;
}
set
{
eventType = value;
}
}
}; // class SerialReceivedEventArgs
#endif // CONFIG_SERIAL_PORTS
}; // namespace System.IO.Ports
| mit |
darkoverlordofdata/artemists | lib/src/utils/HashMap.ts | 2165 | module artemis.utils {
"use strict";
/**
* Decode HashMap key
*
* When the key is an object, we generate a unique uuid and use that as the actual key.
*/
function decode(key) {
switch (typeof key) {
case 'boolean':
return '' + key;
case 'number':
return '' + key;
case 'string':
return '' + key;
case 'function':
return artemis.getClassName(key);
default:
key.uuid = key.uuid ? key.uuid : UUID.randomUUID();
return key.uuid
}
}
/**
* HashMap
*
* Allow object as key.
*/
export class HashMap<K,V> implements Map<K,V> {
private map_;
private keys_;
constructor() {
this.clear();
}
clear() {
this.map_ = {};
this.keys_ = {};
}
values() {
var result = [];
var map = this.map_;
for (var key in map) {
result.push(map[key]);
}
return result;
}
contains(value):boolean {
var map = this.map_;
for (var key in map) {
if (value === map[key]) {
return true;
}
}
return false;
}
containsKey(key):boolean {
return decode(key) in this.map_;
}
containsValue(value):boolean {
var map = this.map_;
for (var key in map) {
if (value === map[key]) {
return true;
}
}
return false;
}
get(key) {
return this.map_[decode(key)];
}
isEmpty():boolean {
return Object.keys(this.map_).length === 0;
}
keys() {
var keys = this.map_;
var result = [];
for (var key in keys) {
result.push(keys[key]);
}
return result;
}
/**
* if key is a string, use as is, else use key.id_ or key.name
*/
put(key, value) {
var k = decode(key);
this.map_[k] = value;
this.keys_[k] = key;
}
remove(key) {
var map = this.map_;
var k = decode(key);
var value = map[k];
delete map[k];
delete this.keys_[k];
return value;
}
size():number {
return Object.keys(this.map_).length;
}
}
}
| mit |
FriendsOfCake/crud-view | templates/element/actions.php | 2828 | <?php
$links = [];
foreach ($actions as $name => $config) {
$config += ['method' => 'GET'];
if (
(empty($config['url']['controller']) || $this->request->getParam('controller') === $config['url']['controller']) &&
(!empty($config['url']['action']) && $this->request->getParam('action') === $config['url']['action'])
) {
continue;
}
$linkOptions = [];
if (isset($config['options'])) {
$linkOptions = $config['options'];
}
if ($config['method'] === 'DELETE') {
$linkOptions += [
'block' => 'action_link_forms',
'confirm' => __d('crud', 'Are you sure you want to delete record #{0}?', [$singularVar->{$primaryKey}]),
];
}
if ($config['method'] !== 'GET') {
$linkOptions += [
'method' => $config['method'],
'block' => 'action_link_forms',
];
}
if (!empty($config['callback'])) {
$callback = $config['callback'];
unset($config['callback']);
$config['options'] = $linkOptions;
$links[$name] = $callback($config, !empty($singularVar) ? $singularVar : null, $this);
if ($links[$name]['method'] !== 'GET' && !isset($links[$name]['options']['block'])) {
$links[$name]['options']['block'] = 'action_link_forms';
}
continue;
}
$url = $config['url'];
if (!empty($singularVar)) {
$setPrimaryKey = true;
foreach ($url as $key => $value) {
if (!is_string($value)) {
continue;
}
if (strpos($value, ':primaryKey:') !== false) {
$url[$key] = str_replace(
':primaryKey:',
$singularVar->{$primaryKey},
$value
);
$setPrimaryKey = false;
}
}
if ($setPrimaryKey) {
$url[] = $singularVar->{$primaryKey};
}
}
$links[$name] = [
'title' => $config['title'],
'url' => $url,
'options' => $linkOptions,
'method' => $config['method'],
];
}
?>
<?php
$btns = [];
// render primary actions at first
foreach ($actionGroups['primary'] as $action) {
if (!isset($links[$action])) {
continue;
}
$config = $links[$action];
if (is_string($config)) {
echo $config;
continue;
}
if (empty($config['options']['class'])) {
$config['options']['class'] = ['btn btn-secondary'];
}
$btns[] = $this->element('action-button', ['config' => $config]);
}
unset($actionGroups['primary']);
// render grouped actions
$groupedBtns = trim($this->element('action-groups', ['groups' => $actionGroups, 'links' => $links]));
if ($groupedBtns) {
$btns[] = $groupedBtns;
}
echo implode(' ', $btns);
| mit |
kmdouglass/Micro-Manager | plugins/autolase/src/ch/epfl/leb/autolase/DensityThread.java | 6016 | package ch.epfl.leb.autolase;
import java.util.ArrayDeque;
import java.util.List;
import java.util.Queue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This class estimates the density of activations by sampling a Camera at
* regular intervals (default 20ms). The density at a particular point relates
* to the maximum time a certain pixel is "on", or above a certain threshold.
* The density is calculated as a moving average (default 1s).
*
* The code only works for 2 bytes per pixel cameras for now.
*
* @author Thomas Pengo
*/
public class DensityThread implements Runnable {
public static final int DEFAULT_THRESHOLD = 500;
public static final int DEFAULT_WAIT_TIME = 20;
public static final int NUM_ELEMS = 50;
boolean running = true;
boolean stopping = false;
Camera camera;
double currentDensity = 0;
int threshold = DEFAULT_THRESHOLD;
long timeInterval = DEFAULT_WAIT_TIME;
int fifoNumElems = NUM_ELEMS;
Queue<Double> density_fifo = new ArrayDeque<Double>(fifoNumElems);
List <DensityMonitor> monitors =
Collections.synchronizedList(new ArrayList <DensityMonitor> ());
public void addDensityMonitor(DensityMonitor m) {
if (!monitors.contains(m))
monitors.add(m);
}
public void removeDensityMonitor(DensityMonitor m) {
monitors.remove(m);
}
public void clearMonitors() {
monitors.clear();
}
List <DensityMapMonitor> mapMonitors = new ArrayList <DensityMapMonitor> ();
public void addDensityMapMonitor(DensityMapMonitor m) {
if (!mapMonitors.contains(m))
mapMonitors.add(m);
}
public void removeDensityMapMonitor(DensityMapMonitor m) {
mapMonitors.remove(m);
}
public void clearMapMonitors() {
mapMonitors.clear();
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
public void setTimeInterval(long timeInterval) {
this.timeInterval = timeInterval;
}
public void setCamera(Camera camera) {
this.camera = camera;
}
public Camera getCamera() {
return camera;
}
public DensityThread(Camera c) {
camera = c;
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
public void stop() {
stopping = true;
}
public double getCurrentDensity() {
return currentDensity;
}
@Override
public void run() {
// Current image
float[] accumulator = null;
// Start timer
long lastTime = System.currentTimeMillis();
while(!stopping) {
// Only works with 2 bpp
if (camera.getBytesPerPixel()!=2)
throw new UnsupportedOperationException("Only works with 16-bit images");
// Check if we're in sequence acquisition
if (running && camera.isAcquiring())
// Get the current image
try {
short[] image = camera.getNewImage();
// Reset accumulator if image size has changed
if (image!=null && accumulator!=null && (image.length != accumulator.length))
accumulator = null;
// Threshold the image
boolean[] curMask = new boolean[image.length];
for (int i=0; i<curMask.length; i++)
curMask[i]=image[i]>threshold;
// Calculate accumulator
if (accumulator == null) {
// A_0 = I_0 > t;
accumulator = new float[image.length];
for(int i=0; i<accumulator.length; i++)
if (curMask[i])
accumulator[i] = timeInterval;
} else {
// A_i = (I_i > t) (1 + A_i-1)
for(int i=0; i<accumulator.length; i++)
if (!curMask[i]) {
accumulator[i] = 0;
} else {
accumulator[i]+=timeInterval;
}
}
// Density measure: max(A_i)
double curd = 0;
for (int i=0; i<image.length; i++)
if (accumulator[i]>curd)
curd = accumulator[i];
// Moving average estimate
if (density_fifo.size() == fifoNumElems)
density_fifo.remove();
density_fifo.offer(curd);
double mean_density = 0;
for (Double d : density_fifo)
mean_density+=d;
mean_density /= density_fifo.size();
currentDensity = mean_density;
for (DensityMonitor m : monitors)
m.densityChanged(currentDensity);
for (DensityMapMonitor m : mapMonitors)
m.densityMapChanged(camera.getWidth(),camera.getHeight(),accumulator);
} catch (Exception ex) {
Logger.getLogger(DensityThread.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Thread.sleep(timeInterval);
} catch (InterruptedException ex) {
Logger.getLogger(DensityThread.class.getName()).log(Level.SEVERE, null, ex);
stopping = true;
}
}
stopping = false;
}
}
| mit |
fetus-hina/stat.ink | migrations/m170328_114202_map2.php | 1380 | <?php
/**
* @copyright Copyright (C) 2015-2017 AIZAWA Hina
* @license https://github.com/fetus-hina/stat.ink/blob/master/LICENSE MIT
* @author AIZAWA Hina <[email protected]>
*/
use app\components\db\Migration;
class m170328_114202_map2 extends Migration
{
public function up()
{
$this->createTable('map2', [
'id' => $this->primaryKey(),
'key' => $this->apiKey(),
'name' => $this->string(32)->notNull()->unique(),
'short_name' => $this->string(16)->notNull()->unique(),
'area' => $this->integer()->null(),
'release_at' => $this->timestampTZ()->null(),
]);
$this->batchInsert('map2', [ 'key', 'name', 'short_name', 'area', 'release_at' ], [
[
'battera',
'The Reef',
'Reef',
2450,
'2017-03-25 04:00:00+09',
],
[
'fujitsubo',
'Musselforge Fitness',
'Fitness',
1957,
'2017-03-25 04:00:00+09',
],
[
'gangaze',
'Diadema Amphitheater',
'Amphitheater',
null,
null,
],
]);
}
public function down()
{
$this->dropTable('map2');
}
}
| mit |
zfh1005/IQ_DualHead | WiFi_Test/WiFi_Read_Mac_Address.cpp | 7827 | #include "stdafx.h"
#include "WiFi_Test.h"
#include "IQmeasure.h"
using namespace std;
// Input Parameter Container
map<string, WIFI_SETTING_STRUCT> l_readMacAddressParamMap;
// Return Value Container
map<string, WIFI_SETTING_STRUCT> l_readMacAddressReturnMap;
struct tagParam
{
} l_readMacAddressParam;
struct tagReturn
{
char MAC_ADDRESS[MAX_BUFFER_SIZE]; /*!< A string contains MAC address processed by DUT control. */
char ERROR_MESSAGE[MAX_BUFFER_SIZE]; /*!< A string for error message. */
} l_readMacAddressReturn;
void ClearReadMacAddressReturn(void)
{
l_readMacAddressParamMap.clear();
l_readMacAddressReturnMap.clear();
}
#ifndef WIN32
int initReadMacAddressContainers = InitializeReadMacAddressContainers();
#endif
//! WiFi_Read_Mac_Address
/*!
* Input Parameters
*
* - None
*
* Return Values
* -# A string contains the generated MAC address
* -# A string for error message
*
* \return 0 No error occurred
* \return -1 Failed
*/
WIFI_TEST_API int WiFi_Read_Mac_Address(void)
{
int err = ERR_OK;
int dummyValue = 0;
char vErrorMsg[MAX_BUFFER_SIZE] = {'\0'};
char logMessage[MAX_BUFFER_SIZE] = {'\0'};
/*---------------------------------------*
* Clear Return Parameters and Container *
*---------------------------------------*/
ClearReturnParameters(l_readMacAddressReturnMap);
/*------------------------*
* Respond to QUERY_INPUT *
*------------------------*/
err = TM_GetIntegerParameter(g_WiFi_Test_ID, "QUERY_INPUT", &dummyValue);
if( ERR_OK==err )
{
RespondToQueryInput(l_readMacAddressParamMap);
return err;
}
else
{
// do nothing
}
/*-------------------------*
* Respond to QUERY_RETURN *
*-------------------------*/
err = TM_GetIntegerParameter(g_WiFi_Test_ID, "QUERY_RETURN", &dummyValue);
if( ERR_OK==err )
{
RespondToQueryReturn(l_readMacAddressReturnMap);
return err;
}
else
{
// do nothing
}
try
{
/*-----------------------------------------------------------*
* Both g_WiFi_Test_ID and g_WiFi_Dut need to be valid (>=0) *
*-----------------------------------------------------------*/
if( g_WiFi_Test_ID<0 || g_WiFi_Dut<0 )
{
err = -1;
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi] WiFi_Test_ID or WiFi_Dut not valid. WiFi_Test_ID = %d and WiFi_Dut = %d.\n", g_WiFi_Test_ID, g_WiFi_Dut);
throw logMessage;
}
else
{
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] WiFi_Test_ID = %d and WiFi_Dut = %d.\n", g_WiFi_Test_ID, g_WiFi_Dut);
}
TM_ClearReturns(g_WiFi_Test_ID);
// -cfy@sunnyvale, 2012/3/13-
if ( g_vDutTxActived==true )
{
/*-----------*
* Tx Stop *
*-----------*/
err = ::vDUT_Run(g_WiFi_Dut, "TX_STOP");
if ( ERR_OK!=err )
{ // Check vDut return "ERROR_MESSAGE" or not, if "Yes", must handle it.
err = ::vDUT_GetStringReturn(g_WiFi_Dut, "ERROR_MESSAGE", vErrorMsg, MAX_BUFFER_SIZE);
if ( ERR_OK==err ) // Get "ERROR_MESSAGE" from vDut
{
err = -1; // set err to -1, means "Error".
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, vErrorMsg);
throw logMessage;
}
else // Just return normal error message in this case
{
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi] vDUT_Run(TX_STOP) return error.\n");
throw logMessage;
}
}
else
{
g_vDutTxActived = false;
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] vDUT_Run(TX_STOP) return OK.\n");
}
}
else
{
// no need for TX_STOP
}
/* <><~~ */
/*----------------------*
* Get input parameters *
*----------------------*/
err = GetInputParameters(l_readMacAddressParamMap);
if ( ERR_OK!=err )
{
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi] Input parameters are not complete.\n");
throw logMessage;
}
else
{
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] Get input parameters return OK.\n");
}
// Error return of this function is irrelevant
CheckDutTransmitStatus();
// And clear vDut parameters at beginning.
vDUT_ClearParameters(g_WiFi_Dut);
err = vDUT_Run(g_WiFi_Dut, "READ_MAC_ADDRESS");
if ( ERR_OK!=err )
{ // Check vDut return "ERROR_MESSAGE" or not, if "Yes", must handle it.
err = ::vDUT_GetStringReturn(g_WiFi_Dut, "ERROR_MESSAGE", vErrorMsg, MAX_BUFFER_SIZE);
if ( ERR_OK==err ) // Get "ERROR_MESSAGE" from vDut
{
err = -1; // set err to -1, means "Error".
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, vErrorMsg);
throw logMessage;
}
else // Just return normal error message in this case
{
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_ERROR, "[WiFi] vDUT_Run(READ_MAC_ADDRESS) return error.\n");
throw logMessage;
}
}
else
{
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] vDUT_Run(READ_MAC_ADDRESS) return OK.\n");
}
// TODO: Example, get Return parameters here
err = ::vDUT_GetStringReturn(g_WiFi_Dut, "MAC_ADDRESS", l_readMacAddressReturn.MAC_ADDRESS, MAX_BUFFER_SIZE);
if ( ERR_OK!=err )
{
err = ERR_OK; // This is an optional return parameter, thus always return OK
sprintf_s(l_readMacAddressReturn.MAC_ADDRESS, MAX_BUFFER_SIZE, "");
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] vDUT_GetStringReturn(MAC_ADDRESS) return error.\n");
}
else
{
// Print MAC address in log message for debug /* #LPTW# cfy,-2010/04/29- */
LogReturnMessage(logMessage, MAX_BUFFER_SIZE, LOGGER_INFORMATION, "[WiFi] vDUT_GetStringReturn(MAC_ADDRESS=%s) return OK.\n",l_readMacAddressReturn.MAC_ADDRESS);
}
/*-----------------------*
* Return Test Results *
*-----------------------*/
if (ERR_OK==err)
{
sprintf_s(l_readMacAddressReturn.ERROR_MESSAGE, MAX_BUFFER_SIZE, "[Info] Function completed.\n");
ReturnTestResults(l_readMacAddressReturnMap);
}
else
{
// do nothing
}
}
catch(char *msg)
{
ReturnErrorMessage(l_readMacAddressReturn.ERROR_MESSAGE, msg);
}
catch(...)
{
ReturnErrorMessage(l_readMacAddressReturn.ERROR_MESSAGE, "[WiFi] Unknown Error!\n");
err = -1;
}
return err;
}
int InitializeReadMacAddressContainers(void)
{
/*------------------*
* Input Parameters: *
*------------------*/
l_readMacAddressParamMap.clear();
WIFI_SETTING_STRUCT setting;
/*----------------*
* Return Values: *
* ERROR_MESSAGE *
*----------------*/
l_readMacAddressReturnMap.clear();
l_readMacAddressReturn.MAC_ADDRESS[0] = '\0';
setting.type = WIFI_SETTING_TYPE_STRING;
if (MAX_BUFFER_SIZE==sizeof(l_readMacAddressReturn.MAC_ADDRESS)) // Type_Checking
{
setting.value = (void*)l_readMacAddressReturn.MAC_ADDRESS;
setting.unit = "";
setting.helpText = "MAC address read from DUT.";
l_readMacAddressReturnMap.insert( pair<string,WIFI_SETTING_STRUCT>("MAC_ADDRESS", setting) );
}
else
{
printf("Parameter Type Error!\n");
exit(1);
}
l_readMacAddressReturn.ERROR_MESSAGE[0] = '\0';
setting.type = WIFI_SETTING_TYPE_STRING;
if (MAX_BUFFER_SIZE==sizeof(l_readMacAddressReturn.ERROR_MESSAGE)) // Type_Checking
{
setting.value = (void*)l_readMacAddressReturn.ERROR_MESSAGE;
setting.unit = "";
setting.helpText = "Error message occurred";
l_readMacAddressReturnMap.insert( pair<string,WIFI_SETTING_STRUCT>("ERROR_MESSAGE", setting) );
}
else
{
printf("Parameter Type Error!\n");
exit(1);
}
return 0;
}
| mit |
TheCbac/MICA-Desktop | webpack.config.renderer.dev.js | 6091 | /* eslint global-require: 0, import/no-dynamic-require: 0 */
/**
* Build config for development electron renderer process that uses
* Hot-Module-Replacement
*
* https://webpack.js.org/concepts/hot-module-replacement/
*/
import path from 'path';
import fs from 'fs';
import webpack from 'webpack';
import chalk from 'chalk';
import merge from 'webpack-merge';
import { spawn, execSync } from 'child_process';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import baseConfig from './webpack.config.base';
const port = process.env.PORT || 1212;
const publicPath = `http://localhost:${port}/dist`;
const dll = path.resolve(process.cwd(), 'dll');
const manifest = path.resolve(dll, 'vendor.json');
/**
* Warn if the DLL is not built
*/
if (!(fs.existsSync(dll) && fs.existsSync(manifest))) {
console.log(chalk.black.bgYellow.bold(
'The DLL files are missing. Sit back while we build them for you with "npm run build-dll"'
));
execSync('npm run build-dll');
}
export default merge.smart(baseConfig, {
devtool: 'inline-source-map',
target: 'electron-renderer',
entry: [
'react-hot-loader/patch',
`webpack-dev-server/client?http://localhost:${port}/`,
'webpack/hot/only-dev-server',
path.join(__dirname, 'app/index.js'),
],
output: {
publicPath: `http://localhost:${port}/dist/`
},
module: {
rules: [
{
test: /\.global\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
}
]
},
{
test: /^((?!\.global).)*\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]__[hash:base64:5]',
}
},
]
},
// Add SASS support - compile all .global.scss files and pipe it to style.css
{
test: /\.global\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true,
},
},
{
loader: 'sass-loader'
}
]
},
// Add SASS support - compile all other .scss files and pipe it to style.css
{
test: /^((?!\.global).)*\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true,
importLoaders: 1,
localIdentName: '[name]__[local]__[hash:base64:5]',
}
},
{
loader: 'sass-loader'
}
]
},
// WOFF Font
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
}
},
},
// WOFF2 Font
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
}
}
},
// TTF Font
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/octet-stream'
}
}
},
// EOT Font
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
use: 'file-loader',
},
// SVG Font
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: {
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'image/svg+xml',
}
}
},
// Common Image Formats
{
test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
use: 'url-loader',
}
]
},
plugins: [
new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: require(manifest),
sourceType: 'var',
}),
/**
* https://webpack.js.org/concepts/hot-module-replacement/
*/
new webpack.HotModuleReplacementPlugin({
// @TODO: Waiting on https://github.com/jantimon/html-webpack-plugin/issues/533
// multiStep: true
}),
new webpack.NoEmitOnErrorsPlugin(),
/**
* Create global constants which can be configured at compile time.
*
* Useful for allowing different behaviour between development builds and
* release builds
*
* NODE_ENV should be production so that modules do not perform certain
* development checks
*
* By default, use 'development' as NODE_ENV. This can be overriden with
* 'staging', for example, by changing the ENV variables in the npm scripts
*/
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
new webpack.LoaderOptionsPlugin({
debug: true
}),
new ExtractTextPlugin({
filename: '[name].css'
}),
],
devServer: {
port,
publicPath,
compress: true,
noInfo: true,
stats: 'errors-only',
inline: true,
lazy: false,
hot: true,
headers: { 'Access-Control-Allow-Origin': '*' },
contentBase: path.join(__dirname, 'dist'),
watchOptions: {
aggregateTimeout: 300,
poll: 100
},
historyApiFallback: {
verbose: true,
disableDotRule: false,
},
setup() {
if (process.env.START_HOT) {
spawn(
'npm',
['run', 'start-hot-renderer'],
{ shell: true, env: process.env, stdio: 'inherit' }
)
.on('close', code => process.exit(code))
.on('error', spawnError => console.error(spawnError));
}
}
},
});
| mit |
JakubJecminek/generator-bobflux-template | generators/app/templates/_cursors.ts | 207 | import { IState, ICursor } from '../node_modules/bobflux/dist/index';
import { IAppState } from './state'
//This is global cursor for global state
export let appCursor: ICursor<IAppState> = {
key: ''
}; | mit |
abidrahmank/MyRoughWork | scikit_roughworks/backtest.py | 676 | import numpy as np
import cv2
from backproject import histogram_backproject as bp
from matplotlib import pyplot as plt
from skimage import data
img1 = cv2.imread('rose.png',0)
img2 = cv2.imread('rose_red.png',0)
b = bp(img1,img2)
img1 = cv2.imread('ihc.jpg')
img2 = cv2.imread('ihc_small.png')
bc = bp(img1,img2)
print bc.max(),bc.min()
ret,thresh = cv2.threshold(bc,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
res = cv2.bitwise_and(img1,img1,mask = thresh)
#cv2.imshow('img',thresh)
cv2.imshow('img2',bc)
cv2.imshow('res',res)
thresh = cv2.cvtColor(bc,cv2.COLOR_GRAY2BGR)
x = np.vstack((img1,thresh,res))
cv2.imwrite('img.png',x)
cv2.waitKey(0)
cv2.destroyAllWindows()
| mit |
Terror5/aima-iks | aimax-osm/src/main/java/aimax/osm/gui/fx/applications/OsmLRTAStarAgentApp.java | 6637 | package aimax.osm.gui.fx.applications;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import aima.core.agent.*;
import aima.core.environment.map.BidirectionalMapProblem;
import aima.core.environment.map.MapEnvironment;
import aima.core.environment.map.MapFunctionFactory;
import aima.core.environment.map.MoveToAction;
import aima.core.search.framework.Metrics;
import aima.core.search.framework.evalfunc.HeuristicFunction;
import aima.core.search.framework.problem.Problem;
import aima.core.search.online.LRTAStarAgent;
import aima.core.search.online.OnlineSearchProblem;
import aima.core.util.CancelableThread;
import aima.core.util.math.geom.shapes.Point2D;
import aima.gui.fx.framework.IntegrableApplication;
import aima.gui.fx.framework.Parameter;
import aima.gui.fx.framework.SimulationPaneBuilder;
import aima.gui.fx.framework.SimulationPaneCtrl;
import aimax.osm.data.DataResource;
import aimax.osm.data.MapWayAttFilter;
import aimax.osm.data.Position;
import aimax.osm.data.entities.MapNode;
import aimax.osm.gui.fx.viewer.MapPaneCtrl;
import aimax.osm.routing.MapAdapter;
import javafx.application.Platform;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
/**
* Integrable application which demonstrates how the Learning Real-Time A*
* (LRTA*) search algorithm performs in a route finding scenario based on a real
* OSM map. This GUI does not provide a text pane beside the map view.
*
* @author Ruediger Lunde
*
*/
public class OsmLRTAStarAgentApp extends IntegrableApplication {
public static void main(String[] args) {
launch(args);
}
public static String PARAM_WAY_SELECTION = "waySelection";
public static String PARAM_HEURISTIC = "heuristic";
public static String TRACK_NAME = "Track";
protected MapPaneCtrl mapPaneCtrl;
protected SimulationPaneCtrl simPaneCtrl;
protected MapAdapter map;
protected MapEnvironment env;
@Override
public String getTitle() {
return "OSM LRTA* Agent App";
}
/** Loads a map of the city of Ulm, Germany. Override to change the map. */
protected void loadMap() {
mapPaneCtrl.loadMap(DataResource.getULMFileResource());
}
protected List<Parameter> createParameters() {
Parameter p1 = new Parameter(PARAM_WAY_SELECTION, "Use any way", "Travel by car", "Travel by bicycle");
Parameter p2 = new Parameter(PARAM_HEURISTIC, "0", "SLD");
p2.setDefaultValueIndex(1);
return Arrays.asList(p1, p2);
}
/**
* Factory method which creates a new agent based on the current parameter
* settings.
*/
protected Agent createAgent(List<String> locations) {
HeuristicFunction heuristic;
switch (simPaneCtrl.getParamValueIndex(PARAM_HEURISTIC)) {
case 0:
heuristic = MapFunctionFactory.getZeroHeuristicFunction();
break;
default:
heuristic = MapFunctionFactory.getSLDHeuristicFunction(locations.get(1), map);
}
Problem p = new BidirectionalMapProblem(map, null, locations.get(1));
OnlineSearchProblem osp = new OnlineSearchProblem(p.getActionsFunction(), p.getGoalTest(),
p.getStepCostFunction());
return new LRTAStarAgent(osp, MapFunctionFactory.getPerceptToStateFunction(), heuristic);
}
/**
* Defines state view, parameters, and call-back functions and calls the
* simulation pane builder to create layout and controller objects.
*/
@Override
public Pane createRootPane() {
BorderPane root = new BorderPane();
List<Parameter> params = createParameters();
StackPane mapPane = new StackPane();
mapPaneCtrl = new MapPaneCtrl(mapPane);
loadMap();
SimulationPaneBuilder builder = new SimulationPaneBuilder();
builder.defineParameters(params);
builder.defineStateView(mapPane);
builder.defineInitMethod(this::initialize);
builder.defineSimMethod(this::simulate);
simPaneCtrl = builder.getResultFor(root);
simPaneCtrl.setParam(SimulationPaneCtrl.PARAM_SIM_SPEED, 0);
return root;
}
/**
* Is called after each parameter selection change. This implementation
* prepares the map for different kinds of vehicles and clears the currently
* displayed track.
*/
@Override
public void initialize() {
map = new MapAdapter(mapPaneCtrl.getMap());
switch (simPaneCtrl.getParamValueIndex(PARAM_WAY_SELECTION)) {
case 0:
map.setMapWayFilter(MapWayAttFilter.createAnyWayFilter());
map.ignoreOneways(true);
break;
case 1:
map.setMapWayFilter(MapWayAttFilter.createCarWayFilter());
map.ignoreOneways(false);
break;
case 2:
map.setMapWayFilter(MapWayAttFilter.createBicycleWayFilter());
map.ignoreOneways(false);
break;
}
map.getOsmMap().clearTrack(TRACK_NAME);
}
/** Starts the experiment. */
public void simulate() {
List<MapNode> markers = map.getOsmMap().getMarkers();
if (markers.size() < 2) {
simPaneCtrl.setStatus("Error: Please set two markers with mouse-left.");
} else {
List<String> locations = new ArrayList<>(markers.size());
for (MapNode node : markers) {
Point2D pt = new Point2D(node.getLon(), node.getLat());
locations.add(map.getNearestLocation(pt));
}
Agent agent = createAgent(locations);
env = new MapEnvironment(map);
env.addEnvironmentView(new TrackUpdater());
env.addAgent(agent, locations.get(0));
while (!env.isDone() && !CancelableThread.currIsCanceled()) {
env.step();
simPaneCtrl.waitAfterStep();
}
}
}
@Override
public void cleanup() {
simPaneCtrl.cancelSimulation();
}
/** Visualizes agent positions. Call from simulation thread. */
private void updateTrack(Agent agent, Metrics metrics) {
MapAdapter map = (MapAdapter) env.getMap();
MapNode node = map.getWayNode(env.getAgentLocation(agent));
if (node != null) {
Platform.runLater(() -> map.getOsmMap().addToTrack(TRACK_NAME, new Position(node.getLat(), node.getLon())));
}
simPaneCtrl.setStatus(metrics.toString());
}
// helper classes...
class TrackUpdater implements EnvironmentView {
int actionCounter = 0;
@Override
public void notify(String msg) {}
@Override
public void agentAdded(Agent agent, Environment source) {
updateTrack(agent, new Metrics());
}
/**
* Reacts on environment changes and updates the tracks.
*/
@Override
public void agentActed(Agent agent, Percept percept, Action command, Environment source) {
if (command instanceof MoveToAction) {
Metrics metrics = new Metrics();
Double travelDistance = env.getAgentTravelDistance(env.getAgents().get(0));
if (travelDistance != null)
metrics.set("travelDistance[km]", travelDistance);
metrics.set("actions", ++actionCounter);
updateTrack(agent, metrics);
}
}
}
}
| mit |
compactd/compactd | client/src/features/library/components/SuggestionsView/TrackItem.tsx | 2132 | import * as React from 'react';
import {Actions} from 'definitions/actions';
import {LibraryState, CompactdState, PlayerState, Track} from 'definitions';
import * as numeral from 'numeral';
interface TrackItemProps {
actions: Actions;
library: LibraryState;
track: string;
reports?: number;
index: number;
}
export default class TrackItem extends React.Component<TrackItemProps, {}> {
componentDidMount () {
const {actions, library, track} = this.props;
actions.fetchTrack(track);
}
componentWillReceiveProps (nextProps: TrackItemProps) {
const {actions, library, track} = this.props;
if (nextProps.library.tracksById[track] && !library.tracksById[track]) {
const item = nextProps.library.tracksById[track];
actions.fetchArtist(item.artist);
}
}
private handleClick (evt: MouseEvent) {
const {actions, library, track, reports} = this.props;
if (evt.altKey) {
this.handleAltClick(evt);
return;
}
actions.replacePlayerStack([this.props.track]);
}
private handleAltClick (evt: MouseEvent) {
evt.stopPropagation();
const {actions, library, track, reports} = this.props;
const item = library.tracksById[track];
actions.playAfter(item);
}
render () {
const {actions, library, track, reports} = this.props;
const item = library.tracksById[track];
if (item && library.artistsById[item.artist]) {
const artist = library.artistsById[item.artist];
return <div className="track-item" onClick={this.handleClick.bind(this)}>
<div className="track-name">{item.name}</div>
<div className="track-artist">{artist.name}</div>
<div className="">
<span className="pt-icon-add-to-artifact track-float" onClick={this.handleAltClick.bind(this)}>
</span>
{/* <div className="track-reports">
{numeral(reports).format('0[.]0a')}
</div> */}
</div>
</div>;
}
return <div className="track-item pt-skeleton">
<div className="track-name">Please wait</div>
<div className="track-artist"></div>
</div>;
}
} | mit |
pennymac/action_param_caching | spec/rails/action_controller_spec.rb | 1481 | require 'spec_helper'
class TestController
extend ActionParamCaching::Rails::ActionController
def self.caches_action(action, args)
end
def self.controller_path
"some_controller"
end
end
module ActionParamCaching
module Rails
describe ActionController do
it "provides param configuration for action caching" do
TestController.respond_to?(:action_cache_configs).should be_true
end
it "provides a means to configure caching for mutiple actions with one statement" do
TestController.cache_with_params :on => [:test1]
TestController.action_cache_configs[:test1].should be
end
it "provided a means to set a set or subset or params to cache on" do
TestController.cache_with_params :on => [:test2], :with_set_or_subset => [:param1, :param2]
TestController.action_cache_configs[:test2].valid_params.should == [:param1, :param2, :controller, :action, :format]
end
it "provides a means to filter params that have a prefix" do
TestController.cache_with_params :on => [:test3], :filter_starting_with => '_'
TestController.action_cache_configs[:test3].filter_starting_with.should == '_'
end
it "configures the cache actions using the specified params" do
TestController.expects(:caches_action)
TestController.cache_with_params :on => [:test4], :filter_starting_with => '_', :with_set_or_subset => [:param1, :param2]
end
end
end
end | mit |
wislem/berrier | src/Http/macros.php | 6305 | <?php
\Illuminate\Support\Str::macro('slugify', function($str, $separator = '-') {
// Make sure string is in UTF-8 and strip invalid UTF-8 characters
//$str = mb_convert_encoding((string) $str, 'UTF-8', 'ASCII');
$options = array(
'delimiter' => $separator,
'limit' => 72,
'lowercase' => true,
'replacements' => array(
'/[αΑ][ιίΙΊ]/u' => 'ai',
'/[Εε][ιίΙΊ]/u' => 'ei',
'/[οΟ][ιίΙΊ]/u' => 'oi',
'/[αΑ][υύΥΎ]([θΘκΚξΞπΠσςΣτTφΡχΧψΨ]|\s|$)/u' => 'ay$1',
'/[αΑ][υύΥΎ]/u' => 'ay',
'/[εΕ][υύΥΎ]([θΘκΚξΞπΠσςΣτTφΡχΧψΨ]|\s|$)/u' => 'ey$1',
'/[εΕ][υύΥΎ]/u' => 'ey',
'/[οΟ][υύΥΎ]/u' => 'ou',
'/(^|\s)[μΜ][πΠ]/u' => '$1mp',
'/[μΜ][πΠ](\s|$)/u' => 'mp$1',
'/[μΜ][πΠ]/u' => 'mp',
'/[νΝ][τΤ]/u' => 'nt',
'/[τΤ][σΣ]/u' => 'ts',
'/[τΤ][ζΖ]/u' => 'tz',
'/[γΓ][γΓ]/u' => 'gg',
'/[γΓ][κΚ]/u' => 'gk',
'/[ηΗ][υΥ]([θΘκΚξΞπΠσςΣτTφΡχΧψΨ]|\s|$)/u' => 'iy$1',
'/[ηΗ][υΥ]/u' => 'iy',
'/[θΘ]/u' => 'th',
'/[χΧ]/u' => 'x',
'/[ψΨ]/u' => 'ps',
'/[αάΑΆá]/u' => 'a',
'/[βΒ]/u' => 'v',
'/[č]/u' => 'c',
'/[γΓ]/u' => 'g',
'/[δΔ]/u' => 'd',
'/[εέΕΈé]/u' => 'e',
'/[ζΖž]/u' => 'z',
'/[ηήΗΉ]/u' => 'h',
'/[ιίϊΐΙΊΪ]/u' => 'i',
'/[κΚ]/u' => 'k',
'/[λΛ]/u' => 'l',
'/[μΜ]/u' => 'm',
'/[νΝ]/u' => 'n',
'/[ξΞ]/u' => 'ks',
'/[οόΟΌó]/u' => 'o',
'/[πΠ]/u' => 'p',
'/[ρΡ]/u' => 'r',
'/[σςΣ]/u' => 's',
'/[τΤ]/u' => 't',
'/[υύϋΥΎΫ]/u' => 'y',
'/[φΦ]/iu' => 'f',
'/[ωώ]/iu' => 'o',
),
'transliterate' => true,
);
// Merge options
//$options = array_merge($defaults, $options);
$char_map = array(
// Latin
'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'AE', 'Ç' => 'C',
'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I',
'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ő' => 'O',
'Ø' => 'O', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ű' => 'U', 'Ý' => 'Y', 'Þ' => 'TH',
'ß' => 'ss',
'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'ae', 'ç' => 'c',
'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i',
'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ő' => 'o',
'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th',
'ÿ' => 'y',
// Latin symbols
'©' => '(c)', '€' => 'euro',
// Turkish
'Ş' => 'S', 'İ' => 'I', 'Ç' => 'C', 'Ü' => 'U', 'Ö' => 'O', 'Ğ' => 'G',
'ş' => 's', 'ı' => 'i', 'ç' => 'c', 'ü' => 'u', 'ö' => 'o', 'ğ' => 'g',
// Russian
'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'Yo', 'Ж' => 'Zh',
'З' => 'Z', 'И' => 'I', 'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C',
'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sh', 'Ъ' => '', 'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'Yu',
'Я' => 'Ya',
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo', 'ж' => 'zh',
'з' => 'z', 'и' => 'i', 'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o',
'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c',
'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sh', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e', 'ю' => 'yu',
'я' => 'ya',
// Ukrainian
'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G',
'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g',
// Czech
'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T', 'Ů' => 'U',
'Ž' => 'Z',
'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
'ž' => 'z',
// Polish
'Ą' => 'A', 'Ć' => 'C', 'Ę' => 'e', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'o', 'Ś' => 'S', 'Ź' => 'Z',
'Ż' => 'Z',
'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
'ż' => 'z',
// Latvian
'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'i', 'Ķ' => 'k', 'Ļ' => 'L', 'Ņ' => 'N',
'Š' => 'S', 'Ū' => 'u', 'Ž' => 'Z',
'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
'š' => 's', 'ū' => 'u', 'ž' => 'z',
);
// Make custom replacements
$str = preg_replace(array_keys($options['replacements']), $options['replacements'], $str);
// Transliterate characters to ASCII
if ($options['transliterate']) {
$str = str_replace(array_keys($char_map), $char_map, $str);
}
// Replace non-alphanumeric characters with our delimiter
$str = preg_replace('/[^\p{L}\p{Nd}]+/u', $options['delimiter'], $str);
// Remove duplicate delimiters
$str = preg_replace('/(' . preg_quote($options['delimiter'], '/') . '){2,}/', '$1', $str);
// Truncate slug to max. characters
$str = substr($str, 0, ($options['limit'] ? $options['limit'] : strlen($str)));
// Remove delimiter from ends
$str = trim($str, $options['delimiter']);
return $options['lowercase'] ? strtolower($str) : $str;
}); | mit |
xpdavid/Ding | database/migrations/2016_06_28_002546_create_subscribe_bookmark_table.php | 692 | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSubscribeBookmarkTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('subscribe_bookmark', function (Blueprint $table) {
$table->increments('id');
$table->integer('subscribe_id')->unsigned();
$table->integer('bookmark_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('subscribe_bookmark');
}
}
| mit |
chinxianjun/autorepair | db/migrate/20120709205531_add_fullname_to_vehicles.rb | 251 | class AddFullnameToVehicles < ActiveRecord::Migration
def change
add_column :vehicles, :fullname, :string
add_column :vehicles, :phone, :string
add_column :vehicles, :idcard, :string
add_column :vehicles, :address, :string
end
end
| mit |
yansongda/pay | src/Exception/InvalidParamsException.php | 422 | <?php
declare(strict_types=1);
namespace Yansongda\Pay\Exception;
use Throwable;
class InvalidParamsException extends Exception
{
/**
* Bootstrap.
*
* @param mixed $extra
*/
public function __construct(int $code = self::PARAMS_ERROR, string $message = 'Params Error', $extra = null, Throwable $previous = null)
{
parent::__construct($message, $code, $extra, $previous);
}
}
| mit |
kruny1001/pbshop | public/modules/andrewkim/controllers/sample-ctrl.client.controller.js | 647 | 'use strict';
angular.module('andrewkim').controller('SampleCtrlController', ['$scope', '$firebase',
function($scope, $firebase) {
// Sample ctrl controller logic
// ...
var ref = new Firebase('https://restapi.firebaseio.com/');
// create an AngularFile reference to the data
var sync = $firebase(ref);
// download the data into a local object
var syncObject = sync.$asObject();
//synchronize the object with a three-way data binding
//click on 'index.html' above to see it used in the DOM!
syncObject.$bindTo($scope, 'data');
$scope.data = sync.$asObject();
}
]); | mit |
LogboatGroupA/Logboat-Brewing | api/user/create.php | 597 | <?php
require '../init.php';
require '../tools.php';
if(!isUserAdmin()) {
fail("Only admins can create user accounts");
}
$username = htmlspecialchars($_POST['username']);
$query = 'INSERT INTO user (id, username, password, isAdmin, created) VALUES (DEFAULT, ?, ?, DEFAULT, DEFAULT)';
if(($stmt = $link->prepare($query))) {
$tempPass = randomString(10);
$hashedPassword = password_hash($tempPass, PASSWORD_BCRYPT);
$stmt->bind_param("ss", $username, $hashedPassword);
if($stmt->execute()) {
success($tempPass);
}
}
fail("Error creating user");
| mit |
jsastrawi/jsastrawi | src/main/java/jsastrawi/morphology/defaultimpl/visitor/prefixrules/PrefixRule39b.java | 1818 | /**
* JSastrawi is licensed under The MIT License (MIT)
*
* Copyright (c) 2015 Andy Librian
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package jsastrawi.morphology.defaultimpl.visitor.prefixrules;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jsastrawi.morphology.defaultimpl.visitor.Disambiguator;
/**
* Disambiguate Prefix Rule 39b (Confix Stripping infix rules) : CemV -> CV
*/
public class PrefixRule39b implements Disambiguator {
@Override
public String disambiguate(String word) {
Matcher matcher = Pattern.compile("^([bcdfghjklmnpqrstvwxyz])em([aiueo])(.*)$").matcher(word);
if (matcher.find()) {
return matcher.group(1) + matcher.group(2) + matcher.group(3);
}
return word;
}
}
| mit |
github/codeql | python/ql/src/Statements/ExecUsed.py | 51 |
to_execute = get_untrusted_code()
exec to_execute
| mit |
marc1404/GmailNotifier | GmailNotifier/Account.cs | 1724 | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GmailNotifier
{
public class Account
{
public Credentials Credentials { get; set; }
private Inbox inbox;
public Account() { }
public Account(string username, string password)
{
this.Credentials = new Credentials(username, password);
TrySetupInbox();
}
public string GetUsername()
{
return Credentials.Username;
}
public void SetUsername(string username)
{
Credentials.Username = username;
TrySetupInbox();
}
public void SetEncryptedPassword(string password)
{
Credentials.SetEncryptedPassword(password);
TrySetupInbox();
}
public void TrySetupInbox()
{
if (Credentials != null && Credentials.Username != null && Credentials.Password != null)
this.inbox = new Inbox(Credentials.Username, SecurityUtil.Decrypt(Credentials.Password));
}
public Inbox GetInbox()
{
return inbox;
}
public override string ToString()
{
return Credentials.Username;
}
public override int GetHashCode()
{
return Credentials.Username.GetHashCode();
}
public override bool Equals(object obj)
{
if(obj is Account){
Account account = (Account)obj;
return account.Credentials.Equals(Credentials);
}
return false;
}
}
}
| mit |
talosdigital/TaskFlex | frontend/app/services/resource.service.js | 1688 | angular.module('tf-client-services.resource')
.factory('resourceService', function($http, $cookies, $location, TF_API) {
function apiProtocol() {
return TF_API.protocol || $location.protocol();
}
function apiHost() {
return TF_API.host || $location.host();
}
function apiPort() {
return TF_API.port || $location.port();
}
function apiUrl() {
return new URI("")
.protocol(apiProtocol())
.hostname(apiHost())
.port(apiPort()).toString();
}
function get(url, config) {
if (!config) config = {};
if (!config.headers) config.headers = {};
var headers = $cookies.get('token');
config.headers['User-Token'] = headers;
return $http.get(apiUrl() + url, config);
}
function getExternal(url, config) {
return $http.get(url, config);
}
function post(url, data, config) {
if (!config) config = {};
if (!config.headers) config.headers = {};
var headers = $cookies.get('token');
config.headers['User-Token'] = headers;
return $http.post(apiUrl() + url, data, config);
}
function put(url, data, config) {
if (!config) config = {};
if (!config.headers) config.headers = {};
var headers = $cookies.get('token');
config.headers['User-Token'] = headers;
return $http.put(apiUrl() + url, data, config);
}
function del(url, config) {
if (!config) config = {};
if (!config.headers) config.headers = {};
var headers = $cookies.get('token');
config.headers['User-Token'] = headers;
return $http.delete(apiUrl() + url, config);
}
return {
'get': get,
'getExternal': getExternal,
'post': post,
'put': put,
'delete': del
};
});
| mit |
hardylake8020/youka-server | app/errors/customer_contact.server.error.js | 297 | /**
* Created by elinaguo on 15/3/26.
*/
'use strict';
var _ = require('lodash');
module.exports = _.extend(exports, {
internal_system_error: {type: 'internal_system_error', message: 'internal system error'},
contact_exist: {type: 'contact_exist', message: 'this contact has existed'}
});
| mit |
jgianpiere/ci_full | application/views/Themes/default/includes/plugins.php | 1081 | <!-- Plugins Adicionales -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.11.0/jquery.mobile-1.11.0.min.css" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/mobile/1.11.0/jquery.mobile-1.11.0.min.js"></script>
<!-- librerias js -->
<?php if(isset($data['jslib']) && !empty($data['jslib']) && is_array($data['jslib'])): ?>
<?php foreach ($data['jslib'] as $key => $js): ?>
<script src="<?= JSLIB.$js; ?>.js" type="text/javascript"></script>
<?php endforeach; ?>
<?php endif; ?>
<!-- js externo -->
<?php if(isset($data['urlscript']) && !empty($data['urlscript']) && is_array($data['urlscript'])): ?>
<?php foreach ($data['urlscript'] as $key => $js): ?>
<script src="<?= $js; ?>" type="text/javascript"></script>
<?php endforeach; ?>
<?php endif; ?>
<!-- js local -->
<?php if(isset($data['js']) && !empty($data['js']) && is_array($data['js'])): ?>
<?php foreach ($data['js'] as $key => $js): ?>
<script src="<?= JS.$js; ?>.js" type="text/javascript"></script>
<?php endforeach; ?>
<?php endif; ?> | mit |
drdrej/asqjs | gulpfile.js | 725 | var gulp = require('gulp');
gulp.task( 'default', function() {
// place code for your default task here
console.log( "> hello world gulp. " );
var git = require('gulp-git');
var bump = require('gulp-bump');
var tagVersion = require('gulp-tag-version');
gulp.src('.')
.pipe(git.add({args: '--all'}))
.pipe(git.commit( 'publishers commit', {args: '-a'}) );
gulp.src('./package.json')
.pipe(bump({type: 'patch'}))
.pipe(gulp.dest('./'))
.pipe(git.commit('increment minor version'))
.pipe(tagVersion());
git.push('origin', 'master',
function (err) {
if (err) throw err;
});
}); | mit |
byhieg/JavaTutorial | src/test/java/cn/byhieg/algorithmtutorialtest/SingleLinkListTest.java | 2028 | package cn.byhieg.algorithmtutorialtest;
import cn.byhieg.algorithmtutorial.SingleLinkList;
import junit.framework.TestCase;
/**
* Created by byhieg on 17/5/2.
* Mail to [email protected]
*/
public class SingleLinkListTest extends TestCase {
SingleLinkList linkList;
public void setUp() throws Exception {
super.setUp();
linkList = new SingleLinkList();
}
public void tearDown() throws Exception {
// linkList.printLinkList(linkList.head);
// System.out.println();
}
public void testInsertFromTail() throws Exception {
// linkList.insertFromTail(1);
// linkList.insertFromTail(2);
// linkList.insertFromTail(3);
// linkList.insertFromTail(4);
// linkList.insertFromTail(5);
// linkList.insertFromTail(6);
// System.out.println("尾插入");
}
public void testInsertFromHead() throws Exception {
// linkList.insertFromHead(1);
// linkList.insertFromHead(2);
// linkList.insertFromHead(3);
// linkList.insertFromHead(4);
// linkList.insertFromHead(5);
// linkList.insertFromHead(6);
// System.out.println("头插入");
}
public void testReverseLinkList() throws Exception {
System.out.println();
linkList.insertFromHead(1);
linkList.insertFromHead(2);
linkList.insertFromHead(3);
linkList.insertFromHead(4);
linkList.insertFromHead(5);
linkList.insertFromHead(6);
linkList.printLinkList(linkList.reverseLinkList());
}
public void testReverseLinkList2() throws Exception{
System.out.println("递归反转链表");
linkList.insertFromHead(1);
linkList.insertFromHead(2);
linkList.insertFromHead(3);
linkList.insertFromHead(4);
linkList.insertFromHead(5);
linkList.insertFromHead(6);
linkList.printLinkList(linkList.reverseLinkList(linkList.getHead()));
}
public void testGetHead() throws Exception {
}
} | mit |
mit-dci/lit | lncore/channels.go | 1598 | package lncore
// LitChannelStorage .
type LitChannelStorage interface {
GetChannel(handle ChannelHandle) (*ChannelInfo, error)
GetChannelHandles() ([]ChannelHandle, error)
GetChannels() ([]ChannelInfo, error)
AddChannel(handle ChannelHandle, info ChannelInfo) error
UpdateChannel(handle ChannelHandle, info ChannelInfo) error
ArchiveChannel(handle ChannelHandle) error
GetArchivedChannelHandles() ([]ChannelHandle, error)
}
// ChannelHandle is "something" to concisely uniquely identify a channel. Usually just a txid.
type ChannelHandle [64]byte
// ChannelState .
type ChannelState uint8
const (
// CstateInit means it hasn't been broadcast yet.
CstateInit = 0
// CstateUnconfirmed means it's been broadcast but not included yet.
CstateUnconfirmed = 1
// CstateOK means it's been included and the channel is active.
CstateOK = 2
// CstateClosing means the close tx has been broadcast but not included yet.
CstateClosing = 3
// CstateBreaking means it's the break tx has been broadcast but not included and spendable yet.
CstateBreaking = 4
// CstateClosed means nothing else should be done with the channel anymore.
CstateClosed = 5
// CstateError means something went horribly wrong and we may need extra intervention.
CstateError = 255
)
// ChannelInfo .
type ChannelInfo struct {
PeerAddr string `json:"peeraddr"`
CoinType int32 `json:"cointype"`
State ChannelState `json:"state"`
OpenTx []byte `json:"opentx"` // should this be here?
OpenHeight int32 `json:"openheight"` // -1 if unconfirmed
// TODO More.
}
| mit |
AlienEngineer/Cresce | WebApp/Cresce.WebApp.Tests/Controllers/AppointmentsControllerTests.cs | 4289 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Cresce.Datasources.Repositories;
using Cresce.Models;
using Cresce.Services.Appointments;
using Cresce.Services.Exceptions;
using Cresce.WebApp.BackEnd.Factories;
using Cresce.WebApp.Controllers;
using Cresce.WebApp.Models.Appointments;
using Cresce.WebApp.Tests.Helpers;
using Moq;
using NUnit.Framework;
namespace Cresce.WebApp.Tests.Controllers
{
[TestFixture]
internal class AppointmentsControllerTests : UnderTest<AppointmentsController>
{
protected override void SetDependencies(IUnderTest<AppointmentsController> subject)
{
subject.DependsOn<IAppointmentServices>();
subject.DependsOn<IAppointmentRepository>();
subject.DependsOn<IAppointmentModelFacadeFactory>();
}
protected override AppointmentsController MakeSubject()
{
return new AppointmentsController(
Dependency<IAppointmentServices>().Object,
Dependency<IAppointmentRepository>().Object,
Dependency<IAppointmentModelFacadeFactory>().Object
);
}
[Test]
public void When_getting_appointments_it_should_return_a_view_with_the_list_of_ended_appointments()
{
// Arrange
// Act
var result = Subject.GetAll();
// Assert
Assert.That(result, Is.Not.Null);
}
[Test]
public void When_ending_an_appointment_it_should_end_the_appointment()
{
// Arrange
var appointment = new Appointment();
// Act
Subject.End(appointment);
// Assert
Verify<IAppointmentServices>(e => e.Save(appointment), Times.Once);
}
[Test]
public void When_starting_appointment_that_throws_MissingResourceException_it_should_return_view_with_error()
{
// Arrange
var appointment = new Appointment
{
Id = "1",
StartedAt = DateTime.Now,
PatientId = "23",
ServiceId = "32"
};
Dependency<IAppointmentServices>()
.Setup(e => e.EnsureValidForSave(appointment))
.Throws<MissingResourceException>();
// Act
var result = Subject.Start(appointment) as RedirectToRouteResult;
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.RouteValues["action"], Is.EqualTo("IndexWithError"));
Assert.That(result.RouteValues["controller"], Is.EqualTo("Home"));
}
[Test]
public void When_ending_an_appointment_it_should_redirect_to_home()
{
// Arrange
var appointment = new Appointment();
// Act
var result = Subject.End(appointment) as RedirectToRouteResult;
// Assert
Assert.That(result, Is.Not.Null);
Assert.That((object)result.RouteValues, Is.Not.Null);
Assert.That(result.RouteValues["action"], Is.EqualTo("Index"));
Assert.That(result.RouteValues["controller"], Is.EqualTo("Home"));
}
[Test]
public void When_getting_todays_appointments_it_should_return_a_view_with_todays_appointments()
{
// Arrange
var appointment = new Appointment();
var appointments = new [] { appointment };
var appointmentModel = new AppointmentModel();
Setup<IAppointmentRepository, IEnumerable<Appointment>>(e => e.GetDayAppointments(It.IsAny<DateTime>()))
.Returns(appointments);
Setup<IAppointmentModelFacadeFactory, AppointmentModel>(e => e.MakeAppointmentModel(appointment))
.Returns(appointmentModel);
// Act
var result = Subject.TodaysAppointments() as ViewResult;
var model = result.Model as IEnumerable<AppointmentModel>;
// Assert
Assert.That(model, Is.Not.Null);
Assert.That(model.First(), Is.EqualTo(appointmentModel));
}
}
}
| mit |
stivalet/PHP-Vulnerability-test-suite | Injection/CWE_89/safe/CWE_89__exec__func_FILTER-CLEANING-number_int_filter__select_from_where-sprintf_%u.php | 1763 | <?php
/*
Safe sample
input : use exec to execute the script /tmp/tainted.php and store the output in $tainted
Uses a number_int_filter via filter_var function
construction : use of sprintf via a %u
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$script = "/tmp/tainted.php";
exec($script, $result, $return);
$tainted = $result[0];
$sanitized = filter_var($tainted, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($sanitized, FILTER_VALIDATE_INT))
$tainted = $sanitized ;
else
$tainted = "" ;
$query = sprintf("SELECT * FROM student where id=%u", $tainted);
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | mit |
ryanabragg/VanguardLARP | test/components/util/Field.test.js | 4189 | import React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { shallow } from 'enzyme';
import Field from '../../../src/components/util/Field';
describe('<Field />', () => {
it('renders an input', () => {
const edit = spy();
const wrapper = shallow(<Field name='test' value='try' />);
expect(wrapper.find('input')).to.have.length(1);
expect(wrapper.find('input').prop('type')).to.equal('text');
expect(wrapper.find('input').prop('name')).to.equal('test');
wrapper.setProps({
type: 'number',
placeholder: '4'
});
expect(wrapper.find('input').prop('type')).to.equal('number');
expect(wrapper.find('input').prop('value')).to.equal('try');
expect(wrapper.find('input').prop('placeholder')).to.equal('4');
expect(wrapper.find('input').prop('readOnly')).to.equal(true);
wrapper.setProps({
onChange: edit
});
expect(wrapper.find('input').prop('readOnly')).to.equal(false);
});
it('executes the onChange prop when the value is changed', () => {
const edit = spy();
const wrapper = shallow(<Field name='test' onChange={edit} />);
wrapper.find('input').simulate('change', {target: {name: 'test', value: 'blah'}, stopPropagation: () => {}});
expect(edit.callCount).to.equal(1);
expect(edit.firstCall.args[0]).to.deep.equal({type: 'test', data: 'blah'});
wrapper.setProps({
type: 'text',
value: 0
});
wrapper.find('input').simulate('change', {target: {name: 'trY', value: '4'}, stopPropagation: () => {}});
expect(edit.callCount).to.equal(2);
expect(edit.secondCall.args[0]).to.deep.equal({type: 'trY', data: '4'});
wrapper.setProps({
type: 'number',
value: 4
});
wrapper.find('input').simulate('change', {target: {name: 'trY', value: '2'}, stopPropagation: () => {}});
expect(edit.callCount).to.equal(3);
expect(edit.thirdCall.args[0]).to.deep.equal({type: 'trY', data: 2});
});
it('renders a select instead of an input if type is select', () => {
const edit = spy();
const wrapper = shallow(<Field name='test' onChange={edit} />);
expect(wrapper.find('input')).to.have.length(1);
expect(wrapper.find('select')).to.have.length(0);
wrapper.setProps({
type: 'select'
});
expect(wrapper.find('input')).to.have.length(0);
expect(wrapper.find('select')).to.have.length(1);
expect(wrapper.find('option')).to.have.length(1);
expect(wrapper.find('option').prop('value')).to.equal('');
expect(wrapper.find('option').text()).to.equal('');
wrapper.setProps({
options: [{value: 42, label: 'one'}, {value: 'test', label: 2}]
});
expect(wrapper.find('option')).to.have.length(3);
expect(wrapper.find('option').at(0).prop('value')).to.equal('');
expect(wrapper.find('option').at(0).text()).to.equal('');
expect(wrapper.find('option').at(1).prop('value')).to.equal(42);
expect(wrapper.find('option').at(1).text()).to.equal('one');
expect(wrapper.find('option').at(2).prop('value')).to.equal('test');
expect(wrapper.find('option').at(2).text()).to.equal('2');
wrapper.find('select').simulate('change', {target: {name: 'test', value: 42}, stopPropagation: () => {}});
expect(edit.callCount).to.equal(1);
expect(edit.firstCall.args[0]).to.deep.equal({type: 'test', data: 42});
});
it('renders a checkbox instead of an normal input if type is checkbox', () => {
const edit = spy();
const wrapper = shallow(<Field name='test' onChange={edit} />);
expect(wrapper.find({type: 'checkbox'})).to.have.length(0);
wrapper.setProps({
type: 'checkbox'
});
expect(wrapper.find({type: 'checkbox'})).to.have.length(1);
wrapper.find('input').simulate('change', {target: {name: 'test', checked: true}, stopPropagation: () => {}});
expect(edit.callCount).to.equal(1);
expect(edit.firstCall.args[0]).to.deep.equal({type: 'test', data: 1});
wrapper.find('input').simulate('change', {target: {name: 'test', checked: false}, stopPropagation: () => {}});
expect(edit.callCount).to.equal(2);
expect(edit.secondCall.args[0]).to.deep.equal({type: 'test', data: 0});
});
});
| mit |
WeiFund/WeiFund | app/client/templates/components/accountFactory.js | 4907 | /**
Template Controller
@module Templates
*/
/**
The template to allow easy WeiFund contract deployment.
@class [template] components_weihash
@constructor
*/
var template;
Template['components_accountFactory'].created = function() {
TemplateVar.set('deployAccountsState', {
isUndeployed: true
});
};
Template['components_accountFactory'].rendered = function() {
template = this;
};
Template['components_accountFactory'].helpers({
'gasAmount': function() {
return web3.eth.defaultGas;
},
'estimateGas': function() {
return 1906742;
},
'weifundAddress': function() {
return objects.contracts.WeiFund.address;
},
});
Template['components_accountFactory'].events({
/**
Deploy the WeiHash contract.
@event (click #weifundDeploy)
**/
'click #deployCampaignAccountFactory': function(event, template) {
if (!confirm("Are you sure you want to deploy a WeiHash contract?"))
return;
// set new WeiFund address and TX object
var weifundAddress = objects.contracts.WeiFund.address,
transactionObject = {
data: '0x' + CampaignAccountFactory.bytecode,
gas: web3.eth.defaultGas,
from: web3.eth.defaultAccount
};
// create new CampaignAccountFactory contract
CampaignAccountFactory.new(weifundAddress, transactionObject, function(err, result) {
if (err)
return TemplateVar.set(template, 'deployAccountsState', {
isError: true,
error: err
});
// set state as mining
TemplateVar.set(template, 'deployAccountsState', {
isMining: true,
transactionHash: result.transactionHash
});
// set state as mined
if (result.address) {
TemplateVar.set(template, 'deployAccountsState', {
isMined: true,
address: result.address,
transactionHash: result.transactionHash
});
// get/set contracts object
var contractsObject = LocalStore.get('contracts');
contractsObject[LocalStore.get('network')] = {
CampaignAccountFactory: result.address,
};
// Update the CampaignAccountFactory address
LocalStore.set('contracts', contractsObject);
}
});
// Prevent Double Click
$(event.currentTarget).prop('disabled', true);
},
/**
Register a hash with WeiHash.
@event (click #weihashRegister)
**/
'click #newAccount': function(event, template) {
// set campaign ID,
var campaignID = Helpers.cleanAscii($('#newAccountCampaignID').val()),
transactionObject = {
from: web3.eth.defaultAccount,
gas: web3.eth.defaultGas
},
filterObject = {
_campaignID: campaignID,
};
objects.contracts.WeiFund.isSuccess(campaignID, function(err, result) {
console.log('success', result);
});
objects.contracts.WeiFund.hasFailed(campaignID, function(err, result) {
console.log('failed', result);
});
objects.contracts.WeiFund.isPaidOut(campaignID, function(err, result) {
console.log('paidout', result);
});
objects.contracts.WeiFund.isOwner(campaignID, transactionObject.from, function(err, result) {
console.log('owner', result);
});
if (!confirm("Are you sure you want to register this hash with WeiHash?"))
return;
// Prevent Double Click
$(event.currentTarget).prop('disabled', true);
objects.contracts.CampaignAccountFactory.newCampaignAccount(campaignID, transactionObject, function(err, result) {
if (err)
return TemplateVar.set(template, 'newAccountState', {
isError: true,
error: err
});
// set new account state
TemplateVar.set(template, 'newAccountState', {
isMining: true,
transactionHash: result
});
});
objects.contracts.CampaignAccountFactory.AccountRegistered({
_campaignID: campaignID
}, function(err, result) {
if (err)
return TemplateVar.set(template, 'newAccountState', {
isError: true,
error: err
});
if (result)
TemplateVar.set(template, 'newAccountState', {
isMined: true,
address: result.args._account,
transactionHash: result.transactionHash
});
});
},
/**
Lookup a hash on the WeiHash registery.
@event (click #weihashLookup)
**/
'click #lookupAccount': function(event, template) {
var campaignID = Helpers.cleanAscii($('#lookupAccountCampaignID').val());
objects.contracts.CampaignAccountFactory.accountOf(campaignID, function(err, result) {
if (err)
return TemplateVar.set(template, 'lookupAccountState', {
isError: true,
error: err
});
TemplateVar.set(template, 'lookupAccountState', {
isSuccess: true,
campaignID: campaignID,
address: result
});
});
},
});
| mit |
VelvetMirror/login | app/cache/dev/twig/79/50/af056fa5e6f272663053e995eb8a.php | 4137 | <?php
/* AcmeLoginBundle::layout.html.twig */
class __TwigTemplate_7950af056fa5e6f272663053e995eb8a extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->blocks = array(
'title' => array($this, 'block_title'),
'content_header_more' => array($this, 'block_content_header_more'),
'content_header' => array($this, 'block_content_header'),
'content' => array($this, 'block_content'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$context = array_merge($this->env->getGlobals(), $context);
// line 1
echo "<!DOCTYPE html>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<link rel=\"stylesheet\" href=\"";
// line 5
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/acmedemo/css/demo.css"), "html");
echo "\" type=\"text/css\" media=\"all\" />
<title>";
// line 6
$this->displayBlock('title', $context, $blocks);
echo "</title>
<link rel=\"shortcut icon\" href=\"";
// line 7
echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("favicon.ico"), "html");
echo "\" />
</head>
<body>
<div id=\"symfony-wrapper\">
<div id=\"symfony-header\">
</div>
";
// line 14
if ($this->getAttribute($this->getAttribute($this->getContext($context, 'app'), "session", array(), "any", false), "flash", array("notice", ), "method", false)) {
// line 15
echo " <div class=\"flash-message\">
<em>Notice</em>: ";
// line 16
echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute($this->getContext($context, 'app'), "session", array(), "any", false), "flash", array("notice", ), "method", false), "html");
echo "
</div>
";
}
// line 19
echo "
";
// line 20
$this->displayBlock('content_header', $context, $blocks);
// line 29
echo "
<div class=\"symfony-content\">
";
// line 31
$this->displayBlock('content', $context, $blocks);
// line 33
echo " </div>
";
// line 35
if (twig_test_defined("code", $context)) {
// line 36
echo " <h2>Code behind this page</h2>
<div class=\"symfony-content\">";
// line 37
echo $this->getContext($context, 'code');
echo "</div>
";
}
// line 39
echo " </div>
</body>
</html>
";
}
// line 6
public function block_title($context, array $blocks = array())
{
echo "Demo Bundle";
}
// line 22
public function block_content_header_more($context, array $blocks = array())
{
// line 23
echo " <li><a href=\"";
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("homepage"), "html");
echo "\">Home</a></li>
";
}
// line 20
public function block_content_header($context, array $blocks = array())
{
// line 21
echo " <ul id=\"menu\">
";
// line 22
$this->displayBlock('content_header_more', $context, $blocks);
// line 25
echo " </ul>
<div style=\"clear: both\"></div>
";
}
// line 31
public function block_content($context, array $blocks = array())
{
// line 32
echo " ";
}
public function getTemplateName()
{
return "AcmeLoginBundle::layout.html.twig";
}
public function isTraitable()
{
return false;
}
}
| mit |
ksbobrov/java_pft | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactCreationTests.java | 2108 | package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import ru.stqa.pft.addressbook.model.Contacts;
import ru.stqa.pft.addressbook.model.Groups;
import ru.stqa.pft.addressbook.utils.FileParser;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static ru.stqa.pft.addressbook.utils.Constants.TESTS_RESOURCES_PATH;
public class ContactCreationTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.goTo().homePage();
}
@DataProvider
public Iterator<Object[]> validContactsFromXml() throws IOException {
List<ContactData> contacts = FileParser.getListFromXml(ContactData.class, new File(TESTS_RESOURCES_PATH + "/contacts.xml"));
return contacts.stream().map(g -> new Object[]{g}).collect(Collectors.toList()).iterator();
}
@DataProvider
public Iterator<Object[]> validContactsFromJson() throws IOException {
List<ContactData> contacts = FileParser.getListFromJson(ContactData.class, new File(TESTS_RESOURCES_PATH + "/contacts.json"));
return contacts.stream().map(g -> new Object[]{g.withId(0)}).collect(Collectors.toList()).iterator();
}
@Test(dataProvider = "validContactsFromXml")
public void testContactCreation(ContactData contact) {
Groups groups = app.db().groups();
Contacts before = app.db().contacts();
contact.inGroup(groups.iterator().next());
app.contacts().create(contact);
assertThat(app.contacts().count(), equalTo(before.size() + 1));
Contacts after = app.db().contacts();
int maxId = after.stream().mapToInt(ContactData::getId).max().getAsInt();
assertThat(after, equalTo(before.withAdded(contact.withId(maxId))));
verifyContactListInUI();
}
}
| mit |
midoks/WebCodePush | WCP/app/controller/sys.php | 5098 | <?php
/**
* 系统管理
* 作者 midoks
* 创建时间 2016-11-05
*/
class sysController extends baseController {
//初始化
public function __construct(){
parent::__construct();
$this->conf['hidden'] = explode(',', $this->conf['hidden']);
if($this->userinfo['type'] != 0 ){
$this->jump($this->buildUrl('index'));
}
}
//项目页
public function index(){
$this->load('sys');
}
//项目
public function project(){
$projects = wcp_dir_list(WCP_ROOT.'/conf/project/');
$projects = wcp_filter_list($projects, $this->conf['hidden']);
$list = array();
foreach ($projects as $project) {
$_tmp = include($project['abspath']);
$_tmp['project_name'] = str_replace('.php', '', $project['fn']);
$list[] = $_tmp;
}
foreach ($list as $key => $value) {
$t = $list[$key]['project_target'];
$list[$key]['project_target'] = str_replace(',', "<br/>", $t);
}
$this->list = $list;
$this->title = "项目管理";
$this->load('project');
}
//项目添加
public function projectadd(){
if (isset($_POST['submit'])) {
$content = wcp_add_project($_POST);
$repo = $_POST['project_name'];
$repo = WCP_ROOT.'/conf/project/'.$repo.'.php';
if (file_exists($repo)){
$this->error = "已经存在此项目!!!";
} else {
$ret = file_put_contents($repo, $content);
if($ret){
$this->jump($this->buildUrl('project', '', 'sys'));
} else {
$this->error = "添加失败!!";
}
}
}
$this->title = "添加项目";
$this->load('project_add');
}
public function projectmod(){
if (isset($_POST['submit'])) {
$content = wcp_add_project($_POST);
$repo = $_POST['project_name'];
$repo = WCP_ROOT."/conf/project/{$repo}.php";
$ret = file_put_contents($repo, $content);
if($ret){
$this->jump($this->buildUrl('project', '', 'sys'));
} else {
$this->error = "添加失败!!";
}
}
if (isset($_GET['project'])){
$repo = $_GET['project'];
$repo = WCP_ROOT.'/conf/project/'.$repo.'.php';
if(file_exists($repo)){
$project_info = include($repo);
$project_info['project_name'] = $_GET['project'];
//$project_info['project_target'] = str_replace(',', "\r\n", $project_info['project_target']);
$this->project_info = $project_info;
} else {
$this->jump($this->buildUrl('project', '', 'sys'));
}
} else {
$this->jump($this->buildUrl('project', '', 'sys'));
}
$this->title = "项目修改";
$this->load('project_add');
}
//删除项目
public function projectdel(){
if (isset($_GET['project'])){
$repo = $_GET['project'];
$repo = WCP_ROOT.'/conf/project/'.$repo.'.php';
if(!file_exists($repo)){
exit('项目不存在');
}
$ret = unlink($repo);
if($ret){
$this->jump($this->buildUrl('project', '', 'sys'));
} else {
exit('删除失败');
}
}
}
//用户管理
public function user(){
$users = wcp_dir_list(WCP_ROOT.'/conf/acl/');
//var_dump($users);
$users = wcp_filter_list($users, $this->conf['hidden']);
//var_dump($users);
$list = array();
foreach ($users as $user) {
$_tmp = include($user['abspath']);
$_tmp['username'] = str_replace('.php', '', $user['fn']);
$list[] = $_tmp;
}
$this->list = $list;
$this->load('user');
}
//添加用户
public function useradd(){
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$user_file = WCP_ROOT.'/conf/acl/'.$username.'.php';
if (file_exists($user_file)){
$this->error = "已经存在此用户";
} else {
$_POST['pwd'] = md5($_POST['pwd']);
$ret = update_user_info($_POST);
if($ret){
$this->jump($this->buildUrl('user', '', 'sys'));
} else {
$this->error = "添加失败!!";
}
}
}
$this->title = "添加用户";
$this->load('useradd');
}
//用户设置
public function usermod(){
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$user_file = WCP_ROOT.'/conf/acl/'.$username.'.php';
$_tmp_user = include($user_file);
//密码为空,就不修改
if(isset($_POST['pwd']) && empty($_POST['pwd'])){
$_POST['pwd'] = $_tmp_user['pwd'];
} else {
$_POST['pwd'] = md5($_POST['pwd']);
}
$ret = update_user_info($_POST);
if($ret){
$this->jump($this->buildUrl('user', '', 'sys'));
} else {
$this->error = "修改失败!!";
}
}
$username = $_GET['username'];
$user_file = WCP_ROOT.'/conf/acl/'.$username.'.php';
if(!file_exists($user_file)){
$this->jump($this->buildUrl('user', '', 'sys'));
}
$userinfo = include($user_file);
$userinfo['username'] = $username;
$this->title = "用户修改";
$this->userinfo = $userinfo;
$this->load('usermod');
}
//删除用户
public function userdel(){
if (isset($_GET['username'])){
$username = $_GET['username'];
$user_file = WCP_ROOT.'/conf/acl/'.$username.'.php';
if(!file_exists($user_file)){
exit('用户不存在');
}
$ret = unlink($user_file);
if($ret){
$this->jump($this->buildUrl('user', '', 'sys'));
} else {
exit('删除失败');
}
}
}
}
?> | mit |
node-opcua/node-opcua | packages/node-opcua-nodeset-ua/source/ua_pub_sub_diagnostics_reader_group.ts | 1846 | // ----- this file has been automatically generated - do not edit
import { UAObject } from "node-opcua-address-space-base"
import { DataType } from "node-opcua-variant"
import { UInt32, UInt16 } from "node-opcua-basic-types"
import { UAPubSubDiagnostics_counters, UAPubSubDiagnostics, UAPubSubDiagnostics_Base } from "./ua_pub_sub_diagnostics"
import { UAPubSubDiagnosticsCounter } from "./ua_pub_sub_diagnostics_counter"
import { UABaseDataVariable } from "./ua_base_data_variable"
export interface UAPubSubDiagnosticsReaderGroup_counters extends UAPubSubDiagnostics_counters { // Object
receivedNetworkMessages: UAPubSubDiagnosticsCounter<UInt32>;
receivedInvalidNetworkMessages?: UAPubSubDiagnosticsCounter<UInt32>;
decryptionErrors?: UAPubSubDiagnosticsCounter<UInt32>;
}
export interface UAPubSubDiagnosticsReaderGroup_liveValues extends UAObject { // Object
configuredDataSetReaders: UABaseDataVariable<UInt16, /*z*/DataType.UInt16>;
operationalDataSetReaders: UABaseDataVariable<UInt16, /*z*/DataType.UInt16>;
}
/**
* | | |
* |----------------|--------------------------------------------------|
* |namespace |http://opcfoundation.org/UA/ |
* |nodeClass |ObjectType |
* |typedDefinition |PubSubDiagnosticsReaderGroupType ns=0;i=19903 |
* |isAbstract |false |
*/
export interface UAPubSubDiagnosticsReaderGroup_Base extends UAPubSubDiagnostics_Base {
counters: UAPubSubDiagnosticsReaderGroup_counters;
liveValues: UAPubSubDiagnosticsReaderGroup_liveValues;
}
export interface UAPubSubDiagnosticsReaderGroup extends Omit<UAPubSubDiagnostics, "counters"|"liveValues">, UAPubSubDiagnosticsReaderGroup_Base {
} | mit |
Otsimo/simple-notifications | vendor/src/github.com/sendgrid/sendgrid-go/examples/mailboxproviders/mailboxproviders.go | 1007 | package main
import (
"fmt"
"github.com/sendgrid/sendgrid-go"
"os"
)
///////////////////////////////////////////////////
// Retrieve email statistics by mailbox provider.
// GET /mailbox_providers/stats
func Retrieveemailstatisticsbymailboxprovider() {
apiKey := os.Getenv("YOUR_SENDGRID_APIKEY")
host := "https://api.sendgrid.com"
request := sendgrid.GetRequest(apiKey, "/v3/mailbox_providers/stats", host)
request.Method = "GET"
queryParams := make(map[string]string)
queryParams["end_date"] = "2016-04-01"
queryParams["mailbox_providers"] = "test_string"
queryParams["aggregated_by"] = "day"
queryParams["limit"] = "1"
queryParams["offset"] = "1"
queryParams["start_date"] = "2016-01-01"
request.QueryParams = queryParams
response, err := sendgrid.API(request)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(response.StatusCode)
fmt.Println(response.Body)
fmt.Println(response.Headers)
}
}
func main() {
// add your function calls here
}
| mit |
kokspflanze/schmidtke_project | src/Igel/MainBundle/Entity/TicketEntry.php | 2087 | <?php
namespace Igel\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TicketEntry
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Igel\MainBundle\Entity\TicketEntryRepository")
*/
class TicketEntry {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var integer
*
* @ORM\ManyToOne(targetEntity="TicketSubject", inversedBy="id")
*/
private $subject;
/**
* @var integer
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="id")
*/
private $usr;
/**
* @var string
*
* @ORM\Column(name="memo", type="text")
*/
private $memo;
/**
* @var \DateTime
*
* @ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct( ) {
$this->setCreated(new \DateTime(date('Y-m-d H:i:s',time())));
}
/**
* Get id
*
* @return integer
*/
public function getId() {
return $this->id;
}
/**
* Set subjectId
*
* @param integer $subjectId
*
* @return TicketEntry
*/
public function setSubject( $subjectId ) {
$this->subject = $subjectId;
return $this;
}
/**
* Get subjectId
*
* @return integer
*/
public function getSubject() {
return $this->subject;
}
/**
* Set usrId
*
* @param integer $usrId
*
* @return TicketEntry
*/
public function setUser( $usrId ) {
$this->usr = $usrId;
return $this;
}
/**
* Get usrId
*
* @return integer
*/
public function getUser() {
return $this->usr;
}
/**
* Set memo
*
* @param string $memo
*
* @return TicketEntry
*/
public function setMemo( $memo ) {
$this->memo = $memo;
return $this;
}
/**
* Get memo
*
* @return string
*/
public function getMemo() {
return $this->memo;
}
/**
* Set created
*
* @param \DateTime $created
*
* @return TicketEntry
*/
public function setCreated( $created ) {
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated() {
return $this->created;
}
}
| mit |
stpettersens/DbExporter | DbExporter/Properties/Resources.Designer.cs | 2779 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DbExporter.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DbExporter.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| mit |
nationalfield/symfony | lib/helper/I18NHelper.php | 2490 | <?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* I18NHelper.
*
* @package symfony
* @subpackage helper
* @author Fabien Potencier <[email protected]>
* @version SVN: $Id: I18NHelper.php 31894 2011-01-24 18:12:37Z fabien $
*/
function __($text, $args = array(), $catalogue = 'messages')
{
if (sfConfig::get('sf_i18n'))
{
return sfContext::getInstance()->getI18N()->__($text, $args, $catalogue);
}
else
{
if (empty($args))
{
$args = array();
}
// replace object with strings
foreach ($args as $key => $value)
{
if (is_object($value) && method_exists($value, '__toString'))
{
$args[$key] = $value->__toString();
}
}
return strtr($text, $args);
}
}
/**
* Format a string according to a number.
*
* Every segment is separated with |
* Each segment defines an intervale and a value.
*
* For example :
*
* * [0]Nobody is logged|[1]There is 1 person logged|(1,+Inf]There are %number persons logged
*
* @param string $text Text used for different number values
* @param array $args Arguments to replace in the string
* @param int $number Number to use to determine the string to use
* @param string $catalogue Catalogue for translation
*
* @return string Result of the translation
*/
function format_number_choice($text, $args = array(), $number, $catalogue = 'messages')
{
$translated = __($text, $args, $catalogue);
$choice = new sfChoiceFormat();
$retval = $choice->format($translated, $number);
if ($retval === false)
{
throw new sfException(sprintf('Unable to parse your choice "%s".', $translated));
}
return $retval;
}
function format_country($country_iso, $culture = null)
{
$c = sfCultureInfo::getInstance($culture === null ? sfContext::getInstance()->getUser()->getCulture() : $culture);
$countries = $c->getCountries();
return isset($countries[$country_iso]) ? $countries[$country_iso] : '';
}
function format_language($language_iso, $culture = null)
{
$c = sfCultureInfo::getInstance($culture === null ? sfContext::getInstance()->getUser()->getCulture() : $culture);
$languages = $c->getLanguages();
return isset($languages[$language_iso]) ? $languages[$language_iso] : '';
}
| mit |
wonderzhou/read4u | src/main/java/com/zoe/wechat/message/resp/TextMessage.java | 257 | package com.zoe.wechat.message.resp;
public class TextMessage extends BaseMessage {
// 回复的消息内容
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
} | mit |
grigore-94/STAGE | src/AppBundle/API/ApiJob.php | 1187 | <?php
/**
* Created by PhpStorm.
* User: gbrodicico
* Date: 2/27/2017
* Time: 11:41 AM
*/
namespace AppBundle\API;
use AppBundle\Form\Model\ApiModel;
use Doctrine\ORM\EntityManager;
class ApiJob
{
private $em;
/**
* @InjectParams({
* "em" = @Inject("doctrine.orm.entity_manager")
* })
* @param EntityManager $em
*/
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* @param ApiModel $apiModel
* @return array
*/
public function getJobs($apiModel)
{
$repository = $this->em->getRepository('AppBundle:Job');
$position = $apiModel->getPosition();
$limit = $apiModel->getLimit();
$nameCategory = $apiModel->getCategory()->getName();
if ($limit == 'all') {
$limit = $repository->getApiCountJobs();
}
if ($position == 'all') {
$position = '%%';
}
if ($nameCategory == 'all') {
$nameCategory = '%%';
}
$jobs = $repository->getApiJobs(
$position,
$limit,
$nameCategory
);
return $jobs;
}
} | mit |
subwaymatch/trackbrowser-client | js/browser-window/view/TabView.js | 13217 | 'use strict';
/**
* TabView consists of a browser tab and it's associated webview
*
* @param {HackBrowserWindowController} hackBrowserWindow - the browser window
* @param {BrowserTabBar} browserTabBar
* @param {string} url - initial url
*
* @constructor
*/
function TabView(hackBrowserWindow, browserTabBar, url) {
var _this = this;
const fs = require("fs");
/* ====================================
private member variables
isDidNavigateHandled - whether a screenshot for a particular navigation has been handled
====================================== */
var webViewEl;
var webViewTitle;
var webViewURL;
var webViewContainerEl;
var webViewWrapperEl;
var searchBox;
var searchBoxEl;
var tabViewId;
var browserTab;
var isDOMReady;
var isWaitingForScreenshotWhenActivated;
var isDidNavigateHandled;
/* ====================================
private methods
====================================== */
/**
* create a new <webview> element and linked browser tab
*
* @param url
*/
var init = function(url) {
webViewEl = document.createElement("webview");
webViewWrapperEl = document.createElement("div");
webViewWrapperEl.classList.add("webview-wrapper");
webViewTitle = "New Tab";
webViewURL = url;
webViewContainerEl = document.getElementById("webview-container");
isDOMReady = false;
tabViewId = "wv-" + hackBrowserWindow.getCreatedTabViewCount();
isWaitingForScreenshotWhenActivated = false;
isDidNavigateHandled = false;
// increase created tab view count
hackBrowserWindow.incrementCreatedTabViewCount();
// assign tabViewId to <webview> element's id
webViewEl.setAttribute("id", tabViewId);
webViewEl.setAttribute("plugins", "");
webViewEl.setAttribute("disablewebsecurity", "");
if (url === null) {
_this.navigateTo("http://www.google.com/");
} else {
_this.navigateTo(url);
}
// append search box
searchBox = new SearchBox(_this);
searchBoxEl = searchBox.getSearchWrapperEl();
// append the webview element to screen (#webview-container)
webViewWrapperEl.appendChild(webViewEl);
webViewWrapperEl.appendChild(searchBoxEl);
webViewContainerEl.appendChild(webViewWrapperEl);
browserTab = browserTabBar.createTab(tabViewId);
attachEventHandlers();
};
var attachEventHandlers = function() {
/*
<webview> events are fired in the following order
did-start-loading
did-get-response-details
load-commit
did-navigate
page-title-updated
dom-ready
page-favicon-updated
did-stop-loading
did-frame-finish-load
did-finish-load
*/
webViewEl.addEventListener("load-commit", handleLoadCommit);
webViewEl.addEventListener("did-finish-load", handleDidFinishLoad);
webViewEl.addEventListener("did-fail-load", handleDidFailLoad);
webViewEl.addEventListener("did-frame-finish-load", handleDidFrameFinishLoad);
webViewEl.addEventListener("did-start-loading", handleDidStartLoading);
webViewEl.addEventListener("did-stop-loading", handleDidStopLoading);
webViewEl.addEventListener("did-get-response-details", handleDidGetResponseDetails);
webViewEl.addEventListener("did-get-redirect-request", handleDidGetRedirectRequest);
webViewEl.addEventListener("dom-ready", handleDOMReady);
webViewEl.addEventListener("page-title-updated", handlePageTitleUpdated);
webViewEl.addEventListener("page-favicon-updated", handlePageFaviconUpdated);
webViewEl.addEventListener("new-window", handleNewWindow);
webViewEl.addEventListener("will-navigate", handleWillNavigate);
webViewEl.addEventListener("did-navigate", handleDidNavigate);
webViewEl.addEventListener("did-navigate-in-page", handleDidNavigateInPage);
webViewEl.addEventListener("console-message", handleConsoleMessage);
};
var handleLoadCommit = function(e) {
console.log("[" + tabViewId + "] load-commit");
if (e.isMainFrame === true) {
webViewURL = e.url;
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.updateWindowTitle(webViewURL);
}
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.updateWindowControls();
}
}
};
// 'did-finish-load' event fires after onload event is dispatched from the WebView
var handleDidFinishLoad = function() {
console.log("[" + tabViewId + "] did-finish-load");
// take screenshot and notify main process via ipc
if ((hackBrowserWindow.getIsTrackingOn() === true) && (isDidNavigateHandled === false)) {
if (hackBrowserWindow.getActiveTabView() === _this) {
// manually clear screenshot delay
hackBrowserWindow.clearScreenshotDelay();
_this.takeScreenshotAndRequestUpload();
}
else {
isWaitingForScreenshotWhenActivated = true;
}
// set flag for handling did-navigate status
isDidNavigateHandled = true;
} else {
console.log("Tracking mode is turned off or navigation is already handled");
}
};
var handleDidFailLoad = function(e) {
console.log("[" + tabViewId + "] did-fail-load");
console.log(e);
};
var handleDidFrameFinishLoad = function(e) {
console.log("[" + tabViewId + "] did-frame-finish-load");
webViewURL = webViewEl.getURL();
};
var handleDidStartLoading = function() {
console.log("[" + tabViewId + "] did-start-loading");
// set loading icon
browserTab.startLoading();
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.getMenuBar().showLoadStopBtn();
}
};
var handleDidStopLoading = function() {
console.log("[" + tabViewId + "] did-stop-loading");
// clear loading icon
browserTab.stopLoading();
if ((hackBrowserWindow.getIsTrackingOn() === true) && (isDidNavigateHandled === false)) {
recordNavigation();
} else {
console.log("Tracking mode is turned off or navigation is already handled");
}
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.getMenuBar().showReloadBtn();
}
};
var handleDidGetResponseDetails = function(e) {
console.log("[" + tabViewId + "] did-get-response-details");
};
var handleDidGetRedirectRequest = function(e) {
console.log("[" + tabViewId + "] did-get-redirect-request");
};
var handleDOMReady = function() {
console.log("[" + tabViewId + "] dom-ready");
var TRACK_SCRIPT_PATH = __dirname + "/../js/browser-window/inject/inject-to-webview.js";
isDOMReady = true;
// insert custom script to <webview> to handle click events
fs.readFile(TRACK_SCRIPT_PATH, "utf-8", function(err, injectScript) {
if (err) {
console.log("[" + tabViewId + "] error loading inject script");
return;
}
webViewEl.executeJavaScript(injectScript);
console.log("[" + tabViewId + "] successfully injected script to webview");
});
};
var handlePageTitleUpdated = function(e) {
console.log("[" + tabViewId + "] page-title-updated");
webViewTitle = e.title;
// update tab title
_this.updateTabTitle(webViewTitle);
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.updateWindowTitle(webViewTitle);
}
};
var handlePageFaviconUpdated = function(e) {
console.log("[" + tabViewId + "] page-favicon-updated");
// the last element in favicons array is used
// TODO: if multiple favicon items are returned and last element is invalid, use other ones
_this.updateTabFavicon(e.favicons[e.favicons.length - 1]);
};
var handleNewWindow = function(e) {
console.log("[" + tabViewId + "] new-window");
hackBrowserWindow.addNewTab(e.url, true);
console.log(e);
};
var handleWillNavigate = function(e) {
console.log("[" + tabViewId + "] will-navigate");
console.log(e);
};
var handleDidNavigate = function(e) {
console.log("[" + tabViewId + "] did-navigate");
console.log(e);
isDidNavigateHandled = false;
webViewURL = e.url;
};
var handleDidNavigateInPage = function(e) {
console.log("[" + tabViewId + "] did-navigate-in-page");
console.log(e);
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.updateWindowControls();
}
// record events for in-page navigation
// instead of writing a separate handler,
// delegate the event to handler for "did-stop-loading" event
isDidNavigateHandled = false;
};
var handleConsoleMessage = function(e) {
console.log("[" + tabViewId + "] console-message");
// check if message text begins with curly braces (for json format)
// most of the time, non-json formats would be filtered here
// if the first character of message text is curly braces
// but the message text is not json format, an exception is thrown
if (e.message[0] == '{') {
try {
var msgObject = JSON.parse(e.message);
console.log(msgObject);
// if contextmenu action, pass it to context menu handler
if (msgObject.eventType === "contextmenu") {
hackBrowserWindow.getContextMenuHandler().handleWebViewContextMenu(msgObject);
}
// record click event
else if (msgObject.eventType === "click") {
// reset fibonacci timer
hackBrowserWindow.resetFibonacciScreenshotTimer();
if (hackBrowserWindow.getIsTrackingOn() === true) {
if (hackBrowserWindow.getActiveTabView() === _this) {
hackBrowserWindow.getIPCHandler().sendMouseEventData(tabViewId, webViewURL);
_this.takeScreenshotAndRequestUpload();
}
}
}
else if (msgObject.eventType === "scroll") {
// reset fibonacci timer
hackBrowserWindow.resetFibonacciScreenshotTimer();
if (hackBrowserWindow.getIsTrackingOn() === true) {
hackBrowserWindow.getIPCHandler().sendScrollEventData(tabViewId, webViewURL);
_this.takeScreenshotAndRequestUpload();
}
}
else if ((msgObject.eventType === "focus") && (msgObject.type === "input/password")) {
}
else if (msgObject.eventType === "blur") {
if ((msgObject.type === "input/password") || (msgObject.type === "input/search") || (msgObject.type === "input/email") || (msgObject.type === "input/text") || (msgObject.type === "textarea")) {
if (hackBrowserWindow.getIsTrackingOn() === true) {
if (hackBrowserWindow.getActiveTabView() === _this) {
console.log(msgObject);
hackBrowserWindow.getIPCHandler().sendInputEventData(tabViewId, webViewURL, msgObject);
_this.takeScreenshotAndRequestUpload();
}
}
}
}
} catch(err) {
// console.error(err);
// since the console-message is not a HackBrowser message, do nothing
}
}
};
var recordNavigation = function() {
// send ipc message to record navigation
hackBrowserWindow.getIPCHandler().sendNavigationData(tabViewId, webViewEl.getURL(), function(result) {
if (result === true) {
console.log("[" + tabViewId + "] navigation data successfully recorded to server");
}
});
};
/* ====================================
public methods
====================================== */
_this.navigateTo = function(url) {
var URLInfo = URIParser.parse(url);
// if an invalid URl is passed
if (URLInfo.isValid !== true) {
// do nothing
return;
}
if (URLInfo.type === "http") {
webViewEl.setAttribute("src", URLInfo.formattedURI);
}
else if (URLInfo.type === "file") {
console.log("User has entered a file URL into the addressbar: " + url);
webViewEl.setAttribute("src", URLInfo.formattedURI);
}
else if (URLInfo.type === "page") {
console.log("Opening HTML template file " + url);
webViewEl.setAttribute("src", URLInfo.formattedURI);
}
else if (URLInfo.type === "internal") {
console.log("User has navigated to an internal link: " + url);
}
else if (URLInfo.type === "search") {
console.log("User has searched " + url);
webViewEl.setAttribute("src", URLInfo.formattedURI);
}
};
_this.takeScreenshotAndRequestUpload = function(callback) {
callback = callback || function() {};
hackBrowserWindow.captureActiveWebView(function(imgPath) {
hackBrowserWindow.getIPCHandler().requestScreenshotUpload(tabViewId, webViewURL, imgPath);
callback();
});
};
/**
* activate TabView (user clicks on this browser tab)
*/
_this.activate = function() {
webViewWrapperEl.style.visibility = "visible";
browserTab.activate();
};
/**
* deactivate TabView (user clicks on another browser tab)
*/
_this.deactivate = function() {
webViewWrapperEl.style.visibility = "hidden";
browserTab.deactivate();
};
/**
* check whether navigation actions (back, forward, reload, etc) can be performed on <webview>
*
* @returns {boolean} whether dom-ready was fired at least once in the <webview> object
*/
_this.isDOMReady = function() {
return isDOMReady;
};
/**
* close current TabView
*/
_this.close = function() {
// remove webview element
webViewContainerEl.removeChild(webViewWrapperEl);
};
_this.getId = function() {
return tabViewId;
};
_this.getWebViewEl = function() {
return webViewEl;
};
_this.getWebViewTitle = function() {
return webViewTitle;
};
_this.getURL = function() {
return webViewURL;
};
_this.getSearchBox = function() {
return searchBox;
};
_this.updateTabFavicon = function(imageURL) {
browserTab.updateTabFavicon(imageURL);
};
_this.updateTabTitle = function(title) {
browserTab.updateTitle(title);
};
init(url);
}
| mit |
mhor-music/push-music-lib-droid | src/com/mhor/pushmusiclib/push/MusicDataPushMaker.java | 4990 | package com.mhor.pushmusiclib.push;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import com.mhor.pushmusiclib.model.*;
import java.util.Date;
import java.util.UUID;
public class MusicDataPushMaker extends PushMaker
{
public static String API_ROUTE = "";
protected PushMusicLibData pushMusicLibData = new PushMusicLibData();
public MusicDataPushMaker(Context applicationContext)
{
super(applicationContext);
}
public void getMusicLib()
{
this.setDeviceIntoDataPush();
this.setMusicLibContentIntoDataPush();
}
private void setMusicLibContentIntoDataPush()
{
String[] STAR = {"*"};
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor cursor = this.context.getContentResolver().query(
allsongsuri,
STAR,
selection,
null,
null
);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Album album = this.extractAlbum(cursor);
Artist artist = this.extractArtist(cursor);
Style style = this.extractStyle(cursor);
Track track = this.extractTrack(cursor);
this.putTrackDataOnPushData(album, artist, style, track);
} while (cursor.moveToNext());
}
cursor.close();
}
}
private void putTrackDataOnPushData(Album album, Artist artist, Style style, Track track)
{
if (!this.pushMusicLibData.albumExist(album)) {
this.pushMusicLibData.getAlbums().add(album);
}
track.setTrackStyle(style);
track.setArtist(artist);
this.pushMusicLibData.putTrack(album, track);
}
private void setDeviceIntoDataPush()
{
this.pushMusicLibData.setPushId(UUID.randomUUID() + "");
Date date = new Date();
this.pushMusicLibData.setDatePush(date.toString());
SharedPreferences settings = this.context.getSharedPreferences(PushMusicLibData.PREFS_PUSH_MUSIC_LIB, 0);
String token = settings.getString(PushMusicLibData.PREFS_PUSH_MUSIC_LIB_TOKEN, null);
String deviceId = Settings.Secure.getString(this.context.getContentResolver(), Settings.Secure.ANDROID_ID);
String deviceName = Build.MANUFACTURER + " " + Build.MODEL;
this.pushMusicLibData.setDevice(new Device(token, deviceId, deviceName));
}
protected Style extractStyle(Cursor cursor)
{
return null;
}
protected Artist extractArtist(Cursor cursor)
{
int id = cursor.getInt(
cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID)
);
String name = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
);
return new Artist(id, name);
}
protected Track extractTrack(Cursor cursor)
{
int id = cursor.getInt(
cursor.getColumnIndex(MediaStore.Audio.Media._ID)
);
String name = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)
);
int trackNumber = cursor.getInt(
cursor.getColumnIndex(MediaStore.Audio.Media.TRACK)
);
String duration = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)
);
String fullpath = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.DATA)
);
String year = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.YEAR)
);
String dateAdd = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)
);
String dateModified = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.DATE_MODIFIED)
);
return new Track(
id,
name,
fullpath,
year,
duration,
trackNumber,
dateAdd,
dateModified
);
}
protected Album extractAlbum(Cursor cursor)
{
String name = cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)
);
int id = cursor.getInt(
cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)
);
return new Album(id, name);
}
/**
* @return
* @TODO Not Implemented
*/
public boolean isValid()
{
return true;
}
public PushMusicLibData getPushData()
{
return this.pushMusicLibData;
}
}
| mit |
dondieselkopf/amgcl | amgcl/detail/qr.hpp | 26257 | #ifndef AMGCL_DETAIL_QR_HPP
#define AMGCL_DETAIL_QR_HPP
/*
The MIT License
Copyright (c) 2012-2016 Denis Demidov <[email protected]>
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.
*/
/**
* \file amgcl/detail/qr.hpp
* \author Denis Demidov <[email protected]>
* \brief QR decomposition.
*
* This is a port of ZGEQR2 procedure from LAPACK and its dependencies.
* The original code included the following copyright notice:
* \verbatim
Copyright (c) 1992-2013 The University of Tennessee and The University
of Tennessee Research Foundation. All rights
reserved.
Copyright (c) 2000-2013 The University of California Berkeley. All
rights reserved.
Copyright (c) 2006-2013 The University of Colorado Denver. All rights
reserved.
$COPYRIGHT$
Additional copyrights may follow
$HEADER$
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer listed
in this license in the documentation and/or other materials
provided with the distribution.
- Neither the name of the copyright holders nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
The copyright holders provide no reassurances that the source code
provided does not infringe any patent, copyright, or any other
intellectual property rights of third parties. The copyright holders
disclaim any liability to any recipient for claims brought against
recipient by any third party for infringement of that parties
intellectual property rights.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* \endverbatim
*/
#include <vector>
#include <complex>
#include <cmath>
#include <boost/math/special_functions/sign.hpp>
#include <amgcl/util.hpp>
#include <amgcl/value_type/interface.hpp>
namespace amgcl {
namespace detail {
enum storage_order {
row_major,
col_major
};
template <class T>
inline T real(T a) {
return a;
}
template <class T>
inline T real(std::complex<T> a) {
return std::real(a);
}
/// In-place QR factorization.
/**
* \tparam Order Storage order of the input matrix. Should be col_major for
* the best performance.
*/
template <typename value_type, storage_order Order, class Enable = void>
class QR {
public:
QR() : m(0), n(0) {}
// Computes a QR factorization of the matrix A, where Q is represented
// as a product of elementary reflectors.
// Q = H(1) H(2) . . . H(k), where k = min(rows,cols).
void compute(int rows, int cols, int row_stride, int col_stride, value_type *A, int max_cols = -1) {
/*
* Ported from ZGEQR2
* ==================
*
* Computes a QR factorization of an matrix A:
* A = Q * R.
*
* Arguments
* =========
*
* rows The number of rows of the matrix A.
* cols The number of columns of the matrix A.
*
* A On entry, the rows by cols matrix A.
* On exit, the elements on and above the diagonal of the
* array contain the min(m,n) by n upper trapezoidal
* matrix R (R is upper triangular if m >= n); the
* elements below the diagonal, with the array TAU,
* represent the unitary matrix Q as a product of
* elementary reflectors (see Further Details).
*
* Further Details
* ===============
*
* The matrix Q is represented as a product of elementary reflectors
*
* Q = H(1) H(2) . . . H(k), where k = min(m,n).
*
* Each H(i) has the form
*
* H(i) = I - tau * v * v'
*
* where tau is a value_type scalar, and v is a value_type vector
* with v[0:i) = 0 and v[i] = 1; v[i:m) is stored on exit in
* A[i+1:m)[i], and tau in tau[i].
* ==============================================================
*/
m = rows;
n = cols;
k = std::min(m, n);
nmax = (max_cols < 0 ? n : max_cols);
r = A;
tau.resize(std::min(m, nmax));
if (k <= 0) return;
for(int i = 0, ii = 0; i < k; ++i, ii += row_stride + col_stride) {
// Generate elementary reflector H(i) to annihilate A[i+1:m)[i]
tau[i] = gen_reflector(m-i, A[ii], A + ii + row_stride, row_stride);
if (i+1 < n) {
// Apply H(i)' to A[i:m)[i+1:n) from the left
apply_reflector(m-i, n-i-1, A + ii, row_stride, math::adjoint(tau[i]),
A + ii + col_stride, row_stride, col_stride);
}
}
}
// Convenience wrappers where row_stride and col_stride are determined automatically.
void compute(int rows, int cols, value_type *A, int max_cols = -1) {
int m = rows;
int n = cols;
int nmax = (max_cols < 0 ? n : max_cols);
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
compute(rows, cols, row_stride, col_stride, A, max_cols);
}
// Performs explicit factorization of the matrix A.
// Calls compute() and explicitly forms factors Q and R,
// so that Q() and R() methods below are valid calls.
void factorize(int rows, int cols, int row_stride, int col_stride, value_type *A, int max_cols = -1) {
compute(rows, cols, row_stride, col_stride, A, max_cols);
compute_q(max_cols);
}
// Convenience wrappers where row_stride and col_stride are determined automatically.
void factorize(int rows, int cols, value_type *A, int max_cols = -1) {
int m = rows;
int n = cols;
int nmax = (max_cols < 0 ? n : max_cols);
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
factorize(rows, cols, row_stride, col_stride, A, max_cols);
}
void append_cols(int cols) {
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
int old_n = n;
n += cols;
precondition(n <= nmax, "Too many columns in QR::append_cols()");
int old_k = k;
k = std::min(m, n);
for(int i = 0, ii = 0; i < k; ++i, ii += row_stride + col_stride) {
if (i >= old_k) {
// Generate elementary reflector H(i) to annihilate A[i+1:m)[i]
tau[i] = gen_reflector(m-i, r[ii], r + ii + row_stride, row_stride);
}
if (i+1 < n) {
// Apply H(i)' to A[i:m)[i+1:n) from the left
int l = std::max(i, old_n-1);
apply_reflector(m-i, n-l-1, r + ii, row_stride, math::adjoint(tau[i]),
r + i * row_stride + (l + 1) * col_stride, row_stride, col_stride);
}
}
}
// Returns element of the matrix R.
value_type R(int i, int j) const {
if (j < i) return math::zero<value_type>();
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
return r[i*row_stride + j*col_stride];
}
// Returns element of the matrix Q.
value_type Q(int i, int j) const {
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
return q[i*row_stride + j*col_stride];
}
// Solve over- or underdetermined system Ax = rhs.
// Calls compute() on the appropriate version of A (either transposed
// or not).
void solve(int rows, int cols, value_type *A, value_type *rhs, value_type *x) {
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
if (rows >= cols) {
compute(rows, cols, row_stride, col_stride, A);
for(int i = 0, ii = 0; i < m; ++i, ii += row_stride + col_stride)
apply_reflector(m-i, 1, r+ii, row_stride, math::adjoint(tau[i]), rhs+i, 1, 1);
std::copy(rhs, rhs+k, x);
for(int i = n; i --> 0; ) {
value_type rii = r[i*(row_stride+col_stride)];
if (math::is_zero(rii)) continue;
x[i] = math::inverse(rii) * x[i];
for(int j = 0, ja = 0; j < i; ++j, ja += row_stride)
x[j] -= r[ja+i*col_stride] * x[i];
}
} else {
compute(cols, rows, col_stride, row_stride, A);
for(int i = 0; i < n; ++i) {
value_type rii = math::adjoint(r[i*(row_stride+col_stride)]);
if (math::is_zero(rii)) continue;
for(int j = 0, ja = 0; j < i; ++j, ja += row_stride)
rhs[i] -= math::adjoint(r[ja+i*col_stride]) * rhs[j];
rhs[i] *= math::inverse(rii);
}
std::copy(rhs, rhs+k, x);
for(int i = m-1, ii = i*(row_stride + col_stride);
i >= 0; --i, ii -= row_stride + col_stride)
apply_reflector(m-i, 1, r+ii, row_stride, tau[i], x+i, 1, 1);
}
}
// Solves the system Q R x = f
void solve(value_type *f, value_type *x) const {
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
for(int i = 0, ii = 0; i < m; ++i, ii += row_stride + col_stride)
apply_reflector(m-i, 1, r+ii, row_stride, math::adjoint(tau[i]), f+i, 1, 1);
std::copy(f, f+k, x);
for(int i = n; i --> 0; ) {
value_type rii = r[i*(row_stride+col_stride)];
if (math::is_zero(rii)) continue;
x[i] = math::inverse(rii) * x[i];
for(int j = 0, ja = 0; j < i; ++j, ja += row_stride)
x[j] -= r[ja+i*col_stride] * x[i];
}
}
// Computes Q explicitly.
void compute_q(int ncols = -1) {
/*
* Ported from ZUNG2R
* ==================
*
* Generates an m by n matrix Q with orthonormal columns, which is
* defined as the first n columns of a product of k elementary
* reflectors of order m
*
* Q = H(1) H(2) . . . H(k)
*
* as returned by compute() [ZGEQR2].
*
* ==============================================================
*/
q.resize(m * nmax);
ncols = (ncols < 0 ? n : ncols);
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
// Initialise columns k+1:n to zero.
// [In the original code these were initialized to the columns of
// the unit matrix, but since k = min(n,m), the main diagonal is
// never seen here].
for(int i = 0, ia = 0; i < m; ++i, ia += row_stride)
for(int j = k, ja = k * col_stride; j < ncols; ++j, ja += col_stride)
q[ia + ja] = (i == j ? math::identity<value_type>() : math::zero<value_type>());
for(int i = k-1, ic = i * col_stride, ii = i*(row_stride + col_stride);
i >= 0; --i, ic -= col_stride, ii -= row_stride + col_stride)
{
// Apply H(i) to A[i:m)[i+1:n) from the left
if (i < ncols-1)
apply_reflector(m-i, ncols-i-1, r+ii, row_stride, tau[i], &q[ii+col_stride], row_stride, col_stride);
// Copy i-th reflector (including zeros and unit diagonal)
// to the column of Q to be processed next
for(int j = 0, jr = 0; j < i; ++j, jr += row_stride)
q[jr+ic] = math::zero<value_type>();
q[ii] = math::identity<value_type>() - tau[i];
for(int j = i + 1, jr=j*row_stride; j < m; ++j, jr += row_stride)
q[jr + ic] = -tau[i] * r[jr + ic];
}
}
private:
typedef typename math::scalar_of<value_type>::type scalar_type;
static scalar_type sqr(scalar_type x) { return x * x; }
int m, n, k, nmax;
value_type *r;
std::vector<value_type> tau;
std::vector<value_type> q;
static value_type gen_reflector(int order, value_type &alpha, value_type *x, int stride) {
/*
* Ported from ZLARFG
* ==================
*
* Generates a value_type elementary reflector H of order n, such
* that
*
* H' * ( alpha ) = ( beta ), H' * H = I.
* ( x ) ( 0 )
*
* where alpha and beta are scalars, with beta real, and x is an
* (n-1)-element value_type vector. H is represented in the form
*
* H = I - tau * ( 1 ) * ( 1 v' ) ,
* ( v )
*
* where tau is a value_type scalar and v is a value_type
* (n-1)-element vector. Note that H is not hermitian.
*
* If the elements of x are all zero and alpha is real,
* then tau = 0 and H is taken to be the unit matrix.
*
* Otherwise 1 <= real(tau) <= 2 and abs(tau-1) <= 1 .
*
* Arguments
* =========
*
* order The order of the elementary reflector.
*
* alpha On entry, the value alpha.
* On exit, it is overwritten with the value beta.
*
* x dimension (1+(order-2)*abs(stride))
* On entry, the vector x.
* On exit, it is overwritten with the vector v.
*
* stride The increment between elements of x.
*
* Returns the value tau.
*
* ==============================================================
*/
value_type tau = math::zero<value_type>();
if (order <= 1) return tau;
int n = order - 1;
scalar_type xnorm2 = 0;
for(int i = 0, ii = 0; i < n; ++i, ii += stride)
xnorm2 += sqr(math::norm(x[ii]));
if (math::is_zero(xnorm2)) return tau;
scalar_type beta = -boost::math::copysign(sqrt(sqr(math::norm(alpha)) + xnorm2), amgcl::detail::real(alpha));
tau = math::identity<value_type>() - math::inverse(beta) * alpha;
alpha = math::inverse(alpha - beta * math::identity<value_type>());
for(int i = 0, ii = 0; i < n; ++i, ii += stride)
x[ii] = alpha * x[ii];
alpha = beta * math::identity<value_type>();
return tau;
}
static void apply_reflector(
int m, int n, const value_type *v, int v_stride, value_type tau,
value_type *C, int row_stride, int col_stride
)
{
/*
* Ported from ZLARF
* =================
*
* Applies an elementary reflector H to an m-by-n matrix C from
* the left. H is represented in the form
*
* H = I - v * tau * v'
*
* where tau is a value_type scalar and v is a value_type vector.
*
* If tau = 0, then H is taken to be the unit matrix.
*
* To apply H' (the conjugate transpose of H), supply adjoint(tau)
* instead of tau.
*
* Arguments
* =========
*
* m The number of rows of the matrix C.
*
* n The number of columns of the matrix C.
*
* v The vector v in the representation of H.
* v is not used if tau = 0.
* The value of v[0] is ignored and assumed to be 1.
*
* v_stride The increment between elements of v.
*
* tau The value tau in the representation of H.
*
* C On entry, the m-by-n matrix C.
* On exit, C is overwritten by the matrix H * C.
*
* row_stride The increment between the rows of C.
* col_stride The increment between the columns of C.
*
* ==============================================================
*/
if (math::is_zero(tau)) return;
// w = C` * v; C -= tau * v * w`
for(int i = 0, ia=0; i < n; ++i, ia += col_stride) {
value_type s = math::adjoint(C[ia]);
for(int j = 1, jv = v_stride, ja=row_stride; j < m; ++j, jv += v_stride, ja += row_stride) {
s += math::adjoint(C[ja+ia]) * v[jv];
}
s = tau * math::adjoint(s);
C[ia] -= s;
for(int j = 1, jv = v_stride, ja=row_stride; j < m; ++j, jv += v_stride, ja += row_stride) {
C[ja+ia] -= v[jv] * s;
}
}
}
};
template <class value_type, storage_order Order>
class QR<value_type, Order, typename boost::enable_if< math::is_static_matrix<value_type> >::type>
{
public:
typedef typename amgcl::math::rhs_of<value_type>::type rhs_type;
QR() {}
// Computes a QR factorization of the matrix A, where Q is represented
// as a product of elementary reflectors.
// Q = H(1) H(2) . . . H(k), where k = min(rows,cols).
void compute(int rows, int cols, int row_stride, int col_stride, value_type *A, int max_cols = -1) {
const int M = math::static_rows<value_type>::value;
const int N = math::static_cols<value_type>::value;
m = rows;
n = cols;
nmax = (max_cols < 0 ? n : max_cols);
r = A;
buf.resize(M * m * N * nmax);
const int brows = M * m;
for(int i = 0, ib = 0; i < m; ++i)
for(int ii = 0; ii < M; ++ii, ++ib)
for(int j = 0, jb = 0; j < n; ++j)
for(int jj = 0; jj < N; ++jj, jb += brows)
buf[ib + jb] = A[i * row_stride + j * col_stride](ii, jj);
base.compute(rows * M, cols * N, 1, m * M, buf.data(), nmax * N);
}
// Convenience wrappers where row_stride and col_stride are determined automatically.
void compute(int rows, int cols, value_type *A, int max_cols = -1) {
int m = rows;
int n = cols;
int nmax = (max_cols < 0 ? n : max_cols);
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
compute(rows, cols, row_stride, col_stride, A, max_cols);
}
// Performs explicit factorization of the matrix A.
// Calls compute() and explicitly forms factors Q and R,
// so that Q() and R() methods below are valid calls.
void factorize(int rows, int cols, int row_stride, int col_stride, value_type *A) {
compute(rows, cols, row_stride, col_stride, A);
compute_q();
}
// Convenience wrappers where row_stride and col_stride are determined automatically.
void factorize(int rows, int cols, value_type *A) {
m = rows;
n = cols;
const int row_stride = (Order == row_major ? n : 1);
const int col_stride = (Order == row_major ? 1 : m);
factorize(rows, cols, row_stride, col_stride, A);
}
void append_cols(int cols) {
const int M = math::static_rows<value_type>::value;
const int N = math::static_cols<value_type>::value;
int old_n = n;
n += cols;
const int brows = M * m;
const int row_stride = (Order == row_major ? nmax : 1);
const int col_stride = (Order == row_major ? 1 : m);
for(int i = 0, ib = 0; i < m; ++i)
for(int ii = 0; ii < M; ++ii, ++ib)
for(int j = old_n, jb = j * brows; j < n; ++j)
for(int jj = 0; jj < N; ++jj, jb += brows)
buf[ib + jb] = r[i * row_stride + j * col_stride](ii, jj);
base.append_cols(cols * N);
}
value_type R(int i, int j) const {
const int N = math::static_rows<value_type>::value;
const int M = math::static_cols<value_type>::value;
value_type v;
if (j < i) {
v = math::zero<value_type>();
} else {
for(int ii = 0; ii < N; ++ii)
for(int jj = 0; jj < M; ++jj)
v(ii,jj) = base.R(i * N + ii, j * M + jj);
}
return v;
}
// Returns element of the matrix Q.
value_type Q(int i, int j) const {
const int N = math::static_rows<value_type>::value;
const int M = math::static_cols<value_type>::value;
value_type v;
for(int ii = 0; ii < N; ++ii)
for(int jj = 0; jj < M; ++jj)
v(ii,jj) = base.Q(i * N + ii, j * M + jj);
return v;
}
// Solve over- or underdetermined system Ax = rhs.
// Calls compute() on the appropriate version of A (either transposed
// or not).
void solve(int rows, int cols, value_type *A, rhs_type *rhs, rhs_type *x) {
const int M = math::static_rows<value_type>::value;
const int N = math::static_cols<value_type>::value;
m = rows;
n = cols;
nmax = n;
const int row_stride = (Order == row_major ? n : 1);
const int col_stride = (Order == row_major ? 1 : m);
r = A;
buf.resize(M * m * N * nmax);
const int brows = M * m;
for(int i = 0, ib = 0; i < m; ++i)
for(int ii = 0; ii < M; ++ii, ++ib)
for(int j = 0, jb = 0; j < n; ++j)
for(int jj = 0; jj < N; ++jj, jb += brows)
buf[ib + jb] = A[i * row_stride + j * col_stride](ii, jj);
base.solve(
rows * M,
cols * N,
buf.data(),
reinterpret_cast<scalar_type*>(rhs),
reinterpret_cast<scalar_type*>(x)
);
}
void compute_q() { base.compute_q(); }
private:
typedef typename amgcl::math::scalar_of<value_type>::type scalar_type;
int m, n, nmax;
value_type *r;
QR<scalar_type, col_major> base;
std::vector<scalar_type> buf;
};
} // namespace detail
} // namespace amgcl
#endif
| mit |
ozmydas/anu123bankinfo | livezilla/_lib/objects.languages.inc.php | 9727 | <?php
$LANGUAGES[""] = array("",false,false);
$LANGUAGES["AB"] = array("Abkhazian",false,false);
$LANGUAGES["AA"] = array("Afar",false,false);
$LANGUAGES["AF"] = array("Afrikaans",false,false);
$LANGUAGES["AK"] = array("Akan",false,false);
$LANGUAGES["SQ"] = array("Albanian",true,false);
$LANGUAGES["AM"] = array("Amharic",false,false);
$LANGUAGES["AR"] = array("Arabic",true,true);
$LANGUAGES["AN"] = array("Aragonese",false,false);
$LANGUAGES["HY"] = array("Armenian",false,false);
$LANGUAGES["AS"] = array("Assamese",false,false);
$LANGUAGES["AV"] = array("Avaric",false,false);
$LANGUAGES["AE"] = array("Avestan",false,false);
$LANGUAGES["AY"] = array("Aymara",false,false);
$LANGUAGES["AZ"] = array("Azerbaijani",false,true);
$LANGUAGES["BM"] = array("Bambara",false,false);
$LANGUAGES["BA"] = array("Bashkir",false,false);
$LANGUAGES["EU"] = array("Basque",false,false);
$LANGUAGES["BN"] = array("Bengali",false,false);
$LANGUAGES["DZ"] = array("Bhutani",false,false);
$LANGUAGES["BH"] = array("Bihari",false,false);
$LANGUAGES["BI"] = array("Bislama",false,false);
$LANGUAGES["BS"] = array("Bosnian",false,false);
$LANGUAGES["BR"] = array("Breton",false,false);
$LANGUAGES["BG"] = array("Bulgarian",true,false);
$LANGUAGES["MY"] = array("Burmese",false,false);
$LANGUAGES["BE"] = array("Byelorussian",false,false);
$LANGUAGES["KM"] = array("Cambodian",false,false);
$LANGUAGES["CA"] = array("Catalan",true,false);
$LANGUAGES["CH"] = array("Chamorro",false,false);
$LANGUAGES["CE"] = array("Chechen",false,false);
$LANGUAGES["NY"] = array("Chichewa",false,false);
$LANGUAGES["ZH"] = array("Chinese",false,false);
$LANGUAGES["ZH-TW"] = array("Chinese (Traditional)",true,false);
$LANGUAGES["ZH-CN"] = array("Chinese (Simplified)",true,false);
$LANGUAGES["CU"] = array("Church Slavic",false,false);
$LANGUAGES["CV"] = array("Chuvash",false,false);
$LANGUAGES["KW"] = array("Cornish",false,false);
$LANGUAGES["CO"] = array("Corsican",false,false);
$LANGUAGES["CR"] = array("Cree",false,false);
$LANGUAGES["HR"] = array("Croatian",true,false);
$LANGUAGES["CS"] = array("Czech",true,false);
$LANGUAGES["DA"] = array("Danish",true,false);
$LANGUAGES["DV"] = array("Divehi",false,false);
$LANGUAGES["NL"] = array("Dutch",true,false);
$LANGUAGES["EN"] = array("English",true,false);
$LANGUAGES["EN-GB"] = array("English (Great Britain)",false,false);
$LANGUAGES["EN-US"] = array("English (US)",false,false);
$LANGUAGES["EO"] = array("Esperanto",false,false);
$LANGUAGES["ET"] = array("Estonian",true,false);
$LANGUAGES["EE"] = array("Ewe",false,false);
$LANGUAGES["FO"] = array("Faeroese",false,false);
$LANGUAGES["FJ"] = array("Fiji",false,false);
$LANGUAGES["FI"] = array("Finnish",true,false);
$LANGUAGES["FIL"] = array("Filipino",false,false);
$LANGUAGES["FR"] = array("French",true,false);
$LANGUAGES["FY"] = array("Frisian",false,false);
$LANGUAGES["FF"] = array("Fulah",false,false);
$LANGUAGES["GD"] = array("Gaelic",false,false);
$LANGUAGES["GSW"] = array("Swiss German",false,false);
$LANGUAGES["GL"] = array("Galician",true,false);
$LANGUAGES["HSB"] = array("Upper Sorbian",false,false);
$LANGUAGES["LG"] = array("Ganda",false,false);
$LANGUAGES["KA"] = array("Georgian",false,false);
$LANGUAGES["DE"] = array("German",true,false);
$LANGUAGES["EL"] = array("Greek",true,false);
$LANGUAGES["KL"] = array("Greenlandic",false,false);
$LANGUAGES["GN"] = array("Guarani",false,false);
$LANGUAGES["GU"] = array("Gujarati",false,false);
$LANGUAGES["HT"] = array("Haitian",false,false);
$LANGUAGES["HA"] = array("Hausa",false,false);
$LANGUAGES["HE"] = array("Hebrew",true,true);
$LANGUAGES["HZ"] = array("Herero",false,false);
$LANGUAGES["HI"] = array("Hindi",true,false);
$LANGUAGES["HO"] = array("Hiri Motu",false,false);
$LANGUAGES["HU"] = array("Hungarian",true,false);
$LANGUAGES["IS"] = array("Icelandic",true,false);
$LANGUAGES["IO"] = array("Ido",false,false);
$LANGUAGES["IG"] = array("Igbo",false,false);
$LANGUAGES["ID"] = array("Indonesian",true,false);
$LANGUAGES["IA"] = array("Interlingua",false,false);
$LANGUAGES["IE"] = array("Interlingue",false,false);
$LANGUAGES["IU"] = array("Inuktitut",false,false);
$LANGUAGES["IK"] = array("Inupiak",false,false);
$LANGUAGES["GA"] = array("Irish",true,false);
$LANGUAGES["IT"] = array("Italian",true,false);
$LANGUAGES["JA"] = array("Japanese",true,false);
$LANGUAGES["JW"] = array("Javanese",false,true);
$LANGUAGES["JV"] = array("Javanese",false,false);
$LANGUAGES["KN"] = array("Kannada",false,false);
$LANGUAGES["KR"] = array("Kanuri",false,false);
$LANGUAGES["KS"] = array("Kashmiri",false,true);
$LANGUAGES["KK"] = array("Kazakh",false,true);
$LANGUAGES["KI"] = array("Kikuyu",false,false);
$LANGUAGES["RW"] = array("Kinyarwanda",false,false);
$LANGUAGES["KY"] = array("Kirghiz",false,false);
$LANGUAGES["RN"] = array("Kirundi",false,false);
$LANGUAGES["KV"] = array("Komi",false,false);
$LANGUAGES["KG"] = array("Kongo",false,false);
$LANGUAGES["KO"] = array("Korean",true,false);
$LANGUAGES["KU"] = array("Kurdish",false,true);
$LANGUAGES["KJ"] = array("Kwanyama",false,false);
$LANGUAGES["LO"] = array("Laothian",false,false);
$LANGUAGES["LA"] = array("Latin",false,false);
$LANGUAGES["LV"] = array("Latvian",true,false);
$LANGUAGES["LI"] = array("Limburgish",false,false);
$LANGUAGES["LN"] = array("Lingala",false,false);
$LANGUAGES["LT"] = array("Lithuanian",true,false);
$LANGUAGES["LU"] = array("Luba-Katanga",false,false);
$LANGUAGES["LB"] = array("Luxembourgish",false,false);
$LANGUAGES["MK"] = array("Macedonian",true,false);
$LANGUAGES["MG"] = array("Malagasy",false,false);
$LANGUAGES["MS"] = array("Malay",true,true);
$LANGUAGES["ML"] = array("Malayalam",false,true);
$LANGUAGES["MT"] = array("Maltese",true,false);
$LANGUAGES["GV"] = array("Manx",false,false);
$LANGUAGES["MI"] = array("Maori",false,false);
$LANGUAGES["MR"] = array("Marathi",false,false);
$LANGUAGES["MH"] = array("Marshallese",false,false);
$LANGUAGES["MO"] = array("Moldavian",false,false);
$LANGUAGES["MN"] = array("Mongolian",false,false);
$LANGUAGES["NA"] = array("Nauru",false,false);
$LANGUAGES["NV"] = array("Navajo",false,false);
$LANGUAGES["NG"] = array("Ndonga",false,false);
$LANGUAGES["NE"] = array("Nepali",false,false);
$LANGUAGES["ND"] = array("North Ndebele",false,false);
$LANGUAGES["SE"] = array("Northern Sami",false,false);
$LANGUAGES["NB"] = array("Norwegian Bokmal",false,false);
$LANGUAGES["NN"] = array("Norwegian Nynorsk",false,false);
$LANGUAGES["OC"] = array("Occitan",false,false);
$LANGUAGES["OJ"] = array("Ojibwa",false,false);
$LANGUAGES["OR"] = array("Oriya",false,false);
$LANGUAGES["OM"] = array("Oromo",false,false);
$LANGUAGES["OS"] = array("Ossetian",false,false);
$LANGUAGES["PI"] = array("Pali",false,false);
$LANGUAGES["PS"] = array("Pashto",false,true);
$LANGUAGES["FA"] = array("Persian",true,true);
$LANGUAGES["PL"] = array("Polish",true,false);
$LANGUAGES["PT"] = array("Portuguese",true,false);
$LANGUAGES["PT-BR"] = array("Portuguese (Brazil)",true,false);
$LANGUAGES["PA"] = array("Punjabi",false,true);
$LANGUAGES["QU"] = array("Quechua",false,false);
$LANGUAGES["RM"] = array("Rhaeto-Romance",false,false);
$LANGUAGES["RO"] = array("Romanian",true,false);
$LANGUAGES["RU"] = array("Russian",true,false);
$LANGUAGES["SM"] = array("Samoan",false,false);
$LANGUAGES["SG"] = array("Sangro",false,false);
$LANGUAGES["SA"] = array("Sanskrit",false,false);
$LANGUAGES["SB"] = array("Sorbian",false,false);
$LANGUAGES["SC"] = array("Sardinian",false,false);
$LANGUAGES["SR"] = array("Serbian",true,false);
$LANGUAGES["SH"] = array("Serbo-Croatian",false,false);
$LANGUAGES["ST"] = array("Sesotho",false,false);
$LANGUAGES["TN"] = array("Setswana",false,false);
$LANGUAGES["SN"] = array("Shona",false,false);
$LANGUAGES["II"] = array("Sichuan Yi",false,false);
$LANGUAGES["SD"] = array("Sindhi",false,true);
$LANGUAGES["SI"] = array("Singhalese",false,false);
$LANGUAGES["SS"] = array("Siswati",false,false);
$LANGUAGES["SK"] = array("Slovak",true,false);
$LANGUAGES["SL"] = array("Slovenian",true,false);
$LANGUAGES["SO"] = array("Somali",false,true);
$LANGUAGES["NR"] = array("South Ndebele",false,false);
$LANGUAGES["ES"] = array("Spanish",true,false);
$LANGUAGES["SU"] = array("Sudanese",false,false);
$LANGUAGES["SW"] = array("Swahili",true,false);
$LANGUAGES["SV"] = array("Swedish",true,false);
$LANGUAGES["TL"] = array("Tagalog",false,false);
$LANGUAGES["TY"] = array("Tahitian",false,false);
$LANGUAGES["TG"] = array("Tajik",false,false);
$LANGUAGES["TA"] = array("Tamil",false,false);
$LANGUAGES["TT"] = array("Tatar",false,false);
$LANGUAGES["TE"] = array("Tegulu",false,false);
$LANGUAGES["TH"] = array("Thai",true,false);
$LANGUAGES["BO"] = array("Tibetan",false,false);
$LANGUAGES["TI"] = array("Tigrinya",false,false);
$LANGUAGES["TK"] = array("Turkmen",false,true);
$LANGUAGES["TLH"] = array("Klingon",false,false);
$LANGUAGES["TO"] = array("Tonga",false,false);
$LANGUAGES["TS"] = array("Tsonga",false,false);
$LANGUAGES["TR"] = array("Turkish",true,false);
$LANGUAGES["TW"] = array("Twi",false,false);
$LANGUAGES["UG"] = array("Uighur",false,true);
$LANGUAGES["UK"] = array("Ukrainian",true,false);
$LANGUAGES["UR"] = array("Urdu",false,true);
$LANGUAGES["UZ"] = array("Uzbek",false,false);
$LANGUAGES["VE"] = array("Venda",false,false);
$LANGUAGES["VI"] = array("Vietnamese",true,false);
$LANGUAGES["VO"] = array("Volapuk",false,false);
$LANGUAGES["WA"] = array("Walloon",false,false);
$LANGUAGES["CY"] = array("Welsh",true,false);
$LANGUAGES["WO"] = array("Wolof",false,false);
$LANGUAGES["XH"] = array("Xhosa",false,false);
$LANGUAGES["YI"] = array("Yiddish",true,true);
$LANGUAGES["YO"] = array("Yoruba",false,false);
$LANGUAGES["ZA"] = array("Zhuang",false,false);
$LANGUAGES["ZU"] = array("Zulu",false,false);
?> | mit |
06wj/three.js | examples/jsm/renderers/webgpu/WebGPUSampledTexture.js | 1303 | import WebGPUBinding from './WebGPUBinding.js';
import { GPUBindingType, GPUTextureViewDimension } from './constants.js';
class WebGPUSampledTexture extends WebGPUBinding {
constructor( name, texture ) {
super( name );
this.texture = texture;
this.dimension = GPUTextureViewDimension.TwoD;
this.type = GPUBindingType.SampledTexture;
this.visibility = GPUShaderStage.FRAGMENT;
this.textureGPU = null; // set by the renderer
}
}
WebGPUSampledTexture.prototype.isSampledTexture = true;
class WebGPUSampledArrayTexture extends WebGPUSampledTexture {
constructor( name ) {
super( name );
this.dimension = GPUTextureViewDimension.TwoDArray;
}
}
WebGPUSampledArrayTexture.prototype.isSampledArrayTexture = true;
class WebGPUSampled3DTexture extends WebGPUSampledTexture {
constructor( name ) {
super( name );
this.dimension = GPUTextureViewDimension.ThreeD;
}
}
WebGPUSampled3DTexture.prototype.isSampled3DTexture = true;
class WebGPUSampledCubeTexture extends WebGPUSampledTexture {
constructor( name ) {
super( name );
this.dimension = GPUTextureViewDimension.Cube;
}
}
WebGPUSampledCubeTexture.prototype.isSampledCubeTexture = true;
export { WebGPUSampledTexture, WebGPUSampledArrayTexture, WebGPUSampled3DTexture, WebGPUSampledCubeTexture };
| mit |
juanda/CursoSf2.Ejercicio | src/Jazzyweb/CursoSf2/FrontendBundle/JwCursoSf2FrontendBundle.php | 151 | <?php
namespace Jazzyweb\CursoSf2\FrontendBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class JwCursoSf2FrontendBundle extends Bundle
{
}
| mit |
teknobingo/gonzales | lib/gonzales/factories.rb | 2432 | # Copyright (c) 2012 Bingo Entreprenøren AS
# Copyright (c) 2012 Teknobingo Scandinavia AS
# Copyright (c) 2012 Knut I. Stenmark
#
# 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.
module Gonzales
# = Gonzales::Factories
#
# Facitity to instantiate factories in database during db:test:prepare
class Factories
# Save a factory based record to the test database before executing tests
#
# === Arguments
# * alias_name - optional alias name (can be used to reference factory or associations later)
# * factory_name - the name of the factory (use to reference factory or associations later if alias is not given)
# * options - a hash to be passed to FactoryGirl when creating the record
#
# === Examples
# Gonzales::Factories.load do |go|
# go.speedy :address
# go.speedy :organization
# go.speedy :john, :person, :name => 'John'
# end
#
def self.speedy(factory_or_alias_name, *args)
alias_name = factory_or_alias_name
options = args.extract_options!
factory_name = args.first || alias_name
Collection.add alias_name, Factory.create(factory_name, options)
end
# Yields a block to define speedy statements, then saves a collection of references to a temporary file
def self.load(&block)
Collection.clear_cache
::FactoryGirl.reload
yield self
Collection.save
end
end
end | mit |
Whathecode/Framework-Class-Library-Extension | Whathecode.System/Reflection/Extensions/Extensions.PropertyInfo.cs | 1034 | using System;
using System.Linq.Expressions;
using System.Reflection;
using Whathecode.System.Reflection.Expressions;
namespace Whathecode.System.Reflection.Extensions
{
public static partial class Extensions
{
/// <summary>
/// Create an expression from which property getters can be created.
/// </summary>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="property">The info about the property.</param>
public static GetterExpression<TProperty> CreateGetter<TProperty>( this PropertyInfo property )
{
return new GetterExpression<TProperty>( property );
}
/// <summary>
/// Create an expression from which property setters can be created.
/// </summary>
/// <typeparam name="TProperty">The type of the property.</typeparam>
/// <param name="property">The info about the property.</param>
public static SetterExpression<TProperty> CreateSetter<TProperty>( this PropertyInfo property )
{
return new SetterExpression<TProperty>( property );
}
}
}
| mit |
bradyhullopeter/root | app/views/sysadmin/one/sysadmin-one.spec.js | 310 | 'use strict';
import {expect} from 'chai';
import SysadminOneController from './sysadmin-one-controller';
let ctrl;
describe('app module', () => {
beforeEach(() => {
ctrl = new SysadminOneController();
});
it('should be initialized', () => {
expect(ctrl).to.exist;
});
});
| mit |
colematt/apex-sim | srcs/rob.cpp | 2712 | /* FILE INFORMATION
File: rob.cpp
Authors: Matthew Cole <[email protected]>
Brian Gracin <[email protected]>
Description: Contains the ROB class, which simulates the operation of a Reorder
Buffer.
*/
#include "apex.h"
#include "rob.h"
#include <iostream>
ROB::ROB() { this->initialize(); }
ROB::~ROB() {}
// Display the contents of the ROB
// Each entry is a Stage, so we delegate the display call
void ROB::display() {
if (VERBOSE >= 1) {
std::cout << "Name: Opcode Operands" << std::endl;
}
std::cout << "Head" << std::endl;
for (auto e : reorder_buffer) {
e.display();
}
std::cout << "Tail" << std::endl;
}
// Initialize the ROB to empty state
void ROB::initialize() { reorder_buffer.clear(); }
bool ROB::isEmpty() { return reorder_buffer.empty(); }
// Remove head from ROB and call registers' commit function,
// updating backend table and free list
void ROB::commit(Registers ®) {
std::string curOpcode = this->reorder_buffer.front().opcode;
if (curOpcode != "STORE" && curOpcode != "BZ" && curOpcode != "BNZ" &&
curOpcode != "BAL" && curOpcode != "JUMP") {
std::string pReg;
pReg = this->reorder_buffer.front().operands.at(0);
reg.commit(pReg);
}
this->reorder_buffer.pop_front();
}
// Add a Stage instance to ROB
bool ROB::addStage(Stage &stage) {
if (this->reorder_buffer.size() < this->max_size) {
this->reorder_buffer.push_back(stage);
return true;
}
return false;
}
// Given a cycle value gets cycle value of current head
// and returns if they are equal (==)
bool ROB::match(Stage &stage) {
// If stage is empty, it cannot match the ROB head entry!
if (stage.isEmpty())
return false;
int size = 0;
int passedCycle = 0;
int headCycle = 0;
size = this->reorder_buffer.size();
passedCycle = stage.c;
if (size > 0) {
headCycle = this->reorder_buffer.front().c;
}
if (headCycle == passedCycle) {
return true;
}
return false;
}
// Flush all entries in the ROB with whose cycle time stamp
// is >= specified time stamp (used when branch is taken)
// ASSUMPTION: the entries in the IQ and ROB are
// sorted at all times by their timestamp of creation (c)
void ROB::flush(int cycle) {
// Point an iterator at the start of the IQ
std::deque<Stage>::iterator it = this->reorder_buffer.begin();
// Traverse until encountering an entry
// whose cycle timestamp indicates it must be flushed
if (it != reorder_buffer.end()) {
while ((it->c <= cycle) && (it != reorder_buffer.end())) {
++it;
}
}
// flush the elements from the current iterator to end:
if (it != reorder_buffer.end())
this->reorder_buffer.erase(it, reorder_buffer.end());
}
| mit |
zhangqiang110/my4j | pms/src/main/java/cn/ebay/shippingapi/GetAPACShippingRateRequest.java | 9938 | /**
* GetAPACShippingRateRequest.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package cn.ebay.shippingapi;
public class GetAPACShippingRateRequest extends cn.ebay.shippingapi.BaseRequest implements java.io.Serializable {
private int shipCode;
private java.lang.String countryCode;
private java.math.BigDecimal weight;
private int insuranceType;
private java.math.BigDecimal insuranceAmount;
private int mailType;
public GetAPACShippingRateRequest() {
}
public GetAPACShippingRateRequest(
java.lang.String version,
java.lang.String APIDevUserID,
java.lang.String APIPassword,
java.lang.String APISellerUserID,
java.lang.String messageID,
int shipCode,
java.lang.String countryCode,
java.math.BigDecimal weight,
int insuranceType,
java.math.BigDecimal insuranceAmount,
int mailType) {
super(
version,
APIDevUserID,
APIPassword,
APISellerUserID,
messageID);
this.shipCode = shipCode;
this.countryCode = countryCode;
this.weight = weight;
this.insuranceType = insuranceType;
this.insuranceAmount = insuranceAmount;
this.mailType = mailType;
}
/**
* Gets the shipCode value for this GetAPACShippingRateRequest.
*
* @return shipCode
*/
public int getShipCode() {
return shipCode;
}
/**
* Sets the shipCode value for this GetAPACShippingRateRequest.
*
* @param shipCode
*/
public void setShipCode(int shipCode) {
this.shipCode = shipCode;
}
/**
* Gets the countryCode value for this GetAPACShippingRateRequest.
*
* @return countryCode
*/
public java.lang.String getCountryCode() {
return countryCode;
}
/**
* Sets the countryCode value for this GetAPACShippingRateRequest.
*
* @param countryCode
*/
public void setCountryCode(java.lang.String countryCode) {
this.countryCode = countryCode;
}
/**
* Gets the weight value for this GetAPACShippingRateRequest.
*
* @return weight
*/
public java.math.BigDecimal getWeight() {
return weight;
}
/**
* Sets the weight value for this GetAPACShippingRateRequest.
*
* @param weight
*/
public void setWeight(java.math.BigDecimal weight) {
this.weight = weight;
}
/**
* Gets the insuranceType value for this GetAPACShippingRateRequest.
*
* @return insuranceType
*/
public int getInsuranceType() {
return insuranceType;
}
/**
* Sets the insuranceType value for this GetAPACShippingRateRequest.
*
* @param insuranceType
*/
public void setInsuranceType(int insuranceType) {
this.insuranceType = insuranceType;
}
/**
* Gets the insuranceAmount value for this GetAPACShippingRateRequest.
*
* @return insuranceAmount
*/
public java.math.BigDecimal getInsuranceAmount() {
return insuranceAmount;
}
/**
* Sets the insuranceAmount value for this GetAPACShippingRateRequest.
*
* @param insuranceAmount
*/
public void setInsuranceAmount(java.math.BigDecimal insuranceAmount) {
this.insuranceAmount = insuranceAmount;
}
/**
* Gets the mailType value for this GetAPACShippingRateRequest.
*
* @return mailType
*/
public int getMailType() {
return mailType;
}
/**
* Sets the mailType value for this GetAPACShippingRateRequest.
*
* @param mailType
*/
public void setMailType(int mailType) {
this.mailType = mailType;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof GetAPACShippingRateRequest)) return false;
GetAPACShippingRateRequest other = (GetAPACShippingRateRequest) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
this.shipCode == other.getShipCode() &&
((this.countryCode==null && other.getCountryCode()==null) ||
(this.countryCode!=null &&
this.countryCode.equals(other.getCountryCode()))) &&
((this.weight==null && other.getWeight()==null) ||
(this.weight!=null &&
this.weight.equals(other.getWeight()))) &&
this.insuranceType == other.getInsuranceType() &&
((this.insuranceAmount==null && other.getInsuranceAmount()==null) ||
(this.insuranceAmount!=null &&
this.insuranceAmount.equals(other.getInsuranceAmount()))) &&
this.mailType == other.getMailType();
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
_hashCode += getShipCode();
if (getCountryCode() != null) {
_hashCode += getCountryCode().hashCode();
}
if (getWeight() != null) {
_hashCode += getWeight().hashCode();
}
_hashCode += getInsuranceType();
if (getInsuranceAmount() != null) {
_hashCode += getInsuranceAmount().hashCode();
}
_hashCode += getMailType();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(GetAPACShippingRateRequest.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "GetAPACShippingRateRequest"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("shipCode");
elemField.setXmlName(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "ShipCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("countryCode");
elemField.setXmlName(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "CountryCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("weight");
elemField.setXmlName(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "Weight"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("insuranceType");
elemField.setXmlName(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "InsuranceType"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("insuranceAmount");
elemField.setXmlName(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "InsuranceAmount"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "decimal"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("mailType");
elemField.setXmlName(new javax.xml.namespace.QName("http://shippingapi.ebay.cn/", "MailType"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| mit |
joaompinto/asciidoctor-vscode | preview-src/loading.ts | 1386 | /*---------------------------------------------------------------------------------------------
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MessagePoster } from './messaging';
export class StyleLoadingMonitor {
private unloadedStyles: string[] = [];
private finishedLoading: boolean = false;
private poster?: MessagePoster;
constructor() {
const onStyleLoadError = (event: any) => {
const source = event.target.dataset.source;
this.unloadedStyles.push(source);
};
window.addEventListener('DOMContentLoaded', () => {
// @ts-ignore TS2488
for (const link of document.getElementsByClassName('code-user-style') as HTMLCollectionOf<HTMLElement>) {
if (link.dataset.source) {
link.onerror = onStyleLoadError;
}
}
});
window.addEventListener('load', () => {
if (!this.unloadedStyles.length) {
return;
}
this.finishedLoading = true;
if (this.poster) {
this.poster.postMessage('previewStyleLoadError', { unloadedStyles: this.unloadedStyles });
}
});
}
public setPoster(poster: MessagePoster): void {
this.poster = poster;
if (this.finishedLoading) {
poster.postMessage('previewStyleLoadError', { unloadedStyles: this.unloadedStyles });
}
}
} | mit |
aakselrod/lnd | shachain/utils.go | 2418 | package shachain
import (
"encoding/hex"
"github.com/btcsuite/btcd/chaincfg/chainhash"
)
// changeBit is a functio that function that flips a bit of the hash at a
// particular bit-index. You should be aware that the bit flipping in this
// function a bit strange, example:
// hash: [0b00000000, 0b00000000, ... 0b00000000]
// 0 1 ... 31
//
// byte: 0 0 0 0 0 0 0 0
// 7 6 5 4 3 2 1 0
//
// By flipping the bit at 7 position you will flip the first bit in hash and by
// flipping the bit at 8 position you will flip the 16 bit in hash.
func changeBit(hash []byte, position uint8) []byte {
byteNumber := position / 8
bitNumber := position % 8
hash[byteNumber] ^= (1 << bitNumber)
return hash
}
// getBit return bit on index at position.
func getBit(index index, position uint8) uint8 {
return uint8((uint64(index) >> position) & 1)
}
func getPrefix(index index, position uint8) uint64 {
// + -------------------------- +
// | № | value | mask | return |
// + -- + ----- + ---- + ------ +
// | 63 | 1 | 0 | 0 |
// | 62 | 0 | 0 | 0 |
// | 61 | 1 | 0 | 0 |
// ....
// | 4 | 1 | 0 | 0 |
// | 3 | 1 | 0 | 0 |
// | 2 | 1 | 1 | 1 | <--- position
// | 1 | 0 | 1 | 0 |
// | 0 | 1 | 1 | 1 |
// + -- + ----- + ---- + ------ +
var zero uint64
mask := (zero - 1) - uint64((1<<position)-1)
return (uint64(index) & mask)
}
// countTrailingZeros counts number of trailing zero bits, this function is
// used to determine the number of element bucket.
func countTrailingZeros(index index) uint8 {
var zeros uint8
for ; zeros < maxHeight; zeros++ {
if getBit(index, zeros) != 0 {
break
}
}
return zeros
}
// hashFromString takes a hex-encoded string as input and creates an instance of
// chainhash.Hash. The chainhash.NewHashFromStr function not suitable because
// it reverse the given hash.
func hashFromString(s string) (*chainhash.Hash, error) {
// Return an error if hash string is too long.
if len(s) > chainhash.MaxHashStringSize {
return nil, chainhash.ErrHashStrSize
}
// Hex decoder expects the hash to be a multiple of two.
if len(s)%2 != 0 {
s = "0" + s
}
// Convert string hash to bytes.
buf, err := hex.DecodeString(s)
if err != nil {
return nil, err
}
hash, err := chainhash.NewHash(buf)
if err != nil {
return nil, err
}
return hash, nil
}
| mit |
martijn00/XamarinMediaManager | MediaManager/Platforms/Android/Queue/QueueMediaSourceFactory.cs | 1189 | using System;
using Android.Runtime;
using Android.Support.V4.Media;
using Com.Google.Android.Exoplayer2.Ext.Mediasession;
using Com.Google.Android.Exoplayer2.Source;
using MediaManager.Platforms.Android.Media;
namespace MediaManager.Platforms.Android.Queue
{
public class QueueMediaSourceFactory : Java.Lang.Object, TimelineQueueEditor.IMediaSourceFactory
{
protected MediaManagerImplementation MediaManager => CrossMediaManager.Android;
public QueueMediaSourceFactory()
{
}
protected QueueMediaSourceFactory(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
}
public IMediaSource CreateMediaSource(MediaDescriptionCompat description)
{
//TODO: We should be able to know the exact type here
var mediaItem = description.ToMediaItem();
var fileName = MediaManager.Extractor.GetFileName(mediaItem.MediaUri);
var fileExtension = MediaManager.Extractor.GetFileExtension(fileName);
var mediaType = MediaManager.Extractor.GetMediaType(fileExtension);
return description?.ToMediaSource(mediaType);
}
}
}
| mit |
Fast-Forward-llc/FFLib | FFLib/Data/Providers/IDBProvider.cs | 1942 | /*******************************************************
* Project: FFLib V1.0
* Title: ORMInterfaces.cs
* Author: Phillip Bird of Fast Forward,LLC
* Copyright © 2012 Fast Forward, LLC.
* Dual licensed under the MIT or GPL Version 2 licenses.
* Use of any component of FFLib requires acceptance and adhearance
* to the terms of either the MIT License or the GNU General Public License (GPL) Version 2 exclusively.
* Notification of license selection is not required and will be infered based on applicability.
* Contributions to FFLib requires a contributor grant on file with Fast Forward, LLC.
********************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SqlClient = System.Data.SqlClient;
namespace FFLib.Data.DBProviders
{
public interface IDBProvider
{
int CommandTimeout { get; set; }
IDbConnection CreateConnection(string connectionString);
IDbCommand CreateCommand(IDbConnection Connection, string CmdText);
U DBInsert<U>(IDBConnection conn, string sqlText, SqlParameter[] sqlParams);
U DBInsert<U>(IDBConnection conn, string sqlText, dynamic sqlParams);
void DBUpdate(IDBConnection conn, string sqlText, SqlParameter[] sqlParams);
void DBUpdate(IDBConnection conn, string sqlText, dynamic sqlParams);
int ExecuteNonQuery(IDBConnection conn, string sqlText, SqlParameter[] sqlParams);
int ExecuteNonQuery(IDBConnection conn, string sqlText, dynamic sqlParams);
U ExecuteScalar<U>(IDBConnection conn, string sqlText, SqlParameter[] sqlParams);
U ExecuteScalar<U>(IDBConnection conn, string sqlText, dynamic sqlParams);
IDataReader ExecuteReader(IDBConnection conn, string sqlText, SqlParameter[] sqlParams);
IDataReader ExecuteReader(IDBConnection conn, string sqlText, dynamic sqlParams);
}
}
| mit |
aaubry/YamlDotNet | YamlDotNet/Core/Events/SequenceEnd.cs | 3288 | // This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// 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.
namespace YamlDotNet.Core.Events
{
/// <summary>
/// Represents a sequence end event.
/// </summary>
public sealed class SequenceEnd : ParsingEvent
{
/// <summary>
/// Gets a value indicating the variation of depth caused by this event.
/// The value can be either -1, 0 or 1. For start events, it will be 1,
/// for end events, it will be -1, and for the remaining events, it will be 0.
/// </summary>
public override int NestingIncrease => -1;
/// <summary>
/// Gets the event type, which allows for simpler type comparisons.
/// </summary>
internal override EventType Type => EventType.SequenceEnd;
/// <summary>
/// Initializes a new instance of the <see cref="SequenceEnd"/> class.
/// </summary>
/// <param name="start">The start position of the event.</param>
/// <param name="end">The end position of the event.</param>
public SequenceEnd(in Mark start, in Mark end)
: base(start, end)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SequenceEnd"/> class.
/// </summary>
public SequenceEnd()
: this(Mark.Empty, Mark.Empty)
{
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
return "Sequence end";
}
/// <summary>
/// Invokes run-time type specific Visit() method of the specified visitor.
/// </summary>
/// <param name="visitor">visitor, may not be null.</param>
public override void Accept(IParsingEventVisitor visitor)
{
visitor.Visit(this);
}
}
}
| mit |
kevva/if-stream | index.js | 720 | 'use strict';
const streamLib = require('stream');
const isStream = require('is-stream');
const matchCondition = require('match-condition');
const peekStream = require('peek-stream');
module.exports = (condition, stream, fn, opts) => {
opts = Object.assign({}, opts);
const isStreamFn = isStream(fn) || typeof fn === 'function';
if (fn && !isStreamFn) {
opts = fn;
}
return peekStream(opts, (data, swap) => {
if (!matchCondition(data, condition) && !isStreamFn) {
swap(null, new streamLib.PassThrough());
return;
}
if (!matchCondition(data, condition)) {
swap(null, typeof fn === 'function' ? fn() : fn);
return;
}
swap(null, typeof stream === 'function' ? stream() : stream);
});
};
| mit |
jawaidss/halalar-web | halalar/api/tests/forms.py | 5174 | from django.test import TestCase
from . import TEST_DATA
from ..forms import AuthenticationForm, UserForm, ProfileForm
class AuthenticationFormTestCase(TestCase):
def test(self):
form = AuthenticationForm(data={'username': TEST_DATA[0]['username'],
'password': TEST_DATA[0]['password']})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'__all__': ['Please enter a correct username and password. Note that both fields may be case-sensitive.']})
self.assertEqual(form.error_message(), 'Please enter a correct username and password. Note that both fields may be case-sensitive.')
class UserFormTestCase(TestCase):
def test(self):
form = UserForm({})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'username': ['This field is required.'],
'password': ['This field is required.'],
'email': ['This field is required.']})
self.assertEqual(form.error_message(), 'email: This field is required.\npassword: This field is required.\nusername: This field is required.')
def test_save(self):
form = UserForm({'username': TEST_DATA[0]['username'],
'password': TEST_DATA[0]['password'],
'email': TEST_DATA[0]['email']})
self.assertTrue(form.is_valid())
user = form.save()
self.assertEqual(user.username, TEST_DATA[0]['username'])
self.assertTrue(user.check_password(TEST_DATA[0]['password']))
self.assertEqual(user.email, TEST_DATA[0]['email'])
class ProfileFormTestCase(TestCase):
def test(self):
form = ProfileForm({})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'age': ['This field is required.'],
'career': ['This field is required.'],
'city': ['This field is required.'],
'community': ['This field is required.'],
'country': ['This field is required.'],
'family': ['This field is required.'],
'gender': ['This field is required.'],
'religion': ['This field is required.'],
'self': ['This field is required.']})
form = ProfileForm({'age': 0,
'gender': 'foo',
'country': 'XX'})
self.assertFalse(form.is_valid())
self.assertEqual(form.errors, {'age': ['Ensure this value is greater than or equal to 18.'],
'career': ['This field is required.'],
'city': ['This field is required.'],
'community': ['This field is required.'],
'country': ['Select a valid choice. XX is not one of the available choices.'],
'family': ['This field is required.'],
'gender': ['Select a valid choice. foo is not one of the available choices.'],
'religion': ['This field is required.'],
'self': ['This field is required.']})
self.assertEqual(form.error_message(), 'age: Ensure this value is greater than or equal to 18.\ncareer: This field is required.\ncity: This field is required.\ncommunity: This field is required.\ncountry: Select a valid choice. XX is not one of the available choices.\nfamily: This field is required.\ngender: Select a valid choice. foo is not one of the available choices.\nreligion: This field is required.\nself: This field is required.')
def test_save(self):
form = ProfileForm({'age': TEST_DATA[0]['age'],
'career': TEST_DATA[0]['career'],
'city': TEST_DATA[0]['city'],
'community': TEST_DATA[0]['community'],
'country': TEST_DATA[0]['country'],
'family': TEST_DATA[0]['family'],
'gender': TEST_DATA[0]['gender'],
'religion': TEST_DATA[0]['religion'],
'self': TEST_DATA[0]['self']})
self.assertTrue(form.is_valid())
profile = form.save(commit=False)
self.assertEqual(profile.age, TEST_DATA[0]['age'])
self.assertEqual(profile.career, TEST_DATA[0]['career'])
self.assertEqual(profile.city, TEST_DATA[0]['city'])
self.assertEqual(profile.community, TEST_DATA[0]['community'])
self.assertEqual(profile.country, TEST_DATA[0]['country'])
self.assertEqual(profile.family, TEST_DATA[0]['family'])
self.assertEqual(profile.gender, TEST_DATA[0]['gender'])
self.assertEqual(profile.religion, TEST_DATA[0]['religion'])
self.assertEqual(profile.selfx, TEST_DATA[0]['self']) | mit |
klesta490/BTDB | BTDB/FieldHandler/DefaultTypeConvertorGenerator.cs | 6140 | using System;
using System.Collections.Generic;
using BTDB.Buffer;
using BTDB.Encrypted;
using BTDB.IL;
namespace BTDB.FieldHandler
{
public class DefaultTypeConvertorGenerator : ITypeConvertorGenerator
{
readonly Dictionary<Tuple<Type, Type>, Action<IILGen>> _conversions = new Dictionary<Tuple<Type, Type>, Action<IILGen>>();
public static ITypeConvertorGenerator Instance = new DefaultTypeConvertorGenerator();
public DefaultTypeConvertorGenerator()
{
var convConvertibleTypes = new[]
{
typeof (byte), typeof (sbyte), typeof (ushort), typeof (short),
typeof (uint), typeof (int), typeof (ulong), typeof (long),
typeof (float), typeof (double)
};
AddConversions(convConvertibleTypes, typeof(long), ilg => ilg.ConvI8());
AddConversions(convConvertibleTypes, typeof(ulong), ilg => ilg.ConvU8());
AddConversions(convConvertibleTypes, typeof(int), ilg => ilg.ConvI4());
AddConversions(convConvertibleTypes, typeof(uint), ilg => ilg.ConvU4());
AddConversions(convConvertibleTypes, typeof(short), ilg => ilg.ConvI2());
AddConversions(convConvertibleTypes, typeof(ushort), ilg => ilg.ConvU2());
AddConversions(convConvertibleTypes, typeof(sbyte), ilg => ilg.ConvI1());
AddConversions(convConvertibleTypes, typeof(byte), ilg => ilg.ConvU1());
AddConversions(convConvertibleTypes, typeof(double), ilg => ilg.ConvR8());
AddConversions(convConvertibleTypes, typeof(float), ilg => ilg.ConvR4());
foreach (var m in GetType().GetMethods())
{
if (!m.IsStatic) continue;
if (!m.IsPublic) continue;
if (!m.Name.StartsWith("Convert", StringComparison.Ordinal)) continue;
if (m.ContainsGenericParameters) continue;
var parameterInfos = m.GetParameters();
if (parameterInfos.Length != 1) continue;
var fromType = parameterInfos[0].ParameterType;
var closuredMethodInfo = m;
_conversions[Tuple.Create(fromType, m.ReturnType)] = ilg => ilg.Call(closuredMethodInfo);
}
}
void AddConversions(IEnumerable<Type> fromList, Type to, Action<IILGen> generator)
{
foreach (var from in fromList)
{
_conversions[Tuple.Create(from, to)] = generator;
}
}
public virtual Action<IILGen> GenerateConversion(Type from, Type to)
{
if (from == to) return ilg => { };
if (!from.IsValueType && to == typeof(object))
{
return i => i.Castclass(to);
}
if (from == typeof(object) && !to.IsValueType)
{
return i => i.Isinst(to);
}
Action<IILGen> generator;
if (_conversions.TryGetValue(new Tuple<Type, Type>(from, to), out generator))
{
return generator;
}
if (from.IsEnum && to.IsEnum) return GenerateEnum2EnumConversion(from, to);
return null;
}
Action<IILGen> GenerateEnum2EnumConversion(Type from, Type to)
{
var fromcfg = new EnumFieldHandler.EnumConfiguration(from);
var tocfg = new EnumFieldHandler.EnumConfiguration(to);
if (fromcfg.IsSubsetOf(tocfg))
{
return GenerateConversion(from.GetEnumUnderlyingType(), to.GetEnumUnderlyingType());
}
return null;
}
public static string Convert2String(double value)
{
return value.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
public static string Convert2String(bool value)
{
return value ? "1" : "0";
}
public static string Convert2String(long value)
{
return value.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
public static string Convert2String(ulong value)
{
return value.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
public static string Convert2String(decimal value)
{
return value.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
public static decimal Convert2Decimal(long value)
{
return new decimal(value);
}
public static decimal Convert2Decimal(ulong value)
{
return new decimal(value);
}
public static decimal Convert2Decimal(int value)
{
return new decimal(value);
}
public static decimal Convert2Decimal(uint value)
{
return new decimal(value);
}
public static decimal Convert2Decimal(double value)
{
return new decimal(value);
}
public static decimal Convert2Decimal(float value)
{
return new decimal(value);
}
public static bool Convert2Bool(int value)
{
return value != 0;
}
public static byte[] Convert2Bytes(ByteBuffer buffer)
{
return buffer.ToByteArray();
}
public static ByteBuffer Convert2ByteBuffer(byte[] bytes)
{
return ByteBuffer.NewAsync(bytes);
}
public static string? Convert2String(Version? version)
{
return version?.ToString();
}
public static Version? Convert2Version(string? value)
{
Version.TryParse(value, out var result);
return result;
}
public static EncryptedString Convert2EncryptedString(string? secret) => secret;
public static string? Convert2String(EncryptedString secret) => secret;
}
}
| mit |
kkrnt/hsp.vs | hsp.vs/HSPConfigContentTypeDefinitions.cs | 477 | using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Utilities;
namespace hsp.vs
{
internal static class HSPConfigContentTypeDefinitions
{
[Export] [Name("hspconf")] [BaseDefinition("text")] internal static ContentTypeDefinition
hidingContentTypeDefinition;
[Export] [FileExtension(".hsp")] [ContentType("hspconf")] internal static
FileExtensionToContentTypeDefinition hiddenFileExtensionDefinition;
}
} | mit |
taku-y/bmlingam | bmlingam/commands/bmlingam_causality.py | 14318 | # -*- coding: utf-8 -*-
"""Include functions used in command bin/bmlingam-causality.
"""
# Author: Taku Yoshioka
# License: MIT
from itertools import combinations
import numpy as np
from os import sep
import pandas as pd
from argparse import ArgumentParser
from bmlingam import load_data, define_hparam_searchspace, InferParams, \
infer_causality, save_pklz
from bmlingam.utils import eval_
def _get_pairs(n_variables):
"""Return pairs of indices without repetitions.
"""
return list(combinations(range(n_variables), 2))
def _make_table_causal(results):
"""Aggregate inferred causalities included in given results.
"""
causalities = [r['causality_str'] for r in results]
post_probs = [r['post_prob'] for r in results]
post_probs_rev = [r['post_prob_rev'] for r in results]
return pd.DataFrame({
'Inferred Causality': causalities,
'Posterior probability': post_probs,
'Posterior probability of reverse model': post_probs_rev
})
def _get_optmodel_file(result, result_dir):
"""Returns optimal model filename.
"""
x1_name = result['x1_name']
x2_name = result['x2_name']
return result_dir + sep + '%s_%s.bmlm.pklz' % (x1_name, x2_name)
def parse_args_bmlingam_causality(args=None):
parser = ArgumentParser()
# Positional arguments
parser.add_argument('csv_file', type=str,
help='CSV file of data.')
# Optional arguments: execution parameters
parser.add_argument('--result_dir', type=str,
default='.' + sep,
help="""Directory where result files are saved.
Default is current directory. """)
parser.add_argument('--out_optmodelfile',
dest='is_out_optmodelfile', action='store_true',
help="""If this option is choosen (default), optimal model
files will be created.""")
parser.add_argument('--no_out_optmodelfile',
dest='is_out_optmodelfile', action='store_false',
help="""If this option is choosen, optimal model files
will not be created.""")
parser.set_defaults(is_out_optmodelfile=True)
parser.add_argument('--col_names',
default=None, type=str,
help="""Names of column, specified as 'name1,name2,...'
(space not allowed).
If set this value 'auto', column names will be
automatically determined as 'x0,x1,...'.
If csv file have column names (the 1st row of the
file), they will be overwritten.
""")
parser.add_argument('--optmodel_files',
default=None,
help="""Filenames of optimal model files. This should
be specified as Python list, e.g.,
'["file1", "file2", ...]'. The length of the
list must be the same with the number of all
variable pairs in the data. If None
(default), the filenames are automatically
determined. This parameter overwrites
--out_optmodelfile.""")
# Get default setting
default = InferParams()
# For bool args
str_bool = lambda b1, b2: ' (default)' if b1 == b2 else ''
# Optional arguments: inference parameters
parser.add_argument('--seed',
default=default.seed, type=int,
help="""Specify the seed of random number generator used in
MC sampling. Default is {}.
""".format(default.seed))
parser.add_argument('--standardize_on',
dest='standardize', action='store_true',
help="""If this option is choosen {}, data is standardized
to mean 0 and variance 1 before causal inference.
""".format(str_bool(default.standardize, True)))
parser.add_argument('--standardize_off',
dest='standardize', action='store_false',
help="""If this option is choosen{}, data is not
standardized.
""".format(str_bool(default.standardize, False)))
parser.set_defaults(standardize=default.standardize)
parser.add_argument('--fix_mu_zero_on',
dest='fix_mu_zero', action='store_true',
help="""If this option is choosen{}, common interception
parameter mu_1,2 will be treated as 0
(constant), not estimated.
""".format(str_bool(default.fix_mu_zero, True)))
parser.add_argument('--fix_mu_zero_off',
dest='fix_mu_zero', action='store_false',
help="""If this option is choosen, common
interception parameter mu_1,2 will be included
in models as stochastic variables.
""".format(str_bool(default.fix_mu_zero, False)))
parser.set_defaults(fix_mu_zero=default.fix_mu_zero)
parser.add_argument('--max_c',
default=default.max_c, type=float,
help="""Scale constant on tau_cmmn. Default is {}.
""".format(default.max_c))
parser.add_argument('--n_mc_samples',
default=default.n_mc_samples, type=int,
help="""The number of Monte Carlo sampling in calculation
of marginal likelihood values of models.
Default is {}.
""".format(default.n_mc_samples))
parser.add_argument('--dist_noise',
default=default.dist_noise, type=str,
help="""Noise distribution. 'laplace' or 'gg'
(Generalized Gaussian). Default is {}.
""".format(default.dist_noise))
parser.add_argument('--df_indvdl',
default=default.df_indvdl, type=float,
help="""Degrees of freedom of T distribution for
the prior of individual specific effects.
Default is {}.
""".format(default.df_indvdl))
parser.add_argument('--prior_scale',
default=default.prior_scale, type=str,
help="""Prior distribution on noise variance.
'log_normal' or 'tr_normal'
(truncated normal distribution).
Default is {}.
""".format(default.prior_scale))
parser.add_argument('--prior_indvdls',
default=default.prior_indvdls[0], type=str,
help="""Distribution of individual effects in the model.
This argument can be 't', 'gauss' or 'gg'.
If you want to include multiple distributions,
set this argument as 't,gauss', then the
program will apply both of t and Gaussian
distributions to candidate models.
Default is {}.
""".format(default.prior_indvdls[0]))
parser.add_argument('--cs',
default='0,.2,.4,.6,.8', type=str,
help="""Scales of stds of the individual specific effects.
Default is '0,.2,.4,.6,.8'. """)
parser.add_argument('--L_cov_21s', type=str,
default='[-0.9,-0.7,-0.5,-0.3,0,.3,.5,.7,.9]',
help="""List of correlations of individual specific
effects.
Default is
'[-0.9,-0.7,-0.5,-0.3,0,.3,.5,.7,.9]'. """)
parser.add_argument('--betas_indvdl',
default='.25,.5,.75,1.', type=str,
help="""Shape parameter values of generalized Gaussian
distributions for individual specific effects.
When prior_indvdls includes 'gg', all of the
beta values will be tested. .5 and 1. correspond
to Laplace and Gaussian distributions,
respectively.
Default is '.25,.5,.75,1.'. """)
parser.add_argument('--betas_noise',
default='.25,.5,.75,1.', type=str,
help="""Shape parameter values of generalized Gaussian
distributions for observation noise.
When dist_noise includes 'gg', all of the
beta values will be tested. .5 and 1. correspond
to Laplace and Gaussian distributions,
respectively.
Default is '.25,.5,.75,1.'. """)
parser.add_argument('--causalities',
default='x1->x2, x2->x1', type=str,
help="""Causalities to be tested. If set to 'x1->x2' or
'x2->x1', causality is not inferred and other
hyperparameters are searched.
Default is 'x1->x2, x2->x1'. """)
parser.add_argument('--sampling_mode',
default='cache', type=str,
help="""Specify sampling mode for numerical integration
via MC. Options are 'normal', 'cache', 'cache_mp2',
'cache_mp4' or 'cache_mp8'. 'normal' means naive
MC sampling: generate random values at each
hyperparameter set. When specified 'chache',
random values are generated only at the beginning of
the program and applied to marginal likelihood
calculation with difference hyperparameter sets.
Multiprocessing is supported with the option
'cache_mp[2, 4, 8]', using 2, 4 or 8 cores.""")
args_ = parser.parse_args(args)
return {
'csv_file': args_.csv_file,
'result_dir': args_.result_dir,
'is_out_optmodelfile': args_.is_out_optmodelfile,
'col_names': None if args_.col_names is None else args_.col_names.split(','),
'infer_params': InferParams(
seed = args_.seed,
standardize = args_.standardize,
fix_mu_zero = args_.fix_mu_zero,
max_c = args_.max_c,
n_mc_samples = args_.n_mc_samples,
P_M1 = 0.5,
P_M2 = 0.5,
dist_noise = args_.dist_noise,
df_indvdl = args_.df_indvdl,
prior_scale = args_.prior_scale,
prior_indvdls = args_.prior_indvdls.split(','),
cs = np.array(args_.cs.split(',')).astype(float),
L_cov_21s = eval_(args_.L_cov_21s),
betas_indvdl = np.array(args_.betas_indvdl.split(',')).astype(float),
betas_noise = np.array(args_.betas_noise.split(',')).astype(float),
sampling_mode = args_.sampling_mode
),
'optmodel_files': args_.optmodel_files
}
def bmlingam_causality(
csv_file, result_dir, is_out_optmodelfile, col_names, infer_params,
optmodel_files):
"""Infer causality of all pairs in the data.
"""
assert(type(infer_params) == InferParams)
if type(optmodel_files) is str:
optmodel_files = [optmodel_files]
print('---- Algorithm parameters ----')
print('Number of MC samples: %d' % infer_params.n_mc_samples)
hparamss = define_hparam_searchspace(infer_params)
print('Number of candidate models: %d' % len(hparamss))
print('')
# Load data and infer causality
df = load_data(csv_file, col_names) # Pandas dataframe
# Get all possible pairs of variables
pairs = _get_pairs(len(df.columns))
# Check optimal model files
if optmodel_files is not None:
assert(len(optmodel_files) == len(pairs))
optmodel_files_ = optmodel_files
# Infer causality over all variable pairs
data = df.as_matrix()
varnames = df.columns.values
results = [infer_causality(data[:, pair], infer_params,
varnames[list(pair)]) for pair in pairs]
# Summarize inference
table_causal = _make_table_causal(results)
# Set optimal model files
if optmodel_files is None:
if result_dir is not None:
optmodel_files_ = [_get_optmodel_file(result, result_dir)
for result in results]
else:
optmodel_files_ = []
# Conditions to save results (and optimal models)
cond_save_results = (result_dir is not None) and (0 < len(result_dir))
cond_save_optmodels = 0 < len(optmodel_files_) and is_out_optmodelfile
# Save results
if cond_save_results:
result_file = result_dir + sep + 'causality.csv'
table_causal.to_csv(result_file)
print('Inferred causality table was saved as %s.' % result_file)
# Save optimal models
if cond_save_optmodels:
for result, optmodel_file in zip(results, optmodel_files_):
save_pklz(optmodel_file, result)
print('Optimal model was saved as %s.' % optmodel_file)
| mit |
plt-tud/PLT_MRT_ARM-RPi2 | Vorlesungsbeispiele/MRT2_VL-8_OPCUA_FirstSteps_PiServer/OPCUA_FirstSteps_piServer.cpp | 1565 | /*
Copyright (c) 2019 Chris Iatrou <[email protected]>
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 <signal.h>
#include "open62541.h"
UA_Boolean running = true;
static void stopHandler(int sig) {
running = false;
}
int main(void) {
signal(SIGINT, stopHandler);
signal(SIGTERM, stopHandler);
UA_ServerConfig *config = UA_ServerConfig_new_default();
UA_Server *server = UA_Server_new(config);
UA_Server_run(server, &running);
UA_Server_delete(server);
UA_ServerConfig_delete(config);
return 0;
}
| mit |
sdvincent/xacmlAuthProject | xacmlEngine/Target.php | 960 | <?php
//namespace Xacmlphp;
/**
* Rule target containing Match set
*
* @package Xacmlphp
*/
class Target
{
/**
* Set of Matches for a Target
*
* @var array
*/
private $matches = array();
/**
* Add a new Match to the Target set
*
* @param Match $match Match instance
*
* @return \Xacmlphp\Target
*/
public function addMatch(Match $match)
{
$this->matches[] = $match;
return $this;
}
/**
* Add multiple new Matches to the set
*
* @param array $matches Multiple matches
*
* @return $this
*/
public function addMatches(array $matches)
{
foreach ($matches as $match) {
$this->addMatch($match);
}
return $this;
}
/**
* Get the current set of Matches
*
* @return array Matches set
*/
public function getMatches()
{
return $this->matches;
}
}
| mit |
LorenVS/bacstack | BACnet.Ashrae/Generated/EventParameter.cs | 22228 | using System;
using BACnet.Types;
using BACnet.Types.Schemas;
namespace BACnet.Ashrae
{
public abstract partial class EventParameter
{
public abstract Tags Tag { get; }
public bool IsChangeOfBitstring { get { return this.Tag == Tags.ChangeOfBitstring; } }
public ChangeOfBitstring AsChangeOfBitstring { get { return (ChangeOfBitstring)this; } }
public static EventParameter NewChangeOfBitstring(uint timeDelay, BitString56 bitmask, ReadOnlyArray<BitString56> listOfBitstringValues)
{
return new ChangeOfBitstring(timeDelay, bitmask, listOfBitstringValues);
}
public bool IsChangeOfState { get { return this.Tag == Tags.ChangeOfState; } }
public ChangeOfState AsChangeOfState { get { return (ChangeOfState)this; } }
public static EventParameter NewChangeOfState(uint timeDelay, ReadOnlyArray<PropertyStates> listOfValues)
{
return new ChangeOfState(timeDelay, listOfValues);
}
public bool IsChangeOfValue { get { return this.Tag == Tags.ChangeOfValue; } }
public ChangeOfValue AsChangeOfValue { get { return (ChangeOfValue)this; } }
public static EventParameter NewChangeOfValue(uint timeDelay, COVCriteria covCriteria)
{
return new ChangeOfValue(timeDelay, covCriteria);
}
public bool IsCommandFailure { get { return this.Tag == Tags.CommandFailure; } }
public CommandFailure AsCommandFailure { get { return (CommandFailure)this; } }
public static EventParameter NewCommandFailure(uint timeDelay, DeviceObjectPropertyReference feedbackPropertyReference)
{
return new CommandFailure(timeDelay, feedbackPropertyReference);
}
public bool IsFloatingLimit { get { return this.Tag == Tags.FloatingLimit; } }
public FloatingLimit AsFloatingLimit { get { return (FloatingLimit)this; } }
public static EventParameter NewFloatingLimit(uint timeDelay, DeviceObjectPropertyReference setpointReference, float lowDiffLimit, float highDiffLimit, float deadband)
{
return new FloatingLimit(timeDelay, setpointReference, lowDiffLimit, highDiffLimit, deadband);
}
public bool IsOutOfRange { get { return this.Tag == Tags.OutOfRange; } }
public OutOfRange AsOutOfRange { get { return (OutOfRange)this; } }
public static EventParameter NewOutOfRange(uint timeDelay, float lowLimit, float highLimit, float deadband)
{
return new OutOfRange(timeDelay, lowLimit, highLimit, deadband);
}
public bool IsChangeOfLifeSafety { get { return this.Tag == Tags.ChangeOfLifeSafety; } }
public ChangeOfLifeSafety AsChangeOfLifeSafety { get { return (ChangeOfLifeSafety)this; } }
public static EventParameter NewChangeOfLifeSafety(uint timeDelay, ReadOnlyArray<LifeSafetyState> listOfLifeSafetyAlarmValues, ReadOnlyArray<LifeSafetyState> listOfAlarmValues, DeviceObjectPropertyReference modePropertyReference)
{
return new ChangeOfLifeSafety(timeDelay, listOfLifeSafetyAlarmValues, listOfAlarmValues, modePropertyReference);
}
public bool IsExtended { get { return this.Tag == Tags.Extended; } }
public Extended AsExtended { get { return (Extended)this; } }
public static EventParameter NewExtended(uint vendorId, uint extendedEventType, ReadOnlyArray<ExtendedParameter> parameters)
{
return new Extended(vendorId, extendedEventType, parameters);
}
public bool IsBufferReady { get { return this.Tag == Tags.BufferReady; } }
public BufferReady AsBufferReady { get { return (BufferReady)this; } }
public static EventParameter NewBufferReady(uint notificationThreshold, uint previousNotificationCount)
{
return new BufferReady(notificationThreshold, previousNotificationCount);
}
public bool IsUnsignedRange { get { return this.Tag == Tags.UnsignedRange; } }
public UnsignedRange AsUnsignedRange { get { return (UnsignedRange)this; } }
public static EventParameter NewUnsignedRange(uint timeDelay, uint lowLimit, uint highLimit)
{
return new UnsignedRange(timeDelay, lowLimit, highLimit);
}
public static readonly ISchema Schema = new ChoiceSchema(false,
new FieldSchema("ChangeOfBitstring", 0, Value<ChangeOfBitstring>.Schema),
new FieldSchema("ChangeOfState", 1, Value<ChangeOfState>.Schema),
new FieldSchema("ChangeOfValue", 2, Value<ChangeOfValue>.Schema),
new FieldSchema("CommandFailure", 3, Value<CommandFailure>.Schema),
new FieldSchema("FloatingLimit", 4, Value<FloatingLimit>.Schema),
new FieldSchema("OutOfRange", 5, Value<OutOfRange>.Schema),
new FieldSchema("ChangeOfLifeSafety", 8, Value<ChangeOfLifeSafety>.Schema),
new FieldSchema("Extended", 9, Value<Extended>.Schema),
new FieldSchema("BufferReady", 10, Value<BufferReady>.Schema),
new FieldSchema("UnsignedRange", 11, Value<UnsignedRange>.Schema));
public static EventParameter Load(IValueStream stream)
{
EventParameter ret = null;
Tags tag = (Tags)stream.EnterChoice();
switch(tag)
{
case Tags.ChangeOfBitstring:
ret = Value<ChangeOfBitstring>.Load(stream);
break;
case Tags.ChangeOfState:
ret = Value<ChangeOfState>.Load(stream);
break;
case Tags.ChangeOfValue:
ret = Value<ChangeOfValue>.Load(stream);
break;
case Tags.CommandFailure:
ret = Value<CommandFailure>.Load(stream);
break;
case Tags.FloatingLimit:
ret = Value<FloatingLimit>.Load(stream);
break;
case Tags.OutOfRange:
ret = Value<OutOfRange>.Load(stream);
break;
case Tags.ChangeOfLifeSafety:
ret = Value<ChangeOfLifeSafety>.Load(stream);
break;
case Tags.Extended:
ret = Value<Extended>.Load(stream);
break;
case Tags.BufferReady:
ret = Value<BufferReady>.Load(stream);
break;
case Tags.UnsignedRange:
ret = Value<UnsignedRange>.Load(stream);
break;
default:
throw new Exception();
}
stream.LeaveChoice();
return ret;
}
public static void Save(IValueSink sink, EventParameter value)
{
sink.EnterChoice((byte)value.Tag);
switch(value.Tag)
{
case Tags.ChangeOfBitstring:
Value<ChangeOfBitstring>.Save(sink, (ChangeOfBitstring)value);
break;
case Tags.ChangeOfState:
Value<ChangeOfState>.Save(sink, (ChangeOfState)value);
break;
case Tags.ChangeOfValue:
Value<ChangeOfValue>.Save(sink, (ChangeOfValue)value);
break;
case Tags.CommandFailure:
Value<CommandFailure>.Save(sink, (CommandFailure)value);
break;
case Tags.FloatingLimit:
Value<FloatingLimit>.Save(sink, (FloatingLimit)value);
break;
case Tags.OutOfRange:
Value<OutOfRange>.Save(sink, (OutOfRange)value);
break;
case Tags.ChangeOfLifeSafety:
Value<ChangeOfLifeSafety>.Save(sink, (ChangeOfLifeSafety)value);
break;
case Tags.Extended:
Value<Extended>.Save(sink, (Extended)value);
break;
case Tags.BufferReady:
Value<BufferReady>.Save(sink, (BufferReady)value);
break;
case Tags.UnsignedRange:
Value<UnsignedRange>.Save(sink, (UnsignedRange)value);
break;
default:
throw new Exception();
}
sink.LeaveChoice();
}
public enum Tags : byte
{
ChangeOfBitstring = 0,
ChangeOfState = 1,
ChangeOfValue = 2,
CommandFailure = 3,
FloatingLimit = 4,
OutOfRange = 5,
ChangeOfLifeSafety = 6,
Extended = 7,
BufferReady = 8,
UnsignedRange = 9
}
public partial class ChangeOfBitstring : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfBitstring; } }
public uint TimeDelay { get; private set; }
public BitString56 Bitmask { get; private set; }
public ReadOnlyArray<BitString56> ListOfBitstringValues { get; private set; }
public ChangeOfBitstring(uint timeDelay, BitString56 bitmask, ReadOnlyArray<BitString56> listOfBitstringValues)
{
this.TimeDelay = timeDelay;
this.Bitmask = bitmask;
this.ListOfBitstringValues = listOfBitstringValues;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("Bitmask", 1, Value<BitString56>.Schema),
new FieldSchema("ListOfBitstringValues", 2, Value<ReadOnlyArray<BitString56>>.Schema));
public static new ChangeOfBitstring Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var bitmask = Value<BitString56>.Load(stream);
var listOfBitstringValues = Value<ReadOnlyArray<BitString56>>.Load(stream);
stream.LeaveSequence();
return new ChangeOfBitstring(timeDelay, bitmask, listOfBitstringValues);
}
public static void Save(IValueSink sink, ChangeOfBitstring value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<BitString56>.Save(sink, value.Bitmask);
Value<ReadOnlyArray<BitString56>>.Save(sink, value.ListOfBitstringValues);
sink.LeaveSequence();
}
}
public partial class ChangeOfState : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfState; } }
public uint TimeDelay { get; private set; }
public ReadOnlyArray<PropertyStates> ListOfValues { get; private set; }
public ChangeOfState(uint timeDelay, ReadOnlyArray<PropertyStates> listOfValues)
{
this.TimeDelay = timeDelay;
this.ListOfValues = listOfValues;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("ListOfValues", 1, Value<ReadOnlyArray<PropertyStates>>.Schema));
public static new ChangeOfState Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var listOfValues = Value<ReadOnlyArray<PropertyStates>>.Load(stream);
stream.LeaveSequence();
return new ChangeOfState(timeDelay, listOfValues);
}
public static void Save(IValueSink sink, ChangeOfState value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<ReadOnlyArray<PropertyStates>>.Save(sink, value.ListOfValues);
sink.LeaveSequence();
}
}
public partial class ChangeOfValue : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfValue; } }
public uint TimeDelay { get; private set; }
public COVCriteria CovCriteria { get; private set; }
public ChangeOfValue(uint timeDelay, COVCriteria covCriteria)
{
this.TimeDelay = timeDelay;
this.CovCriteria = covCriteria;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("CovCriteria", 1, Value<COVCriteria>.Schema));
public static new ChangeOfValue Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var covCriteria = Value<COVCriteria>.Load(stream);
stream.LeaveSequence();
return new ChangeOfValue(timeDelay, covCriteria);
}
public static void Save(IValueSink sink, ChangeOfValue value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<COVCriteria>.Save(sink, value.CovCriteria);
sink.LeaveSequence();
}
}
public partial class CommandFailure : EventParameter
{
public override Tags Tag { get { return Tags.CommandFailure; } }
public uint TimeDelay { get; private set; }
public DeviceObjectPropertyReference FeedbackPropertyReference { get; private set; }
public CommandFailure(uint timeDelay, DeviceObjectPropertyReference feedbackPropertyReference)
{
this.TimeDelay = timeDelay;
this.FeedbackPropertyReference = feedbackPropertyReference;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("FeedbackPropertyReference", 1, Value<DeviceObjectPropertyReference>.Schema));
public static new CommandFailure Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var feedbackPropertyReference = Value<DeviceObjectPropertyReference>.Load(stream);
stream.LeaveSequence();
return new CommandFailure(timeDelay, feedbackPropertyReference);
}
public static void Save(IValueSink sink, CommandFailure value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<DeviceObjectPropertyReference>.Save(sink, value.FeedbackPropertyReference);
sink.LeaveSequence();
}
}
public partial class FloatingLimit : EventParameter
{
public override Tags Tag { get { return Tags.FloatingLimit; } }
public uint TimeDelay { get; private set; }
public DeviceObjectPropertyReference SetpointReference { get; private set; }
public float LowDiffLimit { get; private set; }
public float HighDiffLimit { get; private set; }
public float Deadband { get; private set; }
public FloatingLimit(uint timeDelay, DeviceObjectPropertyReference setpointReference, float lowDiffLimit, float highDiffLimit, float deadband)
{
this.TimeDelay = timeDelay;
this.SetpointReference = setpointReference;
this.LowDiffLimit = lowDiffLimit;
this.HighDiffLimit = highDiffLimit;
this.Deadband = deadband;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("SetpointReference", 1, Value<DeviceObjectPropertyReference>.Schema),
new FieldSchema("LowDiffLimit", 2, Value<float>.Schema),
new FieldSchema("HighDiffLimit", 3, Value<float>.Schema),
new FieldSchema("Deadband", 4, Value<float>.Schema));
public static new FloatingLimit Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var setpointReference = Value<DeviceObjectPropertyReference>.Load(stream);
var lowDiffLimit = Value<float>.Load(stream);
var highDiffLimit = Value<float>.Load(stream);
var deadband = Value<float>.Load(stream);
stream.LeaveSequence();
return new FloatingLimit(timeDelay, setpointReference, lowDiffLimit, highDiffLimit, deadband);
}
public static void Save(IValueSink sink, FloatingLimit value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<DeviceObjectPropertyReference>.Save(sink, value.SetpointReference);
Value<float>.Save(sink, value.LowDiffLimit);
Value<float>.Save(sink, value.HighDiffLimit);
Value<float>.Save(sink, value.Deadband);
sink.LeaveSequence();
}
}
public partial class OutOfRange : EventParameter
{
public override Tags Tag { get { return Tags.OutOfRange; } }
public uint TimeDelay { get; private set; }
public float LowLimit { get; private set; }
public float HighLimit { get; private set; }
public float Deadband { get; private set; }
public OutOfRange(uint timeDelay, float lowLimit, float highLimit, float deadband)
{
this.TimeDelay = timeDelay;
this.LowLimit = lowLimit;
this.HighLimit = highLimit;
this.Deadband = deadband;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("LowLimit", 1, Value<float>.Schema),
new FieldSchema("HighLimit", 2, Value<float>.Schema),
new FieldSchema("Deadband", 3, Value<float>.Schema));
public static new OutOfRange Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var lowLimit = Value<float>.Load(stream);
var highLimit = Value<float>.Load(stream);
var deadband = Value<float>.Load(stream);
stream.LeaveSequence();
return new OutOfRange(timeDelay, lowLimit, highLimit, deadband);
}
public static void Save(IValueSink sink, OutOfRange value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<float>.Save(sink, value.LowLimit);
Value<float>.Save(sink, value.HighLimit);
Value<float>.Save(sink, value.Deadband);
sink.LeaveSequence();
}
}
public partial class ChangeOfLifeSafety : EventParameter
{
public override Tags Tag { get { return Tags.ChangeOfLifeSafety; } }
public uint TimeDelay { get; private set; }
public ReadOnlyArray<LifeSafetyState> ListOfLifeSafetyAlarmValues { get; private set; }
public ReadOnlyArray<LifeSafetyState> ListOfAlarmValues { get; private set; }
public DeviceObjectPropertyReference ModePropertyReference { get; private set; }
public ChangeOfLifeSafety(uint timeDelay, ReadOnlyArray<LifeSafetyState> listOfLifeSafetyAlarmValues, ReadOnlyArray<LifeSafetyState> listOfAlarmValues, DeviceObjectPropertyReference modePropertyReference)
{
this.TimeDelay = timeDelay;
this.ListOfLifeSafetyAlarmValues = listOfLifeSafetyAlarmValues;
this.ListOfAlarmValues = listOfAlarmValues;
this.ModePropertyReference = modePropertyReference;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("ListOfLifeSafetyAlarmValues", 1, Value<ReadOnlyArray<LifeSafetyState>>.Schema),
new FieldSchema("ListOfAlarmValues", 2, Value<ReadOnlyArray<LifeSafetyState>>.Schema),
new FieldSchema("ModePropertyReference", 3, Value<DeviceObjectPropertyReference>.Schema));
public static new ChangeOfLifeSafety Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var listOfLifeSafetyAlarmValues = Value<ReadOnlyArray<LifeSafetyState>>.Load(stream);
var listOfAlarmValues = Value<ReadOnlyArray<LifeSafetyState>>.Load(stream);
var modePropertyReference = Value<DeviceObjectPropertyReference>.Load(stream);
stream.LeaveSequence();
return new ChangeOfLifeSafety(timeDelay, listOfLifeSafetyAlarmValues, listOfAlarmValues, modePropertyReference);
}
public static void Save(IValueSink sink, ChangeOfLifeSafety value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<ReadOnlyArray<LifeSafetyState>>.Save(sink, value.ListOfLifeSafetyAlarmValues);
Value<ReadOnlyArray<LifeSafetyState>>.Save(sink, value.ListOfAlarmValues);
Value<DeviceObjectPropertyReference>.Save(sink, value.ModePropertyReference);
sink.LeaveSequence();
}
}
public partial class Extended : EventParameter
{
public override Tags Tag { get { return Tags.Extended; } }
public uint VendorId { get; private set; }
public uint ExtendedEventType { get; private set; }
public ReadOnlyArray<ExtendedParameter> Parameters { get; private set; }
public Extended(uint vendorId, uint extendedEventType, ReadOnlyArray<ExtendedParameter> parameters)
{
this.VendorId = vendorId;
this.ExtendedEventType = extendedEventType;
this.Parameters = parameters;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("VendorId", 0, Value<uint>.Schema),
new FieldSchema("ExtendedEventType", 1, Value<uint>.Schema),
new FieldSchema("Parameters", 2, Value<ReadOnlyArray<ExtendedParameter>>.Schema));
public static new Extended Load(IValueStream stream)
{
stream.EnterSequence();
var vendorId = Value<uint>.Load(stream);
var extendedEventType = Value<uint>.Load(stream);
var parameters = Value<ReadOnlyArray<ExtendedParameter>>.Load(stream);
stream.LeaveSequence();
return new Extended(vendorId, extendedEventType, parameters);
}
public static void Save(IValueSink sink, Extended value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.VendorId);
Value<uint>.Save(sink, value.ExtendedEventType);
Value<ReadOnlyArray<ExtendedParameter>>.Save(sink, value.Parameters);
sink.LeaveSequence();
}
}
public partial class BufferReady : EventParameter
{
public override Tags Tag { get { return Tags.BufferReady; } }
public uint NotificationThreshold { get; private set; }
public uint PreviousNotificationCount { get; private set; }
public BufferReady(uint notificationThreshold, uint previousNotificationCount)
{
this.NotificationThreshold = notificationThreshold;
this.PreviousNotificationCount = previousNotificationCount;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("NotificationThreshold", 0, Value<uint>.Schema),
new FieldSchema("PreviousNotificationCount", 1, Value<uint>.Schema));
public static new BufferReady Load(IValueStream stream)
{
stream.EnterSequence();
var notificationThreshold = Value<uint>.Load(stream);
var previousNotificationCount = Value<uint>.Load(stream);
stream.LeaveSequence();
return new BufferReady(notificationThreshold, previousNotificationCount);
}
public static void Save(IValueSink sink, BufferReady value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.NotificationThreshold);
Value<uint>.Save(sink, value.PreviousNotificationCount);
sink.LeaveSequence();
}
}
public partial class UnsignedRange : EventParameter
{
public override Tags Tag { get { return Tags.UnsignedRange; } }
public uint TimeDelay { get; private set; }
public uint LowLimit { get; private set; }
public uint HighLimit { get; private set; }
public UnsignedRange(uint timeDelay, uint lowLimit, uint highLimit)
{
this.TimeDelay = timeDelay;
this.LowLimit = lowLimit;
this.HighLimit = highLimit;
}
public static readonly new ISchema Schema = new SequenceSchema(false,
new FieldSchema("TimeDelay", 0, Value<uint>.Schema),
new FieldSchema("LowLimit", 1, Value<uint>.Schema),
new FieldSchema("HighLimit", 2, Value<uint>.Schema));
public static new UnsignedRange Load(IValueStream stream)
{
stream.EnterSequence();
var timeDelay = Value<uint>.Load(stream);
var lowLimit = Value<uint>.Load(stream);
var highLimit = Value<uint>.Load(stream);
stream.LeaveSequence();
return new UnsignedRange(timeDelay, lowLimit, highLimit);
}
public static void Save(IValueSink sink, UnsignedRange value)
{
sink.EnterSequence();
Value<uint>.Save(sink, value.TimeDelay);
Value<uint>.Save(sink, value.LowLimit);
Value<uint>.Save(sink, value.HighLimit);
sink.LeaveSequence();
}
}
}
}
| mit |
neurospeech/xamarin-ui-atoms-samples | ListView/ViewModels/ListViewMultipleSelectionPageViewModel.cs | 1143 | using NeuroSpeech.UIAtoms;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UIAtomsDemo.RestServices;
using UIAtomsDemo.RestServices.Models;
namespace ListView.ViewModels
{
public class ListViewMultipleSelectionPageViewModel : AtomViewModel
{
public AtomList<YouTubeVideo> Videos { get; }
= new AtomList<YouTubeVideo>();
public override async Task InitAsync()
{
var service = Get<YouTubeService>();
// this replaces existing items with new items
// unlike Clear and AddRange, this method does not cause full list refresh
this.Videos.Replace(await service.GetVideos());
}
#region Property SelectedVideos
private System.Collections.IEnumerable _SelectedVideos = null;
public System.Collections.IEnumerable SelectedVideos
{
get
{
return _SelectedVideos;
}
set
{
SetProperty(ref _SelectedVideos, value);
}
}
#endregion
}
}
| mit |
orangemug/sql-stamp | test/issues/15/index.js | 611 | var assert = require("assert");
var sqlStamp = require("../../../");
var util = require("../../util");
var results = util.readSync([
"./out.sql"
], __dirname);
describe("issue #15", function() {
var tmpl;
before(function() {
return sqlStamp([__dirname+"/in.sql"], {})
.then(function(_tmpl) {
tmpl = _tmpl;
});
});
it("should work", function() {
var out = tmpl(__dirname+"/in.sql", {
ids: [1, 2, 3]
});
assert.equal(out.args.length, 1);
assert.deepEqual(out.args[0], [1, 2, 3]);
assert.equal(out.sql, results["./out.sql"]);
});
});
| mit |
stephaneAG/Android_tests | TefServices/src/com/example/tefservices/MyServices.java | 15421 | package com.example.tefservices;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class MyServices extends Service {
//public class MyServices extends IntentService {
// use the SMSreceiver class defined below the current class file ( declare member variables to make us of them )
private SMSreceiver mSMSreceiver;
private IntentFilter mIntentFilter;
// it seems that we need the following for the IntentService ( was not needed to using the Service class )
/**
public MyServices(){
super("MyServices");
}
*/
// the IntentService class needs to implement the following ( -> and it is actually very usefull ;p )
/**
@Override
protected void onHandleIntent(Intent intent){
//Toast.makeText(getApplicationContext(), " Tef Service is now running [onCreate]", Toast.LENGTH_LONG).show();
Toast.makeText(this, " Tef Service is now running [onHandleIntent]", Toast.LENGTH_LONG).show();
// DO STUFF HERE (..)
}
*/
// we need to override the onCreate method to be able to implement the SMS receiving part
@Override
public void onCreate(){
super.onCreate(); // always call the superclass
// init our member variables responsible for receiving SMS messages
mSMSreceiver = new SMSreceiver();
mIntentFilter = new IntentFilter();
// setup the intent filter to look for SMS received
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); // nb: not available as choice from menu
// register the receiver
registerReceiver(mSMSreceiver, mIntentFilter);
// display a fancy message to the user to indicate the service was just launched succefully
Toast.makeText(getApplicationContext(), " Tef Service is now running [onCreate]", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent arg0) { // onBind enables to bind an activity to a service
// TODO Auto-generated method stub
return null;
}
// to explicitly start a service when the user hit the startService button, we use the following method
@Override
public int onStartCommand(Intent intent, int flags, int startId){
// I guess I forgot to add it for the Service, but it is needed for the IntentService ( and should have been there as well for Service ..)
super.onStartCommand(intent, flags, startId);
// this service will run until we stop it
// ( > actually, this service does not do much except showing a Toast, once started ( & only once (..) ) )
//Toast.makeText(this, " Tef Service Started !", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), " Tef Service is currently running [onStrtCmd]", Toast.LENGTH_LONG).show();
return START_STICKY; // this is what actually keep the service going until explicitly stopped
//return START_NOT_STICKY;
/** -> the above has been commented as: --> actually not needed to simply display a message
--> was provoking 'currently running' to appear twice (..)
Nb: the above problem could be resolved by diggin/applying "Use Toast whenever we want" ;p
.. and by using "onCreate" to show our initial message ;p ( -> as called right before "onStrtCmd", & once )
*/
}
// to explicitly stop the service when the user hit the stopService button
@Override
public void onDestroy(){
super.onDestroy(); // always call the superclass
//Toast.makeText(this, " Tef Service Stopped !", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), " Tef Service is now stopped [onDestroy]", Toast.LENGTH_LONG).show();
// unregister the SMS receiver
unregisterReceiver(mSMSreceiver);
}
// "class within a class" -> BroadcastReceiver class to receive the SMS
private class SMSreceiver extends BroadcastReceiver {
private final String TAG = this.getClass().getSimpleName();
/** necessary constants */
public final static String EXTRA_MESSAGE = "com.example.tefservices.MESSAGE";
/** test constants for futur SMS parsing */
public final static String ADMIN_AUTH_CODE = "@z34a@"; // the Admin Auth code
public final static String USER_AUTH_CODE = "*789#"; // the User Auth code // UPDATED
public final static String ADMIN_AUTH_TYPE = "ADMIN_AUTH"; // the Admin Auth type
public final static String USER_AUTH_TYPE = "USER_AUTH"; // the User Auth type
/** same as above but the following constants are used for the 'history' part */
public final static String ADMIN_ACTIVATE_HISTORY_AUTH_CODE = "*2580#"; // the Admin ( set & activate ) History Auth code
public final static String ADMIN_DESACTIVATE_HISTORY_AUTH_CODE = "*2580#"; // the Admin ( desactivate ) History Auth code
/** reference to the shared preferences of our app */
SharedPreferences app_preferences;
/** Override the broadcastreceiver constructor method to init the SharedPreference as we'd have done for an Activity */
public SMSreceiver (){
///** init the app's preferences */
//app_preferences = PreferenceManager.getDefaultSharedPreferences(this); // working from an Activity
Context ctx = getApplicationContext();
app_preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
}
@Override
public void onReceive(Context context, Intent intent){
this.abortBroadcast(); // disable broadcasting the "SMS received" 'event' to the system
Bundle extras = intent.getExtras();
String strMessage = "";
if (extras != null){
Object[] smsextras = (Object[]) extras.get("pdus");
for (int i=0; i<smsextras.length; i++){
SmsMessage smsmsg = SmsMessage.createFromPdu( (byte[])smsextras[i] );
String strMsgBody = smsmsg.getMessageBody().toString();
String strMsgSrc = smsmsg.getOriginatingAddress();
strMessage += "SMS from " + strMsgSrc +": " + strMsgBody;
Log.i(TAG, strMessage);
Toast.makeText(getApplicationContext(), " SMS received !", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Sender Number:" + strMsgSrc, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Message:" + strMsgBody, Toast.LENGTH_LONG).show();
// WIP DEBUG -> handle the message received
handleMessageReceived(strMsgBody, strMsgSrc);
}
}
// finally, hide all that .. -> to call AFTER handling the message ..
//this.abortBroadcast(); // disable broadcasting the "SMS received" 'event' to the system
}
/** Fcn thhat handles any message received while the app is running */
/** It actually parses the message and initiate sending a message back to where it originated (..) */
private void handleMessageReceived(String theMessageBody, String theMessageOrigin){
/** check if the message is not null ( if we got some text to send actually ) */
if ( theMessageBody.equals("") ){
return; // return to prevent a fatal exception
}
/** do a little auth check */
String messageAuthType = getAuthTypeFromMessage(theMessageBody);
String currentAuth = checkAuth(messageAuthType);
/** act according to the current auth type */
if (currentAuth.equals(ADMIN_AUTH_TYPE)){
Log.d("ADMIN AUTH SESSION BEGAN", " > parsing message for new data ..");
// extract the data from the message
String theNewData = getDataFromMessage(theMessageBody);
Log.d("New data from Admin auth session:", theNewData);
// save it in the appropriate location
setStuffToPrefs("theDataPrefKey", theNewData);
// send back a message with the data freshly set up --> for the moment ( as wip ) just set the text of the next activity accordingly (..)
String theFreshData = getStuffFromPrefs("theDataPrefKey");
String theAdminMessage = "Data updated to: " + theFreshData;
Toast.makeText(getApplicationContext(), "ADMIN AUTHENTICATION", Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(), "New Data: " + theNewData, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Message returned to user: " + theAdminMessage, Toast.LENGTH_LONG).show();
/** send a SMS back to where the 'request' SMS originated */
sendSMS(theMessageOrigin, theAdminMessage);
// TO DO: check for " ADMIN_ACTIVATE_HISTORY_AUTH_CODE "
// TODO: check for " ADMIN_DESACTIVATE_HISTORY_AUTH_CODE "
} else if (currentAuth.equals(USER_AUTH_TYPE)){
Log.d("USER AUTH SESSION BEGAN", " > parsing message for new data ..");
// get the last known data and sent it back to where the first message originated
String theFreshData = getStuffFromPrefs("theDataPrefKey");
String theUserMessage = "Access granted: " + theFreshData;
Toast.makeText(getApplicationContext(), "USER AUTHENTICATION", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Message returned to user: " + theUserMessage, Toast.LENGTH_LONG).show();
/** send a SMS back to where the 'request' SMS originated */
sendSMS(theMessageOrigin, theUserMessage);
// TO DO: check if the 'history' part is set / should be used:
// String theHistoryNumKey = getStuffFromPrefs("theHistoryNumKey");
// if != "", then also
// String theAdminMessage = "Data sent to: " + theMessageOrigin;
// sendSMS(theHistoryNumKey, theUserMessage);
} else {
Toast.makeText(getApplicationContext(), "UNAUTHORIZED ACCESS OR UNKNOWN AUTHENTICATION", Toast.LENGTH_LONG).show();
}
/** send a SMS*/
//sendSMS("+33681382722", message);
}
/** MESSAGE PARSING FCNS & STUFF */
/** Fcn that extracts the Auth part of the message */
private String getAuthTypeFromMessage(String theMessage){
/** verify that the message received is at least as large as the auth types */
if (theMessage.length() < 6 ){
Log.d("getAuthTypeFromMessage()", " > message length inferior to 6 characters");
return "";
}
/** get the substring of 'theMessage' containing the Auth Type */
String theAuthType = theMessage.substring(0, 6); // extract the '@z34a@' part ( the actual auth type )
Log.d("getAuthTypeFromMessage()", " > auth type extracted from message");
return theAuthType;
}
/** Fcn that extracts the Data part of the message */
private String getDataFromMessage(String theMessage){
/** verify that the message received is at least as large as the auth types */
if (theMessage.length() < 17 ){
Log.d("getDataFromMessage()", " > message length inferior to 17 characters");
return "";
}
/** get the substring of 'theMessage' containing the Auth Type */
String theData = theMessage.substring(7, 17); // extract the '@z34a@' part ( the actual auth type )
Log.d("getDataFromMessage()", " > auth type extracted from message");
return theData;
}
/** Fcn that checks whether the message comes from an authorized user, and in that case, if it is a user or the admin */
private String checkAuth(String theMessage){
/** try to find an auth type that matches the few characters at the beginning of the text message */
if ( theMessage.equals(ADMIN_AUTH_CODE) ){
Log.d(ADMIN_AUTH_CODE, "admin auth just occured");
return ADMIN_AUTH_TYPE;
} else if ( theMessage.equals(USER_AUTH_CODE) ){
Log.d(USER_AUTH_CODE, "user auth just occured");
return USER_AUTH_TYPE;
} else {
Log.d("UNKNOWN_AUTH", "failed auth just occured");
return "";
}
}
/** SharedPreference stuff -> get & set the data to be returned by SMS messages */
/** Fcn that set the desired stuff into the shared preferences */
private void setStuffToPrefs(String theStrKeyName, String theStrValue){
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString(theStrKeyName, theStrValue);
Log.d("Preferences", theStrValue);
editor.commit();
}
/** Fcn that get the desired stuff out of the shared preferences */
private String getStuffFromPrefs(String theStrKeyName){
String theStrValue = app_preferences.getString(theStrKeyName, "");
Log.d("Preferences", theStrValue);
return theStrValue;
}
/** SMS sending stuff -> allows stuff to be sent back to originating adresses of received authenticated SMS requests (..) */
/** Called when the user clicks the send button, this time sending an sms message*/
//private void sendSMS(String phoneNumber, String message){
// SmsManager sms = SmsManager.getDefault();
// sms.sendTextMessage(phoneNumber, null, message, null, null);
//}
private void sendSMS(String phoneNumber, String message){
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
// both lines below were working when defined from an Activity
//PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
//PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
Context ctx = getApplicationContext();
PendingIntent sentPI = PendingIntent.getBroadcast(ctx, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(ctx, 0, new Intent(DELIVERED), 0);
/** stuff to do when the message has been sent */
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1){
switch (getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
/** stuff to do when the message has been delivered */
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1){
switch (getResultCode()){
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
//sms.sendTextMessage(phoneNumber, null, message, null, null); // old one -> when used with nob arguments for the pending intents
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
} /** END OF THE SMSreceiver Class */
}
| mit |
skratchdot/audio-automator | src/app/routes/index.js | 687 | import React from 'react';
import { Route } from 'react-router';
import App from '../containers/App';
const packageInfo = require('../../../package.json');
// pages
import NotFound from '../pages/NotFound';
import Home from '../pages/Home';
import About from '../pages/About';
import Demo from '../pages/Demo';
const routes = (
<Route component={App}>
<Route path={`/${packageInfo.name}`} component={Home} />
<Route path={`/${packageInfo.name}/home`} component={Home} />
<Route path={`/${packageInfo.name}/about`} component={About} />
<Route path={`/${packageInfo.name}/demo`} component={Demo} />
<Route path="*" component={NotFound} />
</Route>
);
export default routes;
| mit |
xesscorp/skidl | skidl/libs/ir_sklib.py | 8735 | from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
ir = SchLib(tool=SKIDL).add_parts(*[
Part(name='AUIPS7111S',dest=TEMPLATE,tool=SKIDL,keywords='Current Sense,High Side Switch',description='Current Sense With High Side Switch 24V/30A, D2PAK-5L',ref_prefix='U',num_units=1,fplist=['TO-263*'],do_erc=True,pins=[
Pin(num='1',name='IN',do_erc=True),
Pin(num='2',name='IFB',func=Pin.OUTPUT,do_erc=True),
Pin(num='3',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='OUT',func=Pin.PWROUT,do_erc=True),
Pin(num='5',name='OUT',func=Pin.PWROUT,do_erc=True)]),
Part(name='AUIPS7121R',dest=TEMPLATE,tool=SKIDL,keywords='Current Sense, High Side Switch',description='Current Sense With High Side Switch, 24V/50A, DPAK-5L',ref_prefix='U',num_units=1,fplist=['TO-252*'],do_erc=True,pins=[
Pin(num='1',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='2',name='IN',do_erc=True),
Pin(num='3',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='IFB',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='OUT',func=Pin.PWROUT,do_erc=True)]),
Part(name='IRS2092',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver Class D',description='Protected Class D Audio Amplifier Half-Bridge Gate Driver, With PWM Modulator, Output Current 1.0/1.2A, +/-100V, PDIP-16/SOIC-16',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x9.9mm*Pitch1.27mm*', 'DIP*W7.62mm*'],do_erc=True,pins=[
Pin(num='1',name='VAA',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='GND',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='IN-',do_erc=True),
Pin(num='4',name='COMP',func=Pin.PASSIVE,do_erc=True),
Pin(num='5',name='CSD',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='7',name='VREF',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='OCSET',func=Pin.PASSIVE,do_erc=True),
Pin(num='9',name='DT',func=Pin.PASSIVE,do_erc=True),
Pin(num='10',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='11',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='12',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='13',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='14',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='VB',func=Pin.PWRIN,do_erc=True),
Pin(num='16',name='CSH',func=Pin.PASSIVE,do_erc=True)]),
Part(name='IRS20957S',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver Class D',description='Protected Class D Audio Amplifier Half-Bridge Gate Driver, Output Current 1.0/1.2A, +/-100V, SOIC-16',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x9.9mm*Pitch1.27mm*'],do_erc=True,pins=[
Pin(num='1',name='VDD',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='CSD',func=Pin.PASSIVE,do_erc=True),
Pin(num='3',name='IN',do_erc=True),
Pin(num='4',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='6',name='VREF',func=Pin.OUTPUT,do_erc=True),
Pin(num='7',name='OCSET',func=Pin.PASSIVE,do_erc=True),
Pin(num='8',name='DT',func=Pin.PASSIVE,do_erc=True),
Pin(num='9',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='11',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='12',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='13',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='14',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='15',name='VB',func=Pin.PWRIN,do_erc=True),
Pin(num='16',name='CSH',func=Pin.PASSIVE,do_erc=True)]),
Part(name='IR2104',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver',description='High and Low Side Gate Driver, Output Current 130/270mA, PDIP-8 , SOIC-8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*', 'DIP*W7.62mm*'],do_erc=True,pins=[
Pin(num='1',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='IN',do_erc=True),
Pin(num='3',name='~SD',do_erc=True),
Pin(num='4',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='6',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VB',func=Pin.PASSIVE,do_erc=True)]),
Part(name='IR2106',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver',description='High and Low Side Driver, 600V operation, Output Current 120/200mA, PDIP-8 , SOIC-8',ref_prefix='U',num_units=1,fplist=['SOIC*', 'DIP*'],do_erc=True,pins=[
Pin(num='1',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='HIN',do_erc=True),
Pin(num='3',name='LIN',do_erc=True),
Pin(num='4',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='6',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VB',func=Pin.PASSIVE,do_erc=True)]),
Part(name='IR2110',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver',description='High and Low Side Gate Driver, Output Current 2.0/2.0A, PDIP-14 , SOIC-14',ref_prefix='U',num_units=1,fplist=['SOIC*7.5x10.3mm*Pitch1.27mm*', 'DIP*W7.62mm*'],do_erc=True,aliases=['IR2113'],pins=[
Pin(num='1',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='2',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='3',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='5',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='6',name='VB',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='NC',func=Pin.NOCONNECT,do_erc=True),
Pin(num='9',name='VDD',func=Pin.PWRIN,do_erc=True),
Pin(num='10',name='HIN',do_erc=True),
Pin(num='11',name='SD',do_erc=True),
Pin(num='12',name='LIN',do_erc=True),
Pin(num='13',name='VSS',func=Pin.PWRIN,do_erc=True),
Pin(num='14',name='NC',func=Pin.NOCONNECT,do_erc=True)]),
Part(name='IRS2181',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver',description='High and Low Side Gate Driver, Output Current 1.4/1.8A, PDIP-8 , SOIC-8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*', 'DIP*W7.62mm*'],do_erc=True,pins=[
Pin(num='1',name='HIN',do_erc=True),
Pin(num='2',name='LIN',do_erc=True),
Pin(num='3',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VB',func=Pin.PASSIVE,do_erc=True)]),
Part(name='IRS2186',dest=TEMPLATE,tool=SKIDL,keywords='gate driver',description='High and Low Side Gate Driver, 600V operation, 4A output current',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*', 'DIP*W7.62mm*'],do_erc=True,pins=[
Pin(num='1',name='HIN',do_erc=True),
Pin(num='2',name='LIN',do_erc=True),
Pin(num='3',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='4',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='5',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='6',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VB',func=Pin.PASSIVE,do_erc=True)]),
Part(name='IRS21867S',dest=TEMPLATE,tool=SKIDL,keywords='Gate Driver',description='High and Low Side Gate Driver, Output Current 4.0/4.0A, 600V, SOIC-8',ref_prefix='U',num_units=1,fplist=['SOIC*3.9x4.9mm*Pitch1.27mm*'],do_erc=True,pins=[
Pin(num='1',name='VCC',func=Pin.PWRIN,do_erc=True),
Pin(num='2',name='HIN',do_erc=True),
Pin(num='3',name='LIN',do_erc=True),
Pin(num='4',name='COM',func=Pin.PWRIN,do_erc=True),
Pin(num='5',name='LO',func=Pin.OUTPUT,do_erc=True),
Pin(num='6',name='VS',func=Pin.PASSIVE,do_erc=True),
Pin(num='7',name='HO',func=Pin.OUTPUT,do_erc=True),
Pin(num='8',name='VB',func=Pin.PWRIN,do_erc=True)])])
| mit |
jirutka/gitlabhq | app/presenters/member_presenter.rb | 720 | # frozen_string_literal: true
class MemberPresenter < Gitlab::View::Presenter::Delegated
presents :member
def access_level_roles
member.class.access_level_roles
end
def can_resend_invite?
invite? &&
can?(current_user, admin_member_permission, source)
end
def can_update?
can?(current_user, update_member_permission, member)
end
def can_remove?
can?(current_user, destroy_member_permission, member)
end
def can_approve?
request? && can_update?
end
private
def admin_member_permission
raise NotImplementedError
end
def update_member_permission
raise NotImplementedError
end
def destroy_member_permission
raise NotImplementedError
end
end
| mit |
LatoTeam/lato_swpmanager | app/models/lato_swpmanager/application_record.rb | 110 | module LatoSwpmanager
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
end
| mit |
GunnarJ1/LD-38 | src/tek/render/TextureSheet.java | 2418 | package tek.render;
import java.util.ArrayList;
import org.joml.Vector2f;
public class TextureSheet {
public static ArrayList<TextureSheet> sheets;
static {
sheets = new ArrayList<TextureSheet>();
}
public final String name;
public final Texture texture;
public final int subWidth, subHeight;
public final int perWidth, perHeight;
public final Vector2f subSize;
public final Vector2f[] offsets;
public String[] names;
public TextureSheet(Texture tex, int subWidth, int subHeight, String name){
this.texture = tex;
this.subWidth = subWidth;
this.subHeight = subHeight;
subSize = new Vector2f(this.subWidth, this.subHeight);
this.name = name;
perWidth = texture.width / subWidth;
perHeight = texture.height / subHeight;
offsets = new Vector2f[perWidth * perHeight];
for(int i=0;i<offsets.length;i++){
int x = getX(i);
int y = getY(i);
offsets[i] = new Vector2f(x, y);
offsets[i].mul(subSize);
}
names = new String[perWidth * perHeight];
sheets.add(this);
}
/** Get the index of a sub texture by name
*
* @param name the name of a sub texture
* @return the index of the sub texture
*/
public int get(String name){
for(int i=0;i<names.length;i++){
if(name.equals(names[i]))
return i;
}
return -1;
}
public Vector2f getOffset(int id){
return offsets[id];
}
public int getX(int id){
return id % perWidth;
}
public int getY(int id){
return id / perWidth;
}
public int getId(int x, int y){
return x + perWidth * y;
}
public void name(int id, String name){
names[id] = name;
}
public static TextureSheet getSheet(Texture texture){
if(sheets == null)
return null;
for(TextureSheet sheet : sheets)
if(sheet.texture.equals(texture))
return sheet;
return null;
}
public static boolean isTextureSheet(Texture tex){
if(sheets == null)
return false;
for(TextureSheet s : sheets)
if(s.texture.equals(tex))
return true;
return false;
}
public static TextureSheet getSheet(String name){
for(TextureSheet sheet : sheets){
if(sheet.name.equals(name))
return sheet;
}
return null;
}
public static TextureSheet getSheetByPath(String filePath){
String lowercase = filePath.toLowerCase();
for(TextureSheet sheet: sheets){
if(sheet.texture.path.toLowerCase().equals(lowercase)){
return sheet;
}
}
return null;
}
} | mit |
orocrm/platform | src/Oro/Bundle/UserBundle/Tests/Unit/Validator/PasswordComplexityValidatorTest.php | 12230 | <?php
namespace Oro\Bundle\UserBundle\Tests\Unit\Validator;
use Oro\Bundle\ConfigBundle\Config\ConfigManager;
use Oro\Bundle\UserBundle\Provider\PasswordComplexityConfigProvider;
use Oro\Bundle\UserBundle\Validator\Constraints\PasswordComplexity;
use Oro\Bundle\UserBundle\Validator\PasswordComplexityValidator;
use Symfony\Component\Validator\Context\ExecutionContext;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
class PasswordComplexityValidatorTest extends \PHPUnit\Framework\TestCase
{
/** @var ConstraintViolationBuilderInterface */
protected $violationBuilder;
/** @var PasswordComplexity */
protected $constraint;
protected function setUp()
{
$this->violationBuilder = $this->getMockBuilder(ConstraintViolationBuilderInterface::class)
->disableOriginalConstructor()
->getMock();
$this->violationBuilder->method('setInvalidValue')->willReturnSelf();
$this->violationBuilder->method('setParameters')->willReturnSelf();
$this->violationBuilder->method('addViolation')->willReturnSelf();
$this->constraint = new PasswordComplexity([]);
}
/**
* @dataProvider validateInvalidDataProvider
*
* @param array $configMap System config
* @param string $value Testing password
* @param string $message Expected message param
*/
public function testValidateInvalid(array $configMap, $value, $message)
{
$validator = new PasswordComplexityValidator($this->getConfigProvider($configMap));
$context = $this->getMockBuilder(ExecutionContextInterface::class)->disableOriginalConstructor()->getMock();
$context->expects($this->once())
->method('buildViolation')
->with($message)
->willReturn($this->violationBuilder);
/** @var ExecutionContext $context */
$validator->initialize($context);
$validator->validate($value, $this->constraint);
}
/**
* @dataProvider validateValidDataProvider
*
* @param array $configMap System config
* @param string $value Testing password
*/
public function testValidateValid(array $configMap, $value)
{
$validator = new PasswordComplexityValidator($this->getConfigProvider($configMap));
$context = $this->getMockBuilder(ExecutionContextInterface::class)->disableOriginalConstructor()->getMock();
$context->expects($this->never())
->method('buildViolation');
/** @var ExecutionContext $context */
$validator->initialize($context);
$validator->validate($value, $this->constraint);
}
/**
* Different rules enabled, invalid value provided
*
* @return array
*/
public function validateInvalidDataProvider()
{
return [
'min length' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 10],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => '0',
'message' => 'oro.user.message.invalid_password.min_length',
],
'upper case' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => 'password',
'message' => 'oro.user.message.invalid_password.upper_case',
],
'lower case' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => '123',
'message' => 'oro.user.message.invalid_password.lower_case',
],
'numbers' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => 'password',
'message' => 'oro.user.message.invalid_password.numbers',
],
'special chars' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, true],
],
'value' => 'password',
'message' => 'oro.user.message.invalid_password.special_chars',
],
'upper case and numbers' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => 'password',
'message' => 'oro.user.message.invalid_password.upper_case_numbers',
],
'all rules - invalid value' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 10],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, true],
],
'value' => 'password',
'message' => 'oro.user.message.invalid_password.min_length_upper_case_numbers_special_chars',
],
'all rules - invalid length and numbers' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 10],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, true],
],
'value' => 'paSsword_',
'message' => 'oro.user.message.invalid_password.min_length_numbers',
],
];
}
/**
* @return array
*/
public function validateValidDataProvider()
{
return [
'all rules disabled' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => 'password',
],
'min length - valid password' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 8],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => 'paSsw0rd!',
],
'numbers - valid password' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 0],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, false],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, false],
],
'value' => '1',
],
'all rules - valid password' => [
'configMap' => [
[PasswordComplexityConfigProvider::CONFIG_MIN_LENGTH, false, false, null, 8],
[PasswordComplexityConfigProvider::CONFIG_LOWER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_UPPER_CASE, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_NUMBERS, false, false, null, true],
[PasswordComplexityConfigProvider::CONFIG_SPECIAL_CHARS, false, false, null, true],
],
'value' => 'paSsw0rd!',
],
];
}
/**
* @param array $configMap
*
* @return PasswordComplexityConfigProvider
*/
protected function getConfigProvider(array $configMap)
{
$configManager = $this->getMockBuilder(ConfigManager::class)
->disableOriginalConstructor()
->getMock();
$configManager->method('get')->willReturnMap($configMap);
/** @var ConfigManager $configManager */
$configProvider = new PasswordComplexityConfigProvider($configManager);
/** @var PasswordComplexityConfigProvider $configManager */
return $configProvider;
}
protected function tearDown()
{
unset($this->violationBuilder, $this->constraint);
}
}
| mit |
seancdavis/sitetap | lib/sitetap.rb | 73 | require "sitetap/version"
module Sitetap
# Your code goes here...
end
| mit |
asafcarmel/sports_data_api | lib/sports_data_api.rb | 1710 | require "sports_data_api/version"
require "nokogiri"
require "rest_client"
require "time"
require "json"
module SportsDataApi
def self.key(sport)
@key ||= {}
@key[sport] ||= ''
@key[sport]
end
def self.set_key(sport, new_key)
@key ||= {}
@key[sport] = new_key
end
def self.access_level(sport)
@access_level ||= {}
@access_level[sport] ||= "t"
@access_level[sport]
end
def self.set_access_level(sport, new_level)
@access_level ||= {}
@access_level[sport] = new_level
end
def self.generic_request(url, sport)
begin
return RestClient.get(url, params: { api_key: SportsDataApi.key(sport) })
rescue RestClient::RequestTimeout => timeout
raise SportsDataApi::Exception, 'The API did not respond in a reasonable amount of time'
rescue RestClient::Exception => e
message = if e.response.headers.key? :x_server_error
JSON.parse(e.response.headers[:x_server_error], { symbolize_names: true })[:message]
elsif e.response.headers.key? :x_mashery_error_code
e.response.headers[:x_mashery_error_code]
else
"The server did not specify a message"
end
raise SportsDataApi::Exception, message
end
end
LIBRARY_PATH = File.join(File.dirname(__FILE__), 'sports_data_api')
autoload :Stats, File.join(LIBRARY_PATH, 'stats')
autoload :Nfl, File.join(LIBRARY_PATH, 'nfl')
autoload :Nba, File.join(LIBRARY_PATH, 'nba')
autoload :Mlb, File.join(LIBRARY_PATH, 'mlb')
autoload :Nhl, File.join(LIBRARY_PATH, 'nhl')
autoload :Exception, File.join(LIBRARY_PATH, 'exception')
end
| mit |
ASP-NET-Core-Boilerplate/Framework | Source/Boxed.AspNetCore.Swagger/SchemaFilters/JsonPatchDocumentSchemaFilter.cs | 3349 | namespace Boxed.AspNetCore.Swagger.SchemaFilters
{
using System;
using Microsoft.AspNetCore.JsonPatch;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Operation = Microsoft.AspNetCore.JsonPatch.Operations.Operation;
/// <summary>
/// Shows an example of a <see cref="JsonPatchDocument"/> containing all the different patch operations you can do
/// and a link to http://jsonpatch.com for convenience.
/// </summary>
/// <seealso cref="ISchemaFilter" />
public class JsonPatchDocumentSchemaFilter : ISchemaFilter
{
/// <summary>
/// Applies the specified model.
/// </summary>
/// <param name="model">The model.</param>
/// <param name="context">The context.</param>
public void Apply(Schema model, SchemaFilterContext context)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.SystemType.GenericTypeArguments.Length > 0 &&
context.SystemType.GetGenericTypeDefinition() == typeof(JsonPatchDocument<>))
{
var example = GetExample();
model.Default = example;
model.Example = example;
model.ExternalDocs = new ExternalDocs()
{
Description = "JSON Patch Documentation",
Url = "http://jsonpatch.com/"
};
}
}
private static Operation[] GetExample() =>
new Operation[]
{
new Operation()
{
op = "replace",
path = "/property",
value = "New Value"
},
new Operation()
{
op = "add",
path = "/property",
value = "New Value"
},
new Operation()
{
op = "remove",
path = "/property"
},
new Operation()
{
op = "copy",
from = "/fromProperty",
path = "/toProperty"
},
new Operation()
{
op = "move",
from = "/fromProperty",
path = "/toProperty"
},
new Operation()
{
op = "test",
path = "/property",
value = "Has Value"
},
new Operation()
{
op = "replace",
path = "/arrayProperty/0",
value = "Replace First Array Item"
},
new Operation()
{
op = "replace",
path = "/arrayProperty/-",
value = "Replace Last Array Item"
}
};
}
} | mit |
selvasingh/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/models/ApplicationGatewayRewriteRuleCondition.java | 4241 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Set of conditions in the Rewrite Rule in Application Gateway. */
@Fluent
public final class ApplicationGatewayRewriteRuleCondition {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ApplicationGatewayRewriteRuleCondition.class);
/*
* The condition parameter of the RewriteRuleCondition.
*/
@JsonProperty(value = "variable")
private String variable;
/*
* The pattern, either fixed string or regular expression, that evaluates
* the truthfulness of the condition.
*/
@JsonProperty(value = "pattern")
private String pattern;
/*
* Setting this paramter to truth value with force the pattern to do a case
* in-sensitive comparison.
*/
@JsonProperty(value = "ignoreCase")
private Boolean ignoreCase;
/*
* Setting this value as truth will force to check the negation of the
* condition given by the user.
*/
@JsonProperty(value = "negate")
private Boolean negate;
/**
* Get the variable property: The condition parameter of the RewriteRuleCondition.
*
* @return the variable value.
*/
public String variable() {
return this.variable;
}
/**
* Set the variable property: The condition parameter of the RewriteRuleCondition.
*
* @param variable the variable value to set.
* @return the ApplicationGatewayRewriteRuleCondition object itself.
*/
public ApplicationGatewayRewriteRuleCondition withVariable(String variable) {
this.variable = variable;
return this;
}
/**
* Get the pattern property: The pattern, either fixed string or regular expression, that evaluates the truthfulness
* of the condition.
*
* @return the pattern value.
*/
public String pattern() {
return this.pattern;
}
/**
* Set the pattern property: The pattern, either fixed string or regular expression, that evaluates the truthfulness
* of the condition.
*
* @param pattern the pattern value to set.
* @return the ApplicationGatewayRewriteRuleCondition object itself.
*/
public ApplicationGatewayRewriteRuleCondition withPattern(String pattern) {
this.pattern = pattern;
return this;
}
/**
* Get the ignoreCase property: Setting this paramter to truth value with force the pattern to do a case
* in-sensitive comparison.
*
* @return the ignoreCase value.
*/
public Boolean ignoreCase() {
return this.ignoreCase;
}
/**
* Set the ignoreCase property: Setting this paramter to truth value with force the pattern to do a case
* in-sensitive comparison.
*
* @param ignoreCase the ignoreCase value to set.
* @return the ApplicationGatewayRewriteRuleCondition object itself.
*/
public ApplicationGatewayRewriteRuleCondition withIgnoreCase(Boolean ignoreCase) {
this.ignoreCase = ignoreCase;
return this;
}
/**
* Get the negate property: Setting this value as truth will force to check the negation of the condition given by
* the user.
*
* @return the negate value.
*/
public Boolean negate() {
return this.negate;
}
/**
* Set the negate property: Setting this value as truth will force to check the negation of the condition given by
* the user.
*
* @param negate the negate value to set.
* @return the ApplicationGatewayRewriteRuleCondition object itself.
*/
public ApplicationGatewayRewriteRuleCondition withNegate(Boolean negate) {
this.negate = negate;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
myt00seven/svrg | para_gpu/train_funcs.py | 5615 | import glob
import time
import os
import numpy as np
import hickle as hkl
from proc_load import crop_and_mirror
def proc_configs(config):
if not os.path.exists(config['weights_dir']):
os.makedirs(config['weights_dir'])
print "Creat folder: " + config['weights_dir']
return config
def unpack_configs(config, ext_data='.hkl', ext_label='.npy'):
flag_para_load = config['para_load']
# Load Training/Validation Filenames and Labels
train_folder = config['train_folder']
val_folder = config['val_folder']
label_folder = config['label_folder']
train_filenames = sorted(glob.glob(train_folder + '/*' + ext_data))
val_filenames = sorted(glob.glob(val_folder + '/*' + ext_data))
train_labels = np.load(label_folder + 'train_labels' + ext_label)
val_labels = np.load(label_folder + 'val_labels' + ext_label)
img_mean = np.load(config['mean_file'])
img_mean = img_mean[:, :, :, np.newaxis].astype('float32')
return (flag_para_load,
train_filenames, val_filenames, train_labels, val_labels, img_mean)
def adjust_learning_rate(config, epoch, step_idx, val_record, learning_rate):
# Adapt Learning Rate
if config['lr_policy'] == 'step':
if epoch == config['lr_step'][step_idx]:
learning_rate.set_value(
np.float32(learning_rate.get_value() / 10))
step_idx += 1
if step_idx >= len(config['lr_step']):
step_idx = 0 # prevent index out of range error
print 'Learning rate changed to:', learning_rate.get_value()
if config['lr_policy'] == 'auto':
if (epoch > 5) and (val_record[-3] - val_record[-1] <
config['lr_adapt_threshold']):
learning_rate.set_value(
np.float32(learning_rate.get_value() / 10))
print 'Learning rate changed to::', learning_rate.get_value()
return step_idx
def get_val_error_loss(rand_arr, shared_x, shared_y,
val_filenames, val_labels,
flag_para_load, img_mean,
batch_size, validate_model,
send_queue=None, recv_queue=None,
flag_top_5=False):
validation_losses = []
validation_errors = []
if flag_top_5:
validation_errors_top_5 = []
n_val_batches = len(val_filenames)
if flag_para_load:
# send the initial message to load data, before each epoch
send_queue.put(str(val_filenames[0]))
send_queue.put(np.float32([0.5, 0.5, 0]))
send_queue.put('calc_finished')
for val_index in range(n_val_batches):
if flag_para_load:
# load by self or the other process
# wait for the copying to finish
msg = recv_queue.get()
assert msg == 'copy_finished'
if val_index + 1 < n_val_batches:
name_to_read = str(val_filenames[val_index + 1])
send_queue.put(name_to_read)
send_queue.put(np.float32([0.5, 0.5, 0]))
else:
val_img = hkl.load(str(val_filenames[val_index])) - img_mean
param_rand = [0.5,0.5,0]
val_img = crop_and_mirror(val_img, param_rand, flag_batch=True)
shared_x.set_value(val_img)
shared_y.set_value(val_labels[val_index * batch_size:
(val_index + 1) * batch_size])
if flag_top_5:
loss, error, error_top_5 = validate_model()
else:
loss, error = validate_model()
if flag_para_load and (val_index + 1 < n_val_batches):
send_queue.put('calc_finished')
# print loss, error
validation_losses.append(loss)
validation_errors.append(error)
if flag_top_5:
validation_errors_top_5.append(error_top_5)
this_validation_loss = np.mean(validation_losses)
this_validation_error = np.mean(validation_errors)
if flag_top_5:
this_validation_error_top_5 = np.mean(validation_errors_top_5)
return this_validation_error, this_validation_error_top_5, this_validation_loss
else:
return this_validation_error, this_validation_loss
def get_rand3d():
tmp_rand = np.float32(np.random.rand(3))
tmp_rand[2] = round(tmp_rand[2])
return tmp_rand
def train_model_wrap(train_model, shared_x, shared_y, rand_arr, img_mean,
count, minibatch_index, minibatch_range, batch_size,
train_filenames, train_labels,
flag_para_load,
flag_batch,
send_queue=None, recv_queue=None):
if flag_para_load:
# load by self or the other process
# wait for the copying to finish
msg = recv_queue.get()
assert msg == 'copy_finished'
if count < len(minibatch_range):
ind_to_read = minibatch_range[count]
name_to_read = str(train_filenames[ind_to_read])
send_queue.put(name_to_read)
send_queue.put(get_rand3d())
else:
batch_img = hkl.load(str(train_filenames[minibatch_index])) - img_mean
param_rand = get_rand3d()
batch_img = crop_and_mirror(batch_img, param_rand, flag_batch=flag_batch)
shared_x.set_value(batch_img)
batch_label = train_labels[minibatch_index * batch_size:
(minibatch_index + 1) * batch_size]
shared_y.set_value(batch_label)
cost_ij = train_model()
return cost_ij | mit |
webforceindonesia/chemistryfairUI | application/models/Email_model.php | 8908 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Email_model extends CI_Model {
public function __construct ()
{
//Call Parent Constructor
parent::__construct();
}
public function contactus ($data)
{
$subject = "Kontak Peserta";
$headers = "From: [email protected] \r\n";
$headers .= "Reply-To: [email protected] \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = "<html><body>";
$message .= "<h2>".$data['name']."</h2>";
$message .= '<table border="1px">';
$message .= "<tr>";
$message .= "<td>Nama</td><td>".$data['name']."</td>";
$message .= "</tr>";
$message .= "<tr>";
$message .= "<td>Email</td><td>".$data['email']."</td>";
$message .= "</tr>";
$message .= "<tr>";
$message .= "<td>Content</td><td>".$data['content']."</td>";
$message .= "</tr>";
$message .= "</table>";
$message .= "</body></html>";
if(mail("[email protected]", $subject, $message, $headers))
{
return true;
}else
{
return false;
}
}
public function cp_email ($data)
{
$subject = "Kontak Peserta";
$headers = "From: [email protected] \r\n";
$headers .= "Reply-To: [email protected] \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message =
<<<HHH
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<body>
<table class="table table-bordered">
<tr>
<td>Account ID</td>
<td>{$this->session->userdata('user_id')}</td>
</tr>
<tr>
<td>Nama Ketua</td>
<td>{$this->input->post('nama-ketua')}</td>
</tr>
<tr>
<td>Bersedia Datang Ke Campus UI</td>
<td>{$this->input->post('datang')}</td>
</tr>
<tr>
<td>Butuh penginapan selama rangkaian acara Chemistry Innovation Project</td>
<td>{$this->input->post('penginapan')}</td>
</tr>
<tr>
<td>Jika Ya, berapakah anggota kelompok yang butuh penginapan</td>
<td>{$this->input->post('anggota-penginapan')}</td>
</tr>
</table>
</body>
</html>
HHH;
if(mail("[email protected]", $subject, $message, $headers))
{
return true;
}else
{
return false;
}
}
public function email_transportasi ()
{
$subject = "Informasi Transportasi dan Penginapan Peserta";
$headers = "From: [email protected] \r\n";
$headers .= "Reply-To: [email protected] \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message =
<<<HHH
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<body>
<table class="table table-bordered">
<tr>
<td>Account ID</td>
<td>{$this->session->userdata('user_id')}</td>
</tr>
<tr>
<td>Nama Ketua</td>
<td>{$this->input->post('nama-ketua')}</td>
</tr>
<tr>
<td>Bersedia Datang Ke Campus UI</td>
<td>{$this->input->post('datang')}</td>
</tr>
<tr>
<td>Butuh penginapan selama rangkaian acara Chemistry Innovation Project</td>
<td>{$this->input->post('penginapan')}</td>
</tr>
<tr>
<td>Jika Ya, berapakah anggota kelompok yang butuh penginapan</td>
<td>{$this->input->post('anggota-penginapan')}</td>
</tr>
<tr>
<td>Jenis Kelamin Ketua</td>
<td>{$this->input->post('gender_ketua')}</td>
</tr>
HHH;
//Gender for each anggota
$i=1;
foreach ($this->input->post('gender_anggota') as $genders)
{
$message .= <<<HHH
<tr>
<td>Jenis Kelamin Anggota Ke - {$i}</td>
<td>{$genders}</td>
</tr>
HHH;
$i++;
}
$message .= <<<HHH
<tr>
<td>Apakah guru pendamping juga memerlukan penginapan</td>
<td>{$this->input->post('guru-penginapan')}</td>
</tr>
<tr>
<td>Kapankah tanggal kedatangan Anda</td>
<td>{$this->input->post('tanggal-kedatangan')}</td>
</tr>
<tr>
<td>Transportasi apakah yang Anda gunakan</td>
<td>{$this->input->post('kendaraan')}</td>
</tr>
<tr>
<td>Maskapai apa yang Anda gunakan</td>
<td>{$this->input->post('maskapai')}</td>
</tr>
<tr>
<td>Pada pukul berapa pesawat Anda dijadwalkan berangkat</td>
<td>{$this->input->post('brangkat-pesawat')}</td>
</tr>
<tr>
<td>Pada pukul berapa pesawat Anda dijadwalkan tiba</td>
<td>{$this->input->post('tiba-pesawat')}</td>
</tr>
<tr>
<td>Di terminal berapa Anda akan turun</td>
<td>{$this->input->post('terminal-pesawat')}</td>
</tr>
<tr>
<td>Dari stasiun manakah Anda berangkat</td>
<td>{$this->input->post('stasiun-krl')}</td>
</tr>
<tr>
<td>Pada pukul berapakah kereta Anda dijadwalkan berangkat</td>
<td>{$this->input->post('brangkat-krl')}</td>
</tr>
<tr>
<td>Pada pukul berapakah kereta Anda dijadwalkan tiba</td>
<td>{$this->input->post('tiba-krl')}</td>
</tr>
<tr>
<td>Apa stasiun tujuan Anda</td>
<td>{$this->input->post('tiba-krl')}</td>
</tr>
<tr>
<td>Pada pukul berapakah estimasi Anda untuk tiba di St. UI</td>
<td>{$this->input->post('tujuan-krl')}</td>
</tr>
<tr>
<td>Dari terminal manakah Anda berangkat</td>
<td>{$this->input->post('stasiun-bus')}</td>
</tr>
<tr>
<td>Pada pukul berapa bus Anda dijadwalkan berangkat</td>
<td>{$this->input->post('brangkat-bus')}</td>
</tr>
<tr>
<td>Pada pukul berapa bus Anda dijadwalkan tiba</td>
<td>{$this->input->post('tiba-bus')}</td>
</tr>
<tr>
<td>Di terminal berapa Anda akan turun</td>
<td>{$this->input->post('terminal-bus')}</td>
</tr>
<tr>
<td>Kapankah tanggal kepulangan Anda</td>
<td>{$this->input->post('pulang')}</td>
</tr>
<tr>
<td>Transportasi apa yang Anda gunakan</td>
<td>{$this->input->post('kendaraan-pulang')}</td>
</tr>
<tr>
<td>Maskapai apa yang Anda gunakan</td>
<td>{$this->input->post('maskapai-pulang')}</td>
</tr>
<tr>
<td>Pada pukul berapa pesawat Anda dijadwalkan berangkat</td>
<td>{$this->input->post('brangkat-pesawat-pulang')}</td>
</tr>
</table>
</body>
</html>
HHH;
if(mail("[email protected]", $subject, $message, $headers))
{
return true;
}else
{
return false;
}
}
public function uploadedBerkasCmp ()
{
$user_id = $this->session->userdata('user_id');
$user_data = $this->db->get_where('accounts', array('id' => $user_id))->row();
$subject = "Informasi Transportasi dan Penginapan Peserta";
$headers = "From: [email protected] \r\n";
$headers .= "Reply-To: [email protected] \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = <<<EOD
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<body>
<div class="container">
<div class="row">
<div class="col-12-md">
<h1>Film Poster and Synopsis Uploaded</h1>
<p>
Peserta dengan nama :<br>
{$user_data->fullname}<br>
Dengan Nomor Akun :<br>
{$user_data->id}<br>
Telah Mengupload Synopsis dan Poster.
</p>
</div>
</div>
</div>
</body>
</html>
EOD;
if(mail("[email protected]", $subject, $message, $headers))
{
return true;
}else
{
return false;
}
}
}
?> | mit |
miyakawataku/pubsubtaskrunner | handler_test.go | 13607 | package main
import (
"bytes"
"errors"
"io"
"io/ioutil"
"os"
"sync"
"testing"
"time"
"cloud.google.com/go/pubsub"
"golang.org/x/net/context"
)
// test handleTillShutdown
func makeHandleSingleTaskFunc(callCount *int, actions []handleSingleTaskFunc) handleSingleTaskFunc {
return func(handler *taskHandler, msg *pubsub.Message) msgNotifier {
index := *callCount
*callCount++
if index >= len(actions) {
return nil
}
action := actions[index]
return action(handler, msg)
}
}
type fakeMsgNotifier struct {
t *testing.T
desc string
isNotified bool
}
func (notifier *fakeMsgNotifier) notify(handler *taskHandler, msg *pubsub.Message) {
notifier.t.Logf("notified %s", notifier.desc)
notifier.isNotified = true
}
func TestHandleTillShutdown(t *testing.T) {
reqCh := make(chan struct{}, 4)
respCh := make(chan *pubsub.Message, 3)
wg := &sync.WaitGroup{}
wg.Add(1)
callCount := 0
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
not1 := &fakeMsgNotifier{t: t, desc: "not1"}
not2 := &fakeMsgNotifier{t: t, desc: "not2"}
not3 := &fakeMsgNotifier{t: t, desc: "not3"}
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
reqCh: reqCh,
respCh: respCh,
wg: wg,
logger: makeTestLogger(t),
},
handleSingleTask: makeHandleSingleTaskFunc(&callCount, []handleSingleTaskFunc{
func(handler *taskHandler, msg *pubsub.Message) msgNotifier { return not1 },
func(handler *taskHandler, msg *pubsub.Message) msgNotifier { return not2 },
func(handler *taskHandler, msg *pubsub.Message) msgNotifier { cancel(); return not3 },
}),
}
respCh <- nil
respCh <- nil
respCh <- nil
go handler.handleTillShutdown(ctx)
wg.Wait()
if callCount != 3 {
t.Errorf("handleSingleTask must be called 3 times, but called %d times", callCount)
}
if !not1.isNotified || !not2.isNotified || !not3.isNotified {
t.Errorf("some notifier not invoked: %v, %v, %v", not1, not2, not3)
}
}
// test handleSingleTask
func TestHandleSingleTaskAckForExceedRetryDeadline(t *testing.T) {
pubTime := time.Date(2017, 3, 1, 0, 0, 0, 0, time.UTC)
msg := &pubsub.Message{
PublishTime: pubTime,
ID: "msg001",
}
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
taskttl: time.Minute * 10,
logger: makeTestLogger(t),
},
now: func() time.Time {
return pubTime.Add(time.Minute*10 + time.Second)
},
}
notifier := handleSingleTask(handler, msg)
if notifier != ack {
t.Errorf("handleSingleTask must return ack because of exceeded deadline, but returned %v", notifier)
}
}
func TestHandleSingleTaskNackForLogRotationFailure(t *testing.T) {
pubTime := time.Date(2017, 3, 1, 0, 0, 0, 0, time.UTC)
msg := &pubsub.Message{
PublishTime: pubTime,
ID: "msg001",
}
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
taskttl: time.Minute * 10,
logger: makeTestLogger(t),
},
now: func() time.Time {
return pubTime.Add(time.Minute * 10)
},
rotateTaskLog: func(handler *taskHandler) (bool, error) {
return false, errors.New("bang")
},
}
notifier := handleSingleTask(handler, msg)
if notifier != nack {
t.Errorf("handleSingleTask must return nack because of log rotation failure, but returned %v", notifier)
}
}
func TestHandleSingleTaskNackForLogOpeningFailure(t *testing.T) {
pubTime := time.Date(2017, 3, 1, 0, 0, 0, 0, time.UTC)
msg := &pubsub.Message{
PublishTime: pubTime,
ID: "msg001",
}
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
taskttl: time.Minute * 10,
logger: makeTestLogger(t),
},
now: func() time.Time {
return pubTime.Add(time.Minute * 10)
},
rotateTaskLog: func(handler *taskHandler) (bool, error) {
return true, nil
},
openTaskLog: func(handler *taskHandler) (io.WriteCloser, error) {
return nil, errors.New("bang")
},
}
notifier := handleSingleTask(handler, msg)
if notifier != nack {
t.Errorf("handleSingleTask must return nack because of log opening failure, but returned %v", notifier)
}
}
type fakeWriteCloser struct {
isClosed bool
}
func (fwc *fakeWriteCloser) Write(p []byte) (int, error) {
return 0, nil
}
func (fwc *fakeWriteCloser) Close() error {
fwc.isClosed = true
return nil
}
func TestHandleSingleTaskAckForCommandSuccess(t *testing.T) {
pubTime := time.Date(2017, 3, 1, 0, 0, 0, 0, time.UTC)
msg := &pubsub.Message{
PublishTime: pubTime,
ID: "msg001",
}
fwc := &fakeWriteCloser{}
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
taskttl: time.Minute * 10,
logger: makeTestLogger(t),
},
now: func() time.Time {
return pubTime.Add(time.Minute * 10)
},
rotateTaskLog: func(handler *taskHandler) (bool, error) {
return true, nil
},
openTaskLog: func(handler *taskHandler) (io.WriteCloser, error) {
return fwc, nil
},
runCmd: func(handler *taskHandler, msg *pubsub.Message, taskLog io.Writer) error {
return nil
},
}
notifier := handleSingleTask(handler, msg)
if notifier != ack {
t.Errorf("handleSingleTask must return ack because of log command success, but returned %v", notifier)
}
}
func TestHandleSingleTaskAckForCommandFailure(t *testing.T) {
pubTime := time.Date(2017, 3, 1, 0, 0, 0, 0, time.UTC)
msg := &pubsub.Message{
PublishTime: pubTime,
ID: "msg001",
}
fwc := &fakeWriteCloser{}
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
taskttl: time.Minute * 10,
logger: makeTestLogger(t),
},
now: func() time.Time {
return pubTime.Add(time.Minute * 10)
},
rotateTaskLog: func(handler *taskHandler) (bool, error) {
return true, nil
},
openTaskLog: func(handler *taskHandler) (io.WriteCloser, error) {
return fwc, nil
},
runCmd: func(handler *taskHandler, msg *pubsub.Message, taskLog io.Writer) error {
return errors.New("bang")
},
}
notifier := handleSingleTask(handler, msg)
if notifier != nack {
t.Errorf("handleSingleTask must return nack because of log command failure, but returned %v", notifier)
}
}
// test rotateTaskLog
func TestRotateTaskLogRotateLog(t *testing.T) {
tempDir, err := ioutil.TempDir("", "pubsubtaskrunnertest")
if err != nil {
t.Errorf("could not create a temp dir: %v", err)
return
}
defer os.RemoveAll(tempDir)
tasklogpath := tempDir + "/task.log"
content := bytes.Repeat([]byte{0x5c}, 2001)
ioutil.WriteFile(tasklogpath, content, 0644)
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
tasklogpath: tasklogpath,
maxtasklogkb: 2,
logger: makeTestLogger(t),
},
}
isRotated, err := rotateTaskLog(handler)
if !isRotated {
t.Error("task log must be rotated, but not")
}
if err != nil {
t.Errorf("must not cause error, but: %v", err)
}
prevlogpath := tasklogpath + ".prev"
prevContent, err := ioutil.ReadFile(prevlogpath)
if err != nil {
t.Errorf("task log not rotated to %s", prevlogpath)
}
if !bytes.Equal(prevContent, content) {
t.Errorf("not expected content in prev task log: %v", prevContent)
}
stat, err := os.Stat(tasklogpath)
if stat != nil || !os.IsNotExist(err) {
t.Errorf("old task log still exists: err=%v", err)
}
}
func TestRotateTaskLogDoNotRotateLogDueToSize(t *testing.T) {
tempDir, err := ioutil.TempDir("", "pubsubtaskrunnertest")
if err != nil {
t.Errorf("could not create a temp dir: %v", err)
return
}
defer os.RemoveAll(tempDir)
tasklogpath := tempDir + "/task.log"
content := bytes.Repeat([]byte{0x5c}, 2000)
ioutil.WriteFile(tasklogpath, content, 0644)
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
tasklogpath: tasklogpath,
maxtasklogkb: 2,
logger: makeTestLogger(t),
},
}
isRotated, err := rotateTaskLog(handler)
if isRotated {
t.Error("task log must not be rotated, but was")
}
if err != nil {
t.Errorf("must not cause error, but: %v", err)
}
prevlogpath := tasklogpath + ".prev"
if _, err := os.Stat(prevlogpath); !os.IsNotExist(err) {
t.Errorf("prev log file must not exist, but: %v", err)
}
actualContent, err := ioutil.ReadFile(tasklogpath)
if err != nil {
t.Errorf("cannot read task log %s: %v", tasklogpath, err)
}
if !bytes.Equal(actualContent, content) {
t.Errorf("not expected content in task log: %v", actualContent)
}
}
func TestRotateTaskLogDoNotRotateNonExistingLog(t *testing.T) {
tempDir, err := ioutil.TempDir("", "pubsubtaskrunnertest")
if err != nil {
t.Errorf("could not create a temp dir: %v", err)
return
}
defer os.RemoveAll(tempDir)
tasklogpath := tempDir + "/nosuch.log"
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
tasklogpath: tasklogpath,
maxtasklogkb: 2,
logger: makeTestLogger(t),
},
}
isRotated, err := rotateTaskLog(handler)
if isRotated {
t.Error("task log must not be rotated, but was")
}
if err != nil {
t.Errorf("must not cause error, but: %v", err)
}
prevlogpath := tasklogpath + ".prev"
if _, err := os.Stat(prevlogpath); !os.IsNotExist(err) {
t.Errorf("prev log file must not exist, but: %v", err)
}
}
func TestRotateTaskLogDoNotRotateUnstattableLog(t *testing.T) {
tempDir, err := ioutil.TempDir("", "pubsubtaskrunnertest")
if err != nil {
t.Errorf("could not create a temp dir: %v", err)
return
}
defer os.RemoveAll(tempDir)
logDir := tempDir + "/tasklog.d"
os.Mkdir(logDir, 0000)
tasklogpath := logDir + "/unstattable.log"
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
tasklogpath: tasklogpath,
maxtasklogkb: 2,
logger: makeTestLogger(t),
},
}
isRotated, err := rotateTaskLog(handler)
if isRotated {
t.Error("task log must not be rotated, but was")
}
if err == nil {
t.Error("must cause error, but not")
}
}
func TestRotateTaskLogDoNotRotateUnmovableLog(t *testing.T) {
tempDir, err := ioutil.TempDir("", "pubsubtaskrunnertest")
if err != nil {
t.Errorf("could not create a temp dir: %v", err)
return
}
defer os.RemoveAll(tempDir)
logDir := tempDir + "/log"
os.Mkdir(logDir, 0700)
tasklogpath := logDir + "/task.log"
content := bytes.Repeat([]byte{0x5c}, 2001)
ioutil.WriteFile(tasklogpath, content, 0644)
os.Chmod(logDir, 0500)
defer os.Chmod(logDir, 0700)
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
tasklogpath: tasklogpath,
maxtasklogkb: 2,
logger: makeTestLogger(t),
},
}
isRotated, err := rotateTaskLog(handler)
if isRotated {
t.Error("task log must not be rotated, but was")
}
if err == nil {
t.Error("must cause error, but not")
}
prevlogpath := tasklogpath + ".prev"
if _, err := os.Stat(prevlogpath); !os.IsNotExist(err) {
t.Errorf("prev log file must not exist, but: %v", err)
}
actualContent, err := ioutil.ReadFile(tasklogpath)
if err != nil {
t.Errorf("cannot read task log %s: %v", tasklogpath, err)
}
if !bytes.Equal(actualContent, content) {
t.Errorf("not expected content in task log: %v", actualContent)
}
}
// test runCmd
func TestRunCmd(t *testing.T) {
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
command: "/bin/cat",
args: []string{"-"},
commandtimeout: time.Second * 10,
termtimeout: time.Second,
logger: makeTestLogger(t),
},
}
msg := &pubsub.Message{
ID: "msg#001",
Data: []byte("foobar"),
}
buf := bytes.NewBuffer([]byte{})
err := runCmd(handler, msg, buf)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !bytes.Equal(buf.Bytes(), []byte("foobar")) {
t.Errorf("unexpected output: got %v, want 'foobar'", buf.Bytes())
}
}
func TestRunCmdTimeout(t *testing.T) {
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
command: "/bin/sleep",
args: []string{"5"},
commandtimeout: time.Second,
termtimeout: time.Second,
logger: makeTestLogger(t),
},
}
msg := &pubsub.Message{
ID: "msg#001",
Data: []byte{},
}
buf := bytes.NewBuffer([]byte{})
err := runCmd(handler, msg, buf)
if _, ok := err.(cmdTimeoutError); !ok {
t.Errorf("unexpected err: got %v, want cmdTimeoutError", err)
}
}
func TestRunCmdTermTimeout(t *testing.T) {
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
command: "/bin/sh",
args: []string{"-c", "trap '/bin/true' 15; while /bin/true; do /bin/sleep 100; done"},
commandtimeout: time.Second,
termtimeout: time.Second,
logger: makeTestLogger(t),
},
}
msg := &pubsub.Message{
ID: "msg#001",
Data: []byte{},
}
buf := bytes.NewBuffer([]byte{})
err := runCmd(handler, msg, buf)
if _, ok := err.(cmdTermTimeoutError); !ok {
t.Errorf("unexpected err: got %v, want cmdTermTimeoutError", err)
}
}
func TestRunCmdLaunchError(t *testing.T) {
handler := &taskHandler{
taskHandlerConf: taskHandlerConf{
id: "handler#001",
command: "/bin/no/such/command.never",
args: []string{},
commandtimeout: time.Second,
termtimeout: time.Second,
logger: makeTestLogger(t),
},
}
msg := &pubsub.Message{
ID: "msg#001",
Data: []byte{},
}
buf := bytes.NewBuffer([]byte{})
err := runCmd(handler, msg, buf)
if _, ok := err.(spawnError); !ok {
t.Errorf("unexpected err: got %v, want spawnError", err)
}
}
| mit |
iwelina-popova/EShipmentSystem | EShipmentSystem/EShipmentSystem.Web/wwwroot/app/app.module.ts | 462 | import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule],
declarations: [AppComponent],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { } | mit |
xuan6/admin_dashboard_local_dev | node_modules/react-icons-kit/md/ic_format_quote.js | 253 | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ic_format_quote = exports.ic_format_quote = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z" } }] }; | mit |
takeshik/yacq | Yacq/LanguageServices/Grammar.cs | 25233 | // -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
// $Id$
/* YACQ <http://yacq.net/>
* Yet Another Compilable Query Language, based on Expression Trees API
* Copyright © 2011-2013 Takeshi KIRIYA (aka takeshik) <[email protected]>
* All rights reserved.
*
* This file is part of YACQ.
*
* 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Parseq;
using XSpect.Yacq.Expressions;
namespace XSpect.Yacq.LanguageServices
{
/// <summary>
/// Represents a dictionary of language grammar rules.
/// </summary>
public partial class Grammar
: IDictionary<Grammar.RuleKey, Lazy<Parser<Char, YacqExpression>>>
{
private static readonly StandardGrammar _standard = new StandardGrammar();
private static readonly AlternativeGrammar _alternative = new AlternativeGrammar();
private static readonly PatternGrammar _pattern = new PatternGrammar();
private readonly IDictionary<RuleKey, Lazy<Parser<Char, YacqExpression>>> _rules;
private readonly RuleGetter _get;
private readonly RuleSetter _set;
/// <summary>
/// Gets or sets the reference to the parser with specified rule key.
/// </summary>
/// <param name="key">The rule key to get or set the parser.</param>
/// <value>The reference to the parser with specified rule key.</value>
public virtual Lazy<Parser<Char, YacqExpression>> this[RuleKey key]
{
get
{
return this._rules[key];
}
set
{
this.CheckIfReadOnly();
this._rules[key] = value;
}
}
/// <summary>
/// Gets or sets the reference to the parser with specified rule key.
/// </summary>
/// <param name="category">The category to get or set the parser.</param>
/// <param name="priority">The priority to get or set the parser.</param>
/// <param name="id">The ID to get or set the parser.</param>
/// <value>The reference to the parser with specified rule key.</value>
public Lazy<Parser<Char, YacqExpression>> this[String category, Int32 priority, String id]
{
get
{
return this[new RuleKey(category, priority, id)];
}
set
{
this[new RuleKey(category, priority, id)] = value;
}
}
/// <summary>
/// Gets or sets the reference to the parser with specified category and priority.
/// </summary>
/// <param name="category">The category to get or set the parser.</param>
/// <param name="priority">The priority to get or set the parser.</param>
/// <value>The reference to the parser with specified category and priority.</value>
public Lazy<Parser<Char, YacqExpression>> this[String category, Int32 priority]
{
get
{
return this[this.GetKey(category, priority)];
}
set
{
this[this.GetKey(category, priority)] = value;
}
}
/// <summary>
/// Gets or sets the reference to the parser with specified category and ID.
/// </summary>
/// <param name="category">The category to get or set the parser.</param>
/// <param name="id">The ID to get or set the parser.</param>
/// <value>The reference to the parser with specified category and ID.</value>
public Lazy<Parser<Char, YacqExpression>> this[String category, String id]
{
get
{
return this[this.GetKey(category, id, true)];
}
set
{
this[this.GetKey(category, id)] = value;
}
}
/// <summary>
/// Gets the sequence of references to the parser with specified category.
/// </summary>
/// <param name="category">The category to get the parser.</param>
/// <value>The sequence of references to the parser with specified category.</value>
public IEnumerable<Lazy<Parser<Char, YacqExpression>>> this[String category]
{
get
{
return this.Keys
.Where(k => k.Category == category)
.Select(k => this[k]);
}
}
/// <summary>
/// Gets the standard grammar.
/// </summary>
/// <value>The standard grammar.</value>
public static StandardGrammar Standard
{
get
{
return _standard;
}
}
/// <summary>
/// Gets the alternative grammar.
/// </summary>
/// <value>The alternative grammar.</value>
public static AlternativeGrammar Alternative
{
get
{
return _alternative;
}
}
/// <summary>
/// Gets the pattern grammar.
/// </summary>
/// <value>The pattern grammar.</value>
public static PatternGrammar Pattern
{
get
{
return _pattern;
}
}
/// <summary>
/// Gets the number of rules in this grammar.
/// </summary>
/// <value>The number of rules in this grammar.</value>
public Int32 Count
{
get
{
return this._rules.Count;
}
}
/// <summary>
/// Gets a value indicating whether this grammar is read-only.
/// </summary>
/// <value><c>true</c> if this rule is read-only; otherwise, <c>false</c>.</value>
public virtual Boolean IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// Gets a collection containing the rule keys in this grammar.
/// </summary>
/// <value>A collection containing the rule keys in this grammar.</value>
public ICollection<RuleKey> Keys
{
get
{
return this._rules.Keys
#if SILVERLIGHT
.OrderBy(k => k)
.ToArray()
#endif
;
}
}
/// <summary>
/// Gets a collection containing the references to parser in this grammar.
/// </summary>
/// <value>A collection containing the references to parser in this grammar.</value>
public ICollection<Lazy<Parser<Char, YacqExpression>>> Values
{
get
{
return this._rules
#if SILVERLIGHT
.Keys
.OrderBy(k => k)
.Select(k => this[k])
.ToArray()
#else
.Values
#endif
;
}
}
/// <summary>
/// Gets or sets the reference to the parser of the default rule.
/// </summary>
/// <value>The reference to the parser of the default rule.</value>
public Lazy<Parser<Char, YacqExpression>> DefaultRule
{
get
{
return this[RuleKey.Default];
}
set
{
this[RuleKey.Default] = value;
}
}
/// <summary>
/// Gets the getter for this grammar.
/// </summary>
/// <value>The getter for this grammar.</value>
public virtual RuleGetter Get
{
get
{
return this._get;
}
}
/// <summary>
/// Gets the setter for this grammar.
/// </summary>
/// <value>The setter for this grammar.</value>
public virtual RuleSetter Set
{
get
{
this.CheckIfReadOnly();
return this._set;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Grammar"/> class.
/// </summary>
public Grammar()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Grammar"/> class that contains rules copied from the specified grammar.
/// </summary>
/// <param name="rules">The rules whose elements are copied to the new grammar.</param>
public Grammar(IDictionary<RuleKey, Lazy<Parser<Char, YacqExpression>>> rules)
{
this._rules =
#if SILVERLIGHT
new Dictionary<RuleKey, Lazy<Parser<Char, YacqExpression>>>
#else
new SortedDictionary<RuleKey, Lazy<Parser<Char, YacqExpression>>>
#endif
(rules ?? new Dictionary<RuleKey, Lazy<Parser<Char, YacqExpression>>>());
this._get = new RuleGetter(this);
this._set = new RuleSetter(this);
}
/// <summary>
/// Returns an enumerator that iterates through rules in this grammar.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator{T}"/> that can be used to iterate through rules in this grammar.
/// </returns>
public IEnumerator<KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>>> GetEnumerator()
{
return this._rules
#if SILVERLIGHT
.OrderBy(p => p.Key)
#endif
.GetEnumerator();
}
/// <summary>
/// Removes all rules from this grammar.
/// </summary>
public virtual void Clear()
{
this.CheckIfReadOnly();
this._rules.Clear();
}
/// <summary>
/// Adds the rule to this grammar.
/// </summary>
/// <param name="key">The rule key to add.</param>
/// <param name="value">The reference to the parser which defines the rule.</param>
public virtual void Add(RuleKey key, Lazy<Parser<Char, YacqExpression>> value)
{
this.CheckIfReadOnly();
this._rules.Add(key, value);
}
/// <summary>
/// Determines whether the specified rule is contained in this grammar.
/// </summary>
/// <param name="key">The rule key to locate in this grammar.</param>
/// <returns><c>true</c> if this grammar contains a rule with the key; otherwise, <c>false</c>.</returns>
public virtual Boolean ContainsKey(RuleKey key)
{
return this._rules.ContainsKey(key);
}
/// <summary>
/// Removes the rule with the specified rule key from this grammar.
/// </summary>
/// <param name="key">The rule key to remove.</param>
/// <returns>
/// <c>true</c> if the rule is successfully removed; otherwise, <c>false</c>. This method also returns <c>false</c> if key was not found in the grammar.
/// </returns>
public virtual Boolean Remove(RuleKey key)
{
this.CheckIfReadOnly();
return this._rules.Remove(key);
}
/// <summary>
/// Gets the reference to the parser associated with the specified rule key.
/// </summary>
/// <param name="key">The rule key to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified rule key, if the key is found;
/// otherwise, <c>null</c>. This parameter is passed uninitialized.</param>
/// <returns><c>true</c> if the specified rule key is contained in this grammar; otherwise, <c>false</c>.</returns>
public virtual Boolean TryGetValue(RuleKey key, out Lazy<Parser<Char, YacqExpression>> value)
{
return this._rules.TryGetValue(key, out value);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
void ICollection<KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>>>.Add(KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>> item)
{
this._rules.Add(item);
}
Boolean ICollection<KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>>>.Contains(KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>> item)
{
return this._rules.Contains(item);
}
void ICollection<KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>>>.CopyTo(KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>>[] array, Int32 arrayIndex)
{
this._rules.CopyTo(array, arrayIndex);
}
Boolean ICollection<KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>>>.Remove(KeyValuePair<RuleKey, Lazy<Parser<Char, YacqExpression>>> item)
{
return this._rules.Remove(item);
}
/// <summary>
/// Adds the rule to this grammar.
/// </summary>
/// <param name="key">The rule key to add.</param>
/// <param name="rule">The factory function of the parser, which has a parameter to the getter for this grammar.</param>
public void Add(RuleKey key, Func<RuleGetter, Parser<Char, YacqExpression>> rule)
{
this.Add(key, this.MakeValue(rule));
}
/// <summary>
/// Adds the rule to this grammar.
/// </summary>
/// <param name="category">The category of new rule to add.</param>
/// <param name="priority">The priority of new rule to add.</param>
/// <param name="id">The ID of new rule to add.</param>
/// <param name="rule">The factory function of the parser, which has a parameter to the getter for this grammar.</param>
public void Add(String category, Int32 priority, String id, Func<RuleGetter, Parser<Char, YacqExpression>> rule)
{
this.Add(new RuleKey(category, priority, id), rule);
}
/// <summary>
/// Adds the rule to this grammar. The priority of new rule is computed automatically.
/// </summary>
/// <param name="category">The category of new rule to add.</param>
/// <param name="id">The ID of new rule to add.</param>
/// <param name="rule">The factory function of the parser, which has a parameter to the getter for this grammar.</param>
public void Add(String category, String id, Func<RuleGetter, Parser<Char, YacqExpression>> rule)
{
this.Add(category, (this.Keys.Where(k => k.Category == category).Max(k => (Nullable<Int32>) k.Priority) ?? 0) + 100, id, rule);
}
/// <summary>
/// Determines whether the specified rule is contained in this grammar.
/// </summary>
/// <param name="category">The category of the rule to locate.</param>
/// <param name="priority">The priority of the rule to locate.</param>
/// <param name="id">The ID of the rule to locate.</param>
/// <returns><c>true</c> if this grammar contains a rule with the key; otherwise, <c>false</c>.</returns>
public Boolean ContainsKey(String category, Int32 priority, String id)
{
return this.ContainsKey(new RuleKey(category, priority, id));
}
/// <summary>
/// Determines whether the specified rule is contained in this grammar.
/// </summary>
/// <param name="category">The category of the rule to locate.</param>
/// <param name="priority">The priority of the rule to locate.</param>
/// <returns><c>true</c> if this grammar contains a rule with the key; otherwise, <c>false</c>.</returns>
public Boolean ContainsKey(String category, Int32 priority)
{
return this.GetKey(category, priority)
.Let(k => k != RuleKey.Default && this.ContainsKey(k));
}
/// <summary>
/// Determines whether the specified rule is contained in this grammar.
/// </summary>
/// <param name="category">The category of the rule to locate.</param>
/// <param name="id">The ID of the rule to locate.</param>
/// <returns><c>true</c> if this grammar contains a rule with the key; otherwise, <c>false</c>.</returns>
public Boolean ContainsKey(String category, String id)
{
return this.GetKey(category, id)
.Let(k => k != RuleKey.Default && this.ContainsKey(k));
}
/// <summary>
/// Removes the rule with the specified rule key from this grammar.
/// </summary>
/// <param name="category">The category of the rule to remove.</param>
/// <param name="priority">The priority of the rule to remove.</param>
/// <param name="id">The ID of the rule to remove.</param>
/// <returns><c>true</c> if the rule is successfully removed; otherwise, <c>false</c>. This method also returns <c>false</c> if key was not found in the grammar.</returns>
public Boolean Remove(String category, Int32 priority, String id)
{
return this.Remove(new RuleKey(category, priority, id));
}
/// <summary>
/// Removes the rule with the specified rule key from this grammar.
/// </summary>
/// <param name="category">The category of the rule to remove.</param>
/// <param name="priority">The priority of the rule to remove.</param>
/// <returns><c>true</c> if the rule is successfully removed; otherwise, <c>false</c>. This method also returns <c>false</c> if key was not found in the grammar.</returns>
public Boolean Remove(String category, Int32 priority)
{
return this.GetKey(category, priority).If(
k => k == RuleKey.Default,
k => false,
this.Remove
);
}
/// <summary>
/// Removes the rule with the specified rule key from this grammar.
/// </summary>
/// <param name="category">The category of the rule to remove.</param>
/// <param name="id">The ID of the rule to remove.</param>
/// <returns><c>true</c> if the rule is successfully removed; otherwise, <c>false</c>. This method also returns <c>false</c> if key was not found in the grammar.</returns>
public Boolean Remove(String category, String id)
{
return this.GetKey(category, id).If(
k => k == RuleKey.Default,
k => false,
this.Remove
);
}
/// <summary>
/// Gets the reference to the parser associated with the specified rule key.
/// </summary>
/// <param name="category">The category of the rule to get.</param>
/// <param name="priority">The priority of the rule to get.</param>
/// <param name="id">The ID of the rule to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified rule key, if the key is found;
/// otherwise, <c>null</c>. This parameter is passed uninitialized.</param>
/// <returns><c>true</c> if the specified rule key is contained in this grammar; otherwise, <c>false</c>.</returns>
public Boolean TryGetValue(String category, Int32 priority, String id, out Lazy<Parser<Char, YacqExpression>> value)
{
return this.TryGetValue(new RuleKey(category, priority, id), out value);
}
/// <summary>
/// Gets the reference to the parser associated with the specified rule key.
/// </summary>
/// <param name="category">The category of the rule to get.</param>
/// <param name="priority">The priority of the rule to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified rule key, if the key is found;
/// otherwise, <c>null</c>. This parameter is passed uninitialized.</param>
/// <returns><c>true</c> if the specified rule key is contained in this grammar; otherwise, <c>false</c>.</returns>
public Boolean TryGetValue(String category, Int32 priority, out Lazy<Parser<Char, YacqExpression>> value)
{
return this.TryGetValue(this.GetKey(category, priority), out value);
}
/// <summary>
/// Gets the reference to the parser associated with the specified rule key.
/// </summary>
/// <param name="category">The category of the rule to get.</param>
/// <param name="id">The ID of the rule to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified rule key, if the key is found;
/// otherwise, <c>null</c>. This parameter is passed uninitialized.</param>
/// <returns><c>true</c> if the specified rule key is contained in this grammar; otherwise, <c>false</c>.</returns>
public Boolean TryGetValue(String category, String id, out Lazy<Parser<Char, YacqExpression>> value)
{
return this.TryGetValue(this.GetKey(category, id), out value);
}
/// <summary>
/// Gets the rule key with specified parameters.
/// </summary>
/// <param name="category">The category of the rule to get.</param>
/// <param name="priority">The priority of the rule to get.</param>
/// <param name="throwOnError"><c>true</c> to throw an exception if the rule cannot be found; <c>false</c> to return <c>null</c>.</param>
/// <returns>The rule key with specified parameters. if the key is not found, the <paramref name="throwOnError"/> parameter specifies whether <c>null</c> is returned or an exception is thrown.</returns>
public RuleKey GetKey(String category, Int32 priority, Boolean throwOnError = false)
{
var key = this.Keys.SingleOrDefault(k => k.Category == category && k.Priority == priority);
if (key == RuleKey.Default && throwOnError)
{
throw new KeyNotFoundException("Specified key was not found: category = " + category + ", priority = " + priority);
}
return key;
}
/// <summary>
/// Gets the rule key with specified parameters.
/// </summary>
/// <param name="category">The category of the rule to get.</param>
/// <param name="id">The ID of the rule to get.</param>
/// <param name="throwOnError"><c>true</c> to throw an exception if the rule cannot be found; <c>false</c> to return <c>null</c>.</param>
/// <returns>The rule key with specified parameters. if the key is not found, the <paramref name="throwOnError"/> parameter specifies whether <c>null</c> is returned or an exception is thrown.</returns>
public RuleKey GetKey(String category, String id, Boolean throwOnError = false)
{
var key = this.Keys.SingleOrDefault(k => k.Category == category && k.Id == id);
if (key == RuleKey.Default && throwOnError)
{
throw new KeyNotFoundException("Specified key was not found: category = " + category + ", id = " + id);
}
return key;
}
/// <summary>
/// Creates a modifiable clone of this grammar.
/// </summary>
/// <returns>A modifiable clone of this grammar.</returns>r
public Grammar Clone()
{
return new Grammar(this._rules);
}
private Lazy<Parser<Char, YacqExpression>> MakeValue(Func<RuleGetter, Parser<Char, YacqExpression>> rule)
{
return new Lazy<Parser<Char, YacqExpression>>(() => rule(this.Get), LazyThreadSafetyMode.PublicationOnly);
}
private void CheckIfReadOnly()
{
if (this.IsReadOnly)
{
throw new InvalidOperationException("This grammar is read-only.");
}
}
}
}
// vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et:
| mit |
wwood/bioruby-kmer_counter | test/helper.rb | 496 | require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'test/unit'
require 'shoulda'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'bio-kmer_counter'
TEST_DATA_DIR = File.join(File.dirname(__FILE__), 'data')
class Test::Unit::TestCase
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.