repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
iamatypeofwalrus/GlasswavesCo | cdk/node_modules/@aws-cdk/aws-sqs/lib/index.js | 615 | "use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./policy"));
__export(require("./queue"));
__export(require("./queue-ref"));
// AWS::SQS CloudFormation Resources:
__export(require("./sqs.generated"));
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJpbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLDhCQUF5QjtBQUN6Qiw2QkFBd0I7QUFDeEIsaUNBQTRCO0FBRTVCLHFDQUFxQztBQUNyQyxxQ0FBZ0MifQ== | mit |
clouseauu/allotment | lib/allotment/cli.rb | 949 | require "allotment"
module Allotment
module CLI
def run
o = options
raise ArgumentError.new('Missing username and/or password') if (o.username.nil? || o.password.nil?)
log = o.logfile ? Logger.new(o.logfile) : Logger.new(STDOUT)
log.level = Logger::INFO
p = Allotment::Processor.new(provider: o, logger: log)
p.show_usage
end
def options
Trollop::options do
opt :name, "Provider", type: :string, :short => "-n", default: "fuzeconnect"
opt :logfile, "Log File", type: :string, default: "#{File.expand_path(File.join(ENV['HOME'], 'allotment.log'))}"
opt :username, "Username", type: :string
opt :password, "Password", type: :string
opt :puser, "Pushover User Token", type: :string, :short => "-t"
opt :papp, "Pushover App Token", type: :string, :short => "-a"
end
end
module_function :run, :options
end
end | mit |
eagletmt/ffmpeg-ffi | lib/ffmpeg-ffi/c/dictionary_entry.rb | 168 | require 'ffi'
module FFmpeg
module C
class DictionaryEntry < FFI::Struct
layout(
:key, :string,
:value, :string,
)
end
end
end
| mit |
johnthecat/babel-plugin-jsdoc-runtime-typecheck | test/smoke/fixtures/assertion-inject/integration/class-method.js | 1354 | "use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Test = function () {
function Test() {
_classCallCheck(this, Test);
}
_createClass(Test, [{
key: "myMethod",
/**
* @param {Number} a
* @param {Number} b
* @returns {Number}
* @typecheck
*/
value: function myMethod(a, b) {
__executeTypecheck__("method Test.myMethod", "a", a, "\"Number\"");
__executeTypecheck__("method Test.myMethod", "b", b, "\"Number\"");
return __executeTypecheck__("method Test.myMethod", "return", a + b, "\"Number\"");
}
}]);
return Test;
}();
| mit |
aalok05/CodeHub | CodeHub/Views/NotificationsView.xaml.cs | 14747 | using CodeHub.Services;
using CodeHub.ViewModels;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Octokit;
using System.Collections.ObjectModel;
using System.Linq;
using Windows.UI.Xaml.Navigation;
using static CodeHub.Helpers.GlobalHelper;
namespace CodeHub.Views
{
public sealed partial class NotificationsView : Windows.UI.Xaml.Controls.Page
{
public NotificationsViewmodel ViewModel;
public NotificationsView()
{
InitializeComponent();
ViewModel = new NotificationsViewmodel();
DataContext = ViewModel;
Messenger.Default.Register<User>(this, ViewModel.RecieveSignInMessage);
Messenger.Default.Register<SignOutMessageType>(this, ViewModel.RecieveSignOutMessage);
Messenger.Default.Register(this, (UpdateAllNotificationsCountMessageType n) =>
{
AppViewmodel.UnreadNotifications = new ObservableCollection<Notification>(AppViewmodel.UnreadNotifications.OrderBy(un => un.UpdatedAt));
ViewModel.UpdateAllNotificationIndicator(n.Count);
Bindings.Update();
});
Messenger.Default.Register(this, (UpdateUnreadNotificationsCountMessageType n) =>
{
ViewModel.UpdateUnreadNotificationIndicator(n.Count);
Bindings.Update();
});
Messenger.Default.Register(this, (UpdateParticipatingNotificationsCountMessageType n) =>
{
ViewModel.UpdateParticipatingNotificationIndicator(n.Count);
Bindings.Update();
});
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await ViewModel.Load();
}
public RelayCommand<Notification> _MarkasReadAllNotifCommand;
public RelayCommand<Notification> MarkasReadAllNotifCommand
=> _MarkasReadAllNotifCommand
?? (_MarkasReadAllNotifCommand = new RelayCommand<Notification>(
async (Notification notification) =>
{
ViewModel.IsLoadingAll = true;
if (notification.Unread)
{
await NotificationsService.MarkNotificationAsRead(notification.Id);
var index = NotificationsViewmodel.AllNotifications.IndexOf(NotificationsViewmodel.AllNotifications.Where(p => p.Id == notification.Id).First());
NotificationsViewmodel.AllNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
}
ViewModel.IsLoadingAll = false;
Messenger.Default.Send(new UpdateAllNotificationsCountMessageType { Count = 0 });
}));
public RelayCommand<Notification> _MarkasReadUnreadNotifCommand;
public RelayCommand<Notification> MarkasReadUnreadNotifCommand
=> _MarkasReadUnreadNotifCommand
?? (_MarkasReadUnreadNotifCommand = new RelayCommand<Notification>(
async (Notification notification) =>
{
ViewModel.IsLoadingUnread = true;
if (notification.Unread)
{
await NotificationsService.MarkNotificationAsRead(notification.Id);
var index = AppViewmodel.UnreadNotifications.IndexOf(AppViewmodel.UnreadNotifications.Where(p => p.Id == notification.Id).First());
AppViewmodel.UnreadNotifications.RemoveAt(index);
}
ViewModel.IsLoadingUnread = false;
Messenger.Default.Send(new UpdateUnreadNotificationsCountMessageType { Count = AppViewmodel.UnreadNotifications?.Count ?? 0 });
}));
public RelayCommand<Notification> _MarkasReadParticipatingNotifCommand;
public RelayCommand<Notification> MarkasReadParticipatingNotifCommand
=> _MarkasReadParticipatingNotifCommand
?? (_MarkasReadParticipatingNotifCommand = new RelayCommand<Notification>(
async (Notification notification) =>
{
ViewModel.IsloadingParticipating = true;
if (notification.Unread)
{
await NotificationsService.MarkNotificationAsRead(notification.Id);
var index = NotificationsViewmodel
.ParticipatingNotifications
.IndexOf(
NotificationsViewmodel
.ParticipatingNotifications
.Where(p => p.Id == notification.Id)
.First()
);
NotificationsViewmodel.ParticipatingNotifications[index] = await NotificationsService
.GetNotificationById(notification.Id);
}
ViewModel.IsloadingParticipating = false;
Messenger.Default.Send(new UpdateParticipatingNotificationsCountMessageType { Count = NotificationsViewmodel.ParticipatingNotifications?.Count ?? 0 });
}));
public RelayCommand<Notification> _UnsubscribeAllNotifCommand;
public RelayCommand<Notification> UnsubscribeAllNotifCommand
=> _UnsubscribeAllNotifCommand
?? (_UnsubscribeAllNotifCommand = new RelayCommand<Notification>(
async (Notification notification) =>
{
ViewModel.IsLoadingAll = true;
await NotificationsService.SetThreadSubscription(notification.Id, false, true);
if (notification.Unread)
{
await NotificationsService.MarkNotificationAsRead(notification.Id);
var index = NotificationsViewmodel.AllNotifications.IndexOf(NotificationsViewmodel.AllNotifications.Where(p => (p as Notification).Id == notification.Id).First());
NotificationsViewmodel.AllNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
}
ViewModel.IsLoadingAll = false;
}));
public RelayCommand<Notification> _UnsubscribeUnreadNotifCommand;
public RelayCommand<Notification> UnsubscribeUnreadNotifCommand
=> _UnsubscribeUnreadNotifCommand
?? (_UnsubscribeUnreadNotifCommand = new RelayCommand<Notification>(
async (Notification notification) =>
{
ViewModel.IsLoadingUnread = true;
await NotificationsService.SetThreadSubscription(notification.Id, false, true);
if (notification.Unread)
{
await NotificationsService.MarkNotificationAsRead(notification.Id);
var index = AppViewmodel.UnreadNotifications.IndexOf(AppViewmodel.UnreadNotifications.Where(p => (p as Notification).Id == notification.Id).First());
AppViewmodel.UnreadNotifications.RemoveAt(index);
}
ViewModel.IsLoadingUnread = false;
}));
public RelayCommand<Notification> _UnsubscribeParticipatingNotifCommand;
public RelayCommand<Notification> UnsubscribeParticipatingNotifCommand
=> _UnsubscribeParticipatingNotifCommand
?? (_UnsubscribeParticipatingNotifCommand = new RelayCommand<Notification>(
async (Notification notification) =>
{
ViewModel.IsloadingParticipating = true;
await NotificationsService.SetThreadSubscription(notification.Id, false, true);
if (notification.Unread)
{
await NotificationsService.MarkNotificationAsRead(notification.Id);
var index = NotificationsViewmodel.ParticipatingNotifications.IndexOf(NotificationsViewmodel.ParticipatingNotifications.Where(p => (p as Notification).Id == notification.Id).First());
NotificationsViewmodel.ParticipatingNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
}
ViewModel.IsloadingParticipating = false;
}));
//private void MarkasReadUnreadNotif_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
//{
// ViewModel.IsLoadingUnread = true;
// if (notification.Unread)
// {
// await NotificationsService.MarkNotificationAsRead(notification.Id);
// var index = ViewModel.UnreadNotifications.IndexOf(ViewModel.UnreadNotifications.Where(p => p.Id == notification.Id).First());
// ViewModel.UnreadNotifications.RemoveAt(index);
// }
// ViewModel.IsLoadingUnread = false;
// if (ViewModel.UnreadNotifications.Count == 0)
// Messenger.Default.Send(new GlobalHelper.UpdateUnreadNotificationMessageType { IsUnread = false });
//}
//private void MarkasReadParticipatingNotif_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
//{
// ViewModel.IsloadingParticipating = true;
// if (notification.Unread)
// {
// await NotificationsService.MarkNotificationAsRead(notification.Id);
// var index = ViewModel.ParticipatingNotifications.IndexOf(ViewModel.ParticipatingNotifications.Where(p => p.Id == notification.Id).First());
// ViewModel.ParticipatingNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
// }
// ViewModel.IsloadingParticipating = false;
//}
//private void MarkasReadAllNotif_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
//{
// ViewModel.IsLoadingAll = true;
// if (notification.Unread)
// {
// await NotificationsService.MarkNotificationAsRead(notification.Id);
// var index = ViewModel.AllNotifications.IndexOf(ViewModel.AllNotifications.Where(p => p.Id == notification.Id).First());
// ViewModel.AllNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
// }
// ViewModel.IsLoadingAll = false;
//}
//private void UnsubscribeUnreadNotif_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
//{
// ViewModel.IsLoadingUnread = true;
// await NotificationsService.SetThreadSubscription(notification.Id, false, true);
// if (notification.Unread)
// {
// await NotificationsService.MarkNotificationAsRead(notification.Id);
// var index = ViewModel.UnreadNotifications.IndexOf(ViewModel.UnreadNotifications.Where(p => p.Id == notification.Id).First());
// ViewModel.UnreadNotifications.RemoveAt(index);
// }
// ViewModel.IsLoadingUnread = false;
//}
//private void UnsubscribeParticipatingNotif_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
//{
// ViewModel.IsloadingParticipating = true;
// await NotificationsService.SetThreadSubscription(notification.Id, false, true);
// if (notification.Unread)
// {
// await NotificationsService.MarkNotificationAsRead(notification.Id);
// var index = ViewModel.ParticipatingNotifications.IndexOf(ViewModel.ParticipatingNotifications.Where(p => p.Id == notification.Id).First());
// ViewModel.ParticipatingNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
// }
// ViewModel.IsloadingParticipating = false;
//}
//private void UnsubscribeAllNotif_Invoked(SwipeItem sender, SwipeItemInvokedEventArgs args)
//{
// ViewModel.IsLoadingAll = true;
// await NotificationsService.SetThreadSubscription(notification.Id, false, true);
// if (notification.Unread)
// {
// await NotificationsService.MarkNotificationAsRead(notification.Id);
// var index = ViewModel.AllNotifications.IndexOf(ViewModel.AllNotifications.Where(p => p.Id == notification.Id).First());
// ViewModel.AllNotifications[index] = await NotificationsService.GetNotificationById(notification.Id);
// }
// ViewModel.IsLoadingAll = false;
//}
}
}
| mit |
PiotrDabkowski/Js2Py | tests/test_cases/built-ins/Object/defineProperty/15.2.3.6-4-445.js | 1475 | // Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.2.3.6-4-445
description: >
ES5 Attributes - success to update [[Set]] attribute of accessor
property ([[Get]] is undefined, [[Set]] is undefined,
[[Enumerable]] is false, [[Configurable]] is true) to different
value
includes: [runTestCase.js]
---*/
function testcase() {
var obj = {};
var verifySetFunc = "data";
var setFunc = function (value) {
verifySetFunc = value;
};
Object.defineProperty(obj, "prop", {
get: undefined,
set: undefined,
enumerable: false,
configurable: true
});
var desc1 = Object.getOwnPropertyDescriptor(obj, "prop");
var propertyDefineCorrect = obj.hasOwnProperty("prop");
Object.defineProperty(obj, "prop", {
set: setFunc
});
obj.prop = "overrideData";
var desc2 = Object.getOwnPropertyDescriptor(obj, "prop");
return typeof desc1.set === "undefined" && propertyDefineCorrect && desc2.set === setFunc && verifySetFunc === "overrideData";
}
runTestCase(testcase);
| mit |
changedi/better-springboot | src/main/java/me/cloudex/better/springboot/service/AccountService.java | 264 | package me.cloudex.better.springboot.service;
import org.springframework.stereotype.Service;
/**
* Created by zunyuan.jy on 02/05/2017.
*/
@Service
public class AccountService {
public String sayHello(String name) {
return "hello " + name;
}
}
| mit |
nurieff/table-fits | src/dom_change.js | 1921 | let MutationObserver = typeof window !== 'undefined' ? window.MutationObserver || window.WebKitMutationObserver : undefined,
eventListenerSupported = typeof window !== 'undefined' ? window.addEventListener : undefined;
export default class TableFits_Prepare_DomChange {
static addEvent(obj, callback) {
if (MutationObserver) {
// define a new observer
var obs = new MutationObserver(function(mutations, observer) {
if (mutations[0].addedNodes.length || mutations[0].removedNodes.length)
callback();
});
obs.observe(obj, {childList: true, subtree: true});
if (!(obj in TableFits_Prepare_DomChange._storage)) {
TableFits_Prepare_DomChange._storage[obj] = {};
}
TableFits_Prepare_DomChange._storage[obj][callback] = obs;
} else if (eventListenerSupported) {
obj.addEventListener('DOMSubtreeModified', callback, false);
obj.addEventListener('DOMNodeInserted', callback, false);
obj.addEventListener('DOMNodeRemoved', callback, false);
}
}
static removeEvent(obj, callback) {
if (MutationObserver) {
if (!(obj in TableFits_Prepare_DomChange._storage)) {
return;
}
if (!(callback in TableFits_Prepare_DomChange._storage[obj])) {
return;
}
TableFits_Prepare_DomChange._storage[obj][callback].disconnect();
delete TableFits_Prepare_DomChange._storage[obj][callback];
} else if (eventListenerSupported) {
obj.removeEventListener('DOMSubtreeModified', callback, false);
obj.removeEventListener('DOMNodeInserted', callback, false);
obj.removeEventListener('DOMNodeRemoved', callback, false);
}
}
}
TableFits_Prepare_DomChange._storage = {}; | mit |
alexcepoi/cake | cake/color.py | 3044 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import curses
import inspect
import colorama
colorama.init()
ANSI_PATTERN = '\x1b[^m]*m'
class ColorWrapper(object):
""" Wraps a string in a color or returns color """
def __init__(self, color):
self.color = color
def __str__(self):
return self.color
def __call__(self, *args):
reset = colorama.Style.RESET_ALL
string = self.color
for arg in args:
string += str(arg)
return string.replace(reset, reset + self.color) + reset
class ColorHelper(object):
""" Namespace of ColorWrappers """
def __init__(self, opts):
self.opts = opts
def __getattr__(self, key):
if key == key.lower():
key = key.upper()
if key in self.opts:
return ColorWrapper(self.opts[key])
return super(ColorHelper, self).__getattr__(key)
fore = ColorHelper(colorama.Fore.__dict__)
back = ColorHelper(colorama.Back.__dict__)
style = ColorHelper(colorama.Style.__dict__)
def ansi(string, *args):
""" Convenience function to chain multiple ColorWrappers to a string """
ansi = ''
for arg in args:
arg = str(arg)
if not re.match(ANSI_PATTERN, arg):
raise ValueError('Additional arguments must be ansi strings')
ansi += arg
return ansi + string + colorama.Style.RESET_ALL
def puts(*args, **kwargs):
"""
Full feature printing function featuring
trimming and padding for both files and ttys
"""
# parse kwargs
trim = kwargs.pop('trim', False)
padding = kwargs.pop('padding', None)
stream = kwargs.pop('stream', sys.stdout)
# HACK: check if stream is IndentedFile
indent = getattr(stream, 'indent', 0)
# stringify args
args = [str(i) for i in args]
# helpers
def trimstr(ansi, width):
string = ''; size = 0; i = 0
while i < len(ansi):
mobj = re.match(ANSI_PATTERN, ansi[i:])
if mobj:
# append ansi code
string = string + mobj.group(0)
i += len(mobj.group(0))
else:
# loop for more ansi codes even at max width
size += 1
if size > width: break
# append normal char
string = string + ansi[i]
i += 1
return (string, size)
# process strings
if not stream.isatty():
# remove ansi codes and print
for string in args:
stream.write(re.sub(ANSI_PATTERN, '', string) + '\n')
else:
# get terminal width
try: curses.setupterm()
except:
trim = False
padding = None
else:
width = curses.tigetnum('cols') - indent
for string in args:
if trim or padding:
trimmed, size = trimstr(string, width)
# trim string
if trim:
if len(trimmed) < len(string):
trimmed = trimstr(string, width - 3)[0] + colorama.Style.RESET_ALL + '...'
string = trimmed
# add padding
if padding:
string += padding * (width - size)
# print final string
stream.write(string + '\n')
if __name__ == '__main__':
print fore.red('red') + style.bright('bold')
print fore.red('red' + style.bright('bold') + 'red')
print ansi('redbold', fore.red, style.bright)
puts(fore.red('red'), padding='=')
puts(fore.red('red') * 200, trim=True)
| mit |
gabrielStanovsky/oie-benchmark | oie_readers/clausieReader.py | 1496 | from oie_readers.oieReader import OieReader
from oie_readers.extraction import Extraction
class ClausieReader(OieReader):
def __init__(self):
self.name = 'ClausIE'
def read(self, fn):
d = {}
with open(fn) as fin:
for line in fin:
data = line.strip().split('\t')
if len(data) == 1:
text = data[0]
elif len(data) == 5:
arg1, rel, arg2 = [s[1:-1] for s in data[1:4]]
confidence = data[4]
curExtraction = Extraction(pred = rel, sent = text, confidence = float(confidence))
curExtraction.addArg(arg1)
curExtraction.addArg(arg2)
d[text] = d.get(text, []) + [curExtraction]
self.oie = d
self.normalizeConfidence()
def normalizeConfidence(self):
''' Normalize confidence to resemble probabilities '''
EPSILON = 1e-3
confidences = [extraction.confidence for sent in self.oie for extraction in self.oie[sent]]
maxConfidence = max(confidences)
minConfidence = min(confidences)
denom = maxConfidence - minConfidence + (2*EPSILON)
for sent, extractions in list(self.oie.items()):
for extraction in extractions:
extraction.confidence = ( (extraction.confidence - minConfidence) + EPSILON) / denom
| mit |
wkozyra95/react-boilerplate | src/pages/StaticPage/About.js | 233 | /* @flow */
import React from 'react';
import AppLayout from 'pages/AppLayout';
class About extends React.Component {
render() {
return (
<AppLayout>
About
</AppLayout>
);
}
}
export default About;
| mit |
sproutit/sproutcore-buildtools | jsdoc/java/src/JsRun.java | 756 | /**
* A trivial bootstrap class that simply adds the path to the
* .js file as an argument to the Rhino call. This little hack
* allows the code in the .js file to have access to it's own
* path via the Rhino arguments object. This is necessary to
* allow the .js code to find resource files in a location
* relative to itself.
*
* USAGE: java -jar jsrun.jar path/to/file.js
*/
public class JsRun {
public static void main(String[] args) {
String[] jsargs = {"-j="+args[0]};
String[] allArgs = new String[jsargs.length + args.length];
System.arraycopy(args, 0, allArgs, 0, args.length);
System.arraycopy(jsargs, 0, allArgs, args.length ,jsargs.length);
org.mozilla.javascript.tools.shell.Main.main(allArgs);
}
}
| mit |
erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Response/AlipayOpenPublicPersonalizedExtensionCreateResponse.cs | 585 | using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// AlipayOpenPublicPersonalizedExtensionCreateResponse.
/// </summary>
public class AlipayOpenPublicPersonalizedExtensionCreateResponse : AopResponse
{
/// <summary>
/// 扩展区套id,创建个性化扩展区成功后,支付宝会将该字段返回,后续扩展区上下线或者扩展区删除都会用到这个值。
/// </summary>
[XmlElement("extension_key")]
public string ExtensionKey { get; set; }
}
}
| mit |
gagangupt16/vscode | src/vs/platform/workspace/test/common/testWorkspace.ts | 698 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import URI from 'vs/base/common/uri';
import { Workspace } from 'vs/platform/workspace/common/workspace';
const wsUri = URI.file('C:\\testWorkspace');
export const TestWorkspace = testWorkspace(wsUri);
export function testWorkspace(resource: URI): Workspace {
return new Workspace(
resource.toString(),
resource.fsPath,
[resource]
);
} | mit |
jyduque/sagacohub | src/sagaco/DsagacoBundle/Entity/clBenefiHumano.php | 10415 | <?php
namespace sagaco\DsagacoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ESagaco.viBenefiHumano
*
* @ORM\Table(name="e_sagaco.vi_benefi_humano", uniqueConstraints={@ORM\UniqueConstraint(name="uk_vi_benefi_humano_co_recurs_humano_nu_cedula", columns={"nu_cedula"})}, indexes={@ORM\Index(name="IDX_B1B412B472BC55D8", columns={"co_recurs_humano"})})
* @ORM\Entity(repositoryClass="sagaco\DsagacoBundle\Entity\clBenefiHumanoRepository")
*/
class clBenefiHumano
{
/**
* @var integer
*
* @ORM\Column(name="co_benefi_humano", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="SEQUENCE")
* @ORM\SequenceGenerator(sequenceName="e_sagaco.seq_vi_benefi_humano_co_benefi_humano", allocationSize=1, initialValue=1)
*/
private $coBenefiHumano;
/**
* @var string
*
* @ORM\Column(name="nu_cedula", type="decimal", precision=10, scale=0, nullable=true)
*/
private $nuCedula;
/**
* @var string
*
* @ORM\Column(name="in_nacionalidad", type="string", length=2, nullable=false)
*/
private $inNacionalidad;
/**
* @var string
*
* @ORM\Column(name="tx_primer_nombre", type="string", length=15, nullable=false)
*/
private $txPrimerNombre;
/**
* @var string
*
* @ORM\Column(name="tx_segund_nombre", type="string", length=15, nullable=true)
*/
private $txSegundNombre;
/**
* @var string
*
* @ORM\Column(name="tx_primer_apellido", type="string", length=15, nullable=false)
*/
private $txPrimerApellido;
/**
* @var string
*
* @ORM\Column(name="tx_segund_apellido", type="string", length=15, nullable=true)
*/
private $txSegundApellido;
/**
* @var string
*
* @ORM\Column(name="tx_parentesco", type="string", length=6, nullable=false)
*/
private $txParentesco;
/**
* @var string
*
* @ORM\Column(name="in_sexo", type="string", length=2, nullable=false)
*/
private $inSexo;
/**
* @var string
*
* @ORM\Column(name="in_estado_civil", type="string", length=2, nullable=false)
*/
private $inEstadoCivil;
/**
* @var string
*
* @ORM\Column(name="tx_correo_electronico", type="string", length=200, nullable=true)
*/
private $txCorreoElectronico;
/**
* @var string
*
* @ORM\Column(name="tx_telefo_habitacion", type="string", length=15, nullable=true)
*/
private $txTelefoHabitacion;
/**
* @var string
*
* @ORM\Column(name="tx_telefo_celular", type="string", length=15, nullable=true)
*/
private $txTelefoCelular;
/**
* @var string
*
* @ORM\Column(name="tx_lugar_residencia", type="string", length=255, nullable=true)
*/
private $txLugarResidencia;
/**
* @var \DateTime
*
* @ORM\Column(name="fh_creacion", type="datetime", nullable=true)
*/
private $fhCreacion;
/**
* @var \DateTime
*
* @ORM\Column(name="fh_actualizacion", type="datetime", nullable=true)
*/
private $fhActualizacion;
/**
* @var \ESagaco.viRecursHumano
*
* @ORM\ManyToOne(targetEntity="clRecursHumano")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="co_recurs_humano", referencedColumnName="co_recurs_humano")
* })
*/
private $coRecursHumano;
/**
* Get coBenefiHumano
*
* @return integer
*/
public function getCoBenefiHumano()
{
return $this->coBenefiHumano;
}
/**
* Set nuCedula
*
* @param string $nuCedula
* @return clBenefiHumano
*/
public function setNuCedula($nuCedula)
{
$this->nuCedula = $nuCedula;
return $this;
}
/**
* Get nuCedula
*
* @return string
*/
public function getNuCedula()
{
return $this->nuCedula;
}
/**
* Set inNacionalidad
*
* @param string $inNacionalidad
* @return clBenefiHumano
*/
public function setInNacionalidad($inNacionalidad)
{
$this->inNacionalidad = $inNacionalidad;
return $this;
}
/**
* Get inNacionalidad
*
* @return string
*/
public function getInNacionalidad()
{
return $this->inNacionalidad;
}
/**
* Set txPrimerNombre
*
* @param string $txPrimerNombre
* @return clBenefiHumano
*/
public function setTxPrimerNombre($txPrimerNombre)
{
$this->txPrimerNombre = $txPrimerNombre;
return $this;
}
/**
* Get txPrimerNombre
*
* @return string
*/
public function getTxPrimerNombre()
{
return $this->txPrimerNombre;
}
/**
* Set txSegundNombre
*
* @param string $txSegundNombre
* @return clBenefiHumano
*/
public function setTxSegundNombre($txSegundNombre)
{
$this->txSegundNombre = $txSegundNombre;
return $this;
}
/**
* Get txSegundNombre
*
* @return string
*/
public function getTxSegundNombre()
{
return $this->txSegundNombre;
}
/**
* Set txPrimerApellido
*
* @param string $txPrimerApellido
* @return clBenefiHumano
*/
public function setTxPrimerApellido($txPrimerApellido)
{
$this->txPrimerApellido = $txPrimerApellido;
return $this;
}
/**
* Get txPrimerApellido
*
* @return string
*/
public function getTxPrimerApellido()
{
return $this->txPrimerApellido;
}
/**
* Set txSegundApellido
*
* @param string $txSegundApellido
* @return clBenefiHumano
*/
public function setTxSegundApellido($txSegundApellido)
{
$this->txSegundApellido = $txSegundApellido;
return $this;
}
/**
* Get txSegundApellido
*
* @return string
*/
public function getTxSegundApellido()
{
return $this->txSegundApellido;
}
/**
* Set txParentesco
*
* @param string $txParentesco
* @return clBenefiHumano
*/
public function setTxParentesco($txParentesco)
{
$this->txParentesco = $txParentesco;
return $this;
}
/**
* Get txParentesco
*
* @return string
*/
public function getTxParentesco()
{
return $this->txParentesco;
}
/**
* Set inSexo
*
* @param string $inSexo
* @return clBenefiHumano
*/
public function setInSexo($inSexo)
{
$this->inSexo = $inSexo;
return $this;
}
/**
* Get inSexo
*
* @return string
*/
public function getInSexo()
{
return $this->inSexo;
}
/**
* Set inEstadoCivil
*
* @param string $inEstadoCivil
* @return clBenefiHumano
*/
public function setInEstadoCivil($inEstadoCivil)
{
$this->inEstadoCivil = $inEstadoCivil;
return $this;
}
/**
* Get inEstadoCivil
*
* @return string
*/
public function getInEstadoCivil()
{
return $this->inEstadoCivil;
}
/**
* Set txCorreoElectronico
*
* @param string $txCorreoElectronico
* @return clBenefiHumano
*/
public function setTxCorreoElectronico($txCorreoElectronico)
{
$this->txCorreoElectronico = $txCorreoElectronico;
return $this;
}
/**
* Get txCorreoElectronico
*
* @return string
*/
public function getTxCorreoElectronico()
{
return $this->txCorreoElectronico;
}
/**
* Set txTelefoHabitacion
*
* @param string $txTelefoHabitacion
* @return clBenefiHumano
*/
public function setTxTelefoHabitacion($txTelefoHabitacion)
{
$this->txTelefoHabitacion = $txTelefoHabitacion;
return $this;
}
/**
* Get txTelefoHabitacion
*
* @return string
*/
public function getTxTelefoHabitacion()
{
return $this->txTelefoHabitacion;
}
/**
* Set txTelefoCelular
*
* @param string $txTelefoCelular
* @return clBenefiHumano
*/
public function setTxTelefoCelular($txTelefoCelular)
{
$this->txTelefoCelular = $txTelefoCelular;
return $this;
}
/**
* Get txTelefoCelular
*
* @return string
*/
public function getTxTelefoCelular()
{
return $this->txTelefoCelular;
}
/**
* Set txLugarResidencia
*
* @param string $txLugarResidencia
* @return clBenefiHumano
*/
public function setTxLugarResidencia($txLugarResidencia)
{
$this->txLugarResidencia = $txLugarResidencia;
return $this;
}
/**
* Get txLugarResidencia
*
* @return string
*/
public function getTxLugarResidencia()
{
return $this->txLugarResidencia;
}
/**
* Set fhCreacion
*
* @param \DateTime $fhCreacion
* @return clBenefiHumano
*/
public function setFhCreacion($fhCreacion)
{
$this->fhCreacion = $fhCreacion;
return $this;
}
/**
* Get fhCreacion
*
* @return \DateTime
*/
public function getFhCreacion()
{
return $this->fhCreacion;
}
/**
* Set fhActualizacion
*
* @param \DateTime $fhActualizacion
* @return clBenefiHumano
*/
public function setFhActualizacion($fhActualizacion)
{
$this->fhActualizacion = $fhActualizacion;
return $this;
}
/**
* Get fhActualizacion
*
* @return \DateTime
*/
public function getFhActualizacion()
{
return $this->fhActualizacion;
}
/**
* Set coRecursHumano
*
* @param \sagaco\DsagacoBundle\Entity\clRecursHumano $coRecursHumano
* @return clBenefiHumano
*/
public function setCoRecursHumano(\sagaco\DsagacoBundle\Entity\clRecursHumano $coRecursHumano = null)
{
$this->coRecursHumano = $coRecursHumano;
return $this;
}
/**
* Get coRecursHumano
*
* @return \sagaco\DsagacoBundle\Entity\clRecursHumano
*/
public function getCoRecursHumano()
{
return $this->coRecursHumano;
}
}
| mit |
LuisRBarreras/string-builder | test/test-cat.js | 800 | var StringBuilder = require('../src/string-builder');
var assert = require('chai').assert;
var sinon = require('sinon');
var jsonfile = require('jsonfile');
var file = './fixtures/data.json';
var fixtures = jsonfile.readFileSync(file);
describe('StringBuilder #cat', function() {
it('Should concatenate all the parameters', function() {
var sb = new StringBuilder();
sb.cat('Hello', 'CAT');
assert.deepEqual(sb.string(), fixtures.bufferOne.join(''));
});
it('Should concatenate parameters with arrays and functions', function() {
var sb = new StringBuilder();
sb.cat(['one', 'two'])
.cat(() => 'three')
.cat(['four', () => 'five']);
assert.deepEqual(sb.string(), fixtures.numbers.join(''));
});
}); | mit |
heitorschueroff/ctci | ch5/5.04_Next_Number/test_next_number.py | 567 | import unittest
from next_number import *
class TestNextNumber(unittest.TestCase):
def test_next_smallest_number(self):
self.assertEquals(next_smallest_number(0b1011000), 0b1100001)
self.assertEquals(next_smallest_number(0b1010), 0b1100)
self.assertEquals(next_smallest_number(0b1110), 0b10011)
def test_next_largest_number(self):
self.assertEquals(previous_largest_number(0b10010011), 0b10001110)
self.assertEquals(previous_largest_number(0b100101100), 0b100101010)
if __name__ == '__main__':
unittest.main()
| mit |
leblanc-simon/openpasswd | src/OpenPasswd/FormType/UrlType.php | 508 | <?php
/**
* This file is part of the OpenPasswd package.
*
* (c) Simon Leblanc <contact@leblanc-simon.eu>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace OpenPasswd\FormType;
class UrlType
extends ASimpleType
implements FormTypeInterface
{
/**
* @return string The name of the form type (use in database for field)
*/
public function getName()
{
return 'url';
}
} | mit |
matslindh/codingchallenges | adventofcode2020/11.py | 4654 | import copy
def print_seats(seats):
for line in seats:
for char in line:
if char is None:
print('.', end='')
elif not char:
print('L', end='')
else:
print('#', end='')
print()
print("\n\n")
def seatplanner_flippityflipper(f):
seats = [[False if char == 'L' else None for char in line.strip()] for line in open(f)]
def flip_it():
output = copy.deepcopy(seats)
flipped = False
for y, row in enumerate(seats):
for x, spot in enumerate(row):
if spot is not None:
occ = count_occupied(x, y)
if spot and occ >= 4:
flipped = True
output[y][x] = False
elif not spot and occ == 0:
flipped = True
output[y][x] = True
return output, flipped
def count_occupied(x, y):
occupied = 0
for y_i in range(max(0, y - 1), min(y + 2, len(seats))):
for x_i in range(max(0, x - 1), min(x + 2, len(seats[y]))):
if y_i == y and x_i == x:
continue
occupied += seats[y_i][x_i] is True
return occupied
while True:
seats, flipped = flip_it()
if not flipped:
occupied = 0
for row in seats:
for spot in row:
if spot:
occupied += 1
return occupied
def seatplanner_flippityflipper_raytracer(f):
seats = [[False if char == 'L' else None for char in line.strip()] for line in open(f)]
def flip_it():
output = copy.deepcopy(seats)
occupied_table = occupied_seen_table(seats)
flipped = False
for y in range(0, len(seats)):
row = []
for x in range(0, len(seats[y])):
row.append([])
for y, row in enumerate(seats):
for x, spot in enumerate(row):
if spot is not None:
occ = occupied_table[y][x]
if spot and len(occ) >= 5:
flipped = True
output[y][x] = False
elif not spot and len(occ) == 0:
flipped = True
output[y][x] = True
return output, flipped
while True:
seats, flipped = flip_it()
if not flipped:
occupied = 0
for row in seats:
for spot in row:
if spot:
occupied += 1
return occupied
def occupied_seen_table(seats):
occupied_table = []
seen_table = []
for y in range(0, len(seats)):
row = []
row_seen = []
for x in range(0, len(seats[y])):
row.append([])
row_seen.append([])
occupied_table.append(row)
seen_table.append(row_seen)
def populate_table(x, y, x_d, y_d):
occ = False
seen_from = (0, 0)
while x >= 0 and y >= 0 and y < len(seats) and x < len(seats[0]):
if seats[y][x] is not None:
if occ and (x_d, y_d) not in occupied_table[y][x]:
occupied_table[y][x].append((x_d, y_d))
seen_table[y][x].append((seen_from, occ))
occ = seats[y][x]
seen_from = (x, y)
x += x_d
y += y_d
for y in range(0, len(seats)):
populate_table(0, y, 1, 0)
populate_table(0, y, 1, 1)
populate_table(0, y, -1, 1)
populate_table(0, y, 1, -1)
populate_table(len(seats[0]) - 1, y, -1, 0)
populate_table(len(seats[0]) - 1, y, -1, -1)
populate_table(len(seats[0]) - 1, y, -1, 1)
populate_table(len(seats[0]) - 1, y, 1, -1)
for x in range(0, len(seats[0])):
populate_table(x, 0, 0, 1)
populate_table(x, 0, 1, 1)
populate_table(x, 0, -1, 1)
populate_table(x, 0, 1, -1)
populate_table(x, len(seats) - 1, 0, -1)
populate_table(x, len(seats) - 1, -1, -1)
populate_table(x, len(seats) - 1, 1, -1)
populate_table(x, len(seats) - 1, -1, 1)
return occupied_table
def test_seatplanner_flippityflipper():
assert 37 == seatplanner_flippityflipper('input/11.test')
assert 26 == seatplanner_flippityflipper_raytracer('input/11.test')
if __name__ == '__main__':
print(seatplanner_flippityflipper('input/11'))
print(seatplanner_flippityflipper_raytracer('input/11'))
| mit |
deepdeev/nocrime-frontend | src/components/reported_selector.js | 805 | import React from 'react';
const ReportedSelector = (props) => (
<span >
<label>{props.title}</label>
<span >
{props.options.map(option => {
return (
<label key={option}>
<input className="space"
name={props.setName}
onChange={props.controlFunc}
value={option}
checked={props.selectedOptions.indexOf(option) > -1}
type={props.type} /> {option}
</label>
);
})}
</span>
</span>
);
ReportedSelector.propTypes = {
title: React.PropTypes.string.isRequired,
type: React.PropTypes.oneOf(['checkbox', 'radio']).isRequired,
setName: React.PropTypes.string.isRequired,
options: React.PropTypes.array.isRequired,
selectedOptions: React.PropTypes.array,
controlFunc: React.PropTypes.func.isRequired
};
export default ReportedSelector;
| mit |
mobeets/bpcs | bpcs/images2gif.py | 6292 | import numpy as np
import PIL
from PIL import Image, ImageChops
from PIL.GifImagePlugin import getheader, getdata
""" MODULE images2gif
Provides a function (writeGif) to write animated gif from a series
of PIL images or numpy arrays.
This code is provided as is, and is free to use for all.
Almar Klein (June 2009)
- based on gifmaker (in the scripts folder of the source distribution of PIL)
- based on gif file structure as provided by wikipedia
"""
# getheader gives a 87a header and a color palette (two elements in a list).
# getdata()[0] gives the Image Descriptor up to (including) "LZW min code size".
# getdatas()[1:] is the image data itself in chuncks of 256 bytes (well
# technically the first byte says how many bytes follow, after which that
# amount (max 255) follows).
def intToBin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int( i/256)
# make string (little endian)
return chr(i1) + chr(i2)
def getheaderAnim(im):
""" Animation header. To replace the getheader()[0] """
bb = "GIF89a"
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += "\x87\x00\x00"
return bb
def getAppExt(loops=0):
""" Application extention. Part that secifies amount of loops.
if loops is 0, if goes on infinitely.
"""
bb = "\x21\xFF\x0B" # application extension
bb += "NETSCAPE2.0"
bb += "\x03\x01"
if loops == 0:
loops = 2**16-1
bb += intToBin(loops)
bb += '\x00' # end
return bb
def getGraphicsControlExt(duration=0.1):
""" Graphics Control Extension. A sort of header at the start of
each image. Specifies transparancy and duration. """
bb = '\x21\xF9\x04'
bb += '\x08' # no transparancy
bb += intToBin( int(duration*100) ) # in 100th of seconds
bb += '\x00' # no transparant color
bb += '\x00' # end
return bb
def _writeGifToFile(fp, images, durations, loops):
""" Given a set of images writes the bytes to the specified stream.
"""
# init
frames = 0
previous = None
for im in images:
if not previous:
# first image
# gather data
palette = getheader(im)[1]
data = getdata(im)
imdes, data = data[0], data[1:]
header = getheaderAnim(im)
appext = getAppExt(loops)
graphext = getGraphicsControlExt(durations[0])
# write global header
fp.write(header)
fp.write(palette)
fp.write(appext)
# write image
fp.write(graphext)
fp.write(imdes)
for d in data:
fp.write(d)
else:
# gather info (compress difference)
data = getdata(im)
imdes, data = data[0], data[1:]
graphext = getGraphicsControlExt(durations[frames])
# write image
fp.write(graphext)
fp.write(imdes)
for d in data:
fp.write(d)
# # delta frame - does not seem to work
# delta = ImageChops.subtract_modulo(im, previous)
# bbox = delta.getbbox()
#
# if bbox:
#
# # gather info (compress difference)
# data = getdata(im.crop(bbox), offset = bbox[:2])
# imdes, data = data[0], data[1:]
# graphext = getGraphicsControlExt(durations[frames])
#
# # write image
# fp.write(graphext)
# fp.write(imdes)
# for d in data:
# fp.write(d)
#
# else:
# # FIXME: what should we do in this case?
# pass
# prepare for next round
previous = im.copy()
frames = frames + 1
fp.write(";") # end gif
return frames
def writeGif(filename, images, duration=0.1, loops=0, dither=1):
""" writeGif(filename, images, duration=0.1, loops=0, dither=1)
Write an animated gif from the specified images.
images should be a list of numpy arrays of PIL images.
Numpy images of type float should have pixels between 0 and 1.
Numpy images of other types are expected to have values between 0 and 255.
"""
if PIL is None:
raise RuntimeError("Need PIL to write animated gif files.")
images2 = []
# convert to PIL
for im in images:
if isinstance(im,Image.Image):
images2.append( im.convert('P', dither=dither) )
elif np and isinstance(im, np.ndarray):
if im.dtype == np.uint8:
pass
elif im.dtype in [np.float32, np.float64]:
im = (im*255).astype(np.uint8)
else:
im = im.astype(np.uint8)
# convert
if len(im.shape)==3 and im.shape[2]==3:
im = Image.fromarray(im,'RGB').convert('P', dither=dither)
elif len(im.shape)==2:
im = Image.fromarray(im,'L').convert('P', dither=dither)
else:
raise ValueError("Array has invalid shape to be an image.")
images2.append(im)
else:
raise ValueError("Unknown image type.")
# check duration
if hasattr(duration, '__len__'):
if len(duration) == len(images2):
durations = [d for d in duration]
else:
raise ValueError("len(duration) doesn't match amount of images.")
else:
durations = [duration for im in images2]
# open file
fp = open(filename, 'wb')
# write
try:
n = _writeGifToFile(fp, images2, durations, loops)
print n, 'frames written'
finally:
fp.close()
if __name__ == '__main__':
im = np.zeros((200,200), dtype=np.uint8)
im[10:30,:] = 100
im[:,80:120] = 255
im[-50:-40,:] = 50
images = [im*1.0, im*0.8, im*0.6, im*0.4, im*0]
writeGif('lala3.gif',images, duration=0.5, dither=0)
| mit |
empiricalstateofmind/personal_website | app/mod_home/controllers.py | 2646 | from flask import Blueprint, request, render_template, \
flash, g, session, redirect, url_for, Response, \
stream_with_context, config
import json
mod_home = Blueprint('home', __name__, static_folder='static')
@mod_home.context_processor
def inject_dict_for_all_templates():
return dict(project_list={'Mapping the Top 100 Climbs':'/projects/top-climbs.html',
'Sketches & Colourings':'/projects/sketches.html'})
@mod_home.route('/')
def index():
return render_template('/home/index.html')
@mod_home.route('vitae/')
def vitae():
with mod_home.open_resource('static/vitae.json') as w:
data = json.load(w)
publications = data['publications']
conferences = data['conferences']
reviewing = data['reviewing']
teaching = data['teaching']
return render_template('/home/vitae.html', publications=publications,
conferences=conferences,
reviewing=reviewing,
teaching=teaching)
@mod_home.route('research/')
def research():
with mod_home.open_resource('static/research.json') as w:
data = json.load(w)
topics = data['topics']
return render_template('/home/research.html', topics=topics)
@mod_home.route('data/', defaults={'data_slug': None})
@mod_home.route('data/<data_slug>.html')
def data(data_slug):
with mod_home.open_resource('static/data.json') as w:
data = json.load(w)
if data_slug is not None:
dataset_short, data_short = data_slug.split('-')[0], data_slug.split('-')[1:]
data_short = '-'.join(data_short)
dataset = [x for x in data if x['short_name']==dataset_short][0]
data = [x for x in dataset['data'] if x['short_name']==data_short][0]
return render_template('/home/data/data_entry.html', data=data)
else:
return render_template('/home/data.html', datasets=data)
@mod_home.route('projects/', defaults={'project_slug': None})
@mod_home.route('projects/<project_slug>.html')
def projects(project_slug):
if project_slug is None:
return render_template('/home/projects/projects.html')
else:
with mod_home.open_resource('static/projects.json') as w:
data = json.load(w)
return render_template('/home/projects/{}.html'.format(project_slug), data=data)
@mod_home.route('test/')
def test():
return render_template('/home/test.html')
| mit |
Chainsawkitten/UltimateGolf19XX | src/Editor/GUI/VerticalLayout.cpp | 1008 | #include "VerticalLayout.hpp"
#include <Core/Resources.hpp>
namespace GUI {
VerticalLayout::VerticalLayout(Widget* parent) : Container(parent) {
rectangle = Resources().CreateRectangle();
nextPosition = glm::vec2(0.f, 0.f);
}
VerticalLayout::~VerticalLayout() {
Resources().FreeRectangle();
}
void VerticalLayout::Render(const glm::vec2& screenSize) {
// Set color.
glm::vec3 color(0.06666666666f, 0.06274509803f, 0.08235294117f);
rectangle->Render(Position(), size, color, screenSize);
RenderWidgets(screenSize);
}
void VerticalLayout::AddWidget(Widget* widget) {
Container::AddWidget(widget);
widget->SetPosition(Position() + nextPosition);
nextPosition.y += widget->Size().y;
}
glm::vec2 VerticalLayout::Size() const {
return this->size;
}
void VerticalLayout::SetSize(const glm::vec2& size) {
this->size = size;
}
}
| mit |
shanonvl/aurelia-i18next | dist/amd/i18n.js | 5606 | define(['exports', 'i18next', './utils'], function (exports, _i18next, _utils) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _i18n = _interopRequireDefault(_i18next);
var I18N = (function () {
function I18N(ea) {
_classCallCheck(this, I18N);
this.i18next = _i18n['default'];
this.ea = ea;
this.Intl = window.Intl;
}
_createClass(I18N, [{
key: 'setup',
value: function setup(options) {
var defaultOptions = {
resGetPath: 'locale/__lng__/__ns__.json',
lng: 'en',
getAsync: false,
sendMissing: false,
attributes: ['t', 'i18n'],
fallbackLng: 'en',
debug: false
};
_i18n['default'].init(options || defaultOptions);
if (_i18n['default'].options.attributes instanceof String) {
_i18n['default'].options.attributes = [_i18n['default'].options.attributes];
}
}
}, {
key: 'setLocale',
value: function setLocale(locale) {
var _this = this;
return new Promise(function (resolve) {
var oldLocale = _this.getLocale();
_this.i18next.setLng(locale, function (tr) {
_this.ea.publish('i18n:locale:changed', { oldValue: oldLocale, newValue: locale });
resolve(tr);
});
});
}
}, {
key: 'getLocale',
value: function getLocale() {
return this.i18next.lng();
}
}, {
key: 'nf',
value: function nf(options, locales) {
return new this.Intl.NumberFormat(locales || this.getLocale(), options);
}
}, {
key: 'df',
value: function df(options, locales) {
return new this.Intl.DateTimeFormat(locales || this.getLocale(), options);
}
}, {
key: 'tr',
value: function tr(key, options) {
return this.i18next.t(key, (0, _utils.assignObjectToKeys)('', options));
}
}, {
key: 'updateTranslations',
value: function updateTranslations(el) {
var i, l;
var selector = [].concat(this.i18next.options.attributes);
for (i = 0, l = selector.length; i < l; i++) selector[i] = '[' + selector[i] + ']';
selector = selector.join(',');
var nodes = el.querySelectorAll(selector);
for (i = 0, l = nodes.length; i < l; i++) {
var node = nodes[i];
var keys;
for (var i2 = 0, l2 = this.i18next.options.attributes.length; i2 < l2; i2++) {
keys = node.getAttribute(this.i18next.options.attributes[i2]);
if (keys) break;
}
if (!keys) continue;
keys = keys.split(';');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
var re = /\[([a-z]*)\]/g;
var m;
var attr = 'text';
if (node.nodeName == 'IMG') attr = 'src';
while ((m = re.exec(key)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
if (m) {
key = key.replace(m[0], '');
attr = m[1];
}
}
if (!node._textContent) node._textContent = node.textContent;
if (!node._innerHTML) node._innerHTML = node.innerHTML;
switch (attr) {
case 'text':
node.textContent = this.tr(key);
break;
case 'prepend':
node.innerHTML = this.tr(key) + node._innerHTML.trim();
break;
case 'append':
node.innerHTML = node._innerHTML.trim() + this.tr(key);
break;
case 'html':
node.innerHTML = this.tr(key);
break;
default:
node.setAttribute(attr, this.tr(key));
break;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
}
}]);
return I18N;
})();
exports.I18N = I18N;
}); | mit |
henrysun918/jasmine-mock-factory | dist/index.d.ts | 670 | /// <reference types="jasmine" />
export declare type Mock<T> = T & SpyFacade<T>;
export interface SpyFacade<T> {
_spy: Spied<T> & SpiedAny;
}
export declare type Spied<T> = {
[K in keyof T]: SpiedMember;
};
export interface SpiedAny {
[id: string]: SpiedMember;
}
export interface SpiedMember {
_func: jasmine.Spy;
_get: jasmine.Spy;
_set: jasmine.Spy;
}
interface Type<T> extends Function {
new (...args: any[]): T;
}
export declare class MockFactory {
/**
* create a mock object that has the identical interface as the class you passed in
*/
static create<T extends object>(blueprint: Type<T> | T): Mock<T>;
}
export {};
| mit |
bencallis1/meanMaterial | modules/core/client/app/init.js | 1764 | 'use strict';
//Start by defining the main module and adding the module dependencies
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// Setting HTML5 Location Mode
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$mdThemingProvider', '$mdIconProvider',
function($locationProvider, $mdThemingProvider, $mdIconProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
$mdThemingProvider.theme('default')
.primaryPalette('blue', {
'default':'700'
})
.accentPalette('purple', {
'default': '400'
});
// Register the user `avatar` icons
$mdIconProvider
.defaultIconSet('./assets/svg/avatars.svg', 128 )
.icon('cake' , './assets/svg/cake.svg' , 24)
.icon('mail' , './assets/svg/mail.svg' , 24)
.icon('menu' , './assets/svg/menu.svg' , 24)
.icon('share' , './assets/svg/share.svg' , 24)
.icon('google_plus', './assets/svg/google_plus.svg' , 512)
.icon('hangouts' , './assets/svg/hangouts.svg' , 512)
.icon('twitter' , './assets/svg/twitter.svg' , 512)
.icon('phone' , './assets/svg/phone.svg' , 512);
}
]);
//Then define the init function for starting up the application
angular.element(document).ready(function() {
//Fixing facebook bug with redirect
if (window.location.hash === '#_=_') window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
| mit |
mrkva/Dump.js | client.js | 14901 | var CONFIG = { debug: false
, nick: "#" // set in onConnect
, id: null // set in onConnect
, last_message_time: 1
, focus: true //event listeners bound in onConnect
, unread: 0 //updated in the message-processing loop
};
var nicks = [];
// CUT ///////////////////////////////////////////////////////////////////
/* This license and copyright apply to all code until the next "CUT"
http://github.com/jherdman/javascript-relative-time-helpers/
The MIT License
Copyright (c) 2009 James F. Herdman
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.
* Returns a description of this past date in relative terms.
* Takes an optional parameter (default: 0) setting the threshold in ms which
* is considered "Just now".
*
* Examples, where new Date().toString() == "Mon Nov 23 2009 17:36:51 GMT-0500 (EST)":
*
* new Date().toRelativeTime()
* --> 'Just now'
*
* new Date("Nov 21, 2009").toRelativeTime()
* --> '2 days ago'
*
* // One second ago
* new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime()
* --> '1 second ago'
*
* // One second ago, now setting a now_threshold to 5 seconds
* new Date("Nov 23 2009 17:36:50 GMT-0500 (EST)").toRelativeTime(5000)
* --> 'Just now'
*
*/
Date.prototype.toRelativeTime = function(now_threshold) {
var delta = new Date() - this;
now_threshold = parseInt(now_threshold, 10);
if (isNaN(now_threshold)) {
now_threshold = 0;
}
if (delta <= now_threshold) {
return 'Just now';
}
var units = null;
var conversions = {
millisecond: 1, // ms -> ms
second: 1000, // ms -> sec
minute: 60, // sec -> min
hour: 60, // min -> hour
day: 24, // hour -> day
month: 30, // day -> month (roughly)
year: 12 // month -> year
};
for (var key in conversions) {
if (delta < conversions[key]) {
break;
} else {
units = key; // keeps track of the selected key over the iteration
delta = delta / conversions[key];
}
}
// pluralize a unit when the difference is greater than 1.
delta = Math.floor(delta);
if (delta !== 1) { units += "s"; }
return [delta, units].join(" ");
};
/*
* Wraps up a common pattern used with this plugin whereby you take a String
* representation of a Date, and want back a date object.
*/
Date.fromString = function(str) {
return new Date(Date.parse(str));
};
// CUT ///////////////////////////////////////////////////////////////////
//updates the users link to reflect the number of active users
function updateUsersLink ( ) {
var t = nicks.length.toString() + " user";
if (nicks.length != 1) t += "s";
$("#usersLink").text(t);
}
//handles another person joining chat
function userJoin(nick, timestamp) {
//put it in the stream
addMessage(nick, "joined", timestamp, "join");
//if we already know about this user, ignore it
for (var i = 0; i < nicks.length; i++)
if (nicks[i] == nick) return;
//otherwise, add the user to the list
nicks.push(nick);
//update the UI
updateUsersLink();
}
//handles someone leaving
function userPart(nick, timestamp) {
//put it in the stream
addMessage(nick, "left", timestamp, "part");
//remove the user from the list
for (var i = 0; i < nicks.length; i++) {
if (nicks[i] == nick) {
nicks.splice(i,1)
break;
}
}
//update the UI
updateUsersLink();
}
// utility functions
util = {
urlRE: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)?/g,
imgRe: /https?:\/\/([-\w\.]+)+(:\d+)?(\/([^\s]*(\?\S+)?)?)? /g,
// html sanitizer
toStaticHTML: function(inputHtml) {
inputHtml = inputHtml.toString();
return inputHtml.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
},
//pads n with zeros on the left,
//digits is minimum length of output
//zeroPad(3, 5); returns "005"
//zeroPad(2, 500); returns "500"
zeroPad: function (digits, n) {
n = n.toString();
while (n.length < digits)
n = '0' + n;
return n;
},
//it is almost 8 o'clock PM here
//timeString(new Date); returns "19:49"
timeString: function (date) {
var minutes = date.getMinutes().toString();
var hours = date.getHours().toString();
return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
},
//does the argument only contain whitespace?
isBlank: function(text) {
var blank = /^\s*$/;
return (text.match(blank) !== null);
}
};
//used to keep the most recent messages visible
function scrollDown () {
window.scrollBy(0, 100000000000000000);
$("#entry").focus();
}
//inserts an event into the stream for display
//the event may be a msg, join or part type
//from is the user, text is the body and time is the timestamp, defaulting to now
//_class is a css class to apply to the message, usefull for system events
function addMessage (from, text, time, _class) {
if (text === null)
return;
if (time == null) {
// if the time is null or undefined, use the current time.
time = new Date();
} else if ((time instanceof Date) === false) {
// if it's a timestamp, interpret it
time = new Date(time);
}
//every message you see is actually a table with 3 cols:
// the time,
// the person who caused the event,
// and the content
var messageElement = $(document.createElement("table"));
messageElement.cellSpacing="0";
messageElement.cellPadding="0";
messageElement.border="0";
messageElement.addClass("message");
if (_class)
messageElement.addClass(_class);
// sanitize
text = util.toStaticHTML(text);
// If the current user said this, add a special css class
var nick_re = new RegExp(CONFIG.nick);
if (nick_re.exec(text))
messageElement.addClass("personal");
// replace URLs with links & parse images
if (text.match(".(?:jpg|gif|png|jpeg)")) {
text = text.replace(util.urlRE, '<a href="$&" target="_blank"><img style="display: inline; max-height: 200px; max-width:300px;" src="$&" /></a>');
text = text.replace(/<\/a>\s+<a/g, "</a><a");
} else {
text = text.replace(util.urlRE, '<a target="_blank" href="$&">$&</a>');
}
var content = '<tr>'
+ ' <td class="date">' + util.timeString(time) + '</td>'
+ ' <td class="nick">' + util.toStaticHTML(from) + '</td>'
+ ' <td class="msg-text">' + text + '</td>'
+ '</tr>'
;
messageElement.html(content);
//the log is the stream that we view
$("#log").append(messageElement);
//always view the most recent message when it is added
scrollDown();
}
function updateRSS () {
var bytes = parseInt(rss);
if (bytes) {
var megabytes = bytes / (1024*1024);
megabytes = Math.round(megabytes*10)/10;
$("#rss").text(megabytes.toString());
}
}
function updateUptime () {
if (starttime) {
$("#uptime").text(starttime.toRelativeTime());
}
}
var transmission_errors = 0;
var first_poll = true;
//process updates if we have any, request updates from the server,
// and call again with response. the last part is like recursion except the call
// is being made from the response handler, and not at some point during the
// function's execution.
function longPoll (data) {
if (transmission_errors > 2) {
showConnect();
return;
}
if (data && data.rss) {
rss = data.rss;
updateRSS();
}
//process any updates we may have
//data will be null on the first call of longPoll
if (data && data.messages) {
for (var i = 0; i < data.messages.length; i++) {
var message = data.messages[i];
//track oldest message so we only request newer messages from server
if (message.timestamp > CONFIG.last_message_time)
CONFIG.last_message_time = message.timestamp;
//dispatch new messages to their appropriate handlers
switch (message.type) {
case "msg":
if(!CONFIG.focus){
CONFIG.unread++;
}
addMessage(message.nick, message.text, message.timestamp);
break;
case "join":
userJoin(message.nick, message.timestamp);
break;
case "part":
userPart(message.nick, message.timestamp);
break;
}
}
//update the document title to include unread message count if blurred
updateTitle();
//only after the first request for messages do we want to show who is here
if (first_poll) {
first_poll = false;
who();
}
}
//make another request
$.ajax({ cache: false
, type: "GET"
, url: "/recv"
, dataType: "json"
, data: { since: CONFIG.last_message_time, id: CONFIG.id }
, error: function () {
addMessage("", "long poll error. trying again...", new Date(), "error");
transmission_errors += 1;
//don't flood the servers on error, wait 10 seconds before retrying
setTimeout(longPoll, 10*1000);
}
, success: function (data) {
transmission_errors = 0;
//if everything went well, begin another request immediately
//the server will take a long time to respond
//how long? well, it will wait until there is another message
//and then it will return it to us and close the connection.
//since the connection is closed when we get data, we longPoll again
longPoll(data);
}
});
}
//submit a new message to the server
function send(msg) {
if (CONFIG.debug === false) {
// XXX should be POST
// XXX should add to messages immediately
jQuery.get("/send", {id: CONFIG.id, text: msg}, function (data) { }, "json");
}
}
//Transition the page to the state that prompts the user for a nickname
function showConnect () {
$("#connect").show();
$("#loading").hide();
$("#toolbar").hide();
$("#nickInput").focus();
}
//transition the page to the loading screen
function showLoad () {
$("#connect").hide();
$("#loading").show();
$("#toolbar").hide();
}
//transition the page to the main chat view, putting the cursor in the textfield
function showChat (nick) {
$("#toolbar").show();
$("#entry").focus();
$("#connect").hide();
$("#loading").hide();
scrollDown();
}
//we want to show a count of unread messages when the window does not have focus
function updateTitle(){
if (CONFIG.unread) {
document.title = CONFIG.unread.toString() + "!! NEW DUMPZ @ DUMP.TLIS.SK";
} else {
document.title = "DUMP.TLIS.SK";
}
}
// daemon start time
var starttime;
// daemon memory usage
var rss;
//handle the server's response to our nickname and join request
function onConnect (session) {
if (session.error) {
alert("error connecting: " + session.error);
showConnect();
return;
}
CONFIG.nick = session.nick;
CONFIG.id = session.id;
starttime = new Date(session.starttime);
rss = session.rss;
updateRSS();
updateUptime();
//update the UI to show the chat
showChat(CONFIG.nick);
//listen for browser events so we know to update the document title
$(window).bind("blur", function() {
CONFIG.focus = false;
updateTitle();
});
$(window).bind("focus", function() {
CONFIG.focus = true;
CONFIG.unread = 0;
updateTitle();
});
}
//add a list of present chat members to the stream
function outputUsers () {
var nick_string = nicks.length > 0 ? nicks.join(", ") : "(none)";
addMessage("users:", nick_string, new Date(), "notice");
return false;
}
//get a list of the users presently in the room, and add it to the stream
function who () {
jQuery.get("/who", {}, function (data, status) {
if (status != "success") return;
nicks = data.nicks;
outputUsers();
}, "json");
}
$(document).ready(function() {
//submit new messages when the user hits enter if the message isnt blank
$("#entry").keypress(function (e) {
if (e.keyCode != 13 /* Return */) return;
var msg = $("#entry").attr("value").replace("\n", "");
if (!util.isBlank(msg)) send(msg);
$("#entry").attr("value", ""); // clear the entry field.
});
$("#usersLink").click(outputUsers);
//try joining the chat when the user clicks the connect button
$("#connectButton").click(function () {
//lock the UI while waiting for a response
showLoad();
var nick = $("#nickInput").attr("value");
//dont bother the backend if we fail easy validations
if (nick.length > 50) {
alert("Nick too long. 50 character max.");
showConnect();
return false;
}
//more validations
if (/[^\w_\-^!]/.exec(nick)) {
alert("Bad character in nick. Can only have letters, numbers, and '_', '-', '^', '!'");
showConnect();
return false;
}
//make the actual join request to the server
$.ajax({ cache: false
, type: "GET" // XXX should be POST
, dataType: "json"
, url: "/join"
, data: { nick: nick }
, error: function () {
alert("error connecting to server");
showConnect();
}
, success: onConnect
});
return false;
});
// update the daemon uptime every 10 seconds
setInterval(function () {
updateUptime();
}, 10*1000);
if (CONFIG.debug) {
$("#loading").hide();
$("#connect").hide();
scrollDown();
return;
}
// remove fixtures
$("#log table").remove();
//begin listening for updates right away
//interestingly, we don't need to join a room to get its updates
//we just don't show the chat stream to the user until we create a session
longPoll();
showConnect();
});
//if we can, notify the server that we're going away.
$(window).unload(function () {
jQuery.get("/part", {id: CONFIG.id}, function (data) { }, "json");
});
| mit |
ara-ta3/node-quest | src/game/model/effect/FeedbackResult.js | 407 | export default class FeedbackResult {
damaged: number
cured: number
mindDamaged: number
mindCured: number
constructor(
damaged: number,
cured: number,
mindDamaged:number,
mindCured:number) {
this.damaged = damaged || 0;
this.cured = cured || 0;
this.mindDamaged = mindDamaged || 0;
this.mindCured = mindCured || 0;
}
}
| mit |
pilu/abramo | lib/abramo/command.js | 1012 | var dumper = require('./dumper'),
debug = require('./debug');
var commands = {
"dump" : "dump"
};
var Command = exports.Command = function(config, store, startCallback) {
this.config = config;
this.store = store;
this.startCallback = startCallback;
};
Command.prototype.hasCommand = function(command) {
return commands[command] !== undefined;
};
Command.prototype.execute = function(command) {
var commandName = commands[command];
if (commandName) {
this[commandName]();
return true;
} else {
return false;
}
};
Command.prototype.dump = function() {
var d = new dumper.Dumper(this.config, this.store);
d.dump(this.commandStartCallback.bind(this), this.commandEndCallback.bind(this));
};
Command.prototype.commandStartCallback = function(err, message) {
debug.debug(err ? err : message);
this.startCallback(err, message);
};
Command.prototype.commandEndCallback = function(err, message) {
debug.debug(err ? err : message);
}; | mit |
gquintana/beepbeep | src/main/java/com/github/gquintana/beepbeep/http/BasicHttpClientProvider.java | 2966 | package com.github.gquintana.beepbeep.http;
import com.github.gquintana.beepbeep.BeepBeepException;
import com.github.gquintana.beepbeep.util.Strings;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class BasicHttpClientProvider implements HttpClientProvider {
private String url;
private String basePath;
private String username;
private String password;
private HttpHost httpHost;
public BasicHttpClientProvider() {
}
public BasicHttpClientProvider(String url) {
setUrl(url);
}
protected CredentialsProvider getCredentialsProvider() {
if (Strings.isNullOrEmpty(username)) {
return null;
}
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
return credentialsProvider;
}
@Override
public CloseableHttpClient getHttpClient() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CredentialsProvider credentialsProvider = getCredentialsProvider();
if (credentialsProvider != null) {
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
return httpClientBuilder.build();
}
@Override
public HttpHost getHttpHost() {
return httpHost;
}
@Override
public String getBasePath() {
return basePath;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
try {
URL url1 = new URL(url);
String scheme = url1.getProtocol();
String host = url1.getHost();
int port = url1.getPort() < 0 ? url1.getDefaultPort() : url1.getPort();
basePath = url1.getPath();
if (basePath.endsWith("/")) {
this.basePath = Strings.left(basePath, basePath.length() - 1);
}
httpHost = new HttpHost(host, port, scheme);
this.url = url;
} catch (MalformedURLException e) {
throw new BeepBeepException("Invalid HTTP URL " + url, e);
}
}
@Override
public void close() throws IOException {
}
}
| mit |
lasiproject/LASI | LASI.Core/LexicalStructures/UnderpinningTypes/IAggregateLexical.cs | 791 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LASI.Core
{
/// <summary>
/// Defines the requirements for a Lexical type which is simultaneously a single element and a composition of other Lexical elements.
/// </summary>
/// <typeparam name="TLexical">The type Lexical elements of which the IAggregateLexical implementation is composed.
/// This can be any Type which implements the ILexical interface.
/// This type parameter is covariant. That is,
/// you can use either the type you specified or any type that is more derived.
/// </typeparam>
public interface IAggregateLexical<out TLexical> : ILexical, IEnumerable<TLexical> where TLexical : ILexical
{
}
}
| mit |
luguanxing/Data-Structures-and-Algorithms | Homework/project04-中东地图导航/East Campus Guide/East Campus Guide/DLG_ZHENGMEN.cpp | 2622 | // DLG_ZHENGMEN.cpp : ʵÏÖÎļþ
//
#include "stdafx.h"
#include "East Campus Guide.h"
#include "DLG_ZHENGMEN.h"
#include "afxdialogex.h"
extern int start, end;
// DLG_ZHENGMEN ¶Ô»°¿ò
IMPLEMENT_DYNAMIC(DLG_ZHENGMEN, CDialogEx)
DLG_ZHENGMEN::DLG_ZHENGMEN(CWnd* pParent /*=NULL*/)
: CDialogEx(DLG_ZHENGMEN::IDD, pParent)
{
}
DLG_ZHENGMEN::~DLG_ZHENGMEN()
{
}
void DLG_ZHENGMEN::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(DLG_ZHENGMEN, CDialogEx)
ON_WM_PAINT()
// ON_WM_CREATE()
ON_WM_SHOWWINDOW()
ON_WM_CLOSE()
ON_BN_CLICKED(IDC_BUTTON_CLOSE, &DLG_ZHENGMEN::OnBnClickedButtonClose)
//ON_BN_CLICKED(IDOK, &DLG_ZHENGMEN::OnBnClickedOk)
//ON_BN_CLICKED(IDCANCEL, &DLG_ZHENGMEN::OnBnClickedCancel)
ON_BN_CLICKED(ID_START, &DLG_ZHENGMEN::OnBnClickedStart)
ON_BN_CLICKED(ID_END, &DLG_ZHENGMEN::OnBnClickedEnd)
END_MESSAGE_MAP()
// DLG_ZHENGMEN ÏûÏ¢´¦Àí³ÌÐò
void DLG_ZHENGMEN::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: ÔÚ´Ë´¦Ìí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂë
// ²»Îª»æÍ¼ÏûÏ¢µ÷Óà CDialogEx::OnPaint()
CBitmap mybitmap;
mybitmap.LoadBitmap(IDB_BITMAP_ZHENGMEN); //ÔØÈë×ÊÔ´ÀïµÄλͼ
CDC *pdc=GetDC();
CDC bmp;
bmp.CreateCompatibleDC(pdc); //´´½¨Ò»¸ö¼æÈÝpdcµÄÉ豸ÉÏÏÂÎÄ
bmp.SelectObject(&mybitmap); //Ìæ»»É豸»·¾³Î»Í¼
pdc->BitBlt(0,0,400,270,&bmp,0,0,SRCCOPY); //¸´ÖÆÎ»Í¼ÖÁpdc Ò²¾ÍÊÇÖ÷´°¿Ú
mybitmap.DeleteObject();//Êͷŵô¶ÔÏó
ReleaseDC(pdc); //ÊͷŵôÉ豸ÉÏÏÂÎÄ
ReleaseDC(&bmp); //ÊͷŵôÉ豸ÉÏÏÂÎÄ
CDialogEx::OnPaint();
}
//int DLG_ZHENGMEN::OnCreate(LPCREATESTRUCT lpCreateStruct)
//{
// if (CDialogEx::OnCreate(lpCreateStruct) == -1)
// return -1;
//
// // TODO: ÔÚ´ËÌí¼ÓÄúרÓõĴ´½¨´úÂë
//
// return 0;
//}
void DLG_ZHENGMEN::OnShowWindow(BOOL bShow, UINT nStatus)
{
AnimateWindow(200, AW_CENTER); //´°¿ÚµÈë
OnPaint();
CDialogEx::OnShowWindow(bShow, nStatus);
// TODO: ÔÚ´Ë´¦Ìí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂë
}
void DLG_ZHENGMEN::OnClose()
{
// TODO: ÔÚ´ËÌí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂëºÍ/»òµ÷ÓÃĬÈÏÖµ
::AnimateWindow(GetSafeHwnd(), 300, AW_BLEND | AW_HIDE); //µ³ö1Ãë
CDialogEx::OnClose();
}
void DLG_ZHENGMEN::OnBnClickedButtonClose()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
OnClose();
}
void DLG_ZHENGMEN::OnBnClickedStart()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
start = 0;
::MessageBox(NULL, _T("ÆðµãÉèÖÃΪ:ÕýÃÅ"), _T("ÉèÖÃ"), MB_ICONINFORMATION);
}
void DLG_ZHENGMEN::OnBnClickedEnd()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
end = 0;
::MessageBox(NULL, _T("ÖÕµãÉèÖÃΪ:ÕýÃÅ"), _T("ÉèÖÃ"), MB_ICONINFORMATION);
}
| mit |
pjeweb/grunt-iehint | tasks/iehint.js | 1412 | /*
* grunt-iehint
* https://github.com/pjeweb/grunt-iehint
*
* Copyright (c) 2014 Paul Golmann
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('iehint', 'Test common mistakes that break in IE.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
| mit |
bing-ads-sdk/BingAds-Java-SDK | proxies/com/microsoft/bingads/v12/campaignmanagement/GetAdExtensionsEditorialReasonsResponse.java | 2702 |
package com.microsoft.bingads.v12.campaignmanagement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="EditorialReasons" type="{https://bingads.microsoft.com/CampaignManagement/v12}ArrayOfAdExtensionEditorialReasonCollection" minOccurs="0"/>
* <element name="PartialErrors" type="{https://bingads.microsoft.com/CampaignManagement/v12}ArrayOfBatchError" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"editorialReasons",
"partialErrors"
})
@XmlRootElement(name = "GetAdExtensionsEditorialReasonsResponse")
public class GetAdExtensionsEditorialReasonsResponse {
@XmlElement(name = "EditorialReasons", nillable = true)
protected ArrayOfAdExtensionEditorialReasonCollection editorialReasons;
@XmlElement(name = "PartialErrors", nillable = true)
protected ArrayOfBatchError partialErrors;
/**
* Gets the value of the editorialReasons property.
*
* @return
* possible object is
* {@link ArrayOfAdExtensionEditorialReasonCollection }
*
*/
public ArrayOfAdExtensionEditorialReasonCollection getEditorialReasons() {
return editorialReasons;
}
/**
* Sets the value of the editorialReasons property.
*
* @param value
* allowed object is
* {@link ArrayOfAdExtensionEditorialReasonCollection }
*
*/
public void setEditorialReasons(ArrayOfAdExtensionEditorialReasonCollection value) {
this.editorialReasons = value;
}
/**
* Gets the value of the partialErrors property.
*
* @return
* possible object is
* {@link ArrayOfBatchError }
*
*/
public ArrayOfBatchError getPartialErrors() {
return partialErrors;
}
/**
* Sets the value of the partialErrors property.
*
* @param value
* allowed object is
* {@link ArrayOfBatchError }
*
*/
public void setPartialErrors(ArrayOfBatchError value) {
this.partialErrors = value;
}
}
| mit |
objectmastery/stylelint-plugin | src/com/stylelint/StyleLintExternalAnnotator.java | 10423 | package com.stylelint;
import com.intellij.codeInsight.daemon.HighlightDisplayKey;
import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.ExternalAnnotator;
import com.intellij.lang.annotation.HighlightSeverity;
import com.intellij.lang.javascript.linter.JSLinterUtil;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.css.CssFile;
import com.intellij.psi.css.CssFileType;
import com.stylelint.annotator.ExternalLintAnnotationInput;
import com.stylelint.annotator.ExternalLintAnnotationResult;
import com.stylelint.config.StyleLintConfigFileListener;
import com.stylelint.fixes.SuppressFileActionFix;
import com.stylelint.fixes.SuppressLineActionFix;
import com.stylelint.utils.ActualFile;
import com.stylelint.utils.FileUtils;
import com.stylelint.utils.PsiUtil;
import com.stylelint.utils.Result;
import com.stylelint.utils.StyleLintRunner;
import com.stylelint.utils.ThreadLocalActualFile;
import com.stylelint.utils.WarningMessage;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
public class StyleLintExternalAnnotator extends ExternalAnnotator<ExternalLintAnnotationInput, ExternalLintAnnotationResult<Result>> {
private static final Logger LOG = Logger.getInstance(StyleLintBundle.LOG_ID);
private static final String MESSAGE_PREFIX = "StyleLint: ";
private static final Key<ThreadLocalActualFile> STYLELINT_TEMP_FILE_KEY = Key.create("STYLELINT_TEMP_FILE");
@Nullable
@Override
public ExternalLintAnnotationInput collectInformation(@NotNull PsiFile file) {
return collectInformation(file, null);
}
@Nullable
@Override
public ExternalLintAnnotationInput collectInformation(@NotNull PsiFile file, @NotNull Editor editor, boolean hasErrors) {
return collectInformation(file, editor);
}
@NotNull
private static HighlightDisplayKey getHighlightDisplayKeyByClass() {
String id = "StyleLint";
HighlightDisplayKey key = HighlightDisplayKey.find(id);
if (key == null) {
key = new HighlightDisplayKey(id, id);
}
return key;
}
@Override
public void apply(@NotNull PsiFile file, ExternalLintAnnotationResult<Result> annotationResult, @NotNull AnnotationHolder holder) {
if (annotationResult == null) {
return;
}
InspectionProjectProfileManager inspectionProjectProfileManager = InspectionProjectProfileManager.getInstance(file.getProject());
SeverityRegistrar severityRegistrar = inspectionProjectProfileManager.getSeverityRegistrar();
HighlightDisplayKey inspectionKey = getHighlightDisplayKeyByClass();
EditorColorsScheme colorsScheme = annotationResult.input.colorsScheme;
Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
if (document == null) {
return;
}
StyleLintProjectComponent component = annotationResult.input.project.getComponent(StyleLintProjectComponent.class);
for (WarningMessage warn : annotationResult.result.warns) {
HighlightSeverity severity = getHighlightSeverity(warn, component.treatAsWarnings);
TextAttributes forcedTextAttributes = JSLinterUtil.getTextAttributes(colorsScheme, severityRegistrar, severity);
Annotation annotation = createAnnotation(holder, file, document, warn, severity, forcedTextAttributes, false);
if (annotation != null) {
int offset = StringUtil.lineColToOffset(document.getText(), warn.line - 1, warn.column);
PsiElement lit = PsiUtil.getElementAtOffset(file, offset);
//TODO: fix these - currently still trying to browse a JS AST rather than a CSS AST
annotation.registerFix(new SuppressLineActionFix(warn.rule, lit), null, inspectionKey);
annotation.registerFix(new SuppressFileActionFix(warn.rule, lit), null, inspectionKey);
}
}
}
private static HighlightSeverity getHighlightSeverity(WarningMessage warn, boolean treatAsWarnings) {
if (treatAsWarnings) {
return HighlightSeverity.WARNING;
}
return "error".equals(warn.severity) ? HighlightSeverity.ERROR : HighlightSeverity.WARNING;
}
@Nullable
private static Annotation createAnnotation(@NotNull AnnotationHolder holder, @NotNull PsiFile file, @NotNull Document document, @NotNull WarningMessage warn,
@NotNull HighlightSeverity severity, @Nullable TextAttributes forcedTextAttributes,
boolean showErrorOnWholeLine) {
int line = warn.line - 1;
int column = warn.column - 1;
if (line < 0 || line >= document.getLineCount()) {
return null;
}
int lineEndOffset = document.getLineEndOffset(line);
int lineStartOffset = document.getLineStartOffset(line);
int errorLineStartOffset = StringUtil.lineColToOffset(document.getCharsSequence(), line, column);
if (errorLineStartOffset == -1) {
return null;
}
TextRange range;
if (showErrorOnWholeLine) {
range = new TextRange(lineStartOffset, lineEndOffset);
} else {
PsiElement lit = PsiUtil.getElementAtOffset(file, errorLineStartOffset);
range = lit.getTextRange();
}
Annotation annotation = JSLinterUtil.createAnnotation(
holder,
severity,
forcedTextAttributes,
range,
MESSAGE_PREFIX + warn.text + " (" + warn.rule + ")"
);
if (annotation != null) {
annotation.setAfterEndOfLine(errorLineStartOffset == lineEndOffset);
}
return annotation;
}
@Nullable
private static ExternalLintAnnotationInput collectInformation(@NotNull PsiFile psiFile, @Nullable Editor editor) {
if (psiFile.getContext() != null) {
return null;
}
VirtualFile virtualFile = psiFile.getVirtualFile();
if (virtualFile == null || !virtualFile.isInLocalFileSystem()) {
return null;
}
if (psiFile.getViewProvider() instanceof MultiplePsiFilesPerDocumentFileViewProvider) {
return null;
}
Project project = psiFile.getProject();
StyleLintProjectComponent component = project.getComponent(StyleLintProjectComponent.class);
if (!component.isSettingsValid() || !component.isEnabled() || !isCSSFile(psiFile)) {
return null;
}
Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
if (document == null) {
return null;
}
String fileContent = document.getText();
if (StringUtil.isEmptyOrSpaces(fileContent)) {
return null;
}
EditorColorsScheme colorsScheme = editor == null ? null : editor.getColorsScheme();
return new ExternalLintAnnotationInput(project, psiFile, fileContent, colorsScheme);
}
private static boolean isCSSFile(PsiFile file) {
return file instanceof CssFile && file.getFileType().equals(CssFileType.INSTANCE);
}
@Nullable
@Override
public ExternalLintAnnotationResult<Result> doAnnotate(ExternalLintAnnotationInput collectedInfo) {
try {
LOG.info("Running StyleLint inspection");
PsiFile file = collectedInfo.psiFile;
Project project = file.getProject();
StyleLintProjectComponent component = project.getComponent(StyleLintProjectComponent.class);
if (!component.isSettingsValid() || !component.isEnabled() || !isCSSFile(file)) {
return null;
}
StyleLintConfigFileListener.start(collectedInfo.project);
String relativeFile;
ActualFile actualCodeFile = ActualFile.getOrCreateActualFile(STYLELINT_TEMP_FILE_KEY, file.getVirtualFile(), collectedInfo.fileContent);
if (actualCodeFile == null || actualCodeFile.getFile() == null) {
return null;
}
relativeFile = FileUtils.makeRelative(new File(project.getBasePath()), actualCodeFile.getActualFile());
Result result = StyleLintRunner.lint(project.getBasePath(), relativeFile, component.nodeInterpreter, component.stylelintExecutable, component.stylelintRcFile);
actualCodeFile.deleteTemp();
if (StringUtils.isNotEmpty(result.errorOutput)) {
component.showInfoNotification(result.errorOutput, NotificationType.WARNING);
return null;
}
Document document = PsiDocumentManager.getInstance(project).getDocument(file);
if (document == null) {
component.showInfoNotification("Error running StyleLint inspection: Could not get document for file " + file.getName(), NotificationType.WARNING);
LOG.error("Could not get document for file " + file.getName());
return null;
}
return new ExternalLintAnnotationResult<>(collectedInfo, result);
} catch (Exception e) {
LOG.error("Error running StyleLint inspection: ", e);
StyleLintProjectComponent.showNotification("Error running StyleLint inspection: " + e.getMessage(), NotificationType.ERROR);
}
return null;
}
} | mit |
junctiontech/sbk | frontend/js/sb4k.js | 2578 | if(window.location.hostname=="localhost"){
var base_url = 'http://localhost/sbk/';
}
if(window.location.hostname=="searchb4kharch.com"){
var base_url = 'http://searchb4kharch.com/';
}
if(window.location.hostname=="www.searchb4kharch.com"){
var base_url = 'http://www.searchb4kharch.com/';
}
if(window.location.hostname=="192.168.1.151"){
var base_url = 'http://192.168.1.151/sbk/';
}
function compare_product(productid)
{
var count=0;
var productid=[];
$(".chkcount").each(function() {
if($(this).prop('checked') == true){
count=count+1;
productid.push(this.value);
}
});
var pro_id=productid;
if ( pro_id !=='')
{
$.ajax({
type: "POST",
data:{ productid : pro_id },
url: base_url+'Landingpage/fetchdata_compare_product',
cache: false,
success: function(s)
{
if(count>=1)
{
document.getElementById("compare").style.display = "block";
$("#productName").html(s);
}
else
{
document.getElementById("compare").style.display = "none";
}
}
});
}return false;
}
function bodyload (){
$("#body").attr("style", "");
}
function submit_compare(productid)
{
var count=0;
$(".chkcount").each(function() {
if($(this).prop('checked') == true){
count=count+1;
}
});
if(count>=5){
alert('checked product should not more than 4');
return false;
}
else if(count>=2)
{
return true;
}
else if(count==1){
alert('please checked atleast two product');
return false;
}
}
function Match_email(){
var email = document.getElementById("Email").value;
var big=false;
$.ajax({
type: "POST",
data: {data:email },
async: false,
url : base_url+'Landingpage/Match_emails',
})
.done(function(msg){
//alert(msg);
if(msg !=null && msg.length>0){
$("#Username").html(msg);
$("#lekhpal").html('');
big = true;
}else{
$("#lekhpal").html('Please Enter Valid Email');
big= false;
}
});
return big;
}
function match_otp(){
var otp = document.getElementById("otp").value;
var big=false;
$.ajax({
type: "POST",
data: {data:otp },
async: false,
url : base_url+'Landingpage/match_otp',
})
.done(function(msg){
//alert(msg);
if(msg !=null && msg.length>0){
$("#otperror").html('');
big = true;
}else{
$("#otperror").html('Please Enter Valid Otp');
big= false;
}
});
return big;
} | mit |
ericzhang-cn/princeton-algs4 | src/main/java/Deque.java | 4161 | // Coursera Algorithms, Part I Assignment 2
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* 双向队列
*
* 为了保证在O(1)的复杂度内完成双向插入及删除操作,使用双向链表作为内部数据结构
* @author ericzhang <ericzhang.buaa@gmail.com>
*/
public class Deque<Item> implements Iterable<Item> {
/**
* 链表节点
*
* @author ericzhang <ericzhang.buaa@gmail.com>
*/
@SuppressWarnings("hiding")
private class Node<Item> {
private Item value;
private Node<Item> prev;
private Node<Item> next;
public Node(Item value, Node<Item> prev, Node<Item> next) {
this.value = value;
this.prev = prev;
this.next = next;
}
public Node(Item value) {
this(value, null, null);
}
public Item getValue() {
return value;
}
}
/**
* 迭代器
*
* @author ericzhang <ericzhang.buaa@gmail.com>
*/
private class DequeIterator implements Iterator<Item> {
private Node<Item> current;
public DequeIterator(Node<Item> current) {
this.current = current;
}
public boolean hasNext() {
return current != null;
}
public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Node<Item> prev = current;
current = current.next;
return prev.getValue();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private Node<Item> head;
private Node<Item> tail;
private int sz;
/**
* 默认构造函数
*/
public Deque() {
head = null;
tail = null;
sz = 0;
}
/**
* 队列是否为空
*
* @return 空队列返回true,否则返回false
*/
public boolean isEmpty() {
return sz == 0;
}
/**
* 队列元素数量
*
* @return 元素数量
*/
public int size() {
return sz;
}
/**
* 在队头插入新元素
*
* @param item 新元素
*/
public void addFirst(Item item) {
if (item == null) {
throw new NullPointerException();
}
if (isEmpty()) {
head = new Node<Item>(item);
tail = head;
} else {
Node<Item> newNode = new Node<Item>(item, null, head);
head.prev = newNode;
head = newNode;
}
sz += 1;
}
/**
* 在队尾插入新元素
*
* @param item 新元素
*/
public void addLast(Item item) {
if (item == null) {
throw new NullPointerException();
}
if (isEmpty()) {
head = new Node<Item>(item);
tail = head;
} else {
Node<Item> newNode = new Node<Item>(item, tail, null);
tail.next = newNode;
tail = newNode;
}
sz += 1;
}
/**
* 移除队头元素
*
* @return 队头元素
*/
public Item removeFirst() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item r = head.getValue();
if (sz == 1) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
}
sz -= 1;
return r;
}
/**
* 移除队尾元素
*
* @return 队尾元素
*/
public Item removeLast() {
if (isEmpty()) {
throw new NoSuchElementException();
}
Item r = tail.getValue();
if (sz == 1) {
head = null;
tail = null;
} else {
tail = tail.prev;
tail.next = null;
}
sz -= 1;
return r;
}
/**
* 返回一个迭代器
*
* @return 迭代器
*/
public Iterator<Item> iterator() {
return new DequeIterator(head);
}
}
| mit |
KitchenCoster/myob-api | lib/myob/api/models/bill_miscellaneous.rb | 183 | module Myob
module Api
module Model
class BillMiscellaneous < Base
def model_route
'Purchase/Bill/Miscellaneous'
end
end
end
end
end
| mit |
sai-lab/mouryou | lib/ratio/ratio.go | 253 | package ratio
import "github.com/sai-lab/mouryou/lib/calculate"
func Increase(xs []float64, n int) float64 {
if len(xs) == 1 {
return calculate.MovingAverage(xs, n) - xs[0]
}
return (calculate.MovingAverage(xs, n) - xs[0]) / float64(len(xs)-1)
}
| mit |
mrself/ya-form | src/Form/View.php | 461 | <?php
namespace Mrself\YaF\Form;
class View {
public function __construct($data = null) {
if ($data) {
$this->data = $data;
}
}
public function with($key, $val) {
if (is_array($key)) {
$this->data = array_merge($this->data, $key);
} else {
$this->data[$key] = $val;
}
}
public function setPath($path) {
$this->path = $path;
}
public function render() {
return view($this->path, $this->data);
}
} | mit |
jgveire/Vanguard.Framework | src/Vanguard.Framework.Test/TestBase.cs | 1026 | namespace Vanguard.Framework.Test
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
/// <summary>
/// The test base class.
/// </summary>
[TestClass]
public class TestBase
{
/// <summary>
/// Gets the mock repository.
/// </summary>
/// <value>
/// The mock repository.
/// </value>
protected MockRepository MockRepository { get; private set; } = new MockRepository(MockBehavior.Strict);
/// <summary>
/// Initializes each test and therefor is run before each test.
/// </summary>
[TestInitialize]
public virtual void TestInitialize()
{
MockRepository = new MockRepository(MockBehavior.Strict);
}
/// <summary>
/// Cleans up after each test and therefor is run after each test.
/// </summary>
[TestCleanup]
public virtual void TestCleanup()
{
MockRepository.VerifyAll();
}
}
}
| mit |
netis-pl/yii2-crud | widgets/GridView.php | 3688 | <?php
/**
* @link http://netis.pl/
* @copyright Copyright (c) 2015 Netis Sp. z o. o.
*/
namespace netis\crud\widgets;
use netis\crud\db\ActiveQuery;
use Yii;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;
/**
* Extends \yii\grid\GridView, adding two new layout elements: lengthPicker and quickSearch.
* @package netis\crud\widgets
*/
class GridView extends \yii\grid\GridView
{
public $buttons = [];
public $lengthPickerOptions = ['class' => 'pagination pull-right'];
public function init()
{
parent::init();
}
private $clientOptions = [];
/**
* @inheritdoc
*/
public function renderSection($name)
{
if (parent::renderSection($name) !== false) {
return parent::renderSection($name);
}
switch ($name) {
case '{buttons}':
return $this->renderButtons();
case '{lengthPicker}':
return $this->renderLengthPicker();
case '{quickSearch}':
return $this->renderQuickSearch();
default:
return false;
}
}
/**
* Renders toolbar buttons.
* @return string the rendering result
*/
public function renderButtons()
{
return implode('', $this->buttons);
}
/**
* Renders the page length picker.
* @return string the rendering result
*/
public function renderLengthPicker()
{
$pagination = $this->dataProvider->getPagination();
if ($pagination === false || $this->dataProvider->getCount() <= 0) {
return '';
}
$pagination->totalCount = $this->dataProvider->getTotalCount();
$choices = [];
foreach ([10, 25, 50] as $value) {
$cssClass = $value === $pagination->pageSize ? 'active' : '';
$url = $pagination->createUrl($pagination->getPage(), $value);
$choices[] = '<li class="'.$cssClass.'"><a href="' . $url . '">' . $value . '</a></li>';
}
return Html::tag('ul', implode("\n", $choices), $this->lengthPickerOptions);
}
/**
* Renders the quick search input field.
* @return string the rendering result
*/
public function renderQuickSearch()
{
if (!$this->dataProvider instanceof ActiveDataProvider || !$this->dataProvider->query instanceof ActiveQuery) {
return '';
}
$id = $this->getId();
$value = Html::encode($this->dataProvider->query->quickSearchPhrase);
$placeholder = Yii::t('app', 'Search');
$result = <<<HTML
<div class="form-group">
<div class="input-group grid-quick-search">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="mdi mdi-magnify"></i></button>
</div>
<input class="form-control"
id="{$id}-quickSearch" name="search" placeholder="$placeholder" value="$value" type="text"/>
<!--onkeyup="jQuery('#{$id}').yiiGridView('applyFilter')"-->
<div class="input-group-btn">
<button class="btn btn-default" onclick="$('#{$id}-quickSearch').val('').change();return false;">
<i class="mdi mdi-close"></i>
</button>
</div>
</div>
</div>
HTML;
return $result;
}
public function setClientOptions($options) {
$this->clientOptions = $options;
}
protected function getClientOptions()
{
return array_merge($this->clientOptions, parent::getClientOptions());
}
}
| mit |
szpak/mockito | src/main/java/org/mockito/internal/stubbing/BaseStubbing.java | 3269 | /*
* Copyright (c) 2007 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.stubbing;
import org.mockito.internal.stubbing.answers.CallsRealMethods;
import org.mockito.internal.stubbing.answers.Returns;
import org.mockito.internal.stubbing.answers.ThrowsException;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;
import static org.mockito.internal.exceptions.Reporter.notAnException;
import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;
import static org.objenesis.ObjenesisHelper.newInstance;
public abstract class BaseStubbing<T> implements OngoingStubbing<T> {
// Keep strong ref to mock preventing premature garbage collection when using 'One-liner stubs'. See #1541.
private final Object strongMockRef;
BaseStubbing(Object mock) {
this.strongMockRef = mock;
}
@Override
public OngoingStubbing<T> then(Answer<?> answer) {
return thenAnswer(answer);
}
@Override
public OngoingStubbing<T> thenReturn(T value) {
return thenAnswer(new Returns(value));
}
@Override
public OngoingStubbing<T> thenReturn(T value, T... values) {
OngoingStubbing<T> stubbing = thenReturn(value);
if (values == null) {
// For no good reason we're configuring null answer here
// This has been like that since forever, so let's keep it for compatibility (unless users complain)
return stubbing.thenReturn(null);
}
for (T v : values) {
stubbing = stubbing.thenReturn(v);
}
return stubbing;
}
private OngoingStubbing<T> thenThrow(Throwable throwable) {
return thenAnswer(new ThrowsException(throwable));
}
@Override
public OngoingStubbing<T> thenThrow(Throwable... throwables) {
if (throwables == null) {
return thenThrow((Throwable) null);
}
OngoingStubbing<T> stubbing = null;
for (Throwable t : throwables) {
if (stubbing == null) {
stubbing = thenThrow(t);
} else {
stubbing = stubbing.thenThrow(t);
}
}
return stubbing;
}
@Override
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType) {
if (throwableType == null) {
mockingProgress().reset();
throw notAnException();
}
return thenThrow(newInstance(throwableType));
}
@Override
public OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown) {
if (nextToBeThrown == null) {
return thenThrow((Class<Throwable>) null);
}
OngoingStubbing<T> stubbing = thenThrow(toBeThrown);
for (Class<? extends Throwable> t : nextToBeThrown) {
stubbing = stubbing.thenThrow(t);
}
return stubbing;
}
@Override
public OngoingStubbing<T> thenCallRealMethod() {
return thenAnswer(new CallsRealMethods());
}
@Override
@SuppressWarnings("unchecked")
public <M> M getMock() {
return (M) this.strongMockRef;
}
}
| mit |
makelivedotnet/sample-Groceries | app/tns_modules/ui/frame/frame.ios.js | 10228 | var frameCommon = require("ui/frame/frame-common");
var trace = require("trace");
var enums = require("ui/enums");
var utils = require("utils/utils");
var view = require("ui/core/view");
var types = require("utils/types");
global.moduleMerge(frameCommon, exports);
var ENTRY = "_entry";
var navDepth = 0;
var Frame = (function (_super) {
__extends(Frame, _super);
function Frame() {
_super.call(this);
this._shouldSkipNativePop = false;
this._ios = new iOSFrame(this);
}
Frame.prototype.onLoaded = function () {
_super.prototype.onLoaded.call(this);
if (this._paramToNavigate) {
this.navigate(this._paramToNavigate);
this._paramToNavigate = undefined;
}
};
Frame.prototype.navigate = function (param) {
if (this.isLoaded) {
_super.prototype.navigate.call(this, param);
}
else {
this._paramToNavigate = param;
}
};
Frame.prototype._navigateCore = function (backstackEntry) {
var viewController = backstackEntry.resolvedPage.ios;
if (!viewController) {
throw new Error("Required page does have an viewController created.");
}
var animated = false;
if (this.currentPage) {
animated = this._getIsAnimatedNavigation(backstackEntry.entry);
}
this.updateNavigationBar();
viewController[ENTRY] = backstackEntry;
navDepth++;
trace.write("Frame<" + this._domId + ">.pushViewControllerAnimated depth = " + navDepth, trace.categories.Navigation);
this._ios.controller.pushViewControllerAnimated(viewController, animated);
};
Frame.prototype._goBackCore = function (entry) {
navDepth--;
trace.write("Frame<" + this._domId + ">.popViewControllerAnimated depth = " + navDepth, trace.categories.Navigation);
if (!this._shouldSkipNativePop) {
this._ios.controller.popViewControllerAnimated(this._getIsAnimatedNavigation(entry));
}
};
Frame.prototype.updateNavigationBar = function (page) {
var previousValue = !!this._ios.showNavigationBar;
var newValue = false;
switch (this._ios.navBarVisibility) {
case enums.NavigationBarVisibility.always:
newValue = true;
break;
case enums.NavigationBarVisibility.never:
newValue = false;
break;
case enums.NavigationBarVisibility.auto:
var pageInstance = page || this.currentPage;
if (pageInstance && types.isDefined(pageInstance.actionBarHidden)) {
newValue = !pageInstance.actionBarHidden;
}
else {
newValue = this.backStack.length > 0 || (pageInstance && !pageInstance.actionBar._isEmpty());
}
newValue = !!newValue;
break;
}
this._ios.showNavigationBar = newValue;
if (previousValue !== newValue) {
this.requestLayout();
}
};
Object.defineProperty(Frame.prototype, "ios", {
get: function () {
return this._ios;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Frame.prototype, "_nativeView", {
get: function () {
return this._ios.controller.view;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Frame, "defaultAnimatedNavigation", {
get: function () {
return frameCommon.Frame.defaultAnimatedNavigation;
},
set: function (value) {
frameCommon.Frame.defaultAnimatedNavigation = value;
},
enumerable: true,
configurable: true
});
Frame.prototype.requestLayout = function () {
_super.prototype.requestLayout.call(this);
var window = this._nativeView.window;
if (window) {
window.setNeedsLayout();
}
};
Frame.prototype.onMeasure = function (widthMeasureSpec, heightMeasureSpec) {
var width = utils.layout.getMeasureSpecSize(widthMeasureSpec);
var widthMode = utils.layout.getMeasureSpecMode(widthMeasureSpec);
var height = utils.layout.getMeasureSpecSize(heightMeasureSpec);
var heightMode = utils.layout.getMeasureSpecMode(heightMeasureSpec);
var result = view.View.measureChild(this, this.currentPage, widthMeasureSpec, utils.layout.makeMeasureSpec(height - this.navigationBarHeight, heightMode));
if (this._navigateToEntry) {
view.View.measureChild(this, this._navigateToEntry.resolvedPage, widthMeasureSpec, utils.layout.makeMeasureSpec(height - this.navigationBarHeight, heightMode));
}
var widthAndState = view.View.resolveSizeAndState(result.measuredWidth, width, widthMode, 0);
var heightAndState = view.View.resolveSizeAndState(result.measuredHeight, height, heightMode, 0);
this.setMeasuredDimension(widthAndState, heightAndState);
};
Frame.prototype.onLayout = function (left, top, right, bottom) {
view.View.layoutChild(this, this.currentPage, 0, this.navigationBarHeight, right - left, bottom - top);
if (this._navigateToEntry) {
view.View.layoutChild(this, this._navigateToEntry.resolvedPage, 0, this.navigationBarHeight, right - left, bottom - top);
}
};
Object.defineProperty(Frame.prototype, "navigationBarHeight", {
get: function () {
var navigationBar = this._ios.controller.navigationBar;
return (navigationBar && !this._ios.controller.navigationBarHidden) ? navigationBar.frame.size.height : 0;
},
enumerable: true,
configurable: true
});
return Frame;
})(frameCommon.Frame);
exports.Frame = Frame;
var UINavigationControllerImpl = (function (_super) {
__extends(UINavigationControllerImpl, _super);
function UINavigationControllerImpl() {
_super.apply(this, arguments);
}
UINavigationControllerImpl.new = function () {
return _super.new.call(this);
};
UINavigationControllerImpl.prototype.initWithOwner = function (owner) {
this._owner = owner;
return this;
};
UINavigationControllerImpl.prototype.viewDidLoad = function () {
this.view.autoresizesSubviews = false;
this.view.autoresizingMask = UIViewAutoresizing.UIViewAutoresizingNone;
this._owner.onLoaded();
};
UINavigationControllerImpl.prototype.viewDidLayoutSubviews = function () {
trace.write(this._owner + " viewDidLayoutSubviews, isLoaded = " + this._owner.isLoaded, trace.categories.ViewHierarchy);
this._owner._updateLayout();
};
UINavigationControllerImpl.prototype.navigationControllerWillShowViewControllerAnimated = function (navigationController, viewController, animated) {
var frame = this._owner;
var newEntry = viewController[ENTRY];
var newPage = newEntry.resolvedPage;
if (!newPage.parent) {
if (!frame._currentEntry) {
frame._currentEntry = newEntry;
}
else {
frame._navigateToEntry = newEntry;
}
frame._addView(newPage);
}
else if (newPage.parent !== frame) {
throw new Error("Page is already shown on another frame.");
}
newPage.actionBar.update();
};
UINavigationControllerImpl.prototype.navigationControllerDidShowViewControllerAnimated = function (navigationController, viewController, animated) {
var frame = this._owner;
var backStack = frame.backStack;
var currentEntry = backStack.length > 0 ? backStack[backStack.length - 1] : null;
var newEntry = viewController[ENTRY];
var isBack = currentEntry && newEntry === currentEntry;
if (isBack) {
try {
frame._shouldSkipNativePop = true;
frame.goBack();
}
finally {
frame._shouldSkipNativePop = false;
}
}
var page = frame.currentPage;
if (page && !navigationController.viewControllers.containsObject(page.ios)) {
frame._removeView(page);
}
frame._navigateToEntry = null;
frame._currentEntry = newEntry;
frame.updateNavigationBar();
frame.ios.controller.navigationBar.backIndicatorImage;
var newPage = newEntry.resolvedPage;
newPage.onNavigatedTo();
frame._processNavigationQueue(newPage);
};
UINavigationControllerImpl.prototype.supportedInterfaceOrientation = function () {
return UIInterfaceOrientationMask.UIInterfaceOrientationMaskAll;
};
UINavigationControllerImpl.ObjCProtocols = [UINavigationControllerDelegate];
return UINavigationControllerImpl;
})(UINavigationController);
var iOSFrame = (function () {
function iOSFrame(owner) {
this._controller = UINavigationControllerImpl.new().initWithOwner(owner);
this._controller.delegate = this._controller;
this._controller.automaticallyAdjustsScrollViewInsets = false;
this.showNavigationBar = false;
this._navBarVisibility = enums.NavigationBarVisibility.auto;
}
Object.defineProperty(iOSFrame.prototype, "controller", {
get: function () {
return this._controller;
},
enumerable: true,
configurable: true
});
Object.defineProperty(iOSFrame.prototype, "showNavigationBar", {
get: function () {
return this._showNavigationBar;
},
set: function (value) {
this._showNavigationBar = value;
this._controller.navigationBarHidden = !value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(iOSFrame.prototype, "navBarVisibility", {
get: function () {
return this._navBarVisibility;
},
set: function (value) {
this._navBarVisibility = value;
},
enumerable: true,
configurable: true
});
return iOSFrame;
})();
| mit |
xiamidaxia/xiami | meteor/id-map/id-map.js | 2296 | var EJSON = require('meteor/ejson')
var _ = require('meteor/underscore')
var IdMap = module.exports = function (idStringify, idParse) {
var self = this;
self._map = {};
self._idStringify = idStringify || JSON.stringify;
self._idParse = idParse || JSON.parse;
};
// Some of these methods are designed to match methods on OrderedDict, since
// (eg) ObserveMultiplex and _CachingChangeObserver use them interchangeably.
// (Conceivably, this should be replaced with "UnorderedDict" with a specific
// set of methods that overlap between the two.)
_.extend(IdMap.prototype, {
get: function (id) {
var self = this;
var key = self._idStringify(id);
return self._map[key];
},
set: function (id, value) {
var self = this;
var key = self._idStringify(id);
self._map[key] = value;
},
remove: function (id) {
var self = this;
var key = self._idStringify(id);
delete self._map[key];
},
has: function (id) {
var self = this;
var key = self._idStringify(id);
return _.has(self._map, key);
},
empty: function () {
var self = this;
return _.isEmpty(self._map);
},
clear: function () {
var self = this;
self._map = {};
},
// Iterates over the items in the map. Return `false` to break the loop.
forEach: function (iterator) {
var self = this;
// don't use _.each, because we can't break out of it.
var keys = _.keys(self._map);
for (var i = 0; i < keys.length; i++) {
var breakIfFalse = iterator.call(null, self._map[keys[i]],
self._idParse(keys[i]));
if (breakIfFalse === false)
return;
}
},
size: function () {
var self = this;
return _.size(self._map);
},
setDefault: function (id, def) {
var self = this;
var key = self._idStringify(id);
if (_.has(self._map, key))
return self._map[key];
self._map[key] = def;
return def;
},
// Assumes that values are EJSON-cloneable, and that we don't need to clone
// IDs (ie, that nobody is going to mutate an ObjectId).
clone: function () {
var self = this;
var clone = new IdMap(self._idStringify, self._idParse);
self.forEach(function (value, id) {
clone.set(id, EJSON.clone(value));
});
return clone;
}
});
| mit |
G-CorpDev/project | server/src/WorkoutClasses.cpp | 7589 | #include <Models.h>
Models::Exercise::Exercise(const std::string &name, const std::string ¬e, Models::Exercise::Type type, const std::string &reps, const std::string &weight, const bool &done)
: name(name), note(note), type(type), reps(reps), weight(weight), done(done) {}
std::string Models::Exercise::toJSON()
{
json_t *root = json_object();
json_object_set_new(root, "name", json_string(name.c_str()));
json_object_set_new(root, "note", json_string(note.c_str()));
switch (type)
{
case Models::Exercise::Type::JustDone:
json_object_set_new(root, "done", json_boolean(done));
break;
case Models::Exercise::Type::RepsOnly:
json_object_set_new(root, "R",json_string(reps.c_str()));
break;
case Models::Exercise::Type::WeightOnly:
json_object_set_new(root, "W",json_string(weight.c_str()));
break;
case Models::Exercise::Type::RepsAndWeight:
json_object_set_new(root, "W",json_string(weight.c_str()));
json_object_set_new(root, "R",json_string(reps.c_str()));
break;
}
char *raw = json_dumps(root, 0);
std::string json(raw);
delete raw;
json_decref(root);
return json;
}
Models::Workout::Workout(const std::string &name, const std::string &description, const TimeOfDay &time, const bool &done, const bool & skipped)
: name(name), description(description), time(time), done(done), skipped(skipped) {}
std::string Models::Workout::toJSON()
{
json_t *root = json_object();
json_t *exercises = json_array();
json_object_set_new(root, "name", json_string(name.c_str()));
json_object_set_new(root, "description", json_string(description.c_str()));
switch (time)
{
case Models::Workout::TimeOfDay::Morning:
json_object_set_new(root, "time", json_string("morning"));
break;
case Models::Workout::TimeOfDay::Day:
json_object_set_new(root, "time", json_string("day"));
break;
case Models::Workout::TimeOfDay::Evening:
json_object_set_new(root, "time", json_string("night"));
break;
}
json_object_set_new(root, "done", json_boolean(done));
json_object_set_new(root, "skipped", json_boolean(skipped));
for (auto &exercise : this->exercises)
{
json_error_t err;
json_t *tmp = json_loads(exercise.toJSON().c_str(), 0, &err);
json_array_append(exercises, tmp);
json_decref(tmp);
}
json_object_set_new(root, "exercises", exercises);
char *raw = json_dumps(root, 0);
std::string json(raw);
delete raw;
json_decref(root);
return json;
}
void Models::Workout::addExercise(Exercise exercise)
{
this->exercises.push_back(exercise);
}
Models::Workout::TimeOfDay Models::Workout::timeFromString(const std::string & string){
if("Morning"==string || "morning"==string){return Models::Workout::TimeOfDay::Morning;}
if("Day"==string || "day"==string || "Midday"==string || "midday"==string){return Models::Workout::TimeOfDay::Day;}
if("Evening"==string || "evening"==string || "Night"==string || "night"==string){return Models::Workout::TimeOfDay::Evening;}
return Models::Workout::TimeOfDay::Invalid;
}
Models::Day::Day(const Days &dotw) : dayOfTheWeek(dotw)
{
morning = 0;
midday = 0;
evening = 0;
}
std::string Models::Day::toJSON()
{
json_t *root = json_object();
json_t *workouts = json_array();
json_object_set_new(root, "day", json_string(dayAsString(this->dayOfTheWeek).c_str()));
if (morning != 0)
{
json_error_t err;
json_t *tmp = json_loads(morning->toJSON().c_str(), 0, &err);
json_array_append(workouts, tmp);
json_decref(tmp);
}
if (midday != 0)
{
json_error_t err;
json_t *tmp = json_loads(midday->toJSON().c_str(), 0, &err);
json_array_append(workouts, tmp);
json_decref(tmp);
}
if (evening != 0)
{
json_error_t err;
json_t *tmp = json_loads(evening->toJSON().c_str(), 0, &err);
json_array_append(workouts, tmp);
json_decref(tmp);
}
json_object_set_new(root, "workouts", workouts);
char *raw = json_dumps(root, 0);
std::string json(raw);
delete raw;
json_decref(root);
return json;
}
void Models::Day::addWorkout(Workout workout)
{
switch (workout.getTime())
{
case Models::Workout::TimeOfDay::Morning:
morning =std::make_shared<Workout>(workout);
break;
case Models::Workout::TimeOfDay::Day:
midday = std::make_shared<Workout>(workout);
break;
case Models::Workout::TimeOfDay::Evening:
evening = std::make_shared<Workout>(workout);
break;
}
}
std::string Models::Day::dayAsString(const Days &day)
{
switch (day)
{
case Models::Day::Days::Monday:
return "Monday";
case Models::Day::Days::Tuesday:
return "Tuesday";
case Models::Day::Days::Wednesday:
return "Wednesday";
case Models::Day::Days::Thursday:
return "Thursday";
case Models::Day::Days::Friday:
return "Friday";
case Models::Day::Days::Saturday:
return "Saturday";
case Models::Day::Days::Sunday:
return "Sunday";
case Models::Day::Days::Invalid:
return "Invalid day.";
}
return "ERROR";
}
Models::Day::Days Models::Day::fromString(const std::string & string){
if(string=="Monday" || "monday"==string){return Models::Day::Days::Monday;}
if(string=="Tuesday" || "tuesday"==string){return Models::Day::Days::Tuesday;}
if(string=="Wednesday" || "wednesday"==string){return Models::Day::Days::Wednesday;}
if(string=="Thursday" || "thursday"==string){return Models::Day::Days::Thursday;}
if(string=="Friday" || "friday"==string){return Models::Day::Days::Friday;}
if(string=="Saturday" || "saturday"==string){return Models::Day::Days::Saturday;}
if(string=="Sunday" || "sunday"==string){return Models::Day::Days::Sunday;}
return Models::Day::Days::Invalid;
}
void Models::Week::addDay(Day day)
{
this->days.push_back(day);
}
std::string Models::Week::toJSON()
{
std::string json("[");
bool first = true;
for (auto &day : days)
{
if (!first)
{
json.append(",");
}
first = false;
json.append(day.toJSON());
}
json.append("]");
return json;
}
Models::Worksheet::Worksheet(const std::string &name, const std::string &description, const std::string &avgWorkoutLength, const std::string &difficulty)
: name(name), description(description), avgWorkoutLength(avgWorkoutLength), difficulty(difficulty) {}
void Models::Worksheet::addWeek(Week week)
{
this->weeks.push_back(week);
}
std::string Models::Worksheet::toJSON()
{
json_t *root = json_object();
json_object_set_new(root, "name", json_string(this->name.c_str()));
json_object_set_new(root, "description", json_string(this->description.c_str()));
json_object_set_new(root, "difficulty", json_string(this->difficulty.c_str()));
json_object_set_new(root, "avgWorkoutLength", json_string(this->avgWorkoutLength.c_str()));
json_t *weeks = json_array();
for (auto week : this->weeks)
{
json_error_t err;
json_t *tmp = json_loads(week.toJSON().c_str(), 0, &err);
json_array_append(weeks, tmp);
json_decref(tmp);
}
json_object_set_new(root, "weeks", weeks);
char *raw = json_dumps(root, 0);
std::string json(raw);
delete raw;
json_decref(root);
return json;
} | mit |
EbenezerOyenuga/citizenship | application/modules/Admintemplate/controllers/Admintemplate.php | 755 | <?php
class Admintemplate extends MY_Controller{
function __construct()
{
parent::__construct();
}
function call_admin_template($data = NULL){
//call login template
$this->load->model('M_Semesters_Scores');
$data['num_resub_req'] = count($this->M_Semesters_Scores->get_resubmission_requests());
$data['num_resub_pending'] = count($this->M_Semesters_Scores->get_pending_resubmissions());
$data['num_resubs'] = count($this->M_Semesters_Scores->get_resubmissions());
$data['num_rej'] = count($this->M_Semesters_Scores->get_rejections());
$data['num_for'] = count($this->M_Semesters_Scores->get_forward());
$this->load->view('admin_template_v', $data);
}
}
| mit |
Team1786/1786-2018-Robot-Code-Practice | main/java/org/usfirst/frc/team1786/robot/commands/resetGyro.java | 563 | package org.usfirst.frc.team1786.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team1786.robot.Robot;
public class resetGyro extends Command {
public resetGyro() {
requires(Robot.drivetrain);
}
public void initialize() {
}
@Override
protected void execute() {
Robot.drivetrain.resetDrivingAngle();
}
@Override
protected boolean isFinished() {
return true;
}
@Override
protected void end() {
}
protected void interrupted() {
}
}
| mit |
m3libea/TwitterClient | app/src/main/java/com/codepath/apps/twitterclient/activities/TweetActivity.java | 14291 | package com.codepath.apps.twitterclient.activities;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.codepath.apps.twitterclient.R;
import com.codepath.apps.twitterclient.TwitterApplication;
import com.codepath.apps.twitterclient.api.TwitterClient;
import com.codepath.apps.twitterclient.databinding.ActivityTweetBinding;
import com.codepath.apps.twitterclient.fragments.ComposeFragment;
import com.codepath.apps.twitterclient.models.MediaTweet;
import com.codepath.apps.twitterclient.models.Tweet;
import com.codepath.apps.twitterclient.models.User;
import com.codepath.apps.twitterclient.utils.PatternEditableBuilder;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;
import java.util.regex.Pattern;
import cz.msebera.android.httpclient.Header;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import static com.raizlabs.android.dbflow.config.FlowManager.getContext;
public class TweetActivity extends AppCompatActivity implements ComposeFragment.ComposeDialogListener{
private final String TAG = "TweetActivity";
private TwitterClient client;
private Tweet tweet;
ActivityTweetBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_tweet);
client = TwitterApplication.getRestClient();
tweet = Parcels.unwrap(getIntent().getExtras().getParcelable("tweet"));
setupView();
}
private void setupView() {
setupActionBar();
binding.setTweet(tweet);
if((tweet.getRtCount() == 0) && (tweet.getfCount() == 0)){
binding.viewt.setVisibility(View.GONE);
}
if(tweet.getRtCount() == 0){
binding.tvRT.setVisibility(View.GONE);
}
if(tweet.getfCount() == 0){
binding.tvLikes.setVisibility(View.GONE);
}
int idcolor = binding.btRt.isSelected() ? R.color.primary : R.color.lightText;
int color = ContextCompat.getColor(this, idcolor);
binding.btRt.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
Drawable icon = ContextCompat
.getDrawable(this, binding.btLike.isSelected()? R.drawable.ic_twitter_like : R.drawable.ic_twitter_like_outline);
binding.btLike.setBackground(icon);
//Profile image
Glide.with(this)
.load(tweet.getUser().getProfileImageURL())
.asBitmap()
.centerCrop()
.into(new BitmapImageViewTarget(binding.ivProfile) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(getResources(), resource);
circularBitmapDrawable.setCircular(true);
binding.ivProfile.setImageDrawable(circularBitmapDrawable);
}
});
binding.ivProfile.setOnClickListener(view -> {
Intent i = new Intent(this, UserActivity.class);
i.putExtra("user", Parcels.wrap(tweet.user));
startActivity(i);
});
//Set Media
MediaTweet m = tweet.getOneMedia();
if(m != null){
if (m.getType().equals("photo")) {
Glide.with(this)
.load(m.getMediaUrl())
.bitmapTransform(new RoundedCornersTransformation(this, 20, 5))
.into(binding.ivMedia);
binding.ivMedia.setVisibility(View.VISIBLE);
}else {
setVideo(m.getVideoURL());
binding.vvVideo.setVisibility(View.VISIBLE);
}
}
//Replybutton
binding.btReply.setOnClickListener(view -> composeReply());
//RT button
if(tweet.getRetweeted()){
binding.btRt.setEnabled(false);
binding.btRt.getBackground()
.setColorFilter(ContextCompat
.getColor(this, R.color.primary) , PorterDuff.Mode.SRC_IN);
}else{
binding.btRt.setOnClickListener(view -> {
view.setSelected(!view.isSelected());
setRtBT();
view.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.image_click));
int iColor = view.isSelected() ? R.color.primary : R.color.lightText;
int c = ContextCompat.getColor(this, iColor);
view.getBackground().setColorFilter(c, PorterDuff.Mode.SRC_IN);
retweet();
tweet.save();
view.setEnabled(false);
});
}
//Like button
binding.btLike.setOnClickListener(view -> {
view.setSelected(!view.isSelected());
setLikeBT();
view.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.image_click));
Drawable i = ContextCompat
.getDrawable(this, view.isSelected()? R.drawable.ic_twitter_like : R.drawable.ic_twitter_like_outline);
view.setBackground(i);
setFavouriteStatus();
tweet.save();
});
//SPAN hashtag, user
binding.tvBody.setText(tweet.getBody());
setExtraInfo(tweet);
new PatternEditableBuilder()
.addPattern(Pattern.compile("\\@(\\w+)"), ContextCompat.getColor(this, R.color.primary),
text -> showUser(text.replace("@","")))
.addPattern(Pattern.compile("\\#(\\w+)"), ContextCompat.getColor(this, R.color.primary_dark),
text -> showHT(text))
.into(binding.tvBody);
}
private void setExtraInfo(Tweet tweet) {
if (tweet.getRetweet()){
binding.tvExtra.setText("Retweeted by " + tweet.getRetweetedBy());
binding.llExtra.setVisibility(View.VISIBLE);
}else if (tweet.getReplyTo() != null) {
binding.tvExtra.setText("Reply to " + tweet.getReplyTo());
binding.ivExtra.setBackground(ContextCompat.getDrawable(getContext(), R.drawable.ic_reply));
binding.llExtra.setVisibility(View.VISIBLE);
}else{
binding.llExtra.setVisibility(View.GONE);
}
}
private void showHT(String query) {
Intent i = new Intent(this, SearchActivity.class);
i.putExtra("query", query);
startActivity(i);
}
private void showUser(String screename) {
client.getUser(screename, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
User user = null;
try {
user = User.fromJSON(response.getJSONObject(0));
Intent i = new Intent(getContext(), UserActivity.class);
i.putExtra("user", Parcels.wrap(user));
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
});
}
private void setFavouriteStatus() {
if (tweet.getFavorited()) {
client.postFavorite(tweet,new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d(TAG, "Liked" + response.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d(TAG, errorResponse.toString());
}
});
}else{
client.destroyFavorite(tweet,new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d(TAG, "DestroyLiked" + response.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d(TAG, errorResponse.toString());
}
});
}
}
private void retweet() {
client.postRetweet(tweet, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d(TAG, response.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d(TAG, errorResponse.toString());
}
});
}
private void setLikeBT() {
tweet.setFavorited(binding.btLike.isSelected());
tweet.setfCount(tweet.getFavorited()? tweet.getfCount() + 1 : tweet.getfCount() - 1);
if (tweet.getfCount() == 0){
binding.tvLikes.setVisibility(View.GONE);
binding.tvLikes.setText(" ");
}else{
binding.tvLikes.setVisibility(View.VISIBLE);
binding.tvLikes.setText(Integer.toString(tweet.getfCount())+ " Likes");
}
}
private void setRtBT() {
tweet.setRetweeted(binding.btRt.isSelected());
tweet.setRtCount(tweet.getRtCount() + 1 );
binding.tvRT.setText(Integer.toString(tweet.getRtCount())+ " Retweets");
binding.tvRT.setVisibility(View.VISIBLE);
}
private void setVideo(String url) {
binding.vvVideo.setVideoPath(url);
final boolean[] videoTouched = {false};
binding.vvVideo.setOnPreparedListener(mp -> mp.setLooping(true));
Handler mHandler = new Handler();
binding.vvVideo.setOnTouchListener((view, motionEvent) -> {
if(!videoTouched[0]) {
videoTouched[0] = true;
}
if (binding.vvVideo.isPlaying()) {
binding.vvVideo.pause();
} else {
binding.vvVideo.start();
}
mHandler.postDelayed(() -> videoTouched[0] = false, 100);
return true;
});
binding.vvVideo.setOnErrorListener((media, what, extra) -> {
if (what == 100)
{
binding.vvVideo.stopPlayback();
setVideo(url);
}
return true;
});
}
private void composeReply() {
binding.btReply.setOnClickListener(view -> {
FragmentManager fm = getSupportFragmentManager();
ComposeFragment tweetCompose = ComposeFragment.newInstance(tweet.getUser().getScreenName());
tweetCompose.show(fm, "fragment_compose");
});
}
private void setupActionBar() {
setSupportActionBar(binding.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Tweet");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFinishingTweet(String body,Tweet t, Boolean tweet) {
String minBody = body.substring(0, Math.min(getResources().getInteger(R.integer.max_tweet_length), body.length()));
if (isNetworkAvailable()){
client.composeReply(this.tweet.getUser().getScreenName(), this.tweet.getUid(), minBody, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d(TAG, "Tweet created: " + response.toString());
Toast toast = Toast.makeText(TweetActivity.this, R.string.toastTweetCreated, Toast.LENGTH_SHORT);
toast.show();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d(TAG, errorResponse.toString());
}
});
}else{
Snackbar bar = Snackbar.make(findViewById(R.id.activity_tweet), getResources().getString(R.string.connection_error) , Snackbar.LENGTH_LONG);
bar.show();
}
}
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
}
| mit |
USC-CSSL/USC-ObjectsNegotiationTask | WebGames/src/edu/usc/cct/rapport/web_games/client/WebGamesAbstractActivity.java | 359 | package edu.usc.cct.rapport.web_games.client;
abstract public class WebGamesAbstractActivity implements IWebGamesActivity {
@Override
public String mayStop() {
return null;
};
@Override
public void onCancel() {
// There is nothing to do here.
};
@Override
public void onStop() {
// There is nothing to do here.
};
};
| mit |
TwilioDevEd/api-snippets | ip-messaging/rest/roles/delete-role/delete-role.3.x.js | 504 | // To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const Twilio = require('twilio').Twilio;
const client = new Twilio(accountSid, authToken);
const service = client.chat.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
service
.roles('RLXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
.remove()
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
| mit |
smc314/helix | qd/welcome/source/class/welcome/layout/LayoutButton.js | 488 | /* ************************************************************************
Copyright: Hericus Software, LLC
License: The MIT License (MIT)
Authors: Steven M. Cherry
************************************************************************ */
qx.Mixin.define("welcome.layout.LayoutButton", {
members : {
createButton : function ( theThis, elem, parent ) {
var obj = new qx.ui.form.Button();
this.processAttributes( theThis, elem, obj );
return obj;
}
}
});
| mit |
dolare/myCMS | static/fontawesome5/fontawesome-pro-5.0.2/fontawesome-pro-5.0.2/advanced-options/use-with-node-js/fontawesome-pro-solid/faTabletAndroidAlt.js | 402 | module.exports = { prefix: 'fas', iconName: 'tablet-android-alt', icon: [448, 512, [], "f3fc", "M400 0H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V48c0-26.5-21.5-48-48-48zM288 452c0 6.6-5.4 12-12 12H172c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h104c6.6 0 12 5.4 12 12v8zm112-80c0 6.6-5.4 12-12 12H60c-6.6 0-12-5.4-12-12V60c0-6.6 5.4-12 12-12h328c6.6 0 12 5.4 12 12v312z"] }; | mit |
wholesale-design-system/components | build/tasks/prepare-release.js | 1782 | const gulp = require('gulp');
const runSequence = require('run-sequence');
const paths = require('../paths');
const conventionalChangelog = require('gulp-conventional-changelog');
const conventionalGitHubReleaser = require('conventional-github-releaser');
const bump = require('gulp-bump');
const args = require('../args');
const changelogOpts = {
preset: 'angular',
releaseCount: 1,
targetCommitish: args.branch
};
// utilizes the bump plugin to bump the
// semver for the repo
gulp.task('bump-version', () =>
gulp.src(['./package.json'])
.pipe(bump({type: args.bump}))
.pipe(gulp.dest('./'))
);
// generates the CHANGELOG.md file based on commit
// from git commit messages
gulp.task('changelog', () =>
gulp.src(`${paths.doc}/CHANGELOG.md`)
.pipe(conventionalChangelog(changelogOpts))
.pipe(gulp.dest(paths.doc))
);
// calls the listed sequence of tasks in order
gulp.task('prepare-release', callback =>
runSequence(
'build',
'lint',
'bump-version',
'changelog',
callback
)
);
gulp.task('release', callback => {
conventionalGitHubReleaser({
type: 'oauth',
token: args.token || process.env.CONVENTIONAL_GITHUB_RELEASER_TOKEN
}, changelogOpts, {}, {}, {}, {}, (err, data) => {
if (err) {
console.error(err.toString());
return callback();
}
if (!data.length) {
console.log('No GitHub releases created because no git tags available to work with.');
return callback();
}
let allRejected = true;
for (let i = data.length - 1; i >= 0; i--) {
if (data[i].state === 'fulfilled') {
allRejected = false;
break;
}
}
if (allRejected) {
console.error(data);
} else {
console.log(data);
}
return callback();
});
});
| mit |
frisbeesport/frisbeesport.nl | vendor/bolt/common/src/Exception/DumpException.php | 91 | <?php
namespace Bolt\Common\Exception;
class DumpException extends \RuntimeException
{
}
| mit |
glenjamin/react-bootstrap | www/src/examples/OverlayCustom.js | 1331 | function CustomPopover({ className, style }) {
return (
<div
className={className}
style={{
...style,
position: 'absolute',
backgroundColor: '#EEE',
boxShadow: '0 5px 10px rgba(0, 0, 0, 0.2)',
border: '1px solid #CCC',
borderRadius: 3,
marginLeft: -5,
marginTop: 5,
padding: 10,
}}
>
<strong>Holy guacamole!</strong> Check this info.
</div>
);
}
class Example extends React.Component {
constructor(props, context) {
super(props, context);
this.handleToggle = this.handleToggle.bind(this);
this.state = {
show: true,
};
}
handleToggle() {
this.setState(s => ({ show: !s.show }));
}
render() {
return (
<div style={{ height: 100, position: 'relative' }}>
<Button
ref={button => {
this.target = button;
}}
onClick={this.handleToggle}
>
I am an Overlay target
</Button>
<Overlay
show={this.state.show}
onHide={() => this.setState({ show: false })}
placement="right"
container={this}
target={() => ReactDOM.findDOMNode(this.target)}
>
<CustomPopover />
</Overlay>
</div>
);
}
}
render(<Example />);
| mit |
tareqmahmud/URI-CPP | BEGINNER/1075.cpp | 253 | #include <iostream>
using namespace std;
int main() {
// Initialize variable
int N;
// Take input
cin >> N;
for (int i = 1; i <= 10000; i++) {
if (i % N == 2) {
cout << i << endl;
}
}
return 0;
} | mit |
Faldon/pShow | pShow/Properties/AssemblyInfo.cs | 1424 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("pShow")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("pShow")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("815883ed-8703-4c91-81e9-3c36f670ce9d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.0")]
[assembly: AssemblyFileVersion("1.4.0916")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| mit |
nevernotsean/bg-theme | template-parts/buy-board-filters.php | 3958 | <div class="row collapse" id="filters">
<div class="medium-4 large-3 column">
<ul class="menu simple coast-links">
<li class="show-for-medium" style="margin-left: 0px;"><span class="bold">FILTERS:</span></li>
<li><a href="<?php echo site_url() ?>/buy-boards">All</a></li>
<li><a href="<?php echo site_url() ?>/buy-boards/west-coast">West Coast</a></li>
<li><a href="<?php echo site_url() ?>/buy-boards/east-coast">East Coast</a></li>
</ul>
</div>
<div class="medium-8 large-9 column">
<ul class="dropdown menu filters no-fouc" id="js-board-filters">
<?php if ( is_user_logged_in() ){ ?>
<!-- <li>
<a href="" class="parent">Secret Filters</a>
<ul class="unstyled">
<li><a href="<?php echo site_url() ?>/buy-boards/?grabbed=1">Sort by Grab Button Clicks</a></li>
</ul>
</li> -->
<?php } ?>
<?php foreach( $GLOBALS['bg_query_filters'] as $key => $field_key ):
echo '<li class="filterGroup">';
// get the field's settings without attempting to load a value
$field = get_field_object($field_key, false, false);
$name = $field['name'];
// set value if available
if( isset($_GET[ $field_key ]) ) {
$field['value'] = explode(',', $_GET[ $field_key ]);
}
// Loop over filter types
if ( $name == 'board_coast') { ?>
<a href="" class="arrow parent" data-filterkey="style">Board Location</a>
<ul class="unstyled board-coast-list">
<li><a href="#" data-filter="eastcoast" class="filter-btn">East Coast</a></li>
<li><a href="#" data-filter="westcoast" class="filter-btn">West Coast</a></li>
</ul>
<?php }
if ( $name == 'board_location' ) {
echo '<a href="" class="arrow parent" data-filterkey="shop">Board Shop</a>';
echo get_template_part('template-parts/board-shop-list');
} elseif ( $name == 'board_state' ){
echo '<a href="" class="arrow parent" data-filterkey="state">Board State</a>';
include(locate_template('template-parts/board-state-list.php'));
} elseif ( $name == 'board_price' ){ ?>
<?php
$low = get_field('low_range_price', 'option');
$mid = get_field('mid_range_price', 'option');
?>
<a href="" class="arrow parent" data-filterkey="price">Price</a>
<ul class="unstyled board-price-list">
<li><a href="#" data-filter="asc" class="filter-btn">Low to High</a></li>
<li><a href="#" data-filter="desc" class="filter-btn">High to Low</a></li>
<li><a href="#" data-filter="low" class="filter-btn">$1 - $<?php echo $low ?></a></li>
<li><a href="#" data-filter="med" class="filter-btn">$<?php echo $low ?> - $<?php echo $mid ?></a></li>
<li><a href="#" data-filter="high" class="filter-btn">$<?php echo $mid ?> +</a></li>
</ul>
<?php } elseif ( $name == 'board_style') { ?>
<a href="" class="arrow parent" data-filterkey="style">Board Size</a>
<ul class="unstyled board-size-list">
<li><a href="#" data-filter="shortboard" class="filter-btn">Shortboard</a></li>
<li><a href="#" data-filter="longboard" class="filter-btn">Longboard</a></li>
<li><a href="#" data-filter="funboard" class="filter-btn">Funboard</a></li>
<!-- <li><a href="#" data-filter="paddleboard" class="filter-btn">Paddleboard</a></li> -->
</ul>
<?php }
echo '</li>';
endforeach; ?>
<li class="clear-filters"><a href="<?php echo site_url() ?>/buy-boards/">Clear Filters</a></li>
</ul>
</div>
</div>
<hr style="margin-top: 0;"/>
<div class="row column text-center">
<div class="count-container">
<span>Viewing</span>
<span id="board-count">0</span>
<span>Boards</span>
</div>
</div>
| mit |
Sistiandy/ipung | application/helpers/cms_helper.php | 3118 | <?php
if (!function_exists('pretty_date')) {
function pretty_date($date = '', $format = '', $timezone = TRUE) {
$date_str = strtotime($date);
if (empty($format)) {
$date_pretty = date('l, d/m/Y H:i', $date_str);
} else {
$date_pretty = date($format, $date_str);
}
if ($timezone) {
$date_pretty .= ' WIB';
}
$date_pretty = str_replace('Sunday', 'Minggu', $date_pretty);
$date_pretty = str_replace('Monday', 'Senin', $date_pretty);
$date_pretty = str_replace('Tuesday', 'Selasa', $date_pretty);
$date_pretty = str_replace('Wednesday', 'Rabu', $date_pretty);
$date_pretty = str_replace('Thursday', 'Kamis', $date_pretty);
$date_pretty = str_replace('Friday', 'Jumat', $date_pretty);
$date_pretty = str_replace('Saturday', 'Sabtu', $date_pretty);
$date_pretty = str_replace('January', 'Januari', $date_pretty);
$date_pretty = str_replace('February', 'Februari', $date_pretty);
$date_pretty = str_replace('March', 'Maret', $date_pretty);
$date_pretty = str_replace('April', 'April', $date_pretty);
$date_pretty = str_replace('May', 'Mei', $date_pretty);
$date_pretty = str_replace('June', 'Juni', $date_pretty);
$date_pretty = str_replace('July', 'Juli', $date_pretty);
$date_pretty = str_replace('August', 'Agustus', $date_pretty);
$date_pretty = str_replace('September', 'September', $date_pretty);
$date_pretty = str_replace('October', 'Oktober', $date_pretty);
$date_pretty = str_replace('November', 'November', $date_pretty);
$date_pretty = str_replace('December', 'Desember', $date_pretty);
return $date_pretty;
}
if (!function_exists('catalog_url')) {
function catalog_url($catalog = array()) {
list($date, $time) = explode(' ', $catalog['catalog_input_date']);
list($year, $month, $day) = explode('-', $date);
return site_url('catalog/detail/' . $year . '/' . $month . '/' . $day . '/' . $catalog['catalog_id'] . '/' . url_title($catalog['catalog_name'], '-', TRUE) . '.html');
}
}
if (!function_exists('catalog_category_url')) {
function catalog_category_url($category = array()) {
return site_url('catalog/category/' . $category['category_id'] . '/' . url_title($category['category_name'], '-', TRUE) . '.html');
}
}
if (!function_exists('template_media_url')) {
function template_media_url($name = '') {
return base_url('media/templates/' . config_item('template') . '/' . $name);
}
}
if (!function_exists('upload_url')) {
function upload_url($name = '') {
if (stristr($name, '://') !== FALSE) {
return $name;
} else {
return base_url('uploads/' . $name);
}
}
}
if (!function_exists('media_url')) {
function media_url($name = '') {
return base_url('media/' . $name);
}
}
}
?>
| mit |
ricallinson/knot | tests/app/lib/process.js | 3206 | // (The MIT License)
//
// Copyright (c) 2012 Richard S Allinson <rsa@mountainmansoftware.com>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
var assert = require('assert');
describe('process', function () {
describe('.execPath', function () {
it('should return /', function () {
assert.equal(process.execPath, '/', process.execPath);
});
});
describe('.cwd()', function () {
it('should return /', function () {
assert.equal(process.cwd(), '/', process.cwd());
});
});
describe('.version', function () {
it('should return 0.0.3', function () {
assert.equal(process.version, '0.0.3', process.version);
});
});
describe('.versions', function () {
it('should return {knot: val, arch: val}', function () {
assert.equal(process.versions.knot, '0.0.3', process.versions.knot);
assert.ok(process.versions.arch, process.versions.arch);
});
});
describe('.installPrefix', function () {
it('should return /knot/', function () {
assert.equal(process.installPrefix, '/knot/', process.installPrefix);
});
});
describe('.stdout.write()', function () {
it('should return "function"', function () {
assert.equal(typeof process.stdout.write, 'function');
});
});
describe('.stderr.write()', function () {
it('should return "function"', function () {
assert.equal(typeof process.stderr.write, 'function');
});
});
describe('.arch', function () {
it('should return string', function () {
assert.ok(process.arch, process.arch);
});
});
describe('.platform', function () {
it('should return sting', function () {
assert.ok(process.platform, process.platform);
});
});
describe('.uptime()', function () {
it('should return int', function () {
assert.equal(parseInt(process.uptime()).toString(), process.uptime(), process.uptime());
});
});
});
| mit |
mokton/NodeMCU-Document-Download | download.py | 8971 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 10 09:10:48 2017
@author: Angus
"""
import urllib2
import os, re
modules = ["adc","adxl345","am2320","apa102","bit","bme280",
"bmp085","cjson","coap","crypto","dht","encoder","enduser-setup",
"file","gpio","hmc5883l","http","hx711","i2c","l3g4200d","mdns",
"mqtt","net","node","ow","pcm","perf","pwm","rc","rotary",
"rtcfifo","rtcmem","rtctime","sigma-delta","sntp","somfy","spi",
"struct","switec","tm1829","tmr","tsl2561","u8g","uart","ucg",
"wifi","ws2801","ws2812","websocket","cron"]
css = ["http://nodemcu.readthedocs.io/en/master/css/theme.css",
"http://nodemcu.readthedocs.io/en/master/css/theme_extra.css",
"http://nodemcu.readthedocs.io/en/master/css/highlight.css",
"http://nodemcu.readthedocs.io/en/master/css/extra.css",
"https://media.readthedocs.org//css/badge_only.css",
"https://media.readthedocs.org//css/readthedocs-doc-embed.css"]
js = ["http://nodemcu.readthedocs.io/en/master/js/jquery-2.1.1.min.js",
"http://nodemcu.readthedocs.io/en/master/js/modernizr-2.8.3.min.js",
"http://nodemcu.readthedocs.io/en/master/js/highlight.pack.js",
"http://nodemcu.readthedocs.io/en/master/js/theme.js",
"http://nodemcu.readthedocs.io/en/master/js/extra.js",
"https://media.readthedocs.org/static/core/js/readthedocs-doc-embed.js",
"http://nodemcu.readthedocs.io/en/master/readthedocs-data.js",
"http://nodemcu.readthedocs.io/en/master/readthedocs-dynamic-include.js"]
icon = "http://nodemcu.readthedocs.io/en/master/img/favicon.png"
def get_page(url):
page = ""
for i in range(3):
try:
myheaders = {'Connection':'Keep-Alive',
"User-Agent": "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36"}
req = urllib2.Request(url, headers = myheaders)
res = urllib2.urlopen(req, timeout = 15)
page = res.read()
break
except Exception, msg:
print "[-] Error getting html:", msg
return(page)
# level: dev or master
def download(level = "dev", single = False, module = ""):
home = "http://nodemcu.readthedocs.io/en/" + level + "/en/modules/"
direct_path = os.path.abspath(os.curdir) + "/" + level
if not os.path.exists(direct_path):
os.mkdir(direct_path)
if single:
try:
url = home + module
html = get_page(url)
if html <> "":
filename = direct_path + "/" + module + ".html"
f = open(filename, "w")
f.write(html)
f.close()
print(module + " is done.")
else:
print(module + " is empty.")
except Exception, e:
print e
else:
for m in modules:
try:
url = home + m
html = get_page(url)
if html <> "":
filename = direct_path + "/" + m + ".html"
f = open(filename, "w")
f.write(html)
f.close()
print(m + " download is done.")
else:
print(m + " is empty.")
except Exception, e:
print e
def replace_content(level = "dev", single = False, module = ""):
direct_path = os.path.abspath(os.curdir) + "/" + level
if not os.path.exists(direct_path):
os.mkdir(direct_path)
p1 = re.compile(r'<li class="toctree-l1 ">(.*)<li><span>Modules</span></li>', re.S)
p2 = re.compile(r'<li class="toctree-l1 ">(.*?)<a class="" href="(.*?)">(.*?)</a>(.*?)</li>', re.S)
p3 = re.compile(r'<div class="rst-versions.*</div>', re.S)
if single:
try:
filename = direct_path + "/" + module + ".html"
f = open(filename, "r")
content = str(f.read())
f.close()
#print(p2.findall(content))
content = p1.sub('<li class="toctree-l1 "><span>Modules</span></li>', content, 1)
content = p2.sub('<li class="toctree-l1 ">\g<1><a class="" href="\g<3>.html">\g<3></a>\g<4></li>', content)
content = p3.sub('', content)
content = content.replace("../../../img/favicon", "favicon")
content = content.replace("../../../css/", "css/")
content = content.replace("https://media.readthedocs.org//css/", "css/")
content = content.replace("../../../js/", "js/")
content = content.replace("https://media.readthedocs.org/static/core/js/", "js/")
content = content.replace("../../../readthedocs", "js/readthedocs")
content = content.replace("enduser setup.html", "enduser-setup.html")
content = content.replace("ow (1-Wire).html", "ow.html")
content = content.replace("sigma delta.html", "sigma-delta.html")
#print(content)
f = open(filename, "w")
f.write(content)
f.close()
print(module + " replace is done.")
except Exception, e:
print e
else:
for m in modules:
try:
filename = direct_path + "/" + m + ".html"
f = open(filename, "r")
content = str(f.read())
f.close()
content = p1.sub('<li class="toctree-l1 "><span>Modules</span></li>', content, 1)
content = p2.sub('<li class="toctree-l1 ">\g<1><a class="" href="\g<3>.html">\g<3></a>\g<4></li>', content)
content = p3.sub('', content)
content = content.replace("../../../img/favicon", "favicon")
content = content.replace("../../../css/", "css/")
content = content.replace("https://media.readthedocs.org//css/", "css/")
content = content.replace("../../../js/", "js/")
content = content.replace("https://media.readthedocs.org/static/core/js/", "js/")
content = content.replace("../../../readthedocs", "js/readthedocs")
content = content.replace("enduser setup.html", "enduser-setup.html")
content = content.replace("ow (1-Wire).html", "ow.html")
content = content.replace("sigma delta.html", "sigma-delta.html")
#print(content)
f = open(filename, "w")
f.write(content)
f.close()
print(m + " replace is done.")
except Exception, e:
print e
def css_js(level = "dev"):
direct_path = os.path.abspath(os.curdir) + "/" + level + "/css"
if not os.path.exists(direct_path):
os.mkdir(direct_path)
for url in css:
try:
html = get_page(url)
fn = os.path.basename(url)
if html <> "":
filename = direct_path + "/" + fn
f = open(filename, "w")
f.write(html)
f.close()
print(fn + " download is done.")
else:
print(fn + " is empty.")
except Exception, e:
print e
direct_path = os.path.abspath(os.curdir) + "/" + level + "/js"
if not os.path.exists(direct_path):
os.mkdir(direct_path)
for url in js:
try:
html = get_page(url)
fn = os.path.basename(url)
if html <> "":
filename = direct_path + "/" + fn
f = open(filename, "w")
f.write(html)
f.close()
print(fn + " download is done.")
else:
print(fn + " is empty.")
except Exception, e:
print e
try:
html = get_page(icon)
fn = os.path.basename(icon)
direct_path = os.path.abspath(os.curdir) + "/" + level
if html <> "":
filename = direct_path + "/" + fn
f = open(filename, "w")
f.write(html)
f.close()
print(fn + " download is done.")
else:
print(fn + " is empty.")
except Exception, e:
print e
if __name__ == "__main__":
#modules.sort()
#for m in modules:
# print(m)
level = "master" # no cron module
#level = "dev"
download(level=level)
#download(level=level, single=True,module="cron")
replace_content(level=level)
#replace_content(level=level, single=True,module="cron")
css_js(level=level)
#download(level=level, single=True,module="websocket")
#replace_content(level=level, single=True,module="websocket")
| mit |
gpoussel/cyclopaca | database/migrations/2017_08_19_151159_create_rankings_table.php | 862 | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRankingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('rankings', function (Blueprint $table) {
$table->increments('id');
$table->integer('season_id')->unsigned()->index();
$table->foreign('season_id')->references('id')->on('seasons');
$table->integer('cup_id')->unsigned()->index();
$table->foreign('cup_id')->references('id')->on('cups');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('rankings');
}
}
| mit |
noplay/sinatra-api-template | lib/models/user.rb | 1195 | require 'rubygems'
require 'bundler'
Bundler.require(:default)
class User
include DataMapper::Resource
include Paperclip::Resource
property :id, Serial
property :name, String, :unique => true, :length => 3..50, :required => true
property :password, BCryptHash, :required => true
property :email, String, :format => :email_address, :length => 6..50, :required => true
property :secret, String
property :created_at, DateTime
property :updated_at, DateTime
has_attached_file :resume,
:url => "/system/:attachment/:id/:style/:basename.:extension",
:path => "#{APP_ROOT}/public/system/:attachment/:id/:style/:basename.:extension"
def to_json(params = {})
rep = {
:id => self.id,
:name => self.name,
:email => self.email
}
if self.resume.file?
rep[:resume] = self.resume.url
end
JSON.generate(rep)
end
def to_json_private(params={})
JSON.generate({
:id => self.id,
:name => self.name,
:email => self.email,
:secret => self.secret
})
end
end
| mit |
hyn/magician | src/Events/NotifyClientleftview.php | 260 | <?php namespace Hyn\Teamspeak\Daemon\Events;
use Hyn\Teamspeak\Daemon\Abstracts\AbstractEvent;
class NotifyClientleftview extends AbstractEvent {
/**
* @return string
*/
public function getName()
{
return 'client left';
}
} | mit |
RawSanj/SOFRepos | SOFProjectTest/src/CSP600/AddPresentationDAO.java | 1959 | /*
* 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 CSP600;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
*
* @author user
*/
public class AddPresentationDAO {
static Connection currentCon = null;
static ResultSet rs = null;
public static PresentationBean addpresentation(PresentationBean PBean){
System.out.println("JIJIJI");
int presentationID = PBean.getPresentationID();
String presentationDay = PBean.getPresentationDay();
String presentationStart = PBean.getPresentationStart();
String presentationEnd = PBean.getPresentationEnd();
try{
currentCon = JavaConnectionDB.getConnection();
PreparedStatement ps=currentCon.prepareStatement("insert into presentation (presentationID,presentationDay,presentationStart,presentationEnd) values (presentationseq.nextval,?,?,?)");
ps.setString(1,PBean.getPresentationDay());
ps.setString(2,PBean.getPresentationStart());
ps.setString(3,PBean.getPresentationEnd());
//ps.setInt(4,PBean.getPresentationID());
ps.addBatch();
// int[] result=ps.executeBatch();
//System.out.println("no of rows"+ result.length);
// System.out.println("Your presentation ID is " + presentationID);
System.out.println("Your day is " + presentationDay);
System.out.println("Your start is " + presentationStart);
System.out.println("Your end is " + presentationEnd);
}
catch(Exception e){
System.out.println("Add presentation failed: An Exception has occurred! " + e);
}
return PBean;
}
}
| mit |
daveross/Embed | tests/LineTest.php | 718 | <?php
class LineTest extends PHPUnit_Framework_TestCase
{
public function testOne()
{
$info = Embed\Embed::create('https://line.do/embed/8oq/vertical');
$this->assertEquals($info->title, 'PHP Evolution');
$this->assertEquals($info->type, 'rich');
$this->assertEquals($info->code, '<iframe src="https://line.do/embed/8oq/vertical" frameborder="0" allowTransparency="true" style="border:1px solid #e7e7e7;width:640px;height:640px;"></iframe>');
$this->assertEquals($info->width, 640);
$this->assertEquals($info->height, 640);
$this->assertEquals($info->providerName, 'Line.do');
$this->assertEquals($info->providerUrl, 'https://line.do');
}
}
| mit |
dbi/eye | spec/dsl/with_server_spec.rb | 7029 | require File.dirname(__FILE__) + '/../spec_helper'
describe "with_server feature" do
it "should load matched by string process" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
with_server "server1" do
process("1"){ pid_file "1.pid" }
end
with_server "server2" do
process("2"){ pid_file "2.pid" }
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla"=>{:name => "bla", :groups=>{"__default__"=>{:name => "__default__", :application => "bla", :processes=>{"1"=>{:pid_file=>"1.pid", :application=>"bla", :group=>"__default__", :name=>"1"}}}}}}
end
it "should another host conditions" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
with_server %w{server1 server2} do
process("1"){ pid_file "1.pid" }
if Eye::SystemResources == 'server2'
process("2"){ pid_file "2.pid" }
end
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla"=>{:name => "bla", :groups=>{"__default__"=>{:name => "__default__", :application => "bla", :processes=>{"1"=>{:pid_file=>"1.pid", :application=>"bla", :group=>"__default__", :name=>"1"}}}}}}
end
it "should behaves like scoped" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
env "A" => "B"
with_server /server1/ do
env "A" => "C"
group(:a){}
end
group(:b){}
end
E
Eye::Dsl.parse_apps(conf).should == {
"bla" => {:name=>"bla", :environment=>{"A"=>"B"},
:groups=>{
"a"=>{:name=>"a", :environment=>{"A"=>"C"}, :application=>"bla", :processes=>{}},
"b"=>{:name=>"b", :environment=>{"A"=>"B"}, :application=>"bla", :processes=>{}}}}}
end
describe "matches" do
subject{ Eye::Dsl::Opts.new }
it "match string" do
stub(Eye::Local).host{ "server1" }
subject.with_server("server1").should == true
subject.with_server("server2").should == false
subject.with_server('').should == true
subject.with_server(nil).should == true
end
it "match array" do
stub(Eye::Local).host{ "server1" }
subject.with_server(%w{ server1 server2}).should == true
subject.with_server(%w{ server2 server3}).should == false
end
it "match regexp" do
stub(Eye::Local).host{ "server1" }
subject.with_server(%r{server}).should == true
subject.with_server(%r{myserver}).should == false
end
end
describe "helpers" do
it "hostname on with server" do
conf = <<-E
x = current_config_path
Eye.application("bla"){
with_server('muga_server') do
working_dir "/tmp"
end
}
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name => "bla"}}
end
it "with_server work" do
Eye::Local.host = 'mega_server'
conf = <<-E
Eye.application("bla"){
with_server('mega_server') do
group :blo do
working_dir "/tmp"
end
end
}
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name=>"bla", :groups=>{"blo"=>{:name=>"blo", :application=>"bla", :working_dir=>"/tmp", :processes=>{}}}}}
end
it "hostname work" do
Eye::Local.host = 'supa_server'
conf = <<-E
Eye.application("bla"){
working_dir "/tmp"
env "HOST" => hostname
}
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name => "bla", :working_dir=>"/tmp", :environment=>{"HOST"=>"supa_server"}}}
end
end
describe "Merging groups in scoped" do
it "double with_server (was a bug)" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
with_server "server1" do
process("1"){ pid_file "1.pid" }
end
with_server "server1" do
process("2"){ pid_file "2.pid" }
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name=>"bla", :groups=>{"__default__"=>{:name=>"__default__", :application=>"bla", :processes=>{"1"=>{:name=>"1", :application=>"bla", :group=>"__default__", :pid_file=>"1.pid"}, "2"=>{:name=>"2", :application=>"bla", :group=>"__default__", :pid_file=>"2.pid"}}}}}}
end
it "double with_server in a group" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
group :bla do
with_server "server1" do
process("1"){ pid_file "1.pid" }
end
with_server "server1" do
process("2"){ pid_file "2.pid" }
end
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name=>"bla", :groups=>{"bla"=>{:name=>"bla", :application=>"bla", :processes=>{"1"=>{:name=>"1", :application=>"bla", :group=>"bla", :pid_file=>"1.pid"}, "2"=>{:name=>"2", :application=>"bla", :group=>"bla", :pid_file=>"2.pid"}}}}}}
end
it "double with_server in a group" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
with_server "server1" do
group :gr1 do
process("1"){ pid_file "1.pid" }
end
end
with_server "server1" do
group :gr1 do
process("2"){ pid_file "2.pid" }
end
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name=>"bla", :groups=>{"gr1"=>{:name=>"gr1", :application=>"bla", :processes=>{"1"=>{:name=>"1", :application=>"bla", :group=>"gr1", :pid_file=>"1.pid"}, "2"=>{:name=>"2", :application=>"bla", :group=>"gr1", :pid_file=>"2.pid"}}}}}}
end
it "double with_server in a group" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
process("1"){ pid_file "1.pid" }
with_server "server1" do
process("2"){ pid_file "2.pid" }
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name=>"bla", :groups=>{"__default__"=>{:name=>"__default__", :application=>"bla", :processes=>{"1"=>{:name=>"1", :application=>"bla", :group=>"__default__", :pid_file=>"1.pid"}, "2"=>{:name=>"2", :application=>"bla", :group=>"__default__", :pid_file=>"2.pid"}}}}}}
end
it "with scoped" do
stub(Eye::Local).host{ "server1" }
conf = <<-E
Eye.application("bla") do
process("1"){ pid_file "1.pid" }
scoped do
process("2"){ pid_file "2.pid" }
end
end
E
Eye::Dsl.parse_apps(conf).should == {"bla" => {:name=>"bla", :groups=>{"__default__"=>{:name=>"__default__", :application=>"bla", :processes=>{"1"=>{:name=>"1", :application=>"bla", :group=>"__default__", :pid_file=>"1.pid"}, "2"=>{:name=>"2", :application=>"bla", :group=>"__default__", :pid_file=>"2.pid"}}}}}}
end
end
end | mit |
okin/nikola | nikola/data/themes/base/messages/messages_te.py | 2399 | # -*- encoding:utf-8 -*-
"""Autogenerated file, do not edit. Submit translations on Transifex."""
MESSAGES = {
"%d min remaining to read": "%d నిమిషాలు చదవడానికి కావలెను ",
"(active)": "(క్రియాశీల)",
"Also available in:": "ఇందులో కూడా లభించును:",
"Archive": "అభిలేఖలు ",
"Atom feed": "",
"Authors": "రచయితలు",
"Categories": "వర్గాలు",
"Comments": "వ్యాఖ్యలు",
"LANGUAGE": "తెలుగు",
"Languages:": "భాషలు:",
"More posts about %s": "%s గూర్చి మరిన్ని టపాలు",
"Newer posts": "కొత్త టపాలు",
"Next post": "తరువాత టపా",
"Next": "",
"No posts found.": "",
"Nothing found.": "",
"Older posts": "పాత టపాలు",
"Original site": "వాస్తవ సైట్",
"Posted:": "ప్రచురుంచిన తేదీ:",
"Posts about %s": "%s గూర్చి టపాలు",
"Posts by %s": "%s యొక్క టపాలు",
"Posts for year %s": "%s సంవత్సర టపాలు",
"Posts for {month_day_year}": "",
"Posts for {month_year}": "",
"Previous post": "మునుపటి టపా",
"Previous": "",
"Publication date": "ప్రచురణ తేదీ",
"RSS feed": "RSS ఫీడ్",
"Read in English": "తెలుగులో చదవండి",
"Read more": "ఇంకా చదవండి",
"Skip to main content": "ప్రధాన విషయానికి వెళ్ళు",
"Source": "మూలం",
"Subcategories:": "ఉపవర్గాలు:",
"Tags and Categories": "ట్యాగ్లు మరియు వర్గాలు",
"Tags": "ట్యాగ్లు",
"Toggle navigation": "",
"Uncategorized": "వర్గీకరించని",
"Up": "",
"Updates": "నవీకరణలు",
"Write your page here.": "మీ పేజీ ఇక్కడ రాయండి.",
"Write your post here.": "ఇక్కడ మీ టపా ను వ్రాయండి.",
"old posts, page %d": "పాత టపాలు, పేజీ %d",
"page %d": "పేజీ %d",
"updated": "",
}
| mit |
tretum/Avorion-Obj-Converter | waveobjparser/ObjWriter.py | 2925 | import os
from typing import List
from waveobjparser import Face
from waveobjparser import Normal
from waveobjparser import Scene
from waveobjparser import Text_Coord
from waveobjparser import Vertex
from waveobjparser import WaveObject
def writeName(file, name: str):
file.write("o {}\n".format(name))
def writeVertices(file, vertices: List[Vertex]):
for vertex in vertices:
file.write("v {v[0]} {v[1]} {v[2]}\n".format(v=vertex))
def writeTextureCoordinates(file, texture_coords: List[Text_Coord]):
for coord in texture_coords:
file.write("vt {t[0]} {t[1]}\n".format(t=coord))
def writeNormals(file, vertex_normals: List[Normal]):
for normal in vertex_normals:
file.write("vn {n[0]} {n[1]} {n[2]}\n".format(n=normal))
def writeMaterial(file, material):
file.write("usemtl None\n") # TODO Implement
def writeSmoothing(file, smoothing: bool):
string = "on" if smoothing else "off"
file.write("s {}\n".format(string))
class ObjWriter:
def __init__(self, outputFile):
self.vertex_count = 0
self.uv_count = 0
self.normals_count = 0
self.output_file = outputFile
def writeScene(self, scene: Scene):
if type(self.output_file) is os.path:
path = os.path.join(self.output_file)
else:
path = self.output_file
print("Starting output on file ", path)
with open(path, "w") as file:
file.write("mtllib {}\n".format(scene.mtllib))
for object in scene.objects:
writeName(file, object.name)
writeVertices(file, object.vertices)
writeTextureCoordinates(file, object.texture_coords)
writeNormals(file, object.vertex_normals)
writeMaterial(file, object.material)
writeSmoothing(file, object.smoothing)
self.writeFaces(file, object.faces)
self.vertex_count += len(object.vertices)
self.normals_count += len(object.vertex_normals)
self.uv_count += len(object.texture_coords)
def writeFaces(self, file, faces: List[Face]):
for face in faces:
file.write("f ")
for vertex in face:
if vertex[2] != '':
if vertex[1] != '':
file.write("{}/{}/{} ".format(int(vertex[0]) + self.vertex_count,
int(vertex[1]) + self.uv_count,
int(vertex[2]) + self.normals_count))
else:
file.write("{}//{} ".format(int(vertex[0]) + self.vertex_count,
int(vertex[2]) + self.normals_count))
else:
file.write("{} ".format(int(vertex[0] + self.vertex_count)))
file.write("\n")
| mit |
patelsan/fetchpipe | node_modules/log4js/test/smtpAppender-test-compiled.js | 8717 | "use strict";
var vows = require('vows'),
assert = require('assert'),
log4js = require('../lib/log4js'),
sandbox = require('sandboxed-module');
function setupLogging(category, options) {
var msgs = [];
var fakeMailer = {
createTransport: function createTransport(name, options) {
return {
config: options,
sendMail: function sendMail(msg, callback) {
msgs.push(msg);
callback(null, true);
},
close: function close() {}
};
}
};
var fakeLayouts = {
layout: function layout(type, config) {
this.type = type;
this.config = config;
return log4js.layouts.messagePassThroughLayout;
},
basicLayout: log4js.layouts.basicLayout,
messagePassThroughLayout: log4js.layouts.messagePassThroughLayout
};
var fakeConsole = {
errors: [],
error: function error(msg, value) {
this.errors.push({ msg: msg, value: value });
}
};
var fakeTransportPlugin = function fakeTransportPlugin() {};
var smtpModule = sandbox.require('../lib/appenders/smtp', {
requires: {
'nodemailer': fakeMailer,
'nodemailer-sendmail-transport': fakeTransportPlugin,
'nodemailer-smtp-transport': fakeTransportPlugin,
'../layouts': fakeLayouts
},
globals: {
console: fakeConsole
}
});
log4js.addAppender(smtpModule.configure(options), category);
return {
logger: log4js.getLogger(category),
mailer: fakeMailer,
layouts: fakeLayouts,
console: fakeConsole,
results: msgs
};
}
function checkMessages(result, sender, subject) {
for (var i = 0; i < result.results.length; ++i) {
assert.equal(result.results[i].from, sender);
assert.equal(result.results[i].to, 'recipient@domain.com');
assert.equal(result.results[i].subject, subject ? subject : 'Log event #' + (i + 1));
assert.ok(new RegExp('.+Log event #' + (i + 1) + '\n$').test(result.results[i].text));
}
}
log4js.clearAppenders();
vows.describe('log4js smtpAppender').addBatch({
'minimal config': {
topic: function topic() {
var setup = setupLogging('minimal config', {
recipients: 'recipient@domain.com',
SMTP: {
port: 25,
auth: {
user: 'user@domain.com'
}
}
});
setup.logger.info('Log event #1');
return setup;
},
'there should be one message only': function thereShouldBeOneMessageOnly(result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function messageShouldContainProperData(result) {
checkMessages(result);
}
},
'fancy config': {
topic: function topic() {
var setup = setupLogging('fancy config', {
recipients: 'recipient@domain.com',
sender: 'sender@domain.com',
subject: 'This is subject',
SMTP: {
port: 25,
auth: {
user: 'user@domain.com'
}
}
});
setup.logger.info('Log event #1');
return setup;
},
'there should be one message only': function thereShouldBeOneMessageOnly(result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function messageShouldContainProperData(result) {
checkMessages(result, 'sender@domain.com', 'This is subject');
}
},
'config with layout': {
topic: function topic() {
var setup = setupLogging('config with layout', {
layout: {
type: "tester"
}
});
return setup;
},
'should configure layout': function shouldConfigureLayout(result) {
assert.equal(result.layouts.type, 'tester');
}
},
'separate email for each event': {
topic: function topic() {
var self = this;
var setup = setupLogging('separate email for each event', {
recipients: 'recipient@domain.com',
SMTP: {
port: 25,
auth: {
user: 'user@domain.com'
}
}
});
setTimeout(function () {
setup.logger.info('Log event #1');
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 500);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1100);
setTimeout(function () {
self.callback(null, setup);
}, 3000);
},
'there should be three messages': function thereShouldBeThreeMessages(result) {
assert.equal(result.results.length, 3);
},
'messages should contain proper data': function messagesShouldContainProperData(result) {
checkMessages(result);
}
},
'multiple events in one email': {
topic: function topic() {
var self = this;
var setup = setupLogging('multiple events in one email', {
recipients: 'recipient@domain.com',
sendInterval: 1,
SMTP: {
port: 25,
auth: {
user: 'user@domain.com'
}
}
});
setTimeout(function () {
setup.logger.info('Log event #1');
}, 0);
setTimeout(function () {
setup.logger.info('Log event #2');
}, 100);
setTimeout(function () {
setup.logger.info('Log event #3');
}, 1500);
setTimeout(function () {
self.callback(null, setup);
}, 3000);
},
'there should be two messages': function thereShouldBeTwoMessages(result) {
assert.equal(result.results.length, 2);
},
'messages should contain proper data': function messagesShouldContainProperData(result) {
assert.equal(result.results[0].to, 'recipient@domain.com');
assert.equal(result.results[0].subject, 'Log event #1');
assert.equal(result.results[0].text.match(new RegExp('.+Log event #[1-2]$', 'gm')).length, 2);
assert.equal(result.results[1].to, 'recipient@domain.com');
assert.equal(result.results[1].subject, 'Log event #3');
assert.ok(new RegExp('.+Log event #3\n$').test(result.results[1].text));
}
},
'error when sending email': {
topic: function topic() {
var setup = setupLogging('error when sending email', {
recipients: 'recipient@domain.com',
sendInterval: 0,
SMTP: { port: 25, auth: { user: 'user@domain.com' } }
});
setup.mailer.createTransport = function () {
return {
sendMail: function sendMail(msg, cb) {
cb({ message: "oh noes" });
},
close: function close() {}
};
};
setup.logger.info("This will break");
return setup.console;
},
'should be logged to console': function shouldBeLoggedToConsole(cons) {
assert.equal(cons.errors.length, 1);
assert.equal(cons.errors[0].msg, "log4js.smtpAppender - Error happened");
assert.equal(cons.errors[0].value.message, 'oh noes');
}
},
'transport full config': {
topic: function topic() {
var setup = setupLogging('transport full config', {
recipients: 'recipient@domain.com',
transport: {
plugin: 'sendmail',
options: {
path: '/usr/sbin/sendmail'
}
}
});
setup.logger.info('Log event #1');
return setup;
},
'there should be one message only': function thereShouldBeOneMessageOnly(result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function messageShouldContainProperData(result) {
checkMessages(result);
}
},
'transport no-options config': {
topic: function topic() {
var setup = setupLogging('transport no-options config', {
recipients: 'recipient@domain.com',
transport: {
plugin: 'sendmail'
}
});
setup.logger.info('Log event #1');
return setup;
},
'there should be one message only': function thereShouldBeOneMessageOnly(result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function messageShouldContainProperData(result) {
checkMessages(result);
}
},
'transport no-plugin config': {
topic: function topic() {
var setup = setupLogging('transport no-plugin config', {
recipients: 'recipient@domain.com',
transport: {}
});
setup.logger.info('Log event #1');
return setup;
},
'there should be one message only': function thereShouldBeOneMessageOnly(result) {
assert.equal(result.results.length, 1);
},
'message should contain proper data': function messageShouldContainProperData(result) {
checkMessages(result);
}
}
})['export'](module);
//# sourceMappingURL=smtpAppender-test-compiled.js.map | mit |
GeekyAnts/NativeBase | example/storybook/stories/components/composites/CircularProgress/MinMax.tsx | 556 | import React from 'react';
import { CircularProgress, Heading, Center, Box, Text } from 'native-base';
import { number } from '@storybook/addon-knobs';
export const Example = () => {
return (
<Center>
<Heading mb={6}>Adding Min and Max</Heading>
<CircularProgress
value={550}
max={number('Max', 1000)}
min={number('Min', 100)}
size={100}
>
550 / 1000
</CircularProgress>
<Box mt={5}>
<Text>Min: 100</Text>
<Text>Max: 1000</Text>
</Box>
</Center>
);
};
| mit |
flyinghail/Hail-Framework | src/Mail/Exception/SendException.php | 179 | <?php
/**
* Created by IntelliJ IDEA.
* User: Hao
* Date: 2016/10/8 0008
* Time: 15:47
*/
namespace Hail\Mail\Exception;
class SendException extends \RuntimeException
{
} | mit |
LeoMorales/webapps | application/views/autenticacion/bienvenido.php | 92 | <center>
<h1> Hola <?php echo $nombre; ?>! </h1>
<h2><?php echo $email; ?> </h2>
</center> | mit |
alu0100697032/naranjeroLPP | lib/examen/naranjero.rb | 1317 | require 'thread'
class Naranjero
attr_reader :altura, :edad, :contador, :arbolVivo, :produccion
def initialize(altura, edad, contador)
@edad = edad
#si el arbol pasa de 100 años muere
if(@edad >= 100)
@arbolVivo = false
@contador = 0
else
@arbolVivo = true
@contador = contador
@produccion = produccion
end
@altura = altura
end
def uno_mas
@edad = @edad +1
#se comprueba si el arbol ha pasado de 100 años
if(@edad >= 100)
@arbolVivo = false
@contador = 0
else
@altura = @altura + 1
@contador = @edad/5
@produccion = @contador
end
end
def recolectar_una
if(@arbolVivo == false)
mensaje = "El arbol esta muerto"
elsif(@contador == 0)
mensaje = "No hay naranjas"
elsif(@contador > 0)
@contador = @contador -1
mensaje = "La naranja estaba deliciosa"
end
end
def simulaTraza
t1 = Thread.new {100.times{uno_mas; sleep 0.0001}}
t2 = Thread.new {200.times{puts recolectar_una; sleep 0.00001}}
t1.join
t2.join
end
end | mit |
keyroads/DingtalkSDK | Keyroads.DingtalkSDK/IsvModel.cs | 3589 | using System.Collections.Generic;
namespace Keyroads.DingtalkSDK
{
public class GetSuiteTokenRequest
{
public string suite_key { get; set; }
public string suite_secret { get; set; }
public string suite_ticket { get; set; }
}
public class GetSuiteTokenResponse : IResponseValidation
{
public string suite_access_token { get; set; }
public int expires_in { get; set; }
public bool IsValidate()
{
return !string.IsNullOrEmpty(suite_access_token);
}
}
public class GetPermanentCodeRequest
{
public string tmp_auth_code { get; set; }
}
public class GetPermanentCodeResponse : IResponseValidation
{
public string permanent_code { get; set; }
public AuthCorpInfo auth_corp_info { get; set; }
public bool IsValidate()
{
return !string.IsNullOrEmpty(permanent_code) && auth_corp_info != null;
}
}
public class AuthCorpInfo
{
public string corpid { get; set; }
public string corp_name { get; set; }
public string corp_logo_url { get; set; }
public string industry { get; set; }
public string invite_code { get; set; }
public string license_code { get; set; }
public string auth_channel { get; set; }
public bool is_authenticated { get; set; }
public string invite_url { get; set; }
}
public class AuthUserInfo
{
public string userId { get; set; }
}
public class AuthAgentInfo
{
public string agent_name { get; set; }
public int agentid { get; set; }
public int appid { get; set; }
public string logo_url { get; set; }
public bool IsValidate()
{
return true;
}
}
public class AuthInfo
{
public List<AuthAgentInfo> agent { get; set; }
}
/// <summary>
/// 用于 activate_suite get_auth_info get_corp_token 的请求数据
/// </summary>
public class CommonIsvRequest
{
public string suite_key { get; set; }
public string auth_corpid { get; set; }
public string permanent_code { get; set; }
}
public class ActivateSuiteRequest
{
public string suite_key { get; set; }
public string auth_corpid { get; set; }
public string permanent_code { get; set; }
}
public class GetAuthInfoResponse : ErrorResponse
{
public AuthCorpInfo auth_corp_info { get; set; }
public AuthUserInfo auth_user_info { get; set; }
public AuthInfo auth_info { get; set; }
public override bool IsValidate()
{
return auth_corp_info != null && auth_user_info != null && auth_info != null;
}
}
public class GetAgentIsvRequest : CommonIsvRequest
{
public int agentid { get; set; }
}
public class GetAgentResponse : ErrorResponse
{
public int agentid { get; set; }
public string name { get; set; }
public string logo_url { get; set; }
public string description { get; set; }
public int close { get; set; }
public override bool IsValidate()
{
return !string.IsNullOrEmpty(name);
}
}
public class GetCorpTokenResponse : IResponseValidation
{
public string access_token { get; set; }
public int expires_in { get; set; }
public bool IsValidate()
{
return !string.IsNullOrEmpty(access_token);
}
}
}
| mit |
ChuanleiGuo/AlgorithmsPlayground | DP/MinimumWeightPathInATriangle.java | 884 | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MinimumWeightPathInATriangle {
public static int minimumPathTotal(List<List<Integer>> triangle) {
if (triangle.isEmpty()) {
return 0;
}
List<Integer> prevRow = new ArrayList<>(triangle.get(0));
for (int i = 1; i < triangle.size(); i++) {
List<Integer> currRow = new ArrayList<>(triangle.get(i));
currRow.set(0, currRow.get(0) + prevRow.get(0));
for (int j = 1; j < currRow.size() - 1; j++) {
currRow.set(j, currRow.get(j) + Math.min(prevRow.get(j - 1), prevRow.get(j)));
}
currRow.set(currRow.size() - 1, currRow.get(currRow.size() - 1) + prevRow.get(prevRow.size() - 1));
prevRow = currRow;
}
return Collections.min(prevRow);
}
}
| mit |
tjerwinchen/FusionDB | src/fusiondb/fastdb/javacli/Statement.java | 11286 | package javacli;
import java.lang.reflect.*;
/**
* Statement class is used to prepare and execute select statement
*/
public class Statement {
/**
* Cleanup unreferenced statement
*/
public void finalize() {
if (con != null) {
close();
}
}
/**
* Close the statement. This method release all resource assoiated with statement
* at client and server. f close method will not be called, cleanup still
* will be performed later when garbage collector call finilize method of this
* object
*/
public void close() {
if (con == null) {
throw new CliError("Statement already closed");
}
ComBuffer buf = new ComBuffer(Connection.cli_cmd_free_statement, stmtId);
con.send(buf);
con = null;
}
static class Parameter {
Parameter next;
String name;
int type;
int ivalue;
long lvalue;
float fvalue;
double dvalue;
String svalue;
Rectangle rvalue;
Parameter(String name) {
this.name = name;
type = Connection.cli_undefined;
}
}
/**
* Set boolean parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setBool(String name, boolean value) {
Parameter p = getParam(name);
p.ivalue = value ? 1 : 0;
p.type = Connection.cli_bool;
}
/**
* Set byte parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setByte(String name, byte value) {
Parameter p = getParam(name);
p.ivalue = value;
p.type = Connection.cli_int4;
}
/**
* Set short parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setShort(String name, short value) {
Parameter p = getParam(name);
p.ivalue = value;
p.type = Connection.cli_int4;
}
/**
* Set integer parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setInt(String name, int value) {
Parameter p = getParam(name);
p.ivalue = value;
p.type = Connection.cli_int4;
}
/**
* Set long parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setLong(String name, long value) {
Parameter p = getParam(name);
p.lvalue = value;
p.type = Connection.cli_int8;
}
/**
* Set double parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setDouble(String name, double value) {
Parameter p = getParam(name);
p.dvalue = value;
p.type = Connection.cli_real8;
}
/**
* Set float parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setFloat(String name, float value) {
Parameter p = getParam(name);
p.fvalue = value;
p.type = Connection.cli_real4;
}
/**
* Set string parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter
*/
public void setString(String name, String value) {
Parameter p = getParam(name);
p.svalue = value;
p.type = Connection.cli_asciiz;
}
/**
* Set reference parameter
* @param name - name of the parameter started with <code>%</code> character
* @param value - value of the parameter, <code>null</code> means null reference
*/
public void setRef(String name, Reference value) {
Parameter p = getParam(name);
p.ivalue = value != null ? value.oid : 0;
p.type = Connection.cli_oid;
}
/**
* Set rectangle parameter
* @param name - name of the parameter started with <code>%</code> character
* @param rect - value of the parameter
*/
public void setRectangle(String name, Rectangle rect) {
Parameter p = getParam(name);
p.rvalue = rect;
p.type = Connection.cli_rectangle;
}
/**
* Prepare (if needed) and execute select statement
* @return object set with the selected objects
*/
public ObjectSet fetch() {
return fetch(false);
}
/**
* Prepare (if needed) and execute select statement
* Only object set returned by the select for updated statement allows
* update and deletion of the objects.
* @param forUpdate - if cursor is opened in for update mode
* @return object set with the selected objects
*/
public ObjectSet fetch(boolean forUpdate) {
int i, n;
ComBuffer buf;
if (!prepared) {
buf = new ComBuffer(Connection.cli_cmd_prepare_and_execute, stmtId);
n = tableDesc.nColumns;
buf.putByte(nParams);
buf.putByte(n);
int len = stmtLen;
boolean addNull = false;
if (len == 0 || stmt[len-1] != 0) {
addNull = true;
len += nParams;
buf.putShort(len+1);
} else {
len += nParams;
buf.putShort(len);
}
i = 0;
Parameter p = params;
do {
byte ch = stmt[i++];
buf.putByte(ch);
len -= 1;
if (ch == '\0') {
if (len != 0) {
if (p.type == Connection.cli_undefined) {
throw new CliError("Unbound parameter " + p.name);
}
buf.putByte(p.type);
p = p.next;
len -= 1;
}
}
} while (len != 0);
if (addNull) {
buf.putByte('\0');
}
tableDesc.writeColumnDefs(buf);
} else { // statement was already prepared
buf = new ComBuffer(Connection.cli_cmd_execute, stmtId);
}
this.forUpdate = forUpdate;
buf.putByte(forUpdate ? 1 : 0);
for (Parameter p = params; p != null; p = p.next) {
switch (p.type) {
case Connection.cli_oid:
case Connection.cli_int4:
buf.putInt(p.ivalue);
break;
case Connection.cli_int1:
case Connection.cli_bool:
buf.putByte((byte)p.ivalue);
break;
case Connection.cli_int2:
buf.putShort((short)p.ivalue);
break;
case Connection.cli_int8:
buf.putLong(p.lvalue);
break;
case Connection.cli_real4:
buf.putFloat(p.fvalue);
break;
case Connection.cli_real8:
buf.putDouble(p.dvalue);
break;
case Connection.cli_asciiz:
buf.putAsciiz(p.svalue);
break;
}
}
prepared = true;
return new ObjectSet(this, con.sendReceive(buf));
}
protected Statement(Connection con, String sql, int stmtId) {
this.stmtId = stmtId;
int src = 0, dst = 0, len = sql.length();
int p = sql.indexOf("from");
if (p < 0 && (p = sql.indexOf("FROM")) < 0) {
throw new CliError("Bad statment: SELECT FROM expected");
}
p += 5;
while (p < len && sql.charAt(p) == ' ') {
p += 1;
}
int q = p;
while (++q < len && sql.charAt(q) != ' ');
if (p+1 == q) {
throw new CliError("Bad statment: table name expected after FROM");
}
String tableName = sql.substring(p, q);
synchronized (Connection.tableHash) {
tableDesc = (TableDescriptor)Connection.tableHash.get(tableName);
if (tableDesc == null) {
Class tableClass = null;
try {
tableClass = Class.forName(tableName);
} catch (ClassNotFoundException x) {
if (con.pkgs != null) {
String pkgs[] = con.pkgs;
for (int i = pkgs.length; --i >= 0;) {
try {
tableClass = Class.forName(pkgs[i] + '.' + tableName);
break;
} catch (ClassNotFoundException x1) {}
}
}
if (tableClass == null) {
Package pks[] = Package.getPackages();
for (int i = pks.length; --i >= 0;) {
try {
tableClass = Class.forName(pks[i].getName() + '.' + tableName);
break;
} catch (ClassNotFoundException x1) {}
}
}
if (tableClass == null) {
throw new CliError("Class " + tableName + " not found");
}
}
tableDesc = new TableDescriptor(tableClass);
Connection.tableHash.put(tableName, tableDesc);
}
}
byte buf[] = new byte[len];
while (src < len) {
char ch = sql.charAt(src);
if (ch == '\'') {
do {
do {
buf[dst++] = (byte)sql.charAt(src++);
if (src == len) {
throw new CliError("Unterminated string constant in query");
}
} while (sql.charAt(src) != '\'');
buf[dst++] = (byte)'\'';
} while (++src < len && sql.charAt(src) == '\'');
} else if (ch == '%') {
int begin = src;
do {
if (++src == len) {
break;
}
ch = sql.charAt(src);
} while ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9') || ch == '_');
if (ch == '%') {
throw new CliError("Invalid parameter name");
}
Parameter param = new Parameter(sql.substring(begin, src));
if (lastParam == null) {
params = param;
} else {
lastParam.next = param;
}
lastParam = param;
nParams += 1;
buf[dst++] = (byte)'\0';
} else {
buf[dst++]= (byte)sql.charAt(src++);
}
}
stmt = buf;
stmtLen = dst;
this.con = con;
}
protected Parameter getParam(String name) {
for (Parameter p = params; p != null; p = p.next) {
if (p.name.equals(name)) {
return p;
}
}
throw new CliError("No such parameter");
}
byte[] stmt;
int stmtId;
int stmtLen;
Connection con;
Parameter params;
Parameter lastParam;
int nParams;
Field columns;
int nColumns;
boolean prepared;
boolean forUpdate;
TableDescriptor tableDesc;
}
| mit |
jeffsee55/ntbcapital.com | templates/content.php | 608 | <?php if(has_post_thumbnail()) {
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'large', true);
$thumb_url = $thumb_url_array[0];
} else {
$thumb_url = get_theme_mod( 'site_image' );
}
?>
<a class="card article-card" href="<?php the_permalink(); ?>">
<img class="card-img-top" src="<?php echo $thumb_url ?>" alt="">
<div class="card-block">
<h2 class="entry-title"><?php the_title(); ?></h2>
<hr>
<div class="card-text entry-summary">
<?php the_excerpt(); ?>
</div>
<span class="read-more">Read More</span>
</div>
</a>
| mit |
Flexible-User-Experience/fibervent | app/DoctrineMigrations/Version20160709095729.php | 1269 | <?php
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160709095729 extends AbstractMigration
{
/**
* @param Schema $schema
*/
public function up(Schema $schema)
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE blade CHANGE length length DOUBLE PRECISION NOT NULL');
$this->addSql('ALTER TABLE turbine CHANGE rotor_diameter rotor_diameter DOUBLE PRECISION NOT NULL');
}
/**
* @param Schema $schema
*/
public function down(Schema $schema)
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
$this->addSql('ALTER TABLE blade CHANGE length length INT NOT NULL');
$this->addSql('ALTER TABLE turbine CHANGE rotor_diameter rotor_diameter INT NOT NULL');
}
}
| mit |
DaYeSquad/sakura-node-ts | src/util/stringutil.ts | 505 | // Copyright 2018 Frank Lin (lin.xiaoe.f@gmail.com). All rights reserved.
// Use of this source code is governed a license that can be found in the LICENSE file.
/**
* String Utils
*/
export class StringUtil {
/**
* Remove \n in string, useful when unit testing
*/
static removeBreaklines(str: string): string {
return str.replace(/(^[ \t]*\n)/gm, "");
}
static repalceSpaceWithDash(str: string): string {
return str.trim().replace(new RegExp("[ \f\n\r\t\v]+", "g"), "-");
}
}
| mit |
Condors/TunisiaMall | vendor/hwi/oauth-bundle/Security/Core/User/EntityUserProvider.php | 4406 | <?php
/*
* This file is part of the HWIOAuthBundle package.
*
* (c) Hardware.Info <opensource@hardware.info>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HWI\Bundle\OAuthBundle\Security\Core\User;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* User provider for the ORM that loads users given a mapping between resource
* owner names and the properties of the entities.
*
* @author Alexander <iam.asm89@gmail.com>
*/
class EntityUserProvider implements UserProviderInterface, OAuthAwareUserProviderInterface
{
/**
* @var ObjectManager
*/
protected $em;
/**
* @var string
*/
protected $class;
/**
* @var ObjectRepository
*/
protected $repository;
/**
* @var array
*/
protected $properties = array(
'identifier' => 'id',
);
/**
* Constructor.
*
* @param ManagerRegistry $registry Manager registry.
* @param string $class User entity class to load.
* @param array $properties Mapping of resource owners to properties
* @param string $managerName Optional name of the entity manager to use
*/
public function __construct(ManagerRegistry $registry, $class, array $properties, $managerName = null)
{
$this->em = $registry->getManager($managerName);
$this->class = $class;
$this->properties = array_merge($this->properties, $properties);
}
/**
* {@inheritdoc}
*/
public function loadUserByUsername($username)
{
$user = $this->findUser(array('username' => $username));
if (!$user) {
throw new UsernameNotFoundException(sprintf("User '%s' not found.", $username));
}
return $user;
}
/**
* {@inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$resourceOwnerName = $response->getResourceOwner()->getName();
if (!isset($this->properties[$resourceOwnerName])) {
throw new \RuntimeException(sprintf("No property defined for entity for resource owner '%s'.", $resourceOwnerName));
}
$username = $response->getUsername();
if (null === $user = $this->findUser(array($this->properties[$resourceOwnerName] => $username))) {
throw new UsernameNotFoundException(sprintf("User '%s' not found.", $username));
}
return $user;
}
/**
* {@inheritdoc}
*/
public function refreshUser(UserInterface $user)
{
$accessor = PropertyAccess::createPropertyAccessor();
$identifier = $this->properties['identifier'];
if (!$this->supportsClass(get_class($user)) || !$accessor->isReadable($user, $identifier)) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
}
$userId = $accessor->getValue($user, $identifier);
if (null === $user = $this->findUser(array($identifier => $userId))) {
throw new UsernameNotFoundException(sprintf('User with ID "%d" could not be reloaded.', $userId));
}
return $user;
}
/**
* {@inheritdoc}
*/
public function supportsClass($class)
{
return $class === $this->class || is_subclass_of($class, $this->class);
}
/**
* @param array $criteria
*
* @return object
*/
protected function findUser(array $criteria)
{
if (null === $this->repository) {
$this->repository = $this->em->getRepository($this->class);
}
return $this->repository->findOneBy($criteria);
}
}
| mit |
dniklaus/arduino-menusystem-test | src/MenuHandler.cpp | 5397 | //
//
//
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "Wire.h"
#include "LcdKeypad.h"
#include "MenuSystem.h"
#include "MyMenuItem.h"
#include "MenuHandler.h"
class Item1MenuAction: public MyMenuItemAction
{
private:
MenuHandler* m_mHandler;
public:
Item1MenuAction(MenuHandler* mHandler)
: m_mHandler(mHandler)
{ }
void handle()
{
if (0 != m_mHandler)
{
Serial.println("Item1MenuAction performed.");
m_mHandler->setItem1Active(!m_mHandler->isItem1Active());
}
}
private: // forbidden default functions
Item1MenuAction& operator = (const Item1MenuAction& src); // assignment operator
Item1MenuAction(const Item1MenuAction& src); // copy constructor
};
class Item2MenuAction: public MyMenuItemAction
{
private:
MenuHandler* m_mHandler;
public:
Item2MenuAction(MenuHandler* mHandler)
: m_mHandler(mHandler)
{ }
void handle()
{
if (0 != m_mHandler)
{
Serial.println("Item2MenuAction performed.");
m_mHandler->setItem2Active(!m_mHandler->isItem2Active());
}
}
private: // forbidden default functions
Item2MenuAction& operator = (const Item2MenuAction& src); // assignment operator
Item2MenuAction(const Item2MenuAction& src); // copy constructor
};
class MyLcdKeypadAdapter : public LcdKeypadAdapter
{
public:
MyLcdKeypadAdapter(MenuHandler* menuHandler = 0)
: m_menuHandler(menuHandler)
{ }
private:
MenuHandler* m_menuHandler;
public:
void handleKeyChanged(LcdKeypad::Key newKey)
{
Serial.print("MyLcdKeypadAdapter::handleKeyChanged(), newKey: ");
Serial.println((LcdKeypad::NO_KEY == newKey) ? "NO_KEY" :
(LcdKeypad::SELECT_KEY == newKey) ? "SELECT_KEY" :
(LcdKeypad::LEFT_KEY == newKey) ? "LEFT_KEY" :
(LcdKeypad::UP_KEY == newKey) ? "UP_KEY" :
(LcdKeypad::DOWN_KEY == newKey) ? "DOWN_KEY" :
(LcdKeypad::RIGHT_KEY == newKey) ? "RIGHT_KEY" : "OOPS!! Invalid value!!");
if (0 != m_menuHandler)
{
LcdKeypad* lcdKeypad = m_menuHandler->lcd();
if (0 != lcdKeypad)
{
if (LcdKeypad::UP_KEY == newKey)
{
lcdKeypad->setBackLightOn(true);
}
if (LcdKeypad::DOWN_KEY == newKey)
{
lcdKeypad->setBackLightOn(false);
}
}
if (LcdKeypad::SELECT_KEY == newKey)
{
m_menuHandler->selectKeyEvent();
}
if (LcdKeypad::LEFT_KEY == newKey)
{
m_menuHandler->leftKeyEvent();
}
if (LcdKeypad::RIGHT_KEY == newKey)
{
m_menuHandler->rightKeyEvent();
}
}
}
};
//const unsigned int MenuHandler::LCD_I2C_ADDR = 0xC1;
MenuHandler::MenuHandler()
: m_lcd(new LcdKeypad())
, m_menu(new MenuSystem())
, m_mRoot(new Menu("Root Menu"))
, m_mi1(new MyMenuItem("Item 1", m_mRoot, new Item1MenuAction(this)))
, m_mi2(new MyMenuItem("Item 2", m_mRoot, new Item2MenuAction(this)))
, m_isItem1Active(false)
, m_isItem2Active(false)
{
if (0 != m_lcd)
{
m_lcd->attachAdapter(new MyLcdKeypadAdapter(this));
m_lcd->setBackLightOn(true);
}
}
MenuHandler::~MenuHandler()
{
delete m_mi1->action();
delete m_mi1; m_mi1 = 0;
delete m_mi2->action();
delete m_mi2; m_mi2 = 0;
delete m_mRoot; m_mRoot = 0;
delete m_menu; m_menu = 0;
delete m_lcd; m_lcd = 0;
}
void MenuHandler::init()
{
m_menu->set_root_menu(m_mRoot);
displayMenu();
}
void MenuHandler::selectKeyEvent()
{
m_menu->select();
}
void MenuHandler::leftKeyEvent()
{
m_menu->prev(false);
displayMenu();
}
void MenuHandler::rightKeyEvent()
{
m_menu->next(false);
displayMenu();
}
void MenuHandler::handleInput()
{ }
void MenuHandler::displayMenu()
{
if (0 != m_lcd)
{
m_lcd->clear();
m_lcd->setCursor(0, 0);
// Display the menu
Menu const* cp_menu = m_menu->get_current_menu();
//m_lcd.print("Current menu name: ");
m_lcd->print(cp_menu->get_name());
m_lcd->setCursor(0, 1);
m_lcd->print(cp_menu->get_selected()->get_name());
m_lcd->print(" ");
bool isMenuItemActive = false;
const char* selectedName = const_cast<char*>(cp_menu->get_selected()->get_name());
if (0 == strcmp(selectedName, m_mi1->get_name()))
{
isMenuItemActive = isItem1Active();
Serial.print("MenuHandler::displayMenu(), m_mi1->get_name() matches selectedName: ");
Serial.println(selectedName);
}
if (0 == strcmp(selectedName, m_mi2->get_name()))
{
isMenuItemActive = isItem2Active();
Serial.print("MenuHandler::displayMenu(), m_mi2->get_name() matches selectedName: ");
Serial.println(selectedName);
}
m_lcd->print(isMenuItemActive ? "active" : " ");
}
}
LcdKeypad* MenuHandler::lcd()
{
return m_lcd;
}
void MenuHandler::setItem1Active(bool isActive)
{
m_isItem1Active = isActive;
Serial.print("MenuHandler::m_isItem1Active: ");
Serial.println(m_isItem1Active ? "1" : "0");
displayMenu();
}
void MenuHandler::setItem2Active(bool isActive)
{
m_isItem2Active = isActive;
Serial.print("MenuHandler::m_isItem2Active: ");
Serial.println(m_isItem2Active ? "1" : "0");
displayMenu();
}
bool MenuHandler::isItem1Active()
{
return m_isItem1Active;
}
bool MenuHandler::isItem2Active()
{
return m_isItem2Active;
}
| mit |
carto-tragsatec/visorCatastroColombia | WebContent/visorcatastrocol/app/view/ol/VariablesConfiguracion.js | 5213 | /**Variables globales del visor CSP, vienen del fichero configuracion.xml*/
//-----url wms y wfs
var WMS = document.getElementById("WMS").value;
if (WMS.substr(WMS.length - 1) != "?") {
WMS = WMS + "?";
}
var WFS = document.getElementById("WFS").value;
if (WFS.substr(WFS.length - 1) != "?") {
WFS = WFS + "?";
}
//-----fin url wms y wfs
//-----prefijo en geoserver
var prefijo = document.getElementById("prefijo").value;
//-----fin prefijo en geoserver
//-----grupo de capas base
var grupoBase = document.getElementById("grupoBase").value;
var nbBaseOSM = document.getElementById("nbBaseOSM").value;
var urlBaseOSM = document.getElementById("urlBaseOSM").value;
var nbOrtofoto = document.getElementById("nbOrtofoto").value;
var capaOrtofoto = document.getElementById("capaOrtofoto").value;
//-----fin grupo de capas base
//-----grupo de capas prediales
var grupoPredial = document.getElementById("grupoPredial").value;
var nbTerreno = document.getElementById("nbTerreno").value;
var capaTerreno = document.getElementById("capaTerreno").value;
var nbConstruccion = document.getElementById("nbConstruccion").value;
var capaConstruccion = document.getElementById("capaConstruccion").value;
var nbCobertura = document.getElementById("nbCobertura").value;
var capaCobertura = document.getElementById("capaCobertura").value;
var nbUnidad = document.getElementById("nbUnidad").value;
var capaUnidad = document.getElementById("capaUnidad").value;
var nbElPredialesUnion = document.getElementById("nbElPredialesUnion").value;
var capaElPredialesUnion = document.getElementById("capaElPredialesUnion").value;
//-----fin grupo de capas prediales
//-----grupo de capas limites administrativos
var grupoLimites = document.getElementById("grupoLimites").value;
var nbDepartamentos = document.getElementById("nbDepartamentos").value;
var capaDepartamentos = document.getElementById("capaDepartamentos").value;
var nbMunicipios = document.getElementById("nbMunicipios").value;
var capaMunicipios = document.getElementById("capaMunicipios").value;
var nbColombia = document.getElementById("nbColombia").value;
var capaColombia = document.getElementById("capaColombia").value;
//-----fin grupo de capas limites administrativos
//-----grupo de Servicios IGAC
var grupoServiciosIGAC = document.getElementById("grupoServiciosIGAC").value;
var WMSCartoBasica500 = document.getElementById("WMSCartoBasica500").value;
if (WMSCartoBasica500.substr(WMSCartoBasica500.length - 1) != "?") {
WMSCartoBasica500 = WMSCartoBasica500 + "?";
}
var nbCartoBasica500 = document.getElementById("nbCartoBasica500").value;
var capaCartoBasica500 = document.getElementById("capaCartoBasica500").value;
var WMSCartoBasica100 = document.getElementById("WMSCartoBasica100").value;
if (WMSCartoBasica100.substr(WMSCartoBasica100.length - 1) != "?") {
WMSCartoBasica100 = WMSCartoBasica100 + "?";
}
var nbCartoBasica100 = document.getElementById("nbCartoBasica100").value;
var capaCartoBasica100 = document.getElementById("capaCartoBasica100").value;
var WMSCartoBasica10 = document.getElementById("WMSCartoBasica10").value;
if (WMSCartoBasica10.substr(WMSCartoBasica10.length - 1) != "?") {
WMSCartoBasica10 = WMSCartoBasica10 + "?";
}
var nbCartoBasica10 = document.getElementById("nbCartoBasica10").value;
var capaCartoBasica10 = document.getElementById("capaCartoBasica10").value;
var WMSAreasReglaEsp = document.getElementById("WMSAreasReglaEsp").value;
if (WMSAreasReglaEsp.substr(WMSAreasReglaEsp.length - 1) != "?") {
WMSAreasReglaEsp = WMSAreasReglaEsp + "?";
}
var nbResguardosIndigenas = document.getElementById("nbResguardosIndigenas").value;
var capaResguardosIndigenas = document.getElementById("capaResguardosIndigenas").value;
var nbComunidadesNegras = document.getElementById("nbComunidadesNegras").value;
var capaComunidadesNegras = document.getElementById("capaComunidadesNegras").value;
//-----fin grupo de Servicios IGAC
//-----grupo de Servicios IDEAM
var grupoServiciosIDEAM = document.getElementById("grupoServiciosIDEAM").value;
var WMSCoberturasTierra = document.getElementById("WMSCoberturasTierra").value;
if (WMSCoberturasTierra.substr(WMSCoberturasTierra.length - 1) != "?") {
WMSCoberturasTierra = WMSCoberturasTierra + "?";
}
var nbCoberTierra2000_2002 = document.getElementById("nbCoberTierra2000_2002").value;
var capaCoberTierra2000_2002 = document.getElementById("capaCoberTierra2000_2002").value;
var nbCoberTierra2005_2009 = document.getElementById("nbCoberTierra2005_2009").value;
var capaCoberTierra2005_2009 = document.getElementById("capaCoberTierra2005_2009").value;
var nbCoberTierra2010_2012 = document.getElementById("nbCoberTierra2010_2012").value;
var capaCoberTierra2010_2012 = document.getElementById("capaCoberTierra2010_2012").value;
var nbCoberParamos = document.getElementById("nbCoberParamos").value;
var capaCoberParamos = document.getElementById("capaCoberParamos").value;
//-----fin grupo de Servicios IDEAM
//-----Capas de Usuario
var nameUsuario = document.getElementById("nameUsuario").value;
//-----fin Capas de Usuario
//-----URL Geocoder OSM
var urlGeocoderOSM = document.getElementById("urlGeocoderOSM").value;
//-----fin URL Geocoder OSM
| mit |
ryanr1230/bolts | default_config/config/src/main.rs | 217 | extern crate bolts;
use bolts::Bolts;
include!("../config.rs");
fn main() {
let bolts_runner = Bolts::new();
bolts_runner.run(config::default_layout(), config::partial_paths(), config::markdown_files()).unwrap();
}
| mit |
SimplePersistence/SimplePersistence.Model | SimplePersistence.Model/src/SimplePersistence.Model/IEntity.cs | 1673 | #region License
// The MIT License (MIT)
//
// Copyright (c) 2016 SimplePersistence
//
// 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
namespace SimplePersistence.Model
{
/// <summary>
/// Represents an entity with a unique identifier
/// </summary>
/// <typeparam name="TIdentity">The unique identifier type</typeparam>
public interface IEntity<TIdentity> : IEntity
{
/// <summary>
/// The entity unique identifier
/// </summary>
TIdentity Id { get; set; }
}
/// <summary>
/// Represents an entity
/// </summary>
public interface IEntity
{
}
}
| mit |
Alkisum/YTSubscriber | src/main/java/view/dialog/ExceptionDialog.java | 2814 | package view.dialog;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Dialog to show Exceptions.
*
* @author Alkisum
* @version 4.0
* @since 1.0
*/
public final class ExceptionDialog {
/**
* Dialog width.
*/
private static final int WIDTH = 600;
/**
* ExceptionDialog constructor.
*/
private ExceptionDialog() {
}
/**
* Show Exception dialog.
*
* @param exception Exception to show
*/
public static void show(final Exception exception) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
String stackTrace = sw.toString();
buildAlert(exception.getMessage(), stackTrace).showAndWait();
}
/**
* Show Exception dialog.
*
* @param throwable Throwable to show
*/
public static void show(final Throwable throwable) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
throwable.printStackTrace(pw);
String stackTrace = sw.toString();
buildAlert(throwable.getMessage(), stackTrace).showAndWait();
}
/**
* Build the Alert dialog.
*
* @param message Message to show
* @param stackTrace StackTrace to show
* @return Built alert
*/
private static Alert buildAlert(final String message,
final String stackTrace) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText(message);
Label label = new Label("The exception stacktrace was:");
TextArea textArea = new TextArea(stackTrace);
textArea.setEditable(false);
textArea.setWrapText(false);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
expContent.setVgap(10.0);
alert.getDialogPane().setExpandableContent(expContent);
alert.getDialogPane().setPrefWidth(WIDTH);
alert.getDialogPane().expandedProperty().addListener((l) ->
Platform.runLater(() -> {
alert.getDialogPane().requestLayout();
Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
stage.sizeToScene();
}));
return alert;
}
}
| mit |
silvanheller/cineast | src/org/vitrivr/cineast/core/util/images/ZernikeHelper.java | 7629 | package org.vitrivr.cineast.core.util.images;
import static java.awt.image.BufferedImage.TYPE_INT_RGB;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.complex.Complex;
import org.vitrivr.cineast.core.util.math.ZernikeMoments;
import org.vitrivr.cineast.core.util.math.functions.ZernikeBasisFunction;
import boofcv.alg.filter.binary.BinaryImageOps;
import boofcv.alg.filter.binary.Contour;
import boofcv.alg.filter.binary.GThresholdImageOps;
import boofcv.alg.filter.binary.ThresholdImageOps;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.ConnectRule;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.GrayS32;
import boofcv.struct.image.GrayU8;
import georegression.struct.point.Point2D_I32;
/**
* @author rgasser
* @version 1.0
* @created 19.03.17
*/
public final class ZernikeHelper {
/**
* Private constructor; do not instantiate!
*/
private ZernikeHelper() {
}
/**
* Calculates and returns the Zernike Moments of order n for the provided image.
*
* @param image BufferedImage for which Zernike Moments should be extracted.
* @param order Order up to which Zernike Moments should be calculated.
* @return ZernikeMoments for image.
*/
public static ZernikeMoments zernikeMoments(BufferedImage image, int order) {
double[][] data = new double[image.getWidth()][image.getHeight()];
for (int x=0;x<image.getWidth();x++) {
for (int y=0;y<image.getHeight();y++) {
int rgb = image.getRGB(x, y);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb & 0xFF);
/* Store gay level in terms of values between 0.0 and 1.0. */
data[x][y] = (r + g + b) / (3.0 * 255.0);
}
}
ZernikeMoments m = new ZernikeMoments(data);
m.compute(order);
return m;
}
/**
* Calculates and returns a list of Zernike Moments for all shapes that have been detected in the provided
* image. To do so, first the image is transformed into a binary image by means of thresholding. Afterwards,
* contours are detected in the binary image and shapes are extracted for every detected contour. The so
* extracted data is then handed to a class that obtains the Zernike Moments.
*
* @param image BufferedImage for which Zernike Moments should be extracted.
* @param minimal Minimal size of the shape in terms of contour-length. Smaller shapes will be ignored.
* @param order Order up to which Zernike Moments should be calculated.
* @return List of Zernike Moments for the image.
*/
public static List<ZernikeMoments> zernikeMomentsForShapes(BufferedImage image, int minimal, int order) {
/* Extract the contours (shapes) from the buffered image. */
GrayF32 input = ConvertBufferedImage.convertFromSingle(image, null, GrayF32.class);
GrayU8 binary = new GrayU8(input.width,input.height);
GrayS32 label = new GrayS32(input.width,input.height);
/* Select a global threshold using Otsu's method and apply that threshold. */
double threshold = GThresholdImageOps.computeOtsu(input, 0, 255);
ThresholdImageOps.threshold(input, binary,(float)threshold,true);
// remove small blobs through erosion and dilation
// The null in the input indicates that it should internally declare the work image it needs
// this is less efficient, but easier to code.
GrayU8 filtered = BinaryImageOps.erode8(binary, 1, null);
filtered = BinaryImageOps.dilate8(filtered, 1, null);
/* Detect blobs inside the image using an 8-connect rule. */
List<Contour> contours = BinaryImageOps.contour(filtered, ConnectRule.EIGHT, label);
List<ZernikeMoments> moments = new ArrayList<>();
for (Contour contour : contours) {
for (List<Point2D_I32> shape : contour.internal) {
if (shape.size() >= minimal) {
int[] bounds = ContourHelper.bounds(shape);
int w = bounds[1] - bounds[0];
int h = bounds[3] - bounds[2];
double[][] data = new double[w][h];
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
if (filtered.get(x + bounds[0],y + bounds[2]) == 1) {
data[x][y] = 0.0f;
} else {
data[x][y] = 1.0f;
}
}
}
ZernikeMoments m = new ZernikeMoments(data);
m.compute(order);
moments.add(m);
}
}
}
return moments;
}
/**
* Attempts at reconstructing an image from a list of complete Zernike Moments. The list must contain
* a complete set of complex Zernike Moments up to some arbitrary order. The moments must be ordered according
* to Noll's sequential index (ascending).
*
* @param moments
* @return
*/
public static BufferedImage reconstructImage(ZernikeMoments moments) {
return ZernikeHelper.reconstructImage(moments.getHeight(), moments.getHeight(), moments.getMoments());
}
/**
* Attempts at reconstructing an image from a list of complex Zernike Moments. The list must contain
* a complete set of Zernike Moments up to some arbitrary order n. The moments must be ordered
* according to Noll's sequential indexing scheme (ascending).
*
* @param w the width of the desired image
* @param h the height of the desired image
* @param moments List of Zernike Moments is ascending order according to Noll's index.
* @return The reconstructed image
*/
public static BufferedImage reconstructImage(final int w, final int h, final List<Complex> moments) {
/* Scale x and y dimension to unit-disk. */
final double c = -1.0;
final double d = 1.0;
/* Prepare array for imaga data. */
final double[][] imageData = new double[w][h];
double maxValue = 0.0f;
int indexFeature = 0;
for (int n=0; indexFeature < moments.size(); ++n) {
for (int m=0;m<=n;m++) {
if((n-Math.abs(m))%2 == 0) {
final Complex moment = moments.get(indexFeature);
final ZernikeBasisFunction bf1 = new ZernikeBasisFunction(n, m);
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
Complex v = new Complex(c+(i*(d-c))/(w-1), d-(j*(d-c))/(h-1));
Complex res = moment.multiply(bf1.value(v));
imageData[i][j] += res.getReal();
maxValue = Math.max(maxValue, imageData[i][j]);
}
}
indexFeature++;
}
}
}
BufferedImage image = new BufferedImage(w, h, TYPE_INT_RGB);
for (int x = 1; x < w; x++) {
for (int y = 1; y < h; y++) {
int i = (int)(255.0*(imageData[x-1][y-1] )/(maxValue));
int rgb = ((255 & 0xFF) << 24) | ((i & 0xFF) << 16) | ((i & 0xFF) << 8) | ((i & 0xFF) << 0);
image.setRGB(x,y,rgb);
}
}
return image;
}
}
| mit |
bladestery/Sapphire | example_apps/AndroidStudioMinnie/sapphire/src/main/java/org/boofcv/android/recognition/fid.java | 523 | package org.boofcv.android.recognition;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import georegression.struct.se.Se3_F64;
/**
* Created by ubuntu on 17/06/15.
*/
public class fid implements Serializable {
public fid() {
number = new ArrayList<>();
targetToCameral = new ArrayList<>();
width = new ArrayList<>();
}
public int totalFound;
public List<Long> number;
public List<Se3_F64> targetToCameral;
public List<Double> width;
}
| mit |
iaincarsberg/thornyengine | thorny/common/component/moveable.js | 4799 | /*global window*/
(function (module) {
var
/**
* Used to build the attach options.
* @param object $ Contains a reference to thorny
* @param object options Contains the attachment specific options
* @return object Containing the attached options
*/
attachOptions = function ($, options) {
if (typeof options !== 'object') {
options = {};
}
return $._.extend((function () {
return {
user_facing: {x: 0, y: 0},
speed: 1,
easing: 'linear'// TODO
};
}()), options);
},
/**
* Used to build the execute options.
* @param object $ Contains a reference to thorny
* @param object options Contains the attachment specific options
* @return object Containing the attached options
*/
executeOptions = function ($, options) {
if (typeof options !== 'object') {
options = {};
}
return $._.extend((function () {
return {
time: false
};
}()), options);
};
/**
* Used to make an object observable
* @param object subject Contains the object that is to be observed
* @return object Containing the injected observable functionality.
*/
module.exports = function ($, module) {
$.onInit(module, function () {
$.data(module, 'moveable', {});
$.es().registerComponent('moveable', function () {
return {
attach: function (entity, options) {
// The position is required.
if (! entity.hasComponent('position')) {
return false;
}
// Build the options.
options = attachOptions($, options);
// Build a new movable object.
$.data(module, 'moveable')[entity.id] = $._.extend(
entity.getComponent('position').data.expose(entity), {
user_facing: $('thorny math vector2').factory(options.user_facing.x, options.user_facing.y).normalize(),
speed: options.speed,
easing: options.easing,
current_speed: 0,
injected_processors: [],
last_exec_time: $.time().now()
}
);
},
execute: function (entity, options) {
options = executeOptions($, options);
// We need to know the current time, the time option
// exists to make the system more easily testable.
if (options.time === false) {
options.time = $.time().now();
}
var
i,
ii,
self = $.data(module, 'moveable')[entity.id],
processor,
changes,
// Localised data to allow the processor's to
// change the values without requiring access to
// the internal state.
direction = self.facing,
position = self.position,
distance = this.getMoveDistance(options.time, self),
goal = self.position.translate(
self.facing,
distance
);
// Execute any injected processors.
for (i = 0, ii = self.injected_processors.length; i < ii; i += 1) {
processor = self.injected_processors[i];
// Execute the processor code.
changes = processor(entity, {
direction: direction,
position: position,
distance: distance,
goal: goal
});
// Move the changed values back out of the changes
// object, so that they can used by other
// processors, and finally inserted into
// the position.
direction = changes.direction;
position = changes.position;
distance = changes.distance;
goal = changes.goal;
}
// If a direction is set, update it.
if (direction) {
// Set the position and direction back into the
// position component.
self.facing = direction;
self.position = position.translate(
direction,
distance
);
}
},
expose: function (entity) {
return $.data(module, 'moveable')[entity.id];
},
inject: function (entity, code) {
// TODO
// The Idea here is that other components such as the
// pathfinder and collision detector can inject
// functionality into this
var self = $.data(module, 'moveable')[entity.id];
self.injected_processors.push(code);
},
/**
* Used to get the amount of movement allowed.
* @param int now Contains the current time
* @return float Contain how far an entity can move this
* gameloop tick;
*/
getMoveDistance: function (now, options) {
var distance = (
options.speed * (now - options.last_exec_time)
) / 1000;
options.last_exec_time = now;
return distance;
}
};
});
});
};
}((typeof window === 'undefined') ? module : window.thorny_path('./thorny/common/component/moveable'))); | mit |
vampirebitter/go-join-the-activity | resources/views/sponsorInfo/index.blade.php | 6821 | @extends('layouts.vue')
@section('content')
<?php
$this->title = '主办方中心';
?>
<link href="{{ asset('css/sponsor_info.css') }}" rel="stylesheet">
<!-- banner -->
<div class="container_lg bgimg_banner"></div>
<div class="container-default">
<div class="container_left">
<div class="sponsor_info_box">
<img src="{{ asset('upload/sponsorUpload/'.$sponsorInfo['sponsor_icon']) }}" alt="#" class="sponsor_logo">
<h3 class="sponsor_title">{{ $sponsorInfo['sponsor_name'] }}</h3>
<div class="sponsor_a">
@if($sponsorInfo['count'])
<span class="span_border">{{ $sponsorInfo['count'] }}活动</span>
@else
<span class="span_border">{{ $sponsorInfo['count'] }}活动</span>
@endif
<span>{{ $sponsorInfo['follow_count'] }}粉丝</span>
</div>
<div class="focus_share">
<sponsor-follow-button sponsor="{{ $sponsorInfo['id'] }}"></sponsor-follow-button>
{{--<button class="btn-blue focus" id="focus">关注</button>--}}
{{--<button class="btn-white unfocus" id="unfocus">已关注</button>--}}
<button class="btn-white share">分享</button>
</div>
<p class="sponsor_intro">{{ $sponsorInfo['description'] }}</p>
</div>
@if(is_null($sponsorInfo['weixin']))
<div></div>
@else
<div class="other_info">
<img src="img/qrcode.jpg" alt="二维码图片">
<p>多火工作室
微信公众号
duohuostudio
扫一扫关注
更多活动</p>
</div>
@endif
</div>
<div class="container_right">
@foreach($activityInfo as $info)
<div class="actvt_box">
<img src="../../img/Group4.png" alt="#" href="{{ url('detail/'.$info['id']) }}">
<div class="actvt_dtl">
<p class="dtl_title"><a href="{{ url('detail/'.$info['id']) }}">{{ $info['title'] }}</a></p>
<p class="actvt_time"><span class="icon time_icon"></span>时间:{{ $info['hold_time'] }}</p>
<p class="actvt_place"><span class="icon place_icon"></span>地址:{{ $info['hold_address'] }}</p>
<div class="actvt_people">
<p><span class="icon people_icon"></span>报名人数:<span class="number">{{ $info['signUp_count'] }}</span></p>
<p class="border_left"><span class="icon collection_icon"></span>收藏人数:{{ $info['follow_count'] }}<span class="number"></span></p>
</div>
<div class="check_star">
<activity-follow-button activity="{{ $info['id'] }}"></activity-follow-button>
<button class="btn-white star">分享</button>
</div>
</div>
</div>
@endforeach
<div class="page_btn">
<button class="next_page"><</button>
<ul class="page_num">
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
</ul>
<button class="last_page">></button>
</div>
</div>
<div style="clear:both"></div>
</div>
{{--<div class="banner"></div>
<div class="container">
<div class="left">
<div class="introduce">
<img class="logo" src="{{ asset('upload/sponsorUpload/'.$sponsorInfo['sponsor_icon']) }}"/>
<a class="name">{{ $sponsorInfo['sponsor_name'] }}</a>
<div class="numcont">
@if($sponsorInfo['count'])
<a class="nummid leftnum"><span class="num"> {{ $sponsorInfo['count'] }}</span> 活动</a>
@else
<b class="nummid leftnum"><span class="num"> {{ $sponsorInfo['count'] }}</span> 活动</b>
@endif
<div class="line"></div>
<b class="nummid rightnum"><span class="num">{{ $sponsorInfo['follow_count'] }} </span> 粉丝</b>
</div>
<div class="button">
<sponsor-follow-button sponsor=" {{ $sponsorInfo['id'] }} "></sponsor-follow-button>
<button class="fenxiang buttonwrite pull-right">分享</button>
</div>
<p>{{ $sponsorInfo['description'] }}</p>
</div>
@if(is_null($sponsorInfo['weixin']))
<div></div>
@else
<div class="other_info">
<img src="img/qrcode.jpg" alt="二维码图片">
<p>多火工作室
微信公众号
duohuostudio
扫一扫关注
更多活动</p>
</div>
@endif
</div>
<div class="right">
<ul>
@foreach($activityInfo as $info)
<li>
<div class="active-pic"></div>
<div class="active-s">
<p class="active-tit">{{ $info['title'] }}</p>
<p class="active-time"><embed class="icon" src="{{ asset('img/time.svg') }}" type="image/svg+xml" /> 时间:{{ $info['hold_time'] }}</p>
<p class="active-plc"><img class="icon" src="{{ asset('img/addressicon.svg') }}"> 地址:{{ $info['hold_address'] }}</p>
<div class="active-num">
<b class="num-left">报名人数:{{ $info['signUp_count'] }}</b>
<div class="active-line"></div>
<b class="num-right">收藏人数:{{ $info['follow_count'] }}</b>
</div>
<div class="active-button">
<button class="xiangqing buttonblue"><a href="{{ url('detail/'.$info['id']) }}" style="color: white;text-decoration: none;">查看详情</a></button>
<activity-follow-button activity="{{ $info['id'] }}"></activity-follow-button>
</div>
</div>
</li>
@endforeach
</ul>
<div class="page-num">
<button class="but-qian buttongray"><</button>
<button class="but-1 buttonblue">1</button>
<button class="but-2 buttonwrite">2</button>
<button class="but-hou buttongray">></button>
</div>
</div>
</div>--}}
@endsection | mit |
Coregraph/Ayllu | JigSaw - AYPUY - CS/BESA3/BESA3-SRC/BPOBESA/src/BESA/Mobile/Exceptions/ExceptionBESAMessageInterpreterFailedBPO.java | 281 |
package BESA.Mobile.Exceptions;
import BESA.ExceptionBESA;
/**
*
* @author Andrea Barraza
*/
public class ExceptionBESAMessageInterpreterFailedBPO extends ExceptionBESA {
public ExceptionBESAMessageInterpreterFailedBPO(String message){
super(message);
}
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/quill/0.19.1/quill.js | 131 | version https://git-lfs.github.com/spec/v1
oid sha256:2bd7e21a9a31e41dfb9d51f7f4b880e4cf832f34dee1af79d70f13dd1b99053b
size 271959
| mit |
JustinLove/tictactoe | spec/tictactoe/board_spec.rb | 1555 | require 'spec_helper'
require 'tictactoe/board'
describe Tictactoe::Board do
let(:cut) {Tictactoe::Board}
describe 'blank board' do
subject {cut.new}
its(:blank) {should have(9).items}
its(:blank) {should == (0..8).to_a}
its(:finished?) {should be_false}
its(:winning?) {should be_false}
its(:winner) {should == B}
it {subject.next_moves(X).should have(9).items}
end
describe 'after a move' do
subject {cut.new.move(X, 0)}
its(:blank) {should have(8).items}
its(:blank) {should_not include(0)}
its(:finished?) {should be_false}
its(:winning?) {should be_false}
its(:winner) {should == B}
it {subject.next_moves(X).should have(8).items}
end
describe 'winning board' do
subject {cut.new([X,B,B, B,X,B, B,B,X])}
its(:finished?) {should be_true}
its(:winning?) {should be_true}
its(:winner) {should == X}
end
describe 'tied board' do
subject {cut.new([X,O,X, X,O,X, O,X,O])}
its(:blank) {should have(0).items}
its(:finished?) {should be_true}
its(:winning?) {should be_false}
its(:winner) {should == B}
it {subject.next_moves(X).should have(0).items}
end
describe 'each_row' do
subject {
@rows = []
cut.new.each_row {|row| @rows << row}
@rows
}
it {should == [[B,B,B], [B,B,B], [B,B,B]]}
end
describe 'hashable' do
let(:a) {cut.new}
let(:b) {cut.new}
it {a.hash.should == b.hash}
it {a.should eql(b)}
it do
x = {}
x[a] = true
x[b].should be_true
end
end
end
| mit |
Crny/framework | src/Clear/Pagination/PaginationServiceProvider.php | 320 | <?php
namespace Clear\Pagination;
use Clear\Support\ServiceProvider;
class PaginationServiceProvider extends ServiceProvider
{
/**
* register service
*
* @return void
*/
public function register()
{
# code...
}
public function boot()
{
# code...
}
} | mit |
zoitravel/zmz-calendar | src/classes/calendar-state.ts | 2368 | import { isArray, keys, sortBy } from 'lodash';
import { dateHash } from '../helpers';
import { DateMap, State, StateMap } from '../types';
import { startOfDay, parse } from 'date-fns';
// TODO add tests extending states
export const STATES: StateMap<State> = {
NO_STATE: '',
DISABLED: 'disabled',
UNAVAILABLE: 'unavailable',
AVAILABLE: 'available',
SELECTED: 'selected',
SELECTABLE: 'selectable',
NOT_SELECTABLE: 'not-selectable'
};
export class CalendarState {
map: DateMap;
constructor(dates: Date[], defaultState: State = STATES.NO_STATE) {
/** Populate map with stateless dates */
this.map = {};
dates.forEach(date => {
const hash = dateHash(startOfDay(date));
this.map[hash] = [defaultState];
});
}
set(date: Date, state: State) {
const hash = dateHash(date);
if (isArray(this.map[hash]) && this.map[hash].findIndex((st) => st === state) === -1) {
this.map[hash].push(state);
} else if (!isArray(this.map[hash])) {
this.map[hash] = [state];
}
}
toggle(date: Date, state: State) {
const hash = dateHash(date);
let states = this.map[hash];
if (isArray(states)) {
const index = states.findIndex((st) => st === state);
if (index === -1) {
states.push(state);
} else {
states.splice(index, 1);
}
} else {
states = [state];
}
}
has(date: Date, state: State): boolean {
const hash = dateHash(date);
return isArray(this.map[hash]) ? this.map[hash].findIndex((st) => st === state) !== -1 : false;
}
get(date: Date): State[] {
const hash = dateHash(date);
return this.map[hash] || [];
}
remove(date: Date, state: State) {
const hash = dateHash(date);
let states = this.map[hash];
if (isArray(states)) {
const index = states.findIndex((st) => st === state);
if (index !== -1) { states.splice(index, 1); }
}
}
getAll(state: State): Date[] {
const all = keys(this.map).filter((hash) =>
isArray(this.map[hash]) ? this.map[hash].findIndex((st) => st === state) !== -1 : false
);
return all.map((hash) => parse(hash));
}
getLast(state: State): Date {
const all = sortBy(this.getAll(state));
return all[all.length - 1];
}
getFirst(state: State): Date {
const all = sortBy(this.getAll(state));
return all[0];
}
}
| mit |
artsy/force-public | src/desktop/apps/fair_organizer/test/template.test.js | 3760 | /*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const _ = require("underscore")
const jade = require("jade")
const path = require("path")
const fs = require("graceful-fs")
const { fabricate } = require("@artsy/antigravity")
const Fairs = require("../../../collections/fairs")
const FairOrganizer = require("../../../models/fair_organizer")
const Profile = require("../../../models/profile")
const Item = require("../../../models/item")
const Items = require("../../../collections/items")
const cheerio = require("cheerio")
const sdData = require("sharify").data
const render = function (templateName) {
const filename = path.resolve(__dirname, `../templates/${templateName}.jade`)
return jade.compile(fs.readFileSync(filename), { filename })
}
describe("Fair Organizer", () =>
describe("index page", function () {
before(function (done) {
const sd = _.extend(sdData, {
APP_URL: "http://localhost:5000",
API_URL: "http://localhost:5000",
NODE_ENV: "test",
CURRENT_PATH: "/cool-fair",
PROFILE: fabricate("fair_organizer_profile"),
FAIR_ORGANIZER: fabricate("fair_organizer"),
WEBFONT_URL: "http://webfonts.artsy.net/",
})
const fairOrg = new FairOrganizer(sd.FAIR_ORGANIZER)
const profile = new Profile(sd.PROFILE)
const pastFairs = new Fairs([fabricate("fair"), fabricate("fair")])
const editorialItems = new Items([
fabricate("featured_link", { title: "Japanese Art" }),
])
editorialItems.add(
new Item(fabricate("featured_link", { title: "Chinese Art" }))
)
editorialItems.add(
new Item(fabricate("featured_link", { title: "Moar Chinese Art" }))
)
pastFairs.each(fair => (fair.representation = editorialItems))
const template = render("overview")({
sd,
fairOrg,
newestFair: pastFairs.models[0],
pastFairs: pastFairs.models,
profile,
asset() {},
})
this.$template = cheerio.load(template)
return done()
})
return it("renders without errors", function () {
this.$template.html().should.not.containEql("undefined")
return this.$template
.html()
.should.containEql("Explore Armory Show Fair Organizer")
})
}))
describe("Meta tags", () =>
describe("Profile", function () {
before(function () {
this.sd = {
API_URL: "http://localhost:5000",
CURRENT_PATH: "/cool-profile/info",
FAIR_ORGANIZER: fabricate("fair_organizer"),
}
this.file = path.resolve(__dirname, "../templates/meta.jade")
this.profile = new Profile(fabricate("profile"))
return (this.html = jade.render(fs.readFileSync(this.file).toString(), {
sd: this.sd,
profile: this.profile,
}))
})
return it("includes canonical url, twitter card, og tags, and title and respects current_path", function () {
this.html.should.containEql(
'<meta property="twitter:card" content="summary'
)
this.html.should.containEql(
`<link rel=\"canonical\" href=\"${this.sd.APP_URL}/cool-profile/info`
)
this.html.should.containEql(
`<meta property=\"og:url\" content=\"${this.sd.APP_URL}/cool-profile/info`
)
this.html.should.containEql(
`<meta property=\"og:title\" content=\"${this.sd.FAIR_ORGANIZER.name} | Artsy`
)
return this.html.should.containEql(
`<meta property=\"og:description\" content=\"Browse artworks, artists and exhibitors from ${this.sd.FAIR_ORGANIZER.name} on Artsy.`
)
})
}))
| mit |
SevenSpikes/api-plugin-for-nopcommerce | Nop.Plugin.Api/Helpers/IJsonHelper.cs | 338 | using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.IO;
namespace Nop.Plugin.Api.Helpers
{
public interface IJsonHelper
{
Dictionary<string, object> GetRequestJsonDictionaryFromStream(Stream stream, bool rewindStream);
string GetRootPropertyName<T>() where T : class, new();
}
} | mit |
scrbrd/scoreboard | view/app/facebook.py | 731 | """ Module: facebook
Components for interacting with facebook directly.
Note: FacebookLoginButton isn't here because it doesn't interact with Facebook
directly.
"""
from components import AppThumbnail
class FacebookThumbnail(AppThumbnail):
""" FacebookThumbnail takes a facebook id and produces a thumbnail. """
def __init__(self, fb_id, name):
""" Construct a FacebookThumbnail. """
super(FacebookThumbnail, self).__init__(
FacebookThumbnail._prepare_src_from_fb_id(fb_id),
name)
@staticmethod
def _prepare_src_from_fb_id(fb_id):
""" Turn a facebook id into an image source. """
return "http://graph.facebook.com/{}/picture".format(fb_id)
| mit |
maxbrueckl/WorktimeManagement | WorktimeManagement.Core/MutableTimeSpanFactory.cs | 3121 | using System;
using System.Collections.Generic;
using System.Linq;
namespace WorktimeManagement.Core
{
public class MutableTimeSpanFactory : IMutableTimeSpanFactory
{
private const int MinutesPerHour = 60;
public IMutableTimeSpan CreateAsDifferenceOf(IMutableDayTime dayTime, IMutableDayTime andDayTime)
{
IMutableDayTime greaterDayTime;
IMutableDayTime lesserDayTime;
CompareAndSortTwoDayTimes(dayTime, andDayTime, out greaterDayTime, out lesserDayTime);
var hourDifference = (int)(greaterDayTime.Hour - (int)lesserDayTime.Hour);
var minuteDifference = (int)(greaterDayTime.Minute - (int)lesserDayTime.Minute);
if (minuteDifference < 0)
{
hourDifference -= 1;
minuteDifference = MinutesPerHour + minuteDifference;
}
return CreateFrom(hourDifference, minuteDifference);
}
private void CompareAndSortTwoDayTimes(IMutableDayTime dayTimeOne, IMutableDayTime dayTimeTwo, out IMutableDayTime greaterDayTime,
out IMutableDayTime lesserDayTime)
{
if (dayTimeOne.CompareTo(dayTimeTwo) >= 0)
{
greaterDayTime = dayTimeOne;
lesserDayTime = dayTimeTwo;
}
else
{
greaterDayTime = dayTimeTwo;
lesserDayTime = dayTimeOne;
}
}
public IMutableTimeSpan CreateAsSubstractionOf(IMutableTimeSpan timeSpan, IMutableTimeSpan fromTimeSpan)
{
var negativeTimeSpan = CreateFrom(-timeSpan.Hour, timeSpan.Hour == 0 ? -timeSpan.Minute : timeSpan.Minute);
return CreateAsAdditionOf(negativeTimeSpan, fromTimeSpan);
}
public IMutableTimeSpan CreateAsAdditionOf(IMutableTimeSpan timeSpan, IMutableTimeSpan andTimeSpan)
{
var hourInMinutes = (timeSpan.Hour + andTimeSpan.Hour) * MinutesPerHour;
var minuteSignedInMinutes = OneIfZeroSignOf(timeSpan.Hour) * timeSpan.Minute +
OneIfZeroSignOf(andTimeSpan.Hour) * andTimeSpan.Minute;
var totalMinutes = hourInMinutes + minuteSignedInMinutes;
var hoursFromTotalMinutes = totalMinutes / MinutesPerHour;
var remainingMinutesFromTotalMinutes = totalMinutes % MinutesPerHour;
if (hoursFromTotalMinutes != 0)
remainingMinutesFromTotalMinutes = Math.Abs(remainingMinutesFromTotalMinutes);
return CreateFrom(hoursFromTotalMinutes, remainingMinutesFromTotalMinutes);
}
private int OneIfZeroSignOf(int number)
{
return Math.Sign(number) == 0 ? 1 : Math.Sign(number);
}
public IMutableTimeSpan CreateAsAdditionOf(IEnumerable<IMutableTimeSpan> timeSpans)
{
return timeSpans.Aggregate(CreateFrom(0, 0), CreateAsAdditionOf);
}
public IMutableTimeSpan CreateFrom(int hour, int minute)
{
return new MutableTimeSpan(hour, minute);
}
}
} | mit |