repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
nofxx/georuby | spec/geo_ruby/simple_features/geometry_factory_spec.rb | 260 | require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')
describe GeoRuby::SimpleFeatures::GeometryFactory do
# before(:each) do
# @po = GeoRuby::SimpleFeatures::MultiPolygon.new
# end
# it "should f" do
# violated
# end
end
| mit |
BenZhang/pixelforce_recipes | lib/pixelforce_recipes/capistrano_3_recipes/supervisor.rb | 259 | namespace :supervisor do
desc "Setup supervisor configuration for this application"
task :setup do
on roles(:app) do
template "supervisor.erb", "/tmp/supervisor"
sudo "mv /tmp/supervisor /etc/supervisor/supervisord.conf"
end
end
end
| mit |
maccery/pastpapers | resources/views/home.blade.php | 1677 | @extends('layouts.app')
@section('content')
<? $user = Auth::user() ?>
<div class="content-row">
<div class="container">
<h1>Welcome, {{ $user->name }}
</h1>
</div>
</div>
<div class="content-row">
<div class="container">
<div class="alert alert-info">
<p><b>You have {{ $user->points }} points</b></p>
<p>
<small>Users gain points for doing positive things on PastPaper and lose points for doing negative
things. The more points a user has, the more trusted they are.
</small>
</p>
</div>
<div class="alert alert-info">
<p><b>You have +{{ $user->voting_power }} voting power</b></p>
<p>
<small>Every time you vote on something it counts for {{ $user->voting_power }} votes. The more
points you have, the greater your voting power and ultimately your influence on the platform.
</small>
</p>
</div>
<div class="alert alert-info">
<p><b>You are level {{ $user->level[0] }}/{{ $user->level[1] }}</b></p>
<p>
<small>This is how far you have climbed to the top of the PastPaper ladder! The greater your level, the
more voting power you have.
</small>
</p>
</div>
<p><a href="{{ route('view_user', ['user' => $user]) }}">How were my points calculated?</a></p>
</div>
</div>
@endsection
| mit |
clchiou/garage | py/foreman/tests/testdata/path1/pkg3/build.py | 61 | raise AssertionError('This build file should not be loaded')
| mit |
thonkify/thonkify | src/lib/libfuturize/fixes/fix_division_safe.py | 2211 | """
For the ``future`` package.
Adds this import line:
from __future__ import division
at the top and changes any old-style divisions to be calls to
past.utils.old_div so the code runs as before on Py2.6/2.7 and has the same
behaviour on Py3.
If "from __future__ import division" is already in effect, this fixer does
nothing.
"""
from lib2to3 import fixer_base
from lib2to3.fixer_util import syms, does_tree_import
from libfuturize.fixer_util import (token, future_import, touch_import_top,
wrap_in_fn_call)
def match_division(node):
u"""
__future__.division redefines the meaning of a single slash for division,
so we match that and only that.
"""
slash = token.SLASH
return node.type == slash and not node.next_sibling.type == slash and \
not node.prev_sibling.type == slash
class FixDivisionSafe(fixer_base.BaseFix):
# BM_compatible = True
run_order = 4 # this seems to be ignored?
_accept_type = token.SLASH
PATTERN = """
term<(not('/') any)+ '/' ((not('/') any))>
"""
def start_tree(self, tree, name):
"""
Skip this fixer if "__future__.division" is already imported.
"""
super(FixDivisionSafe, self).start_tree(tree, name)
self.skip = "division" in tree.future_features
def match(self, node):
u"""
Since the tree needs to be fixed once and only once if and only if it
matches, we can start discarding matches after the first.
"""
if (node.type == self.syms.term and
len(node.children) == 3 and
match_division(node.children[1])):
expr1, expr2 = node.children[0], node.children[2]
return expr1, expr2
else:
return False
def transform(self, node, results):
if self.skip:
return
future_import(u"division", node)
touch_import_top(u'past.utils', u'old_div', node)
expr1, expr2 = results[0].clone(), results[1].clone()
# Strip any leading space for the first number:
expr1.prefix = u''
return wrap_in_fn_call("old_div", (expr1, expr2), prefix=node.prefix)
| mit |
robbynshaw/stackattack | stackattack/Controllers/UserController.cs | 1203 | using stackattack.Core;
using stackattack.Questions;
using stackattack.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace stackattack.Controllers
{
public class UserController : ApiController
{
private IQuestionStore questionStore;
private IUserStore userStore;
public UserController()
{
// Defaults
this.questionStore = Cache.QuestionStore;
this.userStore = Cache.UserStore;
}
public UserController(IQuestionStore questionStore, IUserStore userStore)
{
this.questionStore = questionStore;
this.userStore = userStore;
}
// GET api/<controller>/5
public IUser Get(int id)
{
return this.userStore.Get(id);
}
// POST api/<controller>/
[HttpGet]
public IGuessResponse CheckScore(int userID, int answerID)
{
IGuessResponse response = this.questionStore.CheckAnswer(answerID);
this.userStore.AddScore(userID, response.Score);
return response;
}
}
} | mit |
siderisltd/Telerik-Academy | Exams/Exams_C#_Part1/CSharp-Fundamentals-2011-2012-Part-1-Sample-Exam/Problem 2 - Miss Cat/MissCat.cs | 3368 | using System;
class Program
{
static void Main()
{
int judge = int.Parse(Console.ReadLine());
int cat1 = 0;
int cat2 = 0;
int cat3 = 0;
int cat4 = 0;
int cat5 = 0;
int cat6 = 0;
int cat7 = 0;
int cat8 = 0;
int cat9 = 0;
int cat10 = 0;
for (int i = 0; i < judge; i++)
{
int catnumber = int.Parse(Console.ReadLine());
switch (catnumber)
{
case 1:
cat1++;
break;
case 2:
cat2++;
break;
case 3:
cat3++;
break;
case 4:
cat4++;
break;
case 5:
cat5++;
break;
case 6:
cat6++;
break;
case 7:
cat7++;
break;
case 8:
cat8++;
break;
case 9:
cat9++;
break;
case 10:
cat10++;
break;
}
}
if (cat1 > cat2 && cat1 > cat3 && cat1 > cat4 && cat1 > cat5 && cat1 > cat6 && cat1 > cat7 && cat1 > cat8
&& cat1 > cat9 && cat1 > cat10)
{
Console.WriteLine("1");
}
if (cat2 > cat1 && cat2 > cat3 && cat2 > cat4 && cat2 > cat5 && cat2 > cat6 && cat2 > cat7 && cat2 > cat8
&& cat2 > cat9 && cat2 > cat10)
{
Console.WriteLine("2");
}
if (cat3 > cat1 && cat3 > cat2 && cat3 > cat4 && cat3 > cat5 && cat3 > cat6 && cat3 > cat7 && cat3 > cat8
&& cat3 > cat9 && cat3 > cat10)
{
Console.WriteLine("3");
}
if (cat4 > cat1 && cat4 > cat2 && cat4 > cat3 && cat4 > cat5 && cat4 > cat6 && cat4 > cat7 && cat4 > cat8
&& cat4 > cat9 && cat4 > cat10)
{
Console.WriteLine("4");
}
if (cat5 > cat1 && cat5 > cat2 && cat5 > cat3 && cat5 > cat4 && cat5 > cat6 && cat5 > cat7 && cat5 > cat8
&& cat5 > cat9 && cat5 > cat10)
{
Console.WriteLine("5");
}
if (cat6 > cat1 && cat6 > cat2 && cat6 > cat3 && cat6 > cat4 && cat6 > cat5 && cat6 > cat7 && cat6 > cat8
&& cat6 > cat9 && cat6 > cat10)
{
Console.WriteLine("6");
}
if (cat7 > cat1 && cat7 > cat2 && cat7 > cat3 && cat7 > cat4 && cat7 > cat5 && cat7 > cat6 && cat7 > cat8
&& cat7 > cat9 && cat7 > cat10)
{
Console.WriteLine("7");
}
if (cat8 > cat7 && cat8 > cat1 && cat8 > cat2 && cat8 > cat3 && cat8 > cat4 && cat8 > cat5 && cat8 > cat6
&& cat8 > cat9 && cat8 > cat10)
{
Console.WriteLine("8");
}
if (cat9 > cat2 && cat9 > cat3 && cat9 > cat4 && cat9 > cat5 && cat9 > cat6 && cat9 > cat7 && cat9 > cat8
&& cat9 > cat1 && cat9 > cat10)
{
Console.WriteLine("9");
}
if (cat10 > cat2 && cat10 > cat3 && cat10 > cat4 && cat10 > cat5 && cat10 > cat6 && cat10 > cat7 && cat10 > cat8
&& cat10 > cat9 && cat10 > cat1)
{
Console.WriteLine("10");
}
}
} | mit |
simplyianm/clububer | infusions/fusionboard4/forum/postnewthread.php | 15618 | <?php
/*
fusionBoard 4.0
php-Invent Team
http://www.php-invent.com
Developer: Ian Unruh (SoBeNoFear)
[email protected]
*/
if (!defined("IN_FUSION")) { die("Access Denied"); }
if (isset($_POST['previewpost']) || isset($_POST['add_poll_option'])) {
$subject = trim(stripinput(censorwords($_POST['subject'])));
$message = trim(stripinput(censorwords($_POST['message'])));
$sticky_thread_check = isset($_POST['sticky_thread']) ? " checked='checked'" : "";
$lock_thread_check = isset($_POST['lock_thread']) ? " checked='checked'" : "";
$sig_checked = isset($_POST['show_sig']) ? " checked='checked'" : "";
$disable_smileys_check = isset($_POST['disable_smileys']) || preg_match("#\[code\](.*?)\[/code\]#si", $message) ? " checked='checked'" : "";
if ($settings['thread_notify']) $notify_checked = isset($_POST['notify_me']) ? " checked='checked'" : "";
if ($fdata['forum_poll'] && checkgroup($fdata['forum_poll'])) {
$poll_title = trim(stripinput(censorwords($_POST['poll_title'])));
if (isset($_POST['poll_options']) && is_array($_POST['poll_options'])) {
foreach ($_POST['poll_options'] as $poll_option) {
if ($poll_option) { $poll_opts[] = stripinput($poll_option); }
}
} else {
$poll_opts = array();
}
if (isset($_POST['add_poll_option'])) {
if (count($poll_opts)) array_push($poll_opts, "");
}
}
if (isset($_POST['previewpost'])) {
if ($subject == "") { $subject = $locale['420']; }
if ($message == "") {
$previewmessage = $locale['421'];
} else {
$previewmessage = $message;
if ($sig_checked) { $previewmessage = $previewmessage."\n\n".$userdata['user_sig']; }
if (!$disable_smileys_check) { $previewmessage = parsesmileys($previewmessage); }
$previewmessage = parseubb($previewmessage);
$previewmessage = nl2br($previewmessage);
}
//$is_mod = iMOD && iUSER < "102" ? true : false;
opentable($locale['400']);
renderPostNav();
if ($fdata['forum_poll'] && checkgroup($fdata['forum_poll'])) {
if ((isset($poll_title) && $poll_title) && (isset($poll_opts) && is_array($poll_opts))) {
echo "<table cellpadding='0' cellspacing='1' width='100%' class='tbl-border' style='margin-bottom:5px'>\n<tr>\n";
echo "<td align='center' class='tbl2'><strong>".$poll_title."</strong></td>\n</tr>\n<tr>\n<td class='tbl1'>\n";
echo "<table align='center' cellpadding='0' cellspacing='0'>\n";
foreach ($poll_opts as $poll_option) {
echo "<tr>\n<td class='tbl1'><input type='radio' name='poll_option' value='$i' style='vertical-align:middle;' /> ".$poll_option."</td>\n</tr>\n";
$i++;
}
echo "</table>\n</td>\n</tr>\n</table>\n";
}
}
echo "<table cellpadding='0' cellspacing='1' width='100%' class='tbl-border'>\n<tr>\n";
echo "<td colspan='2' class='tbl2'><strong>".$subject."</strong></td>\n</tr>\n";
echo "<tr>\n<td class='tbl2' style='width:140px;'><a href='../profile.php?lookup=".$userdata['user_id']."'>".$userdata['user_name']."</a></td>\n";
echo "<td class='tbl2'>".$locale['426'].showdate("forumdate", time())."</td>\n";
echo "</tr>\n<tr>\n<td valign='top' width='140' class='tbl2'>\n";
if ($userdata['user_avatar'] && file_exists(IMAGES."avatars/".$userdata['user_avatar'])) {
echo "<img src='".IMAGES."avatars/".$userdata['user_avatar']."' alt='' /><br /><br />\n";
}
echo "<span class='small'>".getuserlevel($userdata['user_level'])."</span><br /><br />\n";
echo "<span class='small'><strong>".$locale['423']."</strong> ".$userdata['user_posts']."</span><br />\n";
echo "<span class='small'><strong>".$locale['425']."</strong> ".showdate("%d.%m.%y", $userdata['user_joined'])."</span><br />\n";
echo "<br /></td>\n<td valign='top' class='tbl1'>".$previewmessage."</td>\n";;
echo "</tr>\n</table>\n";
closetable();
}
}
if (isset($_POST['postnewthread'])) {
$subject = trim(stripinput(censorwords($_POST['subject'])));
$message = trim(stripinput(censorwords($_POST['message'])));
$flood = false; $error = 0;
$sticky_thread = isset($_POST['sticky_thread']) && (iMOD || iSUPERADMIN) ? 1 : 0;
$lock_thread = isset($_POST['lock_thread']) && (iMOD || iSUPERADMIN) ? 1 : 0;
$sig = isset($_POST['show_sig']) ? 1 : 0;
$smileys = isset($_POST['disable_smileys']) || preg_match("#\[code\](.*?)\[/code\]#si", $message) ? 0 : 1;
$thread_poll = 0;
if ($fdata['forum_poll'] && checkgroup($fdata['forum_poll'])) {
if (isset($_POST['poll_options']) && is_array($_POST['poll_options'])) {
foreach ($_POST['poll_options'] as $poll_option) {
if (trim($poll_option)) $poll_opts[] = trim(stripinput(censorwords($poll_option)));
unset($poll_option);
}
}
$thread_poll = (trim($_POST['poll_title']) && (isset($poll_opts) && is_array($poll_opts)) ? 1 : 0);
}
if (iMEMBER) {
if ($subject != "" && $message != "") {
require_once INCLUDES."flood_include.php";
if (!flood_control("post_datestamp", DB_POSTS, "post_author='".$userdata['user_id']."'")) {
$result = dbquery("INSERT INTO ".DB_THREADS." (forum_id, thread_subject, thread_author, thread_views, thread_lastpost, thread_lastpostid, thread_lastuser, thread_postcount, thread_poll, thread_sticky, thread_locked) VALUES('".$_GET['forum_id']."', '$subject', '".$userdata['user_id']."', '0', '".time()."', '0', '".$userdata['user_id']."', '1', '".$thread_poll."', '".$sticky_thread."', '".$lock_thread."')");
$thread_id = mysql_insert_id();
if(isset($_POST['make_announcement'])){
$result = dbquery("insert into ".DB_PREFIX."fb_threads (thread_id, thread_announcement) values('$thread_id', '1')");
}
$result = dbquery("INSERT INTO ".DB_POSTS." (forum_id, thread_id, post_message, post_showsig, post_smileys, post_author, post_datestamp, post_ip, post_edituser, post_edittime) VALUES ('".$_GET['forum_id']."', '".$thread_id."', '".$message."', '".$sig."', '".$smileys."', '".$userdata['user_id']."', '".time()."', '".USER_IP."', '0', '0')");
$post_id = mysql_insert_id();
$result = dbquery("UPDATE ".DB_FORUMS." SET forum_lastpost='".time()."', forum_postcount=forum_postcount+1, forum_threadcount=forum_threadcount+1, forum_lastuser='".$userdata['user_id']."' WHERE forum_id='".$_GET['forum_id']."'");
$result = dbquery("UPDATE ".DB_THREADS." SET thread_lastpostid='".$post_id."' WHERE thread_id='".$thread_id."'");
$result = dbquery("UPDATE ".DB_USERS." SET user_posts=user_posts+1 WHERE user_id='".$userdata['user_id']."'");
if ($settings['thread_notify'] && isset($_POST['notify_me'])) $result = dbquery("INSERT INTO ".DB_THREAD_NOTIFY." (thread_id, notify_datestamp, notify_user, notify_status) VALUES('".$thread_id."', '".time()."', '".$userdata['user_id']."', '1')");
$icon = (isset($_POST['post_icon']) && verify_image(INFUSIONS."fusionboard4/images/post_icons/".(stripinput($_POST['post_icon']))) ? stripinput($_POST['post_icon']) : "page_white.png");
$result = dbquery("INSERT INTO ".DB_PREFIX."fb_posts (post_id,post_editreason,post_icon) VALUES('$post_id', '', '$icon')");
if (($fdata['forum_poll'] && checkgroup($fdata['forum_poll'])) && $thread_poll) {
$poll_title = trim(stripinput(censorwords($_POST['poll_title'])));
if ($poll_title && (isset($poll_opts) && is_array($poll_opts))) {
$result = dbquery("INSERT INTO ".DB_FORUM_POLLS." (thread_id, forum_poll_title, forum_poll_start, forum_poll_length, forum_poll_votes) VALUES('".$thread_id."', '".$poll_title."', '".time()."', '0', '0')");
$forum_poll_id = mysql_insert_id();
$i = 1;
foreach ($poll_opts as $poll_option) {
$result = dbquery("INSERT INTO ".DB_FORUM_POLL_OPTIONS." (thread_id, forum_poll_option_id, forum_poll_option_text, forum_poll_option_votes) VALUES('".$thread_id."', '".$i."', '".$poll_option."', '0')");
$i++;
}
}
}
if ($fdata['forum_attach'] && checkgroup($fdata['forum_attach'])) {
foreach($_FILES as $attach){
if ($attach['name'] != "" && !empty($attach['name']) && is_uploaded_file($attach['tmp_name'])) {
$attachname = substr($attach['name'], 0, strrpos($attach['name'], "."));
$attachext = strtolower(strrchr($attach['name'],"."));
if (preg_match("/^[-0-9A-Z_\[\]]+$/i", $attachname) && $attach['size'] <= $settings['attachmax']) {
$attachtypes = explode(",", $settings['attachtypes']);
if (in_array($attachext, $attachtypes)) {
$attachname = attach_exists(strtolower($attach['name']));
move_uploaded_file($attach['tmp_name'], FORUM."attachments/".$attachname);
chmod(FORUM."attachments/".$attachname,0644);
if (in_array($attachext, $imagetypes) && (!@getimagesize(FORUM."attachments/".$attachname) || !@verify_image(FORUM."attachments/".$attachname))) {
unlink(FORUM."attachments/".$attachname);
$error = 1;
}
if (!$error) $result = dbquery("INSERT INTO ".DB_FORUM_ATTACHMENTS." (thread_id, post_id, attach_name, attach_ext, attach_size) VALUES ('".$thread_id."', '".$post_id."', '$attachname', '$attachext', '".$attach['size']."')");
} else {
@unlink($attach['tmp_name']);
$error = 1;
}
} else {
@unlink($attach['tmp_name']);
$error = 2;
}
}
}
}
} else {
redirect("viewforum.php?forum_id=".$_GET['forum_id']);
}
} else {
$error = 3;
}
} else {
$error = 4;
}
if ($error > 2) {
redirect("postify.php?post=new&error=$error&forum_id=".$_GET['forum_id']);
} else {
redirect("postify.php?post=new&error=$error&forum_id=".$_GET['forum_id']."&thread_id=".$thread_id."");
}
} else {
if (!isset($_POST['previewpost']) && !isset($_POST['add_poll_option'])) {
$subject = "";
$message = "";
$sticky_thread_check = "";
$lock_thread_check = "";
$disable_smileys_check = "";
$sig_checked = " checked='checked'";
if ($settings['thread_notify']) $notify_checked = "";
$poll_title = "";
$poll_opts = array();
}
add_to_title($locale['global_201'].$locale['401']);
opentable($locale['401']);
if(!isset($_POST['previewpost'])) renderPostNav($_GET['action']);
echo "<form id='inputform' method='post' action='".FUSION_SELF."?action=newthread&forum_id=".$_GET['forum_id']."' enctype='multipart/form-data' onsubmit='return checkForm();'>\n";
echo "<table cellpadding='0' cellspacing='1' width='100%' class='tbl-border'>\n<tr>\n";
echo "<td width='145' class='tbl2'>".$locale['460']."</td>\n";
echo "<td class='tbl1'><input type='text' name='subject' value='".$subject."' class='textbox' maxlength='255' style='width: 250px' /></td>\n";
echo "</tr>\n<tr>\n";
echo "<td valign='top' width='145' class='tbl2'>".$locale['461']."</td>\n";
echo "<td class='tbl1'><textarea name='message' cols='60' rows='15' class='textbox' style='width:98%'>".$message."</textarea>";
if($fb4['spell_check']){
echo "<script type='text/javascript' src='http://buttercup.spellingcow.com/spell/scayt'></script>
<script type='text/javascript'>
<!--
var sc_ayt_params = {
highlight_err_type : 'highlight', // note that there are commas after the fist 2 entries
highlight_err_color : 'gray',
ayt_default : 'on' // notice there's no comma after the last entry
} ;
//-->
</script>";
}
echo "</td>\n";
echo "</tr>\n<tr>\n";
echo "<td width='145' class='tbl2'> </td>\n";
echo "<td class='tbl1'>".display_bbcodes("99%", "message")."</td>\n";
echo "</tr>\n<tr>\n";
if($fb4['post_icons']){
echo "<td valign='top' width='145' class='tbl2'>".$locale['fb613']."</td>\n";
echo "<td class='tbl1'>\n";
echo "<label><input type='radio' name='post_icon' value='page_white.png' checked> ".$locale['fb614']."</label><br />\n";
$postIcons = makefilelist(INFUSIONS."fusionboard4/images/post_icons/", ".|..|index.php|Thumbs.db");
foreach($postIcons as $icon){
echo "<label><input type='radio' name='post_icon' value='$icon'> <img src='".INFUSIONS."fusionboard4/images/post_icons/$icon' alt='$icon'></label> ";
}
echo "</td>\n</tr>\n<tr>\n";
}
echo "<td valign='top' width='145' class='tbl2'>".$locale['463']."</td>\n";
echo "<td class='tbl1'>\n";
if (iMOD || iSUPERADMIN) {
echo "<label><input type='checkbox' name='sticky_thread' value='1'".$sticky_thread_check." /> ".$locale['480']."</label><br />\n";
echo "<label><input type='checkbox' name='lock_thread' value='1'".$lock_thread_check." /> ".$locale['481']."</label><br />\n";
}
if($fb4['announce_enable'] && checkgroup($fb4['announce_create'])){
echo "<label><input type='checkbox' name='make_announcement' value='1' /> ".$locale['fb903']."</label><br />\n";
}
echo "<label><input type='checkbox' name='disable_smileys' value='1'".$disable_smileys_check." /> ".$locale['482']."</label>";
if (array_key_exists("user_sig", $userdata) && $userdata['user_sig']) {
echo "<br />\n<label><input type='checkbox' name='show_sig' value='1'".$sig_checked." /> ".$locale['483']."</label>";
}
if ($settings['thread_notify']) echo "<br />\n<label><input type='checkbox' name='notify_me' value='1'".$notify_checked." /> ".$locale['486']."</label>";
echo "</td>\n</tr>\n";
if ($fdata['forum_attach'] && checkgroup($fdata['forum_attach'])) {
echo "<tr>\n<td width='145' class='tbl2'>".$locale['464']."</td>\n";
echo "<td class='tbl1'><input id='my_file_element' type='file' name='file_1' style='width:200px;' class='textbox' /><br /><div id='files_list'></div>
<script>
<!-- Create an instance of the multiSelector class, pass it the output target and the max number of files -->
var multi_selector = new MultiSelector( document.getElementById( \"files_list\" ), ".($fb4['max_attach'])." );
<!-- Pass in the file element -->
multi_selector.addElement( document.getElementById( \"my_file_element\" ) );
</script></td>\n</tr>\n";
}
if ($fdata['forum_poll'] && checkgroup($fdata['forum_poll'])) {
echo "<tr>\n<td align='center' colspan='2' class='tbl2'>".$locale['467']."</td>\n";
echo "</tr>\n<tr>\n";
echo "<td width='145' class='tbl2'>".$locale['469']."</td>\n";
echo "<td class='tbl1'><input type='text' name='poll_title' value='".$poll_title."' class='textbox' maxlength='255' style='width:250px' /></td>\n";
echo "</tr>\n";
$i = 1;
if (isset($poll_opts) && is_array($poll_opts) && count($poll_opts)) {
foreach ($poll_opts as $poll_option) {
echo "<tr>\n<td width='145' class='tbl2'>".$locale['470']." ".$i."</td>\n";
echo "<td class='tbl1'><input type='text' name='poll_options[$i]' value='".$poll_option."' class='textbox' maxlength='255' style='width:250px'>";
if ($i == count($poll_opts)) {
echo " <input type='submit' name='add_poll_option' value='".$locale['471']."' class='button' />";
}
echo "</td>\n</tr>\n";
$i++;
}
} else {
echo "<tr>\n<td width='145' class='tbl2'>".$locale['470']." 1</td>\n";
echo "<td class='tbl1'><input type='text' name='poll_options[1]' value='' class='textbox' maxlength='255' style='width:250px' /> ";
echo "<tr>\n<td width='145' class='tbl2'>".$locale['470']." 2</td>\n";
echo "<td class='tbl1'><input type='text' name='poll_options[2]' value='' class='textbox' maxlength='255' style='width:250px' /> ";
echo "<input type='submit' name='add_poll_option' value='".$locale['471']."' class='button' /></td>\n</tr>\n";
}
}
echo "<tr>\n<td align='center' colspan='2' class='tbl1'>\n";
echo "<input type='submit' name='previewpost' value='".$locale['400']."' class='button' />\n";
echo "<input type='submit' name='postnewthread' value='".$locale['401']."' class='button' />\n";
echo "</td>\n</tr>\n</table>\n</form>\n";
echo "<div style='text-align:right; margin-top:5px;'>".showPoweredBy()."</div>";
closetable();
}
?> | mit |
kunalvarma05/Eloquent | src/main/java/eloquent/exceptions/EloquentException.java | 185 | package eloquent.exceptions;
/**
* @author Kunal
*/
public class EloquentException extends Exception {
public EloquentException(String message) {
super(message);
}
}
| mit |
edinferno/coach | edinferno_coach/include/lsd_opencv.hpp | 8111 | /*M///////////////////////////////////////////////////////////////////////////////////////
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef _OPENCV_LSD_HPP_
#define _OPENCV_LSD_HPP_
#ifdef __cplusplus
#include <opencv2/core/core.hpp>
namespace cv {
enum {LSD_NO_SIZE_LIMIT = -1,
LSD_REFINE_NONE = 0,
LSD_REFINE_STD = 1,
LSD_REFINE_ADV = 2,
};
class LineSegmentDetector
{
public:
/**
* Detect lines in the input image with the specified ROI.
*
* @param _image A grayscale(CV_8UC1) input image.
* If only a roi needs to be selected, use
* lsd_ptr->detect(image(roi), ..., lines);
* lines += Scalar(roi.x, roi.y, roi.x, roi.y);
* @param _lines Return: A vector of Vec4i elements specifying the beginning and ending point of a line.
* Where Vec4i is (x1, y1, x2, y2), point 1 is the start, point 2 - end.
* Returned lines are strictly oriented depending on the gradient.
* @param _roi Return: ROI of the image, where lines are to be found. If specified, the returning
* lines coordinates are image wise.
* @param width Return: Vector of widths of the regions, where the lines are found. E.g. Width of line.
* @param prec Return: Vector of precisions with which the lines are found.
* @param nfa Return: Vector containing number of false alarms in the line region, with precision of 10%.
* The bigger the value, logarithmically better the detection.
* * -1 corresponds to 10 mean false alarms
* * 0 corresponds to 1 mean false alarm
* * 1 corresponds to 0.1 mean false alarms
* This vector will be calculated _only_ when the objects type is REFINE_ADV
*/
virtual void detect(InputArray _image, OutputArray _lines,
OutputArray width = noArray(), OutputArray prec = noArray(),
OutputArray nfa = noArray()) = 0;
/**
* Draw lines on the given canvas.
*
* @param image The image, where lines will be drawn.
* Should have the size of the image, where the lines were found
* @param lines The lines that need to be drawn
*/
virtual void drawSegments(InputOutputArray _image, InputArray lines) = 0;
/**
* Draw both vectors on the image canvas. Uses blue for lines 1 and red for lines 2.
*
* @param image The image, where lines will be drawn.
* Should have the size of the image, where the lines were found.
* @param lines1 The first lines that need to be drawn. Color - Blue.
* @param lines2 The second lines that need to be drawn. Color - Red.
* @return The number of mismatching pixels between lines1 and lines2.
*/
virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray _image = noArray()) = 0;
/**
* Find all line elements that are *not* fullfilling the angle and range requirenmnets.
* Take all lines, whose angle(line_segment) is outside [min_angle, max_angle] range.
*
* @param lines Input lines.
* @param filtered The output vector of lines not containing those fulfilling the requirement.
* @param min_angle The min angle to be considered in degrees. Should be in range [0..180].
* @param max_angle The max angle to be considered in degrees. Should be >= min_angle and widthin range [0..180].
* @return Returns the number of line segments not included in the output vector.
*/
CV_WRAP virtual int filterOutAngle(InputArray lines, OutputArray filtered, float min_angle, float max_angle) = 0;
/**
* Find all line elements that are fullfilling the angle and range requirenmnets.
* Take all lines, whose angle(line_segment) is inside [min_angle, max_angle] range.
* The opposite of the filterOutAngle method.
*
* @param lines Input lines.
* @param filtered The output vector of lines not containing those fulfilling the requirement.
* @param min_angle The min angle to be considered in degrees. Should be in range [0..180].
* @param max_angle The max angle to be considered in degrees. Should be >= min_angle and widthin range [0..180].
* @return Returns the number of line segments not included in the output vector.
*/
CV_WRAP virtual int retainAngle(InputArray lines, OutputArray filtered, float min_angle, float max_angle) = 0;
/**
* Find all line elements that *are* fullfilling the size requirenmnets.
* Lines which are shorter than max_length and longer than min_length.
*
* @param lines Input lines.
* @param filtered The output vector of lines containing those fulfilling the requirement.
* @param max_length Maximum length of the line segment.
* @param min_length Minimum length of the line segment.
* @return Returns the number of line segments not included in the output vector.
*/
CV_WRAP virtual int filterSize(InputArray lines, OutputArray filtered, float min_length, float max_length = LSD_NO_SIZE_LIMIT) = 0;
/*
* Find itnersection point of 2 lines.
*
* @param line1 First line in format Vec4i(x1, y1, x2, y2).
* @param line2 Second line in the same format as line1.
* @param P The point where line1 and line2 intersect.
* @return The value in variable P is only valid when the return value is true.
* Otherwise, the lines are parallel and the value can be ignored.
*/
CV_WRAP virtual bool intersection(InputArray line1, InputArray line2, Point& P) = 0;
virtual ~LineSegmentDetector() {};
};
//! Returns a pointer to a LineSegmentDetector class.
CV_EXPORTS Ptr<LineSegmentDetector> createLineSegmentDetectorPtr(
int _refine = LSD_REFINE_STD, double _scale = 0.8,
double _sigma_scale = 0.6, double _quant = 2.0, double _ang_th = 22.5,
double _log_eps = 0, double _density_th = 0.7, int _n_bins = 1024);
}
#endif
#endif
| mit |
ledermann/datev | lib/datev/field/boolean_field.rb | 336 | module Datev
class BooleanField < Field
def validate!(value)
super
unless value.nil?
raise ArgumentError.new("Value given for field '#{name}' is not a Boolean") unless [true, false].include?(value)
end
end
def output(value, _context=nil)
value ? 1 : 0 unless value.nil?
end
end
end
| mit |
paulcull/mean-swimclub | public/modules/entities/config/entities.client.config.js | 403 | 'use strict';
// Configuring the Articles module
angular.module('entities').run(['Menus',
function(Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', 'Entities', 'entities', 'dropdown', '/entities/(/create)?');
Menus.addSubMenuItem('topbar', 'entities', 'List Entities', 'entities');
Menus.addSubMenuItem('topbar', 'entities', 'New Entities', 'entities/create');
}
]); | mit |
lysyi3m/npmdc | lib/npmdc/version.rb | 44 | module Npmdc
VERSION = '0.5.1'.freeze
end
| mit |
potatolondon/fluent-2.0 | fluent/tests/test_models.py | 5231 | # -*- coding: utf-8 -*-
from djangae.test import TestCase
from django.conf import settings
from django.core.exceptions import ValidationError
from django.test import override_settings
from fluent.models import MasterTranslation, Translation
class MasterTranslationTests(TestCase):
def test_creation_creates_counterpart(self):
mt = MasterTranslation.objects.create(
text="Hello",
hint="World!",
language_code="en"
)
self.assertEqual(1, Translation.objects.count())
self.assertTrue("en" in mt.translations_by_language_code)
self.assertItemsEqual(["en"], mt.translations.values_list("language_code", flat=True))
def test_adding_new_translations(self):
mt = MasterTranslation.objects.create(text="Hello World!")
mt.create_or_update_translation("fr", "Bonjour!")
self.assertEqual(2, Translation.objects.count())
self.assertEqual(2, len(mt.translations_by_language_code))
self.assertItemsEqual(["fr", settings.LANGUAGE_CODE], mt.translations.values_list("language_code", flat=True))
def test_pk_is_set_correctly(self):
mt1 = MasterTranslation.objects.create(text="Hello World!", language_code="en")
self.assertEqual(mt1.pk, MasterTranslation.generate_key("Hello World!", "", "en"))
mt2 = MasterTranslation.objects.create(text="Hello World!", language_code="fr")
self.assertEqual(mt2.pk, MasterTranslation.generate_key("Hello World!", "", "fr"))
# Make sure that it differs
self.assertNotEqual(mt1.pk, mt2.pk)
@override_settings(LANGUAGES=[("en", "English"), ("de", "German")])
def test_text_for_language_code(self):
mt = MasterTranslation.objects.create(text="Hello World!")
text = mt.text_for_language_code("de") # try to fetch an translation we don't have
self.assertEqual(text, "Hello World!")
mt.create_or_update_translation("de", "Hallo Welt!")
text = mt.text_for_language_code("de")
self.assertEqual(text, "Hallo Welt!")
@override_settings(LANGUAGES=[("en", "English"), ("de", "German")])
def test_invalid_language_code(self):
mt = MasterTranslation.objects.create(text="Hello World!")
errors = mt.create_or_update_translation("es", "¡Hola, mundo!")
mt = MasterTranslation.objects.get(id=mt.id)
self.assertNotIn('es', mt.translated_into_languages)
self.assertEqual(
errors,
["'es' is not included as a language in your settings file"]
)
def test_unicode_magic_single(self):
mt = MasterTranslation.objects.create(
text="Hello",
hint="World!",
language_code="en"
)
self.assertEqual(unicode(mt), "Hello (en)")
def test_unicode_magic_plural(self):
mt = MasterTranslation.objects.create(
text="Hello",
plural_text={"h": "Helloes"},
hint="World!",
language_code="en"
)
self.assertEqual(unicode(mt), "Hello (en plural)")
def test_repr(self):
mt = MasterTranslation.objects.create(
text="Hello",
plural_text={"h": "Helloes"},
hint="World!",
language_code="en"
)
self.assertEqual(repr(mt), "{}".format(mt.id))
def test_first_letter_is_not_a_whitespace(self):
mt = MasterTranslation.objects.create(
text="\n\n\nHello",
hint="World!",
language_code="en"
)
mt.refresh_from_db()
self.assertEqual(mt.first_letter, "H")
class TranslationTests(TestCase):
def test_unicode_magic_single(self):
mt = MasterTranslation.objects.create(
text="Hello",
hint="World!",
language_code="en"
)
translation = mt.translations.get()
self.assertEqual(unicode(translation), "Translation of Hello for en")
def test_unicode_magic_plural(self):
mt = MasterTranslation.objects.create(
text="Hello",
plural_text={"h": "Helloes"},
hint="World!",
language_code="en"
)
translation = mt.translations.get()
self.assertEqual(unicode(translation), "Translation of Hello for en")
def test_repr(self):
mt = MasterTranslation.objects.create(
text="Hello",
hint="World!",
language_code="en"
)
translation = mt.translations.get()
self.assertEqual(repr(translation), "{}".format(translation.id))
def test_clean(self):
MasterTranslation.objects.create(text="Buttons!")
translation = Translation.objects.get()
translation.full_clean()
translation.plural_texts["o"] = "Buttons%s"
with self.assertRaises(ValidationError):
translation.full_clean()
def test_can_create_translation_from_non_ascii_master(self):
master_text = u'\u0141uk\u0105\u015b\u017a' # Lukasz.
mt = MasterTranslation.objects.create(text=master_text)
# Previously this would raise UnicodeEncodeError.
mt.create_or_update_translation('en', singular_text=u'Lukasz')
| mit |
matz-e/lobster | lobster/cmssw/dataset.py | 7741 | import hashlib
import logging
import math
import os
import pickle
import re
import requests
from retrying import retry
import xdg.BaseDirectory
from lobster.core.dataset import DatasetInfo
from lobster.util import Configurable
from dbs.apis.dbsClient import DbsApi
from WMCore.Credential.Proxy import Proxy
from WMCore.DataStructs.LumiList import LumiList
logger = logging.getLogger('lobster.cmssw.dataset')
class DASWrapper(DbsApi):
@retry(stop_max_attempt_number=10)
def listFileLumis(self, *args, **kwargs):
return super(DASWrapper, self).listFileLumis(*args, **kwargs)
@retry(stop_max_attempt_number=10)
def listFileSummaries(self, *args, **kwargs):
return super(DASWrapper, self).listFileSummaries(*args, **kwargs)
@retry(stop_max_attempt_number=10)
def listFiles(self, *args, **kwargs):
return super(DASWrapper, self).listFiles(*args, **kwargs)
@retry(stop_max_attempt_number=10)
def listBlocks(self, *args, **kwargs):
return super(DASWrapper, self).listBlocks(*args, **kwargs)
class Cache(object):
def __init__(self):
self.cachedir = xdg.BaseDirectory.save_cache_path('lobster')
def __cachename(self, name, mask):
m = hashlib.sha256()
m.update(name)
if mask:
m.update(mask)
return os.path.join(self.cachedir,
"{}-{}.pkl".format(name.strip('/').split('/')[0], m.hexdigest()))
def cache(self, name, mask, baseinfo, dataset):
logger.debug("writing dataset '{}' to cache".format(name))
with open(self.__cachename(name, mask), 'wb') as fd:
pickle.dump((baseinfo, dataset), fd)
def cached(self, name, mask, baseinfo):
try:
with open(self.__cachename(name, mask), 'rb') as fd:
info, dset = pickle.load(fd)
if baseinfo == info:
logger.debug("retrieved dataset '{}' from cache".format(name))
return dset
return None
except Exception:
return None
class Dataset(Configurable):
"""
Specification for processing a dataset stored in DBS.
Parameters
----------
dataset : str
The full dataset name as in DBS.
lumis_per_task : int
How many luminosity sections to process in one task. May be
modified by Lobster to match the user-specified task runtime.
events_per_task : int
Adjust `lumis_per_task` to contain as many luminosity sections
to process the specified amount of events.
lumi_mask : str
The URL or filename of a JSON luminosity section mask, as
customary in CMS.
file_based : bool
Process whole files instead of single luminosity sections.
dbs_instance : str
Which DBS instance to query for the `dataset`.
"""
_mutable = {}
__apis = {}
__dsets = {}
__cache = Cache()
def __init__(self, dataset, lumis_per_task=25, events_per_task=None, lumi_mask=None, file_based=False, dbs_instance='global'):
self.dataset = dataset
self.lumi_mask = lumi_mask
self.lumis_per_task = lumis_per_task
self.events_per_task = events_per_task
self.file_based = file_based
self.dbs_instance = 'https://cmsweb.cern.ch/dbs/prod/{0}/DBSReader'.format(dbs_instance)
self.total_units = 0
def __get_mask(self, url):
if not re.match(r'https?://', url):
return url
fn = os.path.basename(url)
cached = os.path.join(Dataset.__cache.cachedir, fn)
if not os.path.isfile(cached):
r = requests.get(url)
if not r.ok:
raise IOError("unable to retrieve '{0}'".format(url))
with open(cached, 'w') as f:
f.write(r.text)
return cached
def validate(self):
if self.dataset in Dataset.__dsets:
return True
if self.lumi_mask:
self.lumi_mask = self.__get_mask(self.lumi_mask)
cred = Proxy({'logger': logging.getLogger("WMCore")})
dbs = DASWrapper(self.dbs_instance, ca_info=cred.getProxyFilename())
baseinfo = dbs.listFileSummaries(dataset=self.dataset)
if baseinfo is None or (len(baseinfo) == 1 and baseinfo[0] is None):
return False
return True
def get_info(self):
if self.dataset not in Dataset.__dsets:
if self.lumi_mask:
self.lumi_mask = self.__get_mask(self.lumi_mask)
res = self.query_database()
if self.events_per_task:
if res.total_events > 0:
res.tasksize = int(math.ceil(self.events_per_task / float(res.total_events) * res.total_units))
else:
res.tasksize = 1
else:
res.tasksize = self.lumis_per_task
Dataset.__dsets[self.dataset] = res
self.total_units = Dataset.__dsets[self.dataset].total_units
return Dataset.__dsets[self.dataset]
def query_database(self):
cred = Proxy({'logger': logging.getLogger("WMCore")})
dbs = DASWrapper(self.dbs_instance, ca_info=cred.getProxyFilename())
baseinfo = dbs.listFileSummaries(dataset=self.dataset)
if baseinfo is None or (len(baseinfo) == 1 and baseinfo[0] is None):
raise ValueError('unable to retrive information for dataset {}'.format(self.dataset))
if not self.file_based:
result = self.__cache.cached(self.dataset, self.lumi_mask, baseinfo)
if result:
return result
total_lumis = sum([info['num_lumi'] for info in baseinfo])
result = DatasetInfo()
result.total_events = sum([info['num_event'] for info in baseinfo])
for info in dbs.listFiles(dataset=self.dataset, detail=True):
fn = info['logical_file_name']
result.files[fn].events = info['event_count']
result.files[fn].size = info['file_size']
if self.file_based:
for info in dbs.listFiles(dataset=self.dataset):
fn = info['logical_file_name']
result.files[fn].lumis = [(-2, -2)]
else:
blocks = dbs.listBlocks(dataset=self.dataset)
if self.lumi_mask:
unmasked_lumis = LumiList(filename=self.lumi_mask)
for block in blocks:
runs = dbs.listFileLumis(block_name=block['block_name'])
for run in runs:
fn = run['logical_file_name']
for lumi in run['lumi_section_num']:
if not self.lumi_mask or ((run['run_num'], lumi) in unmasked_lumis):
result.files[fn].lumis.append((run['run_num'], lumi))
elif self.lumi_mask and ((run['run_num'], lumi) not in unmasked_lumis):
result.masked_units += 1
result.unmasked_units = sum([len(f.lumis) for f in result.files.values()])
result.total_units = result.unmasked_units + result.masked_units
if not self.file_based:
self.__cache.cache(self.dataset, self.lumi_mask, baseinfo, result)
result.stop_on_file_boundary = (result.total_units != total_lumis) and not self.file_based
if result.stop_on_file_boundary:
logger.debug("split lumis detected in {} - "
"{} unique (run, lumi) but "
"{} unique (run, lumi, file) - "
"enforcing a limit of one file per task".format(self.dataset, total_lumis, result.total_units))
return result
| mit |
maastermedia/sfWhoisPlugin | lib/phpwhois/example.php | 3591 | <?php
/*
Whois.php PHP classes to conduct whois queries
Copyright (C)1999,2005 easyDNS Technologies Inc. & Mark Jeftovic
Maintained by David Saez ([email protected])
For the most recent version of this package visit:
http://www.phpwhois.org
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
header('Content-Type: text/html; charset=UTF-8');
$out = implode('', file('example.html'));
$out = str_replace('{self}', $_SERVER['PHP_SELF'], $out);
$resout = extract_block($out, 'results');
if (isSet($_GET['query']))
{
$query = $_GET['query'];
if (!empty($_GET['output']))
$output = $_GET['output'];
else
$output = '';
include_once('whois.main.php');
include_once('whois.utils.php');
$whois = new Whois();
// Set to true if you want to allow proxy requests
$allowproxy = false;
// uncomment the following line to get faster but less acurate results
// $whois->deep_whois = false;
// To use special whois servers (see README)
//$whois->UseServer('uk','whois.nic.uk:1043?{hname} {ip} {query}');
//$whois->UseServer('au','whois-check.ausregistry.net.au');
// uncomment the following line to add support for non ICANN tld's
// $whois->non_icann = true;
$result = $whois->Lookup($query);
$resout = str_replace('{query}', $query, $resout);
$winfo = '';
switch ($output)
{
case 'object':
if ($whois->Query['status'] < 0)
{
$winfo = implode($whois->Query['errstr'],"\n<br></br>");
}
else
{
$utils = new utils;
$winfo = $utils->showObject($result);
}
break;
case 'nice':
if (!empty($result['rawdata']))
{
$utils = new utils;
$winfo = $utils->showHTML($result);
}
else
{
if (isset($whois->Query['errstr']))
$winfo = implode($whois->Query['errstr'],"\n<br></br>");
else
$winfo = 'Unexpected error';
}
break;
case 'proxy':
if ($allowproxy)
exit(serialize($result));
default:
if(!empty($result['rawdata']))
{
$winfo .= '<pre>'.implode($result['rawdata'],"\n").'</pre>';
}
else
{
$winfo = implode($whois->Query['errstr'],"\n<br></br>");
}
}
//$winfo = utf8_encode($winfo);
$resout = str_replace('{result}', $winfo, $resout);
}
else
$resout = '';
echo str_replace('{results}', $resout, $out);
//-------------------------------------------------------------------------
function extract_block (&$plantilla,$mark,$retmark='')
{
$start = strpos($plantilla,'<!--'.$mark.'-->');
$final = strpos($plantilla,'<!--/'.$mark.'-->');
if ($start === false || $final === false) return;
$ini = $start+7+strlen($mark);
$ret=substr($plantilla,$ini,$final-$ini);
$final+=8+strlen($mark);
if ($retmark===false)
$plantilla=substr($plantilla,0,$start).substr($plantilla,$final);
else
{
if ($retmark=='') $retmark=$mark;
$plantilla=substr($plantilla,0,$start).'{'.$retmark.'}'.substr($plantilla,$final);
}
return $ret;
}
?>
| mit |
webdesignberlin/styleguide-colors | options.js | 378 | module.exports = class{
constructor(opt){
if(!opt){
opt = {}
}
this.separator = opt.separator || ',';
this.headline = opt.headline || 'Colors';
this.wrapper = opt.wrapper || 'section';
this.templatePath = opt.templatePath || __dirname+'/template.html';
this.sassPath = opt.sassPath || '';
this.outputFile = opt.outputFile || null;
}
};
| mit |
shavenzov/free-sound-client | src/app/components/sort/sort-button/sort-button.component.ts | 1075 | /**
*
* This code has been written by Denis Shavenzov
* If you have any questions or notices you can contact me by email [email protected]
*
*/
import {Input, Output, Component, EventEmitter} from '@angular/core';
@Component({
selector: 'sort-button',
templateUrl: './sort-button.component.html',
styleUrls: ['./sort-button.component.less']
})
export class SortButtonComponent {
@Input()
public sortField : SortButtonParam;
@Input()
public selected : FreeSoundSort;
@Output()
public onClick : EventEmitter<FreeSoundSort> = new EventEmitter<FreeSoundSort>();
public get isSelectedInSortField() : boolean
{
return ( this.selected == this.sortField.descSort ) || ( this.selected == this.sortField.ascSort );
}
public clickHandler() : void
{
if ( this.isSelectedInSortField && this.sortField.descSort )
{
this.selected = ( this.selected == this.sortField.descSort ) ? this.sortField.ascSort : this.sortField.descSort;
this.onClick.emit( this.selected );
return;
}
this.onClick.emit( this.sortField.ascSort );
}
}
| mit |
ishmal/ldpc | test/rawcodes.js | 6849 | /**
* hwere we will keep the raw codes from the 801.11n spec for tests, so that
they will no add to the memory profile
*/
export const RawCodes = {
"1/2": {
"648": [
" 0 - - - 0 0 - - 0 - - 0 1 0 - - - - - - - - - -",
"22 0 - - 17 - 0 0 12 - - - - 0 0 - - - - - - - - -",
" 6 - 0 - 10 - - - 24 - 0 - - - 0 0 - - - - - - - -",
" 2 - - 0 20 - - - 25 0 - - - - - 0 0 - - - - - - -",
"23 - - - 3 - - - 0 - 9 11 - - - - 0 0 - - - - - -",
"24 - 23 1 17 - 3 - 10 - - - - - - - - 0 0 - - - - -",
"25 - - - 8 - - - 7 18 - - 0 - - - - - 0 0 - - - -",
"13 24 - - 0 - 8 - 6 - - - - - - - - - - 0 0 - - -",
" 7 20 - 16 22 10 - - 23 - - - - - - - - - - - 0 0 - -",
"11 - - - 19 - - - 13 - 3 17 - - - - - - - - - 0 0 -",
"25 - 8 - 23 18 - 14 9 - - - - - - - - - - - - - 0 0",
" 3 - - - 16 - - 2 25 5 - - 1 - - - - - - - - - - 0"
],
"1296": [
"40 - - - 22 - 49 23 43 - - - 1 0 - - - - - - - - - -",
"50 1 - - 48 35 - - 13 - 30 - - 0 0 - - - - - - - - -",
"39 50 - - 4 - 2 - - - - 49 - - 0 0 - - - - - - - -",
"33 - - 38 37 - - 4 1 - - - - - - 0 0 - - - - - - -",
"45 - - - 0 22 - - 20 42 - - - - - - 0 0 - - - - - -",
"51 - - 48 35 - - - 44 - 18 - - - - - - 0 0 - - - - -",
"47 11 - - - 17 - - 51 - - - 0 - - - - - 0 0 - - - -",
" 5 - 25 - 6 - 45 - 13 40 - - - - - - - - - 0 0 - - -",
"33 - - 34 24 - - - 23 - - 46 - - - - - - - - 0 0 - -",
" 1 - 27 - 1 - - - 38 - 44 - - - - - - - - - - 0 0 -",
" - 18 - - 23 - - 8 0 35 - - - - - - - - - - - - 0 0",
"49 - 17 - 30 - - - 34 - - 19 1 - - - - - - - - - - 0"
],
"1944": [
"57 - - - 50 - 11 - 50 - 79 - 1 0 - - - - - - - - - -",
" 3 - 28 - 0 - - - 55 7 - - - 0 0 - - - - - - - - -",
"30 - - - 24 37 - - 56 14 - - - - 0 0 - - - - - - - -",
"62 53 - - 53 - - 3 35 - - - - - - 0 0 - - - - - - -",
"40 - - 20 66 - - 22 28 - - - - - - - 0 0 - - - - - -",
" 0 - - - 8 - 42 - 50 - - 8 - - - - - 0 0 - - - - -",
"69 79 79 - - - 56 - 52 - - - 0 - - - - - 0 0 - - - -",
"65 - - - 38 57 - - 72 - 27 - - - - - - - - 0 0 - - -",
"64 - - - 14 52 - - 30 - - 32 - - - - - - - - 0 0 - -",
" - 45 - 70 0 - - - 77 9 - - - - - - - - - - - 0 0 -",
" 2 56 - 57 35 - - - - - 12 - - - - - - - - - - - 0 0",
"24 - 61 - 60 - - 27 51 - - 16 1 - - - - - - - - - - 0"
],
},
"2/3": {
"648": [
"25 26 14 - 20 - 2 - 4 - - 8 - 16 - 18 1 0 - - - - - -",
"10 9 15 11 - 0 - 1 - - 18 - 8 - 10 - - 0 0 - - - - -",
"16 2 20 26 21 - 6 - 1 26 - 7 - - - - - - 0 0 - - - -",
"10 13 5 0 - 3 - 7 - - 26 - - 13 - 16 - - - 0 0 - - -",
"23 14 24 - 12 - 19 - 17 - - - 20 - 21 - 0 - - - 0 0 - -",
" 6 22 9 20 - 25 - 17 - 8 - 14 - 18 - - - - - - - 0 0 -",
"14 23 21 11 20 - 24 - 18 - 19 - - - - 22 - - - - - - 0 0",
"17 11 11 20 - 21 - 26 - 3 - - 18 - 26 - 1 - - - - - - 0"
],
"1296": [
"39 31 22 43 - 40 4 - 11 - - 50 - - - 6 1 0 - - - - - -",
"25 52 41 2 6 - 14 - 34 - - - 24 - 37 - - 0 0 - - - - -",
"43 31 29 0 21 - 28 - - 2 - - 7 - 17 - - - 0 0 - - - -",
"20 33 48 - 4 13 - 26 - - 22 - - 46 42 - - - - 0 0 - - -",
"45 7 18 51 12 25 - - - 50 - - 5 - - - 0 - - - 0 0 - -",
"35 40 32 16 5 - - 18 - - 43 51 - 32 - - - - - - - 0 0 -",
" 9 24 13 22 28 - - 37 - - 25 - - 52 - 13 - - - - - - 0 0",
"32 22 4 21 16 - - - 27 28 - 38 - - - 8 1 - - - - - - 0"
],
"1944": [
"61 75 4 63 56 - - - - - - 8 - 2 17 25 1 0 - - - - - -",
"56 74 77 20 - - - 64 24 4 67 - 7 - - - - 0 0 - - - - -",
"28 21 68 10 7 14 65 - - - 23 - - - 75 - - - 0 0 - - - -",
"48 38 43 78 76 - - - - 5 36 - 15 72 - - - - - 0 0 - - -",
"40 2 53 25 - 52 62 - 20 - - 44 - - - - 0 - - - 0 0 - -",
"69 23 64 10 22 - 21 - - - - - 68 23 29 - - - - - - 0 0 -",
"12 0 68 20 55 61 - 40 - - - 52 - - - 44 - - - - - - 0 0",
"58 8 34 64 78 - - 11 78 24 - - - - - 58 1 - - - - - - 0"
],
},
"3/4": {
"648": [
"16 17 22 24 9 3 14 - 4 2 7 - 26 - 2 - 21 - 1 0 - - - -",
"25 12 12 3 3 26 6 21 - 15 22 - 15 - 4 - - 16 - 0 0 - - -",
"25 18 26 16 22 23 9 - 0 - 4 - 4 - 8 23 11 - - - 0 0 - -",
" 9 7 0 1 17 - - 7 3 - 3 23 - 16 - - 21 - 0 - - 0 0 -",
"24 5 26 7 1 - - 15 24 15 - 8 - 13 - 13 - 11 - - - - 0 0",
" 2 2 19 14 24 1 15 19 - 21 - 2 - 24 - 3 - 2 1 - - - - 0"
],
"1296": [
"39 40 51 41 3 29 8 36 - 14 - 6 - 33 - 11 - 4 1 0 - - - -",
"48 21 47 9 48 35 51 - 38 - 28 - 34 - 50 - 50 - - 0 0 - - -",
"30 39 28 42 50 39 5 17 - 6 - 18 - 20 - 15 - 40 - - 0 0 - -",
"29 0 1 43 36 30 47 - 49 - 47 - 3 - 35 - 34 - 0 - - 0 0 -",
" 1 32 11 23 10 44 12 7 - 48 - 4 - 9 - 17 - 16 - - - - 0 0",
"13 7 15 47 23 16 47 - 43 - 29 - 52 - 2 - 53 - 1 - - - - 0"
],
"1944": [
"48 29 28 39 9 61 - - - 63 45 80 - - - 37 32 22 1 0 - - - -",
" 4 49 42 48 11 30 - - - 49 17 41 37 15 - 54 - - - 0 0 - - -",
"35 76 78 51 37 35 21 - 17 64 - - - 59 7 - - 32 - - 0 0 - -",
" 9 65 44 9 54 56 73 34 42 - - - 35 - - - 46 39 0 - - 0 0 -",
" 3 62 7 80 68 26 - 80 55 - 36 - 26 - 9 - 72 - - - - - 0 0",
"26 75 33 21 69 59 3 38 - - - 35 - 62 36 26 - - 1 - - - - 0"
]
},
"5/6": {
"648": [
"17 13 8 21 9 3 18 12 10 0 4 15 19 2 5 10 26 19 13 13 1 0 - -",
" 3 12 11 14 11 25 5 18 0 9 2 26 26 10 24 7 14 20 4 2 - 0 0 -",
"22 16 4 3 10 21 12 5 21 14 19 5 - 8 5 18 11 5 5 15 0 - 0 0",
" 7 7 14 14 4 16 16 24 24 10 1 7 15 6 10 26 8 18 21 14 1 - - 0"
],
"1296": [
"48 29 37 52 2 16 6 14 53 31 34 5 18 42 53 31 45 - 46 52 1 0 - -",
"17 4 30 7 43 11 24 6 14 21 6 39 17 40 47 7 15 41 19 - - 0 0 -",
" 7 2 51 31 46 23 16 11 53 40 10 7 46 53 33 35 - 25 35 38 0 - 0 0",
"19 48 41 1 10 7 36 47 5 29 52 52 31 10 26 6 3 2 - 51 1 - - 0"
],
"1944": [
"13 48 80 66 4 74 7 30 76 52 37 60 - 49 73 31 74 73 23 - 1 0 - -",
"69 63 74 56 64 77 57 65 6 16 51 - 64 - 68 9 48 62 54 27 - 0 0 -",
"51 15 0 80 24 25 42 54 44 71 71 9 67 35 - 58 - 29 - 53 0 - 0 0",
"16 29 36 41 44 56 59 37 50 24 - 65 4 65 52 - 4 - 73 52 1 - - 0"
]
}
};
| mit |
IrinKos/ArraysHomework | 17. SubsetKWithSumS/Properties/AssemblyInfo.cs | 1416 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("17. SubsetKWithSumS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("17. SubsetKWithSumS")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("924a6eb7-b633-496f-a2d9-03d906506873")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
braindata/sfAdminThemejRollerPlugin | data/generator/sfDoctrineModule/jroller/template/templates/_pagination.php | 2701 | [?php
$first = ($pager->getPage() * $pager->getMaxPerPage() - $pager->getMaxPerPage() + 1);
$last = $first + $pager->getMaxPerPage() - 1;
?]
<table id="sf_admin_pager">
<tbody>
<tr>
<td class="left"></td>
<td class="center">
<table align="center" class="sf_admin_pagination">
<tbody>
<tr>
[?php if ($pager->haveToPaginate()): ?]
<td class="button">
<a href="[?php echo url_for('@<?php echo $this->getUrlForAction('list') ?>?page=1') ?]"[?php if ($pager->getPage() == 1) echo ' class="ui-state-disabled"' ?]>
<?php echo UIHelper::addIconByConf('first') ?>
</a>
</td>
<td class="button">
<a href="[?php echo url_for('@<?php echo $this->getUrlForAction('list') ?>?page='.$pager->getPreviousPage()) ?]"[?php if ($pager->getPage() == 1) echo ' class="ui-state-disabled"' ?]>
<?php echo UIHelper::addIconByConf('previous') ?>
</a>
</td>
<td align="center">
[?php echo __('Page') ?]
<form action="[?php echo url_for('@<?php echo $this->getUrlForAction('list') ?>') ?]" method="get">
<input type="text" name="page" value="[?php echo $pager->getPage() ?]" data-url="[?php echo url_for('@<?php echo $this->getUrlForAction('list') ?>') ?]" maxlength="7" size="2" />
</form>
[?php echo __('of %1%', array('%1%' => $pager->getLastPage())) ?]
</td>
<td class="button">
<a href="[?php echo url_for('@<?php echo $this->getUrlForAction('list') ?>?page='.$pager->getNextPage()) ?]"[?php if ($pager->getPage() == $pager->getLastPage()) echo ' class="ui-state-disabled"' ?]>
<?php echo UIHelper::addIconByConf('next') ?>
</a>
</td>
<td class="button">
<a href="[?php echo url_for('@<?php echo $this->getUrlForAction('list') ?>?page='.$pager->getLastPage()) ?]"[?php if ($pager->getPage() == $pager->getLastPage()) echo ' class="ui-state-disabled"' ?]>
<?php echo UIHelper::addIconByConf('last') ?>
</a>
</td>
[?php endif; ?]
</tr>
</tbody>
</table>
</td>
<td class="right">
[?php
echo __('View %1% - %2% of %3%',
array(
'%1%' => $first,
'%2%' => ($last > $pager->getNbResults()) ? $pager->getNbResults() : $last,
'%3%' => $pager->getNbResults()
)
)
?]
</td>
</tr>
</tbody>
</table>
| mit |
LagoVista/Admin | src/LagoVista.UserManagement/Managers/IAppUserManager.cs | 777 | using LagoVista.Core.Models;
using LagoVista.Core.Validation;
using LagoVista.UserManagement.Models.Account;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace LagoVista.UserManagement.Managers
{
public interface IAppUserManager
{
Task<AppUser> GetUserByIdAsync(String id, EntityHeader requestedByUser);
Task<InvokeResult> UpdateUserAsync(AppUser user, EntityHeader updatedByUser);
Task<InvokeResult> AddUserAsync(AppUser user, EntityHeader org, EntityHeader updatedByUserId);
Task<InvokeResult> DeleteUserAsync(String id, EntityHeader deletedByUser);
Task<IEnumerable<EntityHeader>> SearchUsers(string firstName, string lastName, EntityHeader searchedBy);
}
}
| mit |
johnshew/Pipeline | test/compiler/data/stagename-inline-simple/expected.js | 110 | const stageName = "fancyStage";
var tc = new TestClass();
tc.forward("fancyStage", {}, function (cs, ds) {}); | mit |
krcourville/mvc-grid-experiment | MvcTypescript.MvcWebClient/FormDesign/FormGridRow.cs | 1300 | using System;
using System.Collections.Generic;
using System.Linq;
namespace MvcTypescript.MvcWebClient.FormDesign
{
public class FormGridRow
{
private IFormSectionMetaProvider formSectionMeta;
public FormGridRow(IFormSectionMetaProvider formSectionMeta, ICollection<GriddedPropertyMetadata> items)
{
this.formSectionMeta = formSectionMeta;
LoadCells(items);
}
public ICollection<FormGridCell> Cells { get; private set; }
private void LoadCells(ICollection<GriddedPropertyMetadata> items)
{
//TODO: support spanning multiple columns
var dupe = items.GroupBy(g => g.Grid.Column)
.SelectMany(g => g.Skip(1))
.FirstOrDefault();
if (dupe != null)
{
throw new InvalidOperationException(string.Format("Found duplicate grid: {0}", dupe));
}
var lookup = items.ToDictionary(d => d.Grid.Column, d => d.Property);
Cells = Enumerable.Range(1, formSectionMeta.GetTotalColumns())
.Select(i => lookup.ContainsKey(i)
? new FormGridCell(lookup[i])
: FormGridCell.Empty
)
.ToList();
}
}
} | mit |
rednaxelafx/jvm.go | jvmgo/native/sun/misc/Unsafe.go | 1333 | package misc
import (
//"unsafe"
. "github.com/zxh0/jvm.go/jvmgo/any"
"github.com/zxh0/jvm.go/jvmgo/jvm/rtda"
rtc "github.com/zxh0/jvm.go/jvmgo/jvm/rtda/class"
)
func init() {
_unsafe(arrayBaseOffset, "arrayBaseOffset", "(Ljava/lang/Class;)I")
_unsafe(arrayIndexScale, "arrayIndexScale", "(Ljava/lang/Class;)I")
_unsafe(objectFieldOffset, "objectFieldOffset", "(Ljava/lang/reflect/Field;)J")
}
func _unsafe(method Any, name, desc string) {
rtc.RegisterNativeMethod("sun/misc/Unsafe", name, desc, method)
}
// public native int arrayBaseOffset(Class<?> type);
// (Ljava/lang/Class;)I
func arrayBaseOffset(frame *rtda.Frame) {
vars := frame.LocalVars()
vars.GetRef(0) // this
vars.GetRef(1) // type
stack := frame.OperandStack()
stack.PushInt(0) // todo
}
// public native int arrayIndexScale(Class<?> type);
// (Ljava/lang/Class;)I
func arrayIndexScale(frame *rtda.Frame) {
//stack.PopRef() // type
//stack.PopRef() // this
stack := frame.OperandStack()
stack.PushInt(1) // todo
}
// public native long objectFieldOffset(Field field);
// (Ljava/lang/reflect/Field;)J
func objectFieldOffset(frame *rtda.Frame) {
vars := frame.LocalVars()
// this := vars.GetRef(0)
jField := vars.GetRef(1)
offset := jField.GetFieldValue("slot", "I").(int32)
stack := frame.OperandStack()
stack.PushLong(int64(offset))
}
| mit |
MHerszak/meteor-react-starter | packages/lib-react/package.js | 2291 | Package.describe({
name: 'base2ind:lib-react',
version: '0.0.1',
// Brief, one-line summary of the package.
summary: '',
// URL to the Git repository containing the source code for this package.
git: '',
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Npm.depends({
"immutable" : "3.6.2",
"flux" : "2.1.1",
"react-mixin": "3.0.3",
});
Package.onUse(function(api)
{
api.versionsFrom('1.2.1');
var packages = [
// packages needed for all apps with react
'ecmascript',
'[email protected]_1',
'jquery',
'session',
'check',
// css
'fourseven:[email protected]',
// packages needed for packages that depend on this one
'underscore',
// routing
'kadira:[email protected]',
'kadira:[email protected]',
// collections schema and extended functionality
'aldeed:[email protected]',
'aldeed:[email protected]',
'aldeed:[email protected]',
/*'poetic:[email protected]_1',*/ // not really a good choice
// fonts
'ixdi:[email protected]',
// helpers for insert update on collections
'matb33:[email protected]',
// accounts ui
/*'universe:[email protected]',*/
'universe:[email protected]',
/*'tap:[email protected]',*/
'[email protected]',
'service-configuration',
'accounts-base',
'accounts-oauth',
'accounts-password',
'accounts-facebook',
'accounts-ui',
// making nmp packages work
'cosmos:browserify',
'kadira:[email protected]',
'browserstudios:[email protected]',
'browserstudios:[email protected]',
'izzilab:[email protected]',
];
api.use(packages);
api.imply(packages);
api.addFiles([
'./lib/core.jsx',
'./lib/callbacks.js',
'./lib/router.js',
'./lib/modules.js',
'./lib/menu.js',
'./lib/collections.js',
'./lib/utils.js',
'./client.browserify.js',
'./lib/base.js',
],['client','server']);
api.addFiles([
'./lib/bind-component.jsx',
// Dispatcher
'./lib/app-dispatcher.jsx',
// Flux utils
'./lib/flux-utils.jsx',
// Mixin
'./lib/store-mixin.jsx',
],['client']);
api.export([
// export the namespace
'Base2Ind',
'ReactMixin',
]);
});
| mit |
florin-chelaru/urho | Bindings/Portable/Skeleton.cs | 1340 | using System;
using System.Runtime.InteropServices;
namespace Urho {
// Skeletons are typically references to internal storage in other objects
// we surface this to C# as a pointer to the data, but to ensure that we do not
// have dangling pointers, we only surface the constructor that retains a copy
// to the container
public partial class Skeleton {
IntPtr handle;
[Preserve]
public Skeleton (IntPtr handle, object container)
{
this.handle = handle;
}
public BoneWrapper GetBoneSafe(uint index)
{
Runtime.ValidateObject(this);
unsafe
{
Bone* result = Skeleton_GetBone(handle, index);
if (result == null)
return null;
return new BoneWrapper(this, result);
}
}
public BoneWrapper GetBoneSafe(String name)
{
Runtime.ValidateObject(this);
unsafe
{
Bone* result = Skeleton_GetBone0(handle, new StringHash(name).Code);
if (result == null)
return null;
return new BoneWrapper(this, result);
}
}
}
public partial class AnimatedModel {
[DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
extern static IntPtr AnimatedModel_GetSkeleton (IntPtr handle);
public Skeleton Skeleton {
get
{
Runtime.ValidateObject(this);
return new Skeleton (AnimatedModel_GetSkeleton (handle), this);
}
}
}
}
| mit |
astex/living-with-django | front/main.js | 1056 | require.config({
paths: {
text: 'lib/require-text',
json: 'lib/require-json',
css: 'lib/require-css',
jquery: 'lib/jquery',
underscore: 'lib/underscore',
'underscore.crunch': 'lib/underscore.crunch',
backbone: 'lib/backbone',
marked: 'lib/marked',
'marked.highlight': 'lib/marked.highlight',
moment: 'lib/moment',
highlight: 'lib/highlight'
},
shim: {
highlight: {
deps: ['css!style/highlight.css'],
exports: 'hljs'
}
}
});
require(
[
'backbone', 'models', 'views', 'css!style/main.css'
], function(B, M, V) {
new (B.Router.extend({
routes: {'': 'list', 'e/:slug': 'entry'},
list: function() {
new V.Main({View: V.List, active: new M.Entry({})});
},
entry: function(slug) {
(new V.Main({View: V.List, active: new M.Entry({slug: slug})}))
.on('ready', function() {
$('.body').scrollTop($('.expanded').position().top - 45);
});
}
}));
B.history.start({pushState: true});
}
);
| mit |
eush77/blackbox | examples/stress/trivial.py | 98 | #!/usr/bin/python3
if __name__ == '__main__':
n = int(input())
print(sum(range(1, n+1)))
| mit |
rkkautsar/cp-solutions | UVa/11733.cpp | 2704 | //IO
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
//C Header
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
//container
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <bitset>
//misc
#include <algorithm>
#include <functional>
#include <limits>
#include <string>
using namespace std;
// typedef
typedef long long ll;
typedef pair<int,int> ii;
typedef pair<double,double> dd;
typedef pair<int,ii> iii;
typedef pair<double,dd> ddd;
typedef vector<ll> vll;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<char> vc;
typedef vector<ii> vii;
typedef vector<dd> vdd;
typedef vector<vi> vvi;
typedef vector<vd> vvd;
typedef vector<vc> vvc;
typedef vector<bool> vb;
//defines
#define abs(_x) ((_x)<0?-(_x):(_x))
#define REP(_x) for(int __x=0;__x<_x;++__x)
#define mp(_x,_y) make_pair((_x),(_y))
#define mp3(_x,_y,_z) make_pair((_x),(mp(_y,_z)))
#define fir first
#define sec second
#define PI 3.1415926535897932385
#define EPS 1e-9
#define PHI 1.6180339887498948482
#define INF 0x7FFFFFFF
#define INFLL 0x7FFFFFFFFFFFFFFFLL
#define readl(_s) getline(cin,_s);cin.ignore(9999,'\n')
#define ceildiv(_a,_b) ((_a)%(_b)==0?(_a)/(_b):((_a)/(_b))+1)
//classes
//Union Find
class UnionFind{
private:
vi parent;
vi rank;
int disjoint;
public:
UnionFind(int n){
rank.resize(n,0);
parent.resize(n);
disjoint=n;
for(int i=0;i<n;++i)parent[i]=i;
}
int findSet(int i){
return (parent[i]==i)? i : (parent[i]=findSet(parent[i]));
}
bool isSameSet(int i,int j){
return findSet(i)==findSet(j);
}
void unionSet(int i,int j){
if(!isSameSet(i,j)){
int x=findSet(i), y=findSet(j);
if(rank[x]>rank[y]) parent[y]=x;
else {
parent[x]=y;
if(rank[x]==rank[y]) ++rank[y];
}
--disjoint;
}
}
int countDisjointSet(){
return disjoint;
}
};
int main(int argc, char **argv){
ios_base::sync_with_stdio(0);
cin.tie(0);
int t,n,m,a,u,v,w,cost,airport;
cin>>t;
for(int testcase=1;testcase<=t;++testcase){
cin>>n>>m>>a;
UnionFind uf(n);
vector<iii> edge(m);
cost=0;
for(int i=0;i<m;++i){
cin>>u>>v>>w;
edge[i]=mp3(w,u-1,v-1);
}
sort(edge.begin(),edge.end());
for(int i=0;i<m;++i){
w=edge[i].first;
u=edge[i].second.first;
v=edge[i].second.second;
if(!uf.isSameSet(u,v) && w<a){
uf.unionSet(u,v);
cost+=w;
}
}
airport=uf.countDisjointSet();
cost+=airport*a;
cout<<"Case #"<<testcase<<": "<<cost<<' '<<airport<<'\n';
}
return 0;
}
| mit |
n0ts/kumogata-template | template/cloudfront-origin-access-identity.rb | 561 | #
# CloudFront origin access identity
# https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudfront-cloudfrontoriginaccessidentity.html
#
require 'kumogata/template/helper'
name = _resource_name(args[:name], "origin access identity")
comment = args[:comment] || "access-identity-#{args[:name]}"
depends = _depends([], args)
_(name) do
Type "AWS::CloudFront::CloudFrontOriginAccessIdentity"
Properties do
CloudFrontOriginAccessIdentityConfig _{
Comment comment
}
end
DependsOn depends unless depends.empty?
end
| mit |
jhendess/metadict | metadict-core/src/main/java/org/xlrnet/metadict/core/services/storage/StorageInitializationException.java | 1912 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jakob Hendeß
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.xlrnet.metadict.core.services.storage;
import org.xlrnet.metadict.api.exception.MetadictTechnicalException;
/**
* An error to indicate a fatal error while booting the storage subsystem from Metadict. Whenever an such an error is
* thrown, the Metadict core should shut down and not continue any booting attempts.
*/
public class StorageInitializationException extends MetadictTechnicalException {
private static final long serialVersionUID = -3554446165563236820L;
StorageInitializationException(String message) {
super(message);
}
StorageInitializationException(String message, Throwable cause) {
super(message, cause);
}
StorageInitializationException(Throwable cause) {
super(cause);
}
}
| mit |
rkusa/pdfjs | font/ZapfDingbats.js | 103 | const AFMFont = require('../lib/font/afm')
module.exports = new AFMFont(require('./ZapfDingbats.json')) | mit |
Maxwolf/DCM | Src/Forms/MainMenuBox.Designer.cs | 5892 | namespace DCM.Forms
{
partial class MainMenuBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnMainMenu_NewGame = new System.Windows.Forms.Button();
this.btnMainMenu_LoadGame = new System.Windows.Forms.Button();
this.btnMainMenu_Exit = new System.Windows.Forms.Button();
this.toolTip_MainMenu = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// btnMainMenu_NewGame
//
this.btnMainMenu_NewGame.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnMainMenu_NewGame.Image = global::DCM.Properties.Resources.add;
this.btnMainMenu_NewGame.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnMainMenu_NewGame.Location = new System.Drawing.Point(12, 12);
this.btnMainMenu_NewGame.Name = "btnMainMenu_NewGame";
this.btnMainMenu_NewGame.Padding = new System.Windows.Forms.Padding(25, 0, 0, 0);
this.btnMainMenu_NewGame.Size = new System.Drawing.Size(228, 48);
this.btnMainMenu_NewGame.TabIndex = 0;
this.btnMainMenu_NewGame.Text = "New Game";
this.toolTip_MainMenu.SetToolTip(this.btnMainMenu_NewGame, "Displays new game dialog letting you specify company and president name.");
this.btnMainMenu_NewGame.UseVisualStyleBackColor = true;
//
// btnMainMenu_LoadGame
//
this.btnMainMenu_LoadGame.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnMainMenu_LoadGame.Image = global::DCM.Properties.Resources.drive_disk;
this.btnMainMenu_LoadGame.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnMainMenu_LoadGame.Location = new System.Drawing.Point(12, 66);
this.btnMainMenu_LoadGame.Name = "btnMainMenu_LoadGame";
this.btnMainMenu_LoadGame.Padding = new System.Windows.Forms.Padding(25, 0, 0, 0);
this.btnMainMenu_LoadGame.Size = new System.Drawing.Size(228, 48);
this.btnMainMenu_LoadGame.TabIndex = 1;
this.btnMainMenu_LoadGame.Text = "Load Game";
this.toolTip_MainMenu.SetToolTip(this.btnMainMenu_LoadGame, "Loads a previously saved game.");
this.btnMainMenu_LoadGame.UseVisualStyleBackColor = true;
this.btnMainMenu_LoadGame.Click += new System.EventHandler(this.btnMainMenu_LoadGame_Click);
//
// btnMainMenu_Exit
//
this.btnMainMenu_Exit.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnMainMenu_Exit.Image = global::DCM.Properties.Resources.stop;
this.btnMainMenu_Exit.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnMainMenu_Exit.Location = new System.Drawing.Point(12, 157);
this.btnMainMenu_Exit.Name = "btnMainMenu_Exit";
this.btnMainMenu_Exit.Padding = new System.Windows.Forms.Padding(25, 0, 0, 0);
this.btnMainMenu_Exit.Size = new System.Drawing.Size(228, 48);
this.btnMainMenu_Exit.TabIndex = 3;
this.btnMainMenu_Exit.Text = "Exit to Desktop";
this.toolTip_MainMenu.SetToolTip(this.btnMainMenu_Exit, "Quits the game and exits to desktop.");
this.btnMainMenu_Exit.UseVisualStyleBackColor = true;
this.btnMainMenu_Exit.Click += new System.EventHandler(this.btnMainMenu_Exit_Click);
//
// MainMenuBox
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(252, 223);
this.ControlBox = false;
this.Controls.Add(this.btnMainMenu_Exit);
this.Controls.Add(this.btnMainMenu_LoadGame);
this.Controls.Add(this.btnMainMenu_NewGame);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MainMenuBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Main Menu";
this.TopMost = true;
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.Button btnMainMenu_NewGame;
public System.Windows.Forms.Button btnMainMenu_LoadGame;
public System.Windows.Forms.Button btnMainMenu_Exit;
private System.Windows.Forms.ToolTip toolTip_MainMenu;
}
} | mit |
twilio/twilio-php | src/Twilio/Rest/Supersim/V1/NetworkContext.php | 1603 | <?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Supersim\V1;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Values;
use Twilio\Version;
/**
* PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
*/
class NetworkContext extends InstanceContext {
/**
* Initialize the NetworkContext
*
* @param Version $version Version that contains the resource
* @param string $sid The SID of the Network resource to fetch
*/
public function __construct(Version $version, $sid) {
parent::__construct($version);
// Path Solution
$this->solution = ['sid' => $sid, ];
$this->uri = '/Networks/' . \rawurlencode($sid) . '';
}
/**
* Fetch the NetworkInstance
*
* @return NetworkInstance Fetched NetworkInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch(): NetworkInstance {
$payload = $this->version->fetch('GET', $this->uri);
return new NetworkInstance($this->version, $payload, $this->solution['sid']);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string {
$context = [];
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Supersim.V1.NetworkContext ' . \implode(' ', $context) . ']';
}
} | mit |
jjhesk/v-server-sdk-bank | core/connect_json_api.php | 4578 | <?php
/**
* Created by PhpStorm. 2013 @ imusictech
* developed by Heskeyo Kam
* User: Hesk
* Date: 13年12月4日
* Time: 下午3:16
* Prevent loading this file directly
* source: http://wordpress.org/plugins/json-api/other_notes/
*
* 5.2. Developing JSON API controllers
* Creating a controller
* To start a new JSON API controller, create a file called hello.php inside wp-content/plugins/json-api/controllers. Add the following class definition:
*
* <-php
*
* class JSON_API_Hello_Controller {
*
* public function hello_world() {
* return array(
* "message" => "Hello, world"
* );
* }
*
* }
*
* ->
*
*
*/
defined('ABSPATH') || exit;
if (!class_exists('connect_json_api')) {
class connect_json_api
{
public function __construct()
{
$this->start_api_interface();
}
public static function init()
{
new self();
}
public static function getpath()
{
return CORE_PATH . "api/";
}
private $list_functions;
private function start_api_interface()
{
// global $json_module_init_path;
if ($this->is_da_plugin_active()) {
$this->list_functions = array(
'personal',
'authen',
'email',
'systemlog',
'vcoin',
'cms',
'mission',
'redemption'
);
add_filter('json_api_email_controller_path', function () {
return connect_json_api::getpath() . 'email.php';
});
add_filter('json_api_systemlog_controller_path', function () {
return connect_json_api::getpath() . 'systemlog.php';
});
add_filter('json_api_vcoin_controller_path', function () {
return connect_json_api::getpath() . 'vcoin.php';
});
add_filter('json_api_cms_controller_path', function () {
return connect_json_api::getpath() . 'cms.php';
});
add_filter('json_api_personal_controller_path', function () {
return connect_json_api::getpath() . 'personal.php';
});
add_filter('json_api_mission_controller_path', function () {
return connect_json_api::getpath() . 'mission.php';
});
add_filter('json_api_redemption_controller_path', function () {
return connect_json_api::getpath() . 'redemption.php';
});
add_filter('json_api_authen_controller_path', function () {
return connect_json_api::getpath() . 'authen.php';
});
add_filter('json_api_controllers', array($this, 'add_json_controllers'), 10, 1);
} else {
$error = "Json-API is not activated please make sure that plugin is activated. Download it at http://wordpress.org/plugins/json-api/other_notes/";
echo $error;
}
}
/**
* @param $controllers
* @return array
*/
public function add_json_controller_new($controllers)
{
$controllers = array_merge($controllers, $this->list_functions);
return $controllers;
}
/**
* @param $controllers
* @internal param $existing_controllers
* @return array
*/
public function add_json_controllers($controllers)
{
//$additional_controllers = array('channels', 'slide', 'email', 'staff', 'redemption', 'innopost');
$controllers = array_merge($controllers, $this->list_functions);
return $controllers;
}
/**
* @return mixed
*/
private function is_da_plugin_active()
{
include_once(ABSPATH . 'wp-admin/includes/plugin.php');
return is_plugin_active('json-api/json-api.php');
}
/**
* not in use first
*/
public function add_to_core_functions()
{
// Disable get_author_index method (e.g., for security reasons)
add_action('json_api-core-get_channel_from_core', 'my_disable_author_index');
function my_disable_author_index()
{
// Stop execution
exit;
}
}
}
}
| mit |
szapata/Migol | app/cache/dev/twig/fe/7c/7e6328bcea9d45c502da2e2c4a3e.php | 748 | <?php
/* TwigBundle:Exception:error.css.twig */
class __TwigTemplate_fe7c7e6328bcea9d45c502da2e2c4a3e extends Twig_Template
{
protected function doDisplay(array $context, array $blocks = array())
{
$context = array_merge($this->env->getGlobals(), $context);
// line 1
echo "/*
";
// line 2
echo twig_escape_filter($this->env, $this->getContext($context, 'status_code'), "html");
echo " ";
echo twig_escape_filter($this->env, $this->getContext($context, 'status_text'), "html");
echo "
*/
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.css.twig";
}
public function isTraitable()
{
return false;
}
}
| mit |
weenhanceit/infrastructure | test/domain_test.rb | 1094 | # frozen_string_literal: true
require "minitest/autorun"
require "shared_infrastructure"
require "test"
class DomainTest < Test
include TestHelpers
def setup
@o = SharedInfrastructure::Domain.new("example.com")
end
attr_reader :o
def test_file_names
assert_equal "/var/www/example.com/html", o.site_root
assert_equal "/etc/letsencrypt/live/example.com", o.certificate_directory
assert_equal "/etc/nginx/sites-available/example.com", o.available_site
assert_equal "/etc/nginx/sites-enabled/example.com", o.enabled_site
assert_equal "example.com www.example.com", o.certbot_domain_names
end
def test_fake_file_names
SharedInfrastructure::Output.fake_root("/tmp") do
assert_equal "/var/www/example.com/html", o.site_root
assert_equal "/etc/letsencrypt/live/example.com", o.certificate_directory
assert_equal "/etc/nginx/sites-available/example.com", o.available_site
assert_equal "/etc/nginx/sites-enabled/example.com", o.enabled_site
assert_equal "example.com www.example.com", o.certbot_domain_names
end
end
end
| mit |
l33tdaima/l33tdaima | p735m/asteroid_collision.py | 839 | from typing import List
class Solution:
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for n in asteroids:
while n < 0 and stack and stack[-1] > 0:
if n + stack[-1] == 0:
stack.pop()
break
elif n + stack[-1] < 0:
stack.pop()
else:
break
else:
stack.append(n)
return stack
# TESTS
for asteroids, expected in [
([5, 10, -5], [5, 10]),
([8, -8], []),
([10, 2, -5], [10]),
([-2, -1, 1, 2], [-2, -1, 1, 2]),
([1, 2, -4, 3], [-4, 3]),
]:
sol = Solution()
actual = sol.asteroidCollision(asteroids)
print("After all collisions in", asteroids, "->", actual)
assert actual == expected
| mit |
lury-lang/lury | src/Lury.Core/Runtime/LuryEngine.cs | 2259 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tomona Nanase
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
using System.Runtime.CompilerServices;
using Antlr4.Runtime;
using Lury.Core.Compiler;
namespace Lury.Core.Runtime
{
public class LuryEngine
{
#region -- Public Properties --
#endregion
#region -- Constructors --
public LuryEngine()
{
}
#endregion
#region -- Public Methods --
public LuryObject Execute(string source)
{
var inputStream = new AntlrInputStream(source);
var luryLexer = new LuryLexer(inputStream);
var commonTokenStream = new CommonTokenStream(luryLexer);
var luryParser = new LuryParser(commonTokenStream);
var programContext = luryParser.program();
var pruningVisitor = new AstVisitor();
return luryVisitor.VisitProgram(programContext);
}
#endregion
#region -- Public Static Methods --
public static LuryObject Run(string source)
{
var engine = new LuryEngine();
return engine.Execute(source);
}
#endregion
}
}
| mit |
ershad/shipit-engine | app/controllers/concerns/api/paginable.rb | 792 | module Api
module Paginable
extend ActiveSupport::Concern
LINK = 'Link'.freeze
included do
class_attribute :max_page_size
class_attribute :default_page_size
class_attribute :default_order
self.max_page_size = 100
self.default_page_size = 30
self.default_order = {id: :desc}.freeze
end
private
def render_resources(resource, *)
paginator = Shipit::Paginator.new(
resource,
self,
order: default_order,
max_page_size: max_page_size,
default_page_size: default_page_size,
)
headers[LINK] = render_links(paginator.links)
super(paginator.to_a)
end
def render_links(links)
links.map { |rel, url| %(<#{url}>; rel="#{rel}") }.join(', ')
end
end
end
| mit |
juroland/maze | model/evaluation.cpp | 4218 | #include "evaluation.h"
#include "maze.h"
#include "mazesolver.h"
#include "mazegenerator.h"
#include "algorithm.h"
#include <chrono>
#include <valarray>
#include <QVector>
struct EvaluationParameter {
size_t nrow;
size_t ncol;
MazeSolver::ProgramFactory* programFactory;
MazeGeneratorFactory* generatorFactory;
};
Evaluation evaluate(const EvaluationParameter& param)
{
auto maze = std::make_unique<Maze>(param.nrow, param.ncol);
auto solver = std::make_unique<MazeSolver>(maze->getStart(), maze->getEnd());
solver->start(param.programFactory->makeProgram());
auto generator = param.generatorFactory->makeGenerator(maze.get());
while (!generator->isFinished())
generator->step();
using clock = std::chrono::steady_clock;
clock::time_point start = clock::now();
int nstep = 0;
while (!solver->isFinished()) {
++nstep;
solver->step();
}
clock::time_point end = clock::now();
Evaluation eval;
eval.step = nstep;
auto execTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
eval.execTime = execTime.count()/1000.0;
return eval;
}
EvaluationReportProducer::EvaluationReportProducer()
{
QObject::connect(&futureWatcher_, SIGNAL(finished()), this, SLOT(handleFinishedProduce()));
QObject::connect(&futureWatcher_, SIGNAL(progressRangeChanged(int,int)), this, SIGNAL(progressRangeChanged(int,int)));
QObject::connect(&futureWatcher_, SIGNAL(progressValueChanged(int)), this, SIGNAL(progressValueChanged(int)));
programFactories.emplace_back("DFS", std::make_unique<ConcreteProgramFactory<DFSProgram>>());
programFactories.emplace_back("Custom", std::make_unique<ConcreteProgramFactory<CustomProgram>>());
generatorFactories.emplace_back("DFS", std::make_unique<ConcreteMazeGeneratorFactory<DFSMazeGenerator>>());
generatorFactories.emplace_back("Kruskall", std::make_unique<ConcreteMazeGeneratorFactory<KruskallMazeGenerator>>());
}
void EvaluationReportProducer::produce()
{
QVector<EvaluationParameter> input;
for (auto& programFactory : programFactories) {
for (auto& generatorFactory : generatorFactories) {
std::string title = programFactory.first + " solver on " + generatorFactory.first + " generated Maze";
evaluationTitles.push_back(title);
for (size_t i = 0; i < populationSize; ++i) {
input.push_back(EvaluationParameter{nrow, ncol,
programFactory.second.get(),
generatorFactory.second.get()});
}
}
}
futureWatcher_.setFuture(QtConcurrent::mapped(input, evaluate));
}
std::vector<EvaluationReport> EvaluationReportProducer::reports()
{
if (isCanceled())
return {};
futureWatcher_.waitForFinished();
std::vector<EvaluationReport> reports;
size_t resultIndex = 0;
QList<Evaluation> results = futureWatcher_.future().results();
std::valarray<double> steps(populationSize);
double totalExecTime = 0.0;
for (size_t i = 0; i < evaluationTitles.size(); ++i) {
for (size_t j = 0; j < populationSize; ++j) {
Evaluation eval = results.at(static_cast<int>(resultIndex + j));
steps[j] = eval.step;
totalExecTime += eval.execTime;
}
resultIndex += populationSize;
EvaluationReport report;
report.title = evaluationTitles[i];
report.max = static_cast<int>(steps.max());
report.min = static_cast<int>(steps.min());
report.mean = steps.sum()/static_cast<double>(steps.size());
report.stdDev = std::sqrt(std::pow(steps - report.mean, 2.0).sum()/static_cast<double>(steps.size()));
report.totalExecTime = totalExecTime;
reports.emplace_back(report);
}
return reports;
}
bool EvaluationReportProducer::isCanceled()
{
return futureWatcher_.isCanceled();
}
void EvaluationReportProducer::cancel()
{
futureWatcher_.cancel();
}
void EvaluationReportProducer::handleFinishedProduce()
{
if (!isCanceled())
emit resultReady(reports());
emit finished();
}
| mit |
hslayers/hslayers-ng | projects/hslayers/src/components/save-map/layman-utils.ts | 1838 | import {Layer} from 'ol/layer';
import {Source} from 'ol/source';
import {HsLaymanLayerDescriptor} from './layman-layer-descriptor.interface';
import {getName, getTitle} from '../../common/layer-extensions';
export const PREFER_RESUMABLE_SIZE_LIMIT = 2 * 1024 * 1024; // 2 MB
/**
* Get Layman friendly name for layer based on its title by
* replacing spaces with underscores, converting to lowercase, etc.
* see https://github.com/jirik/layman/blob/c79edab5d9be51dee0e2bfc5b2f6a380d2657cbd/src/layman/util.py#L30
* @param title - Title to get Layman-friendly name for
* @returns New layer name
*/
export function getLaymanFriendlyLayerName(title: string): string {
//TODO: Unidecode on server side or just drop the unsupported letters.
title = title
.toLowerCase()
.replace(/[^\w\s\-\.]/gm, '') //Remove spaces
.trim()
.replace(/[\s\-\._]+/gm, '_') //Remove dashes
.replace(/[^\x00-\x7F]/g, ''); //Remove non-ascii letters https://stackoverflow.com/questions/20856197/remove-non-ascii-character-in-string
return title;
}
/**
* Get layman friendly name of layer based primary on name
* and secondary on title attributes.
*
* @param layer - Layer to get the name for
*/
export function getLayerName(layer: Layer<Source>): string {
const layerName = getName(layer) || getTitle(layer);
if (layerName == undefined) {
this.$log.warn('Layer title/name not set for', layer);
}
return getLaymanFriendlyLayerName(layerName);
}
export function wfsNotAvailable(descr: HsLaymanLayerDescriptor) {
return descr.wfs?.status == 'NOT_AVAILABLE';
}
export function wfsPendingOrStarting(descr: HsLaymanLayerDescriptor) {
return descr.wfs?.status == 'PENDING' || descr.wfs?.status == 'STARTED';
}
export function wfsFailed(descr: HsLaymanLayerDescriptor) {
return descr.wfs?.status == 'FAILURE';
}
| mit |
iwa-yuki/Actalogic | Actalogic/Actalogic/EntityWireUp.cpp | 518 | #include "pch.h"
#include "EntityWireUp.h"
EntityWireUp::EntityWireUp() :
EntityWireUp({ 0, 0 })
{
}
EntityWireUp::EntityWireUp(const POINT &pt, bool removable) :
EntityActalogicCell(pt, ActalogicCellType::WIRE_UP, removable)
{
}
EntityWireUp::~EntityWireUp()
{
}
void EntityWireUp::OnPreRender(InputHelper *pInputHelper)
{
EntityActalogicCell::OnPreRender(pInputHelper);
m_postValue = m_pLinkedCells[ActalogicCellDirection::DOWN] == nullptr ? 0 :
m_pLinkedCells[ActalogicCellDirection::DOWN]->GetValue();
}
| mit |
t2krew/lintcode-solution | python/9.fizz-buzz.py | 981 | # 9.Fizz Buzz 问题 / fizz-buzz
# http://www.lintcode.com/problem/fizz-buzz
# 给你一个整数n. 从 1 到 n 按照下面的规则打印每个数:
# 如果这个数被3整除,打印fizz.
# 如果这个数被5整除,打印buzz.
# 如果这个数能同时被3和5整除,打印fizz buzz.
# Example:
# 比如 n = 15, 返回一个字符串数组
# [
# "1", "2", "fizz",
# "4", "buzz", "fizz",
# "7", "8", "fizz",
# "buzz", "11", "fizz",
# "13", "14", "fizz buzz"
# ]
class Solution:
"""
@param n: An integer as description
@return: A list of strings.
For example, if n = 7, your code should return
["1", "2", "fizz", "4", "buzz", "fizz", "7"]
"""
def fizzBuzz(self, n):
results = []
for i in range(1, n+1):
if i % 15 == 0:
results.append("fizz buzz")
elif i % 5 == 0:
results.append("buzz")
elif i % 3 == 0:
results.append("fizz")
else:
results.append(str(i))
return results
| mit |
yoshuawuyts/frontend-server | server.js | 1187 |
const responseTime = require('koa-response-time')
const summary = require('server-summary')
const wreq = require('koa-watchify')
const logger = require('koa-logger')
const browserify = require('browserify')
const route = require('koa-route')
const watchify = require('watchify')
const km = require('koa-myth')
const rework = require('rework')
const myth = require('myth')
const path = require('path')
const koa = require('koa')
const fs = require('fs')
const env = process.env.NODE_ENV || 'development'
const port = process.env.port || 1337
const app = koa()
module.exports = app
if ('test' != env) app.use(logger())
app.use(responseTime())
// browserify
const bundle = browserify({
entries: [path.join(process.cwd(), 'index.js')],
fullPaths: true,
packageCache: {},
cache: {}
})
if ('development' == process.env.NODE_ENV) bundle = watchify(bundle)
app.use(route.get('/bundle.js', wreq(bundle)))
// css
const css = fs.readFileSync('index.css', 'utf8')
const styles = rework(css).use(myth())
app.use(route.get('/styles.css', km(styles)))
if (!module.parent) app.listen(port, summary)
| mit |
aqibmushtaq/servicenow-log-tailer | properties.js | 163 | module.exports = {
cookie: {
'JSESSIONID' : '',
'BIGipServerpool_[insert instance name here]' : ''
},
sessionToken: '',
host: ''
}
| mit |
pjkarlik/ReactUI | src/containers/HomeRange.js | 926 | import React from 'react';
import { resolve } from '../styles';
import RangeSlider from '../components/range/RangeSlider';
import SiteStyles from '../styles/Site.less';
/**
Generic Home Page
*/
export default class Home extends React.Component {
static displayName = 'Home';
static propTypes = {
classes: React.PropTypes.object,
};
static defaultProps = {
classes: SiteStyles,
};
constructor(props) {
super(props);
// keeping for state later //
}
myCallback = (config) => {
const value = config || true;
/* eslint no-console: 0 */
console.log(value);
}
render() {
const config = {
value: 1,
min: 0,
max: 100,
};
const background = `home${~~(Math.random() * 7)}`;
return (
<div {...resolve(this.props, 'container', background)}>
<RangeSlider snapToGrid onChange = {this.myCallback} config = {config} />
</div>
);
}
}
| mit |
GusBeare/NancyAngularTests | NancyAngularJS/Content/Components/home/home.ts | 238 |
(() => {
angular
.module('mySPA')
.controller('homeController', homeController)
function homeController () {
const vm = this;
vm.message = 'home controller message!'
}
})() | mit |
WorldBrain/WebMemex | src/sidebar-overlay/epics.ts | 2163 | import 'rxjs/add/operator/debounceTime'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/filter'
import { acts as searchBarActs } from 'src/overview/search-bar'
import { acts as resultActs } from 'src/overview/results'
import { actions as filterActs } from 'src/search-filters'
import { searchAnnotations } from 'src/annotations/actions'
const searchUpdateActions = [
searchBarActs.setQuery.getType(),
searchBarActs.setStartDate.getType(),
searchBarActs.setEndDate.getType(),
filterActs.toggleBookmarkFilter.getType(),
filterActs.addTagFilter.getType(),
filterActs.delTagFilter.getType(),
filterActs.addExcTagFilter.getType(),
filterActs.delExcTagFilter.getType(),
filterActs.toggleTagFilter.getType(),
filterActs.addIncDomainFilter.getType(),
filterActs.addExcDomainFilter.getType(),
filterActs.delIncDomainFilter.getType(),
filterActs.delExcDomainFilter.getType(),
filterActs.setIncDomainFilters.getType(),
filterActs.setExcDomainFilters.getType(),
filterActs.setTagFilters.getType(),
filterActs.setExcTagFilters.getType(),
filterActs.resetFilters.getType(),
filterActs.toggleListFilter.getType(),
filterActs.delListFilter.getType(),
filterActs.toggleHighlightsFilter.getType(),
filterActs.toggleNotesFilter.getType(),
filterActs.toggleWebsitesFilter.getType(),
filterActs.setAnnotationsFilter.getType(),
filterActs.clearFilterTypes.getType(),
resultActs.setSearchType.getType(),
]
// When the query changed, refresh the search results
export const refreshSearchResultsUponQueryChange = action$ =>
action$
.filter(action => searchUpdateActions.includes(action.type))
.debounceTime(500) // wait until typing stops for 500ms
.map(() =>
searchBarActs.search({ overwrite: true, fromOverview: false }),
) // Schedule new fresh (overwriting) search
export const refreshSidebarSearchResultsUponQueryChange = action$ =>
action$
.filter(action => searchUpdateActions.includes(action.type))
.debounceTime(500) // wait until typing stops for 500ms
.map(() => searchAnnotations())
| mit |
jandoczy/superfakturacppapi | thirdparty/include/jsoncpp/jsoncpp.cpp | 153915 | /// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).
/// It is intended to be used with #include "json/json.h"
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
Copyright (c) 2007-2010 Baptiste Lepilleur
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.
========================================================================
(END LICENSE TEXT)
The MIT license is compatible with both the GPL and commercial
software, affording one all of the rights of Public Domain with the
minor nuisance of being required to keep the above copyright notice
and license text in the source code. Note also that by accepting the
Public Domain "license" you can re-license your copy using whatever
license you like.
*/
// //////////////////////////////////////////////////////////////////////
// End of content of file: LICENSE
// //////////////////////////////////////////////////////////////////////
#include "json/json.h"
#ifndef JSON_IS_AMALGAMATION
#error "Compile with -I PATH_TO_JSON_DIRECTORY"
#endif
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_tool.h
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
#define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
/* This header provides common string manipulation support, such as UTF-8,
* portable conversion from/to string...
*
* It is an internal header that must not be exposed.
*/
namespace Json {
/// Converts a unicode code-point to UTF-8.
static inline JSONCPP_STRING codePointToUTF8(unsigned int cp) {
JSONCPP_STRING result;
// based on description from http://en.wikipedia.org/wiki/UTF-8
if (cp <= 0x7f) {
result.resize(1);
result[0] = static_cast<char>(cp);
} else if (cp <= 0x7FF) {
result.resize(2);
result[1] = static_cast<char>(0x80 | (0x3f & cp));
result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
} else if (cp <= 0xFFFF) {
result.resize(3);
result[2] = static_cast<char>(0x80 | (0x3f & cp));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
} else if (cp <= 0x10FFFF) {
result.resize(4);
result[3] = static_cast<char>(0x80 | (0x3f & cp));
result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
}
return result;
}
/// Returns true if ch is a control character (in range [1,31]).
static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
enum {
/// Constant that specify the size of the buffer that must be passed to
/// uintToString.
uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
};
// Defines a char buffer for use with uintToString().
typedef char UIntToStringBuffer[uintToStringBufferSize];
/** Converts an unsigned integer to string.
* @param value Unsigned interger to convert to string
* @param current Input/Output string buffer.
* Must have at least uintToStringBufferSize chars free.
*/
static inline void uintToString(LargestUInt value, char*& current) {
*--current = 0;
do {
*--current = static_cast<char>(value % 10U + static_cast<unsigned>('0'));
value /= 10;
} while (value != 0);
}
/** Change ',' to '.' everywhere in buffer.
*
* We had a sophisticated way, but it did not work in WinCE.
* @see https://github.com/open-source-parsers/jsoncpp/pull/9
*/
static inline void fixNumericLocale(char* begin, char* end) {
while (begin < end) {
if (*begin == ',') {
*begin = '.';
}
++begin;
}
}
} // namespace Json {
#endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_tool.h
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_reader.cpp
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2011 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include <json/assertions.h>
#include <json/reader.h>
#include <json/value.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <istream>
#include <sstream>
#include <memory>
#include <set>
#include <limits>
#if defined(_MSC_VER)
#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
#define snprintf sprintf_s
#elif _MSC_VER >= 1900 // VC++ 14.0 and above
#define snprintf std::snprintf
#else
#define snprintf _snprintf
#endif
#elif defined(__ANDROID__) || defined(__QNXNTO__)
#define snprintf snprintf
#elif __cplusplus >= 201103L
#if !defined(__MINGW32__) && !defined(__CYGWIN__)
#define snprintf std::snprintf
#endif
#endif
#if defined(__QNXNTO__)
#define sscanf std::sscanf
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
static int const stackLimit_g = 1000;
static int stackDepth_g = 0; // see readValue()
namespace Json {
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
typedef std::unique_ptr<CharReader> CharReaderPtr;
#else
typedef std::auto_ptr<CharReader> CharReaderPtr;
#endif
// Implementation of class Features
// ////////////////////////////////
Features::Features()
: allowComments_(true), strictRoot_(false),
allowDroppedNullPlaceholders_(false), allowNumericKeys_(false) {}
Features Features::all() { return Features(); }
Features Features::strictMode() {
Features features;
features.allowComments_ = false;
features.strictRoot_ = true;
features.allowDroppedNullPlaceholders_ = false;
features.allowNumericKeys_ = false;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
static bool containsNewLine(Reader::Location begin, Reader::Location end) {
for (; begin < end; ++begin)
if (*begin == '\n' || *begin == '\r')
return true;
return false;
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader()
: errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
lastValue_(), commentsBefore_(), features_(Features::all()),
collectComments_() {}
Reader::Reader(const Features& features)
: errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
lastValue_(), commentsBefore_(), features_(features), collectComments_() {
}
bool
Reader::parse(const std::string& document, Value& root, bool collectComments) {
JSONCPP_STRING documentCopy(document.data(), document.data() + document.capacity());
std::swap(documentCopy, document_);
const char* begin = document_.c_str();
const char* end = begin + document_.length();
return parse(begin, end, root, collectComments);
}
bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
// std::istream_iterator<char> begin(sin);
// std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since JSONCPP_STRING is reference-counted, this at least does not
// create an extra copy.
JSONCPP_STRING doc;
std::getline(sin, doc, (char)EOF);
return parse(doc.data(), doc.data() + doc.size(), root, collectComments);
}
bool Reader::parse(const char* beginDoc,
const char* endDoc,
Value& root,
bool collectComments) {
if (!features_.allowComments_) {
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
commentsBefore_ = "";
errors_.clear();
while (!nodes_.empty())
nodes_.pop();
nodes_.push(&root);
stackDepth_g = 0; // Yes, this is bad coding, but options are limited.
bool successful = readValue();
Token token;
skipCommentTokens(token);
if (collectComments_ && !commentsBefore_.empty())
root.setComment(commentsBefore_, commentAfter);
if (features_.strictRoot_) {
if (!root.isArray() && !root.isObject()) {
// Set error location to start of doc, ideally should be first token found
// in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError(
"A valid JSON document must be either an array or an object value.",
token);
return false;
}
}
return successful;
}
bool Reader::readValue() {
// This is a non-reentrant way to support a stackLimit. Terrible!
// But this deprecated class has a security problem: Bad input can
// cause a seg-fault. This seems like a fair, binary-compatible way
// to prevent the problem.
if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
++stackDepth_g;
Token token;
skipCommentTokens(token);
bool successful = true;
if (collectComments_ && !commentsBefore_.empty()) {
currentValue().setComment(commentsBefore_, commentBefore);
commentsBefore_ = "";
}
switch (token.type_) {
case tokenObjectBegin:
successful = readObject(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenArrayBegin:
successful = readArray(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenNumber:
successful = decodeNumber(token);
break;
case tokenString:
successful = decodeString(token);
break;
case tokenTrue:
{
Value v(true);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenFalse:
{
Value v(false);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenNull:
{
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
current_--;
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
} // Else, fall through...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return addError("Syntax error: value, object or array expected.", token);
}
if (collectComments_) {
lastValueEnd_ = current_;
lastValue_ = ¤tValue();
}
--stackDepth_g;
return successful;
}
void Reader::skipCommentTokens(Token& token) {
if (features_.allowComments_) {
do {
readToken(token);
} while (token.type_ == tokenComment);
} else {
readToken(token);
}
}
bool Reader::readToken(Token& token) {
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch (c) {
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
break;
case 't':
token.type_ = tokenTrue;
ok = match("rue", 3);
break;
case 'f':
token.type_ = tokenFalse;
ok = match("alse", 4);
break;
case 'n':
token.type_ = tokenNull;
ok = match("ull", 3);
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if (!ok)
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void Reader::skipSpaces() {
while (current_ != end_) {
Char c = *current_;
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++current_;
else
break;
}
}
bool Reader::match(Location pattern, int patternLength) {
if (end_ - current_ < patternLength)
return false;
int index = patternLength;
while (index--)
if (current_[index] != pattern[index])
return false;
current_ += patternLength;
return true;
}
bool Reader::readComment() {
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if (c == '*')
successful = readCStyleComment();
else if (c == '/')
successful = readCppStyleComment();
if (!successful)
return false;
if (collectComments_) {
CommentPlacement placement = commentBefore;
if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
if (c != '*' || !containsNewLine(commentBegin, current_))
placement = commentAfterOnSameLine;
}
addComment(commentBegin, current_, placement);
}
return true;
}
static JSONCPP_STRING normalizeEOL(Reader::Location begin, Reader::Location end) {
JSONCPP_STRING normalized;
normalized.reserve(static_cast<size_t>(end - begin));
Reader::Location current = begin;
while (current != end) {
char c = *current++;
if (c == '\r') {
if (current != end && *current == '\n')
// convert dos EOL
++current;
// convert Mac EOL
normalized += '\n';
} else {
normalized += c;
}
}
return normalized;
}
void
Reader::addComment(Location begin, Location end, CommentPlacement placement) {
assert(collectComments_);
const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != 0);
lastValue_->setComment(normalized, placement);
} else {
commentsBefore_ += normalized;
}
}
bool Reader::readCStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
if (c == '*' && *current_ == '/')
break;
}
return getNextChar() == '/';
}
bool Reader::readCppStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
if (c == '\n')
break;
if (c == '\r') {
// Consume DOS EOL. It will be normalized in addComment.
if (current_ != end_ && *current_ == '\n')
getNextChar();
// Break on Moc OS 9 EOL.
break;
}
}
return true;
}
void Reader::readNumber() {
const char *p = current_;
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
// fractional part
if (c == '.') {
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
// exponential part
if (c == 'e' || c == 'E') {
c = (current_ = p) < end_ ? *p++ : '\0';
if (c == '+' || c == '-')
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
}
bool Reader::readString() {
Char c = '\0';
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '"')
break;
}
return c == '"';
}
bool Reader::readObject(Token& tokenStart) {
Token tokenName;
JSONCPP_STRING name;
Value init(objectValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
while (tokenName.type_ == tokenComment && initialTokenOk)
initialTokenOk = readToken(tokenName);
if (!initialTokenOk)
break;
if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
return true;
name = "";
if (tokenName.type_ == tokenString) {
if (!decodeString(tokenName, name))
return recoverFromError(tokenObjectEnd);
} else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
name = JSONCPP_STRING(numberName.asCString());
} else {
break;
}
Token colon;
if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
return addErrorAndRecover(
"Missing ':' after object member name", colon, tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenObjectEnd);
Token comma;
if (!readToken(comma) ||
(comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment)) {
return addErrorAndRecover(
"Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
}
bool finalizeTokenOk = true;
while (comma.type_ == tokenComment && finalizeTokenOk)
finalizeTokenOk = readToken(comma);
if (comma.type_ == tokenObjectEnd)
return true;
}
return addErrorAndRecover(
"Missing '}' or object member name", tokenName, tokenObjectEnd);
}
bool Reader::readArray(Token& tokenStart) {
Value init(arrayValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
skipSpaces();
if (*current_ == ']') // empty array
{
Token endArray;
readToken(endArray);
return true;
}
int index = 0;
for (;;) {
Value& value = currentValue()[index++];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenArrayEnd);
Token token;
// Accept Comment after last item in the array.
ok = readToken(token);
while (token.type_ == tokenComment && ok) {
ok = readToken(token);
}
bool badTokenType =
(token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
if (!ok || badTokenType) {
return addErrorAndRecover(
"Missing ',' or ']' in array declaration", token, tokenArrayEnd);
}
if (token.type_ == tokenArrayEnd)
break;
}
return true;
}
bool Reader::decodeNumber(Token& token) {
Value decoded;
if (!decodeNumber(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeNumber(Token& token, Value& decoded) {
// Attempts to parse the number as an integer. If the number is
// larger than the maximum supported value of an integer then
// we decode the number as a double.
Location current = token.start_;
bool isNegative = *current == '-';
if (isNegative)
++current;
// TODO: Help the compiler do the div and mod at compile time or get rid of them.
Value::LargestUInt maxIntegerValue =
isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
: Value::maxLargestUInt;
Value::LargestUInt threshold = maxIntegerValue / 10;
Value::LargestUInt value = 0;
while (current < token.end_) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
Value::UInt digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
// c) it's small enough to fit in that rounding delta, we're okay.
// Otherwise treat this number as a double to avoid overflow.
if (value > threshold || current != token.end_ ||
digit > maxIntegerValue % 10) {
return decodeDouble(token, decoded);
}
}
value = value * 10 + digit;
}
if (isNegative && value == maxIntegerValue)
decoded = Value::minLargestInt;
else if (isNegative)
decoded = -Value::LargestInt(value);
else if (value <= Value::LargestUInt(Value::maxInt))
decoded = Value::LargestInt(value);
else
decoded = value;
return true;
}
bool Reader::decodeDouble(Token& token) {
Value decoded;
if (!decodeDouble(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
JSONCPP_STRING buffer(token.start_, token.end_);
JSONCPP_ISTRINGSTREAM is(buffer);
if (!(is >> value))
return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
"' is not a number.",
token);
decoded = value;
return true;
}
bool Reader::decodeString(Token& token) {
JSONCPP_STRING decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool Reader::decodeString(Token& token, JSONCPP_STRING& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while (current != end) {
Char c = *current++;
if (c == '"')
break;
else if (c == '\\') {
if (current == end)
return addError("Empty escape sequence in string", token, current);
Char escape = *current++;
switch (escape) {
case '"':
decoded += '"';
break;
case '/':
decoded += '/';
break;
case '\\':
decoded += '\\';
break;
case 'b':
decoded += '\b';
break;
case 'f':
decoded += '\f';
break;
case 'n':
decoded += '\n';
break;
case 'r':
decoded += '\r';
break;
case 't':
decoded += '\t';
break;
case 'u': {
unsigned int unicode;
if (!decodeUnicodeCodePoint(token, current, end, unicode))
return false;
decoded += codePointToUTF8(unicode);
} break;
default:
return addError("Bad escape sequence in string", token, current);
}
} else {
decoded += c;
}
}
return true;
}
bool Reader::decodeUnicodeCodePoint(Token& token,
Location& current,
Location end,
unsigned int& unicode) {
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF) {
// surrogate pairs
if (end - current < 6)
return addError(
"additional six characters expected to parse unicode surrogate pair.",
token,
current);
unsigned int surrogatePair;
if (*(current++) == '\\' && *(current++) == 'u') {
if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
} else
return false;
} else
return addError("expecting another \\u token to begin the second half of "
"a unicode surrogate pair",
token,
current);
}
return true;
}
bool Reader::decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.",
token,
current);
int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
if (c >= '0' && c <= '9')
unicode += c - '0';
else if (c >= 'a' && c <= 'f')
unicode += c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
unicode += c - 'A' + 10;
else
return addError(
"Bad unicode escape sequence in string: hexadecimal digit expected.",
token,
current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool
Reader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back(info);
return false;
}
bool Reader::recoverFromError(TokenType skipUntilToken) {
size_t const errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
errors_.resize(errorCount); // discard errors caused by recovery
if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
break;
}
errors_.resize(errorCount);
return false;
}
bool Reader::addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
}
Value& Reader::currentValue() { return *(nodes_.top()); }
Reader::Char Reader::getNextChar() {
if (current_ == end_)
return 0;
return *current_++;
}
void Reader::getLocationLineAndColumn(Location location,
int& line,
int& column) const {
Location current = begin_;
Location lastLineStart = current;
line = 0;
while (current < location && current != end_) {
Char c = *current++;
if (c == '\r') {
if (*current == '\n')
++current;
lastLineStart = current;
++line;
} else if (c == '\n') {
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
JSONCPP_STRING Reader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
return buffer;
}
// Deprecated. Preserved for backward compatibility
JSONCPP_STRING Reader::getFormatedErrorMessages() const {
return getFormattedErrorMessages();
}
JSONCPP_STRING Reader::getFormattedErrorMessages() const {
JSONCPP_STRING formattedMessage;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
const ErrorInfo& error = *itError;
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
if (error.extra_)
formattedMessage +=
"See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
}
return formattedMessage;
}
std::vector<Reader::StructuredError> Reader::getStructuredErrors() const {
std::vector<Reader::StructuredError> allErrors;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
const ErrorInfo& error = *itError;
Reader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
structured.message = error.message_;
allErrors.push_back(structured);
}
return allErrors;
}
bool Reader::pushError(const Value& value, const JSONCPP_STRING& message) {
ptrdiff_t const length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
token.end_ = end_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = 0;
errors_.push_back(info);
return true;
}
bool Reader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
ptrdiff_t const length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length
|| extra.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
token.end_ = begin_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = begin_ + extra.getOffsetStart();
errors_.push_back(info);
return true;
}
bool Reader::good() const {
return !errors_.size();
}
// exact copy of Features
class OurFeatures {
public:
static OurFeatures all();
bool allowComments_;
bool strictRoot_;
bool allowDroppedNullPlaceholders_;
bool allowNumericKeys_;
bool allowSingleQuotes_;
bool failIfExtra_;
bool rejectDupKeys_;
bool allowSpecialFloats_;
int stackLimit_;
}; // OurFeatures
// exact copy of Implementation of class Features
// ////////////////////////////////
OurFeatures OurFeatures::all() { return OurFeatures(); }
// Implementation of class Reader
// ////////////////////////////////
// exact copy of Reader, renamed to OurReader
class OurReader {
public:
typedef char Char;
typedef const Char* Location;
struct StructuredError {
ptrdiff_t offset_start;
ptrdiff_t offset_limit;
JSONCPP_STRING message;
};
OurReader(OurFeatures const& features);
bool parse(const char* beginDoc,
const char* endDoc,
Value& root,
bool collectComments = true);
JSONCPP_STRING getFormattedErrorMessages() const;
std::vector<StructuredError> getStructuredErrors() const;
bool pushError(const Value& value, const JSONCPP_STRING& message);
bool pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra);
bool good() const;
private:
OurReader(OurReader const&); // no impl
void operator=(OurReader const&); // no impl
enum TokenType {
tokenEndOfStream = 0,
tokenObjectBegin,
tokenObjectEnd,
tokenArrayBegin,
tokenArrayEnd,
tokenString,
tokenNumber,
tokenTrue,
tokenFalse,
tokenNull,
tokenNaN,
tokenPosInf,
tokenNegInf,
tokenArraySeparator,
tokenMemberSeparator,
tokenComment,
tokenError
};
class Token {
public:
TokenType type_;
Location start_;
Location end_;
};
class ErrorInfo {
public:
Token token_;
JSONCPP_STRING message_;
Location extra_;
};
typedef std::deque<ErrorInfo> Errors;
bool readToken(Token& token);
void skipSpaces();
bool match(Location pattern, int patternLength);
bool readComment();
bool readCStyleComment();
bool readCppStyleComment();
bool readString();
bool readStringSingleQuote();
bool readNumber(bool checkInf);
bool readValue();
bool readObject(Token& token);
bool readArray(Token& token);
bool decodeNumber(Token& token);
bool decodeNumber(Token& token, Value& decoded);
bool decodeString(Token& token);
bool decodeString(Token& token, JSONCPP_STRING& decoded);
bool decodeDouble(Token& token);
bool decodeDouble(Token& token, Value& decoded);
bool decodeUnicodeCodePoint(Token& token,
Location& current,
Location end,
unsigned int& unicode);
bool decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
unsigned int& unicode);
bool addError(const JSONCPP_STRING& message, Token& token, Location extra = 0);
bool recoverFromError(TokenType skipUntilToken);
bool addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken);
void skipUntilSpace();
Value& currentValue();
Char getNextChar();
void
getLocationLineAndColumn(Location location, int& line, int& column) const;
JSONCPP_STRING getLocationLineAndColumn(Location location) const;
void addComment(Location begin, Location end, CommentPlacement placement);
void skipCommentTokens(Token& token);
typedef std::stack<Value*> Nodes;
Nodes nodes_;
Errors errors_;
JSONCPP_STRING document_;
Location begin_;
Location end_;
Location current_;
Location lastValueEnd_;
Value* lastValue_;
JSONCPP_STRING commentsBefore_;
int stackDepth_;
OurFeatures const features_;
bool collectComments_;
}; // OurReader
// complete copy of Read impl, for OurReader
OurReader::OurReader(OurFeatures const& features)
: errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
lastValue_(), commentsBefore_(),
stackDepth_(0),
features_(features), collectComments_() {
}
bool OurReader::parse(const char* beginDoc,
const char* endDoc,
Value& root,
bool collectComments) {
if (!features_.allowComments_) {
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
commentsBefore_ = "";
errors_.clear();
while (!nodes_.empty())
nodes_.pop();
nodes_.push(&root);
stackDepth_ = 0;
bool successful = readValue();
Token token;
skipCommentTokens(token);
if (features_.failIfExtra_) {
if (token.type_ != tokenError && token.type_ != tokenEndOfStream) {
addError("Extra non-whitespace after JSON value.", token);
return false;
}
}
if (collectComments_ && !commentsBefore_.empty())
root.setComment(commentsBefore_, commentAfter);
if (features_.strictRoot_) {
if (!root.isArray() && !root.isObject()) {
// Set error location to start of doc, ideally should be first token found
// in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError(
"A valid JSON document must be either an array or an object value.",
token);
return false;
}
}
return successful;
}
bool OurReader::readValue() {
if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
++stackDepth_;
Token token;
skipCommentTokens(token);
bool successful = true;
if (collectComments_ && !commentsBefore_.empty()) {
currentValue().setComment(commentsBefore_, commentBefore);
commentsBefore_ = "";
}
switch (token.type_) {
case tokenObjectBegin:
successful = readObject(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenArrayBegin:
successful = readArray(token);
currentValue().setOffsetLimit(current_ - begin_);
break;
case tokenNumber:
successful = decodeNumber(token);
break;
case tokenString:
successful = decodeString(token);
break;
case tokenTrue:
{
Value v(true);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenFalse:
{
Value v(false);
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenNull:
{
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenNaN:
{
Value v(std::numeric_limits<double>::quiet_NaN());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenPosInf:
{
Value v(std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenNegInf:
{
Value v(-std::numeric_limits<double>::infinity());
currentValue().swapPayload(v);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
}
break;
case tokenArraySeparator:
case tokenObjectEnd:
case tokenArrayEnd:
if (features_.allowDroppedNullPlaceholders_) {
// "Un-read" the current token and mark the current value as a null
// token.
current_--;
Value v;
currentValue().swapPayload(v);
currentValue().setOffsetStart(current_ - begin_ - 1);
currentValue().setOffsetLimit(current_ - begin_);
break;
} // else, fall through ...
default:
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return addError("Syntax error: value, object or array expected.", token);
}
if (collectComments_) {
lastValueEnd_ = current_;
lastValue_ = ¤tValue();
}
--stackDepth_;
return successful;
}
void OurReader::skipCommentTokens(Token& token) {
if (features_.allowComments_) {
do {
readToken(token);
} while (token.type_ == tokenComment);
} else {
readToken(token);
}
}
bool OurReader::readToken(Token& token) {
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch (c) {
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '\'':
if (features_.allowSingleQuotes_) {
token.type_ = tokenString;
ok = readStringSingleQuote();
break;
} // else continue
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
token.type_ = tokenNumber;
readNumber(false);
break;
case '-':
if (readNumber(true)) {
token.type_ = tokenNumber;
} else {
token.type_ = tokenNegInf;
ok = features_.allowSpecialFloats_ && match("nfinity", 7);
}
break;
case 't':
token.type_ = tokenTrue;
ok = match("rue", 3);
break;
case 'f':
token.type_ = tokenFalse;
ok = match("alse", 4);
break;
case 'n':
token.type_ = tokenNull;
ok = match("ull", 3);
break;
case 'N':
if (features_.allowSpecialFloats_) {
token.type_ = tokenNaN;
ok = match("aN", 2);
} else {
ok = false;
}
break;
case 'I':
if (features_.allowSpecialFloats_) {
token.type_ = tokenPosInf;
ok = match("nfinity", 7);
} else {
ok = false;
}
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if (!ok)
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void OurReader::skipSpaces() {
while (current_ != end_) {
Char c = *current_;
if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
++current_;
else
break;
}
}
bool OurReader::match(Location pattern, int patternLength) {
if (end_ - current_ < patternLength)
return false;
int index = patternLength;
while (index--)
if (current_[index] != pattern[index])
return false;
current_ += patternLength;
return true;
}
bool OurReader::readComment() {
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if (c == '*')
successful = readCStyleComment();
else if (c == '/')
successful = readCppStyleComment();
if (!successful)
return false;
if (collectComments_) {
CommentPlacement placement = commentBefore;
if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
if (c != '*' || !containsNewLine(commentBegin, current_))
placement = commentAfterOnSameLine;
}
addComment(commentBegin, current_, placement);
}
return true;
}
void
OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
assert(collectComments_);
const JSONCPP_STRING& normalized = normalizeEOL(begin, end);
if (placement == commentAfterOnSameLine) {
assert(lastValue_ != 0);
lastValue_->setComment(normalized, placement);
} else {
commentsBefore_ += normalized;
}
}
bool OurReader::readCStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
if (c == '*' && *current_ == '/')
break;
}
return getNextChar() == '/';
}
bool OurReader::readCppStyleComment() {
while (current_ != end_) {
Char c = getNextChar();
if (c == '\n')
break;
if (c == '\r') {
// Consume DOS EOL. It will be normalized in addComment.
if (current_ != end_ && *current_ == '\n')
getNextChar();
// Break on Moc OS 9 EOL.
break;
}
}
return true;
}
bool OurReader::readNumber(bool checkInf) {
const char *p = current_;
if (checkInf && p != end_ && *p == 'I') {
current_ = ++p;
return false;
}
char c = '0'; // stopgap for already consumed character
// integral part
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
// fractional part
if (c == '.') {
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
// exponential part
if (c == 'e' || c == 'E') {
c = (current_ = p) < end_ ? *p++ : '\0';
if (c == '+' || c == '-')
c = (current_ = p) < end_ ? *p++ : '\0';
while (c >= '0' && c <= '9')
c = (current_ = p) < end_ ? *p++ : '\0';
}
return true;
}
bool OurReader::readString() {
Char c = 0;
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '"')
break;
}
return c == '"';
}
bool OurReader::readStringSingleQuote() {
Char c = 0;
while (current_ != end_) {
c = getNextChar();
if (c == '\\')
getNextChar();
else if (c == '\'')
break;
}
return c == '\'';
}
bool OurReader::readObject(Token& tokenStart) {
Token tokenName;
JSONCPP_STRING name;
Value init(objectValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
while (readToken(tokenName)) {
bool initialTokenOk = true;
while (tokenName.type_ == tokenComment && initialTokenOk)
initialTokenOk = readToken(tokenName);
if (!initialTokenOk)
break;
if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
return true;
name = "";
if (tokenName.type_ == tokenString) {
if (!decodeString(tokenName, name))
return recoverFromError(tokenObjectEnd);
} else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
Value numberName;
if (!decodeNumber(tokenName, numberName))
return recoverFromError(tokenObjectEnd);
name = numberName.asString();
} else {
break;
}
Token colon;
if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
return addErrorAndRecover(
"Missing ':' after object member name", colon, tokenObjectEnd);
}
if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
JSONCPP_STRING msg = "Duplicate key: '" + name + "'";
return addErrorAndRecover(
msg, tokenName, tokenObjectEnd);
}
Value& value = currentValue()[name];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenObjectEnd);
Token comma;
if (!readToken(comma) ||
(comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment)) {
return addErrorAndRecover(
"Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
}
bool finalizeTokenOk = true;
while (comma.type_ == tokenComment && finalizeTokenOk)
finalizeTokenOk = readToken(comma);
if (comma.type_ == tokenObjectEnd)
return true;
}
return addErrorAndRecover(
"Missing '}' or object member name", tokenName, tokenObjectEnd);
}
bool OurReader::readArray(Token& tokenStart) {
Value init(arrayValue);
currentValue().swapPayload(init);
currentValue().setOffsetStart(tokenStart.start_ - begin_);
skipSpaces();
if (*current_ == ']') // empty array
{
Token endArray;
readToken(endArray);
return true;
}
int index = 0;
for (;;) {
Value& value = currentValue()[index++];
nodes_.push(&value);
bool ok = readValue();
nodes_.pop();
if (!ok) // error already set
return recoverFromError(tokenArrayEnd);
Token token;
// Accept Comment after last item in the array.
ok = readToken(token);
while (token.type_ == tokenComment && ok) {
ok = readToken(token);
}
bool badTokenType =
(token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
if (!ok || badTokenType) {
return addErrorAndRecover(
"Missing ',' or ']' in array declaration", token, tokenArrayEnd);
}
if (token.type_ == tokenArrayEnd)
break;
}
return true;
}
bool OurReader::decodeNumber(Token& token) {
Value decoded;
if (!decodeNumber(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool OurReader::decodeNumber(Token& token, Value& decoded) {
// Attempts to parse the number as an integer. If the number is
// larger than the maximum supported value of an integer then
// we decode the number as a double.
Location current = token.start_;
bool isNegative = *current == '-';
if (isNegative)
++current;
// TODO: Help the compiler do the div and mod at compile time or get rid of them.
Value::LargestUInt maxIntegerValue =
isNegative ? Value::LargestUInt(-Value::minLargestInt)
: Value::maxLargestUInt;
Value::LargestUInt threshold = maxIntegerValue / 10;
Value::LargestUInt value = 0;
while (current < token.end_) {
Char c = *current++;
if (c < '0' || c > '9')
return decodeDouble(token, decoded);
Value::UInt digit(static_cast<Value::UInt>(c - '0'));
if (value >= threshold) {
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
// c) it's small enough to fit in that rounding delta, we're okay.
// Otherwise treat this number as a double to avoid overflow.
if (value > threshold || current != token.end_ ||
digit > maxIntegerValue % 10) {
return decodeDouble(token, decoded);
}
}
value = value * 10 + digit;
}
if (isNegative)
decoded = -Value::LargestInt(value);
else if (value <= Value::LargestUInt(Value::maxInt))
decoded = Value::LargestInt(value);
else
decoded = value;
return true;
}
bool OurReader::decodeDouble(Token& token) {
Value decoded;
if (!decodeDouble(token, decoded))
return false;
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool OurReader::decodeDouble(Token& token, Value& decoded) {
double value = 0;
const int bufferSize = 32;
int count;
ptrdiff_t const length = token.end_ - token.start_;
// Sanity check to avoid buffer overflow exploits.
if (length < 0) {
return addError("Unable to parse token length", token);
}
size_t const ulength = static_cast<size_t>(length);
// Avoid using a string constant for the format control string given to
// sscanf, as this can cause hard to debug crashes on OS X. See here for more
// info:
//
// http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
char format[] = "%lf";
if (length <= bufferSize) {
Char buffer[bufferSize + 1];
memcpy(buffer, token.start_, ulength);
buffer[length] = 0;
count = sscanf(buffer, format, &value);
} else {
JSONCPP_STRING buffer(token.start_, token.end_);
count = sscanf(buffer.c_str(), format, &value);
}
if (count != 1)
return addError("'" + JSONCPP_STRING(token.start_, token.end_) +
"' is not a number.",
token);
decoded = value;
return true;
}
bool OurReader::decodeString(Token& token) {
JSONCPP_STRING decoded_string;
if (!decodeString(token, decoded_string))
return false;
Value decoded(decoded_string);
currentValue().swapPayload(decoded);
currentValue().setOffsetStart(token.start_ - begin_);
currentValue().setOffsetLimit(token.end_ - begin_);
return true;
}
bool OurReader::decodeString(Token& token, JSONCPP_STRING& decoded) {
decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2));
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while (current != end) {
Char c = *current++;
if (c == '"')
break;
else if (c == '\\') {
if (current == end)
return addError("Empty escape sequence in string", token, current);
Char escape = *current++;
switch (escape) {
case '"':
decoded += '"';
break;
case '/':
decoded += '/';
break;
case '\\':
decoded += '\\';
break;
case 'b':
decoded += '\b';
break;
case 'f':
decoded += '\f';
break;
case 'n':
decoded += '\n';
break;
case 'r':
decoded += '\r';
break;
case 't':
decoded += '\t';
break;
case 'u': {
unsigned int unicode;
if (!decodeUnicodeCodePoint(token, current, end, unicode))
return false;
decoded += codePointToUTF8(unicode);
} break;
default:
return addError("Bad escape sequence in string", token, current);
}
} else {
decoded += c;
}
}
return true;
}
bool OurReader::decodeUnicodeCodePoint(Token& token,
Location& current,
Location end,
unsigned int& unicode) {
if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF) {
// surrogate pairs
if (end - current < 6)
return addError(
"additional six characters expected to parse unicode surrogate pair.",
token,
current);
unsigned int surrogatePair;
if (*(current++) == '\\' && *(current++) == 'u') {
if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
} else
return false;
} else
return addError("expecting another \\u token to begin the second half of "
"a unicode surrogate pair",
token,
current);
}
return true;
}
bool OurReader::decodeUnicodeEscapeSequence(Token& token,
Location& current,
Location end,
unsigned int& ret_unicode) {
if (end - current < 4)
return addError(
"Bad unicode escape sequence in string: four digits expected.",
token,
current);
int unicode = 0;
for (int index = 0; index < 4; ++index) {
Char c = *current++;
unicode *= 16;
if (c >= '0' && c <= '9')
unicode += c - '0';
else if (c >= 'a' && c <= 'f')
unicode += c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
unicode += c - 'A' + 10;
else
return addError(
"Bad unicode escape sequence in string: hexadecimal digit expected.",
token,
current);
}
ret_unicode = static_cast<unsigned int>(unicode);
return true;
}
bool
OurReader::addError(const JSONCPP_STRING& message, Token& token, Location extra) {
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back(info);
return false;
}
bool OurReader::recoverFromError(TokenType skipUntilToken) {
size_t errorCount = errors_.size();
Token skip;
for (;;) {
if (!readToken(skip))
errors_.resize(errorCount); // discard errors caused by recovery
if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
break;
}
errors_.resize(errorCount);
return false;
}
bool OurReader::addErrorAndRecover(const JSONCPP_STRING& message,
Token& token,
TokenType skipUntilToken) {
addError(message, token);
return recoverFromError(skipUntilToken);
}
Value& OurReader::currentValue() { return *(nodes_.top()); }
OurReader::Char OurReader::getNextChar() {
if (current_ == end_)
return 0;
return *current_++;
}
void OurReader::getLocationLineAndColumn(Location location,
int& line,
int& column) const {
Location current = begin_;
Location lastLineStart = current;
line = 0;
while (current < location && current != end_) {
Char c = *current++;
if (c == '\r') {
if (*current == '\n')
++current;
lastLineStart = current;
++line;
} else if (c == '\n') {
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
JSONCPP_STRING OurReader::getLocationLineAndColumn(Location location) const {
int line, column;
getLocationLineAndColumn(location, line, column);
char buffer[18 + 16 + 16 + 1];
snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
return buffer;
}
JSONCPP_STRING OurReader::getFormattedErrorMessages() const {
JSONCPP_STRING formattedMessage;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
const ErrorInfo& error = *itError;
formattedMessage +=
"* " + getLocationLineAndColumn(error.token_.start_) + "\n";
formattedMessage += " " + error.message_ + "\n";
if (error.extra_)
formattedMessage +=
"See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
}
return formattedMessage;
}
std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const {
std::vector<OurReader::StructuredError> allErrors;
for (Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError) {
const ErrorInfo& error = *itError;
OurReader::StructuredError structured;
structured.offset_start = error.token_.start_ - begin_;
structured.offset_limit = error.token_.end_ - begin_;
structured.message = error.message_;
allErrors.push_back(structured);
}
return allErrors;
}
bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message) {
ptrdiff_t length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
token.end_ = end_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = 0;
errors_.push_back(info);
return true;
}
bool OurReader::pushError(const Value& value, const JSONCPP_STRING& message, const Value& extra) {
ptrdiff_t length = end_ - begin_;
if(value.getOffsetStart() > length
|| value.getOffsetLimit() > length
|| extra.getOffsetLimit() > length)
return false;
Token token;
token.type_ = tokenError;
token.start_ = begin_ + value.getOffsetStart();
token.end_ = begin_ + value.getOffsetLimit();
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = begin_ + extra.getOffsetStart();
errors_.push_back(info);
return true;
}
bool OurReader::good() const {
return !errors_.size();
}
class OurCharReader : public CharReader {
bool const collectComments_;
OurReader reader_;
public:
OurCharReader(
bool collectComments,
OurFeatures const& features)
: collectComments_(collectComments)
, reader_(features)
{}
bool parse(
char const* beginDoc, char const* endDoc,
Value* root, JSONCPP_STRING* errs) JSONCPP_OVERRIDE {
bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
if (errs) {
*errs = reader_.getFormattedErrorMessages();
}
return ok;
}
};
CharReaderBuilder::CharReaderBuilder()
{
setDefaults(&settings_);
}
CharReaderBuilder::~CharReaderBuilder()
{}
CharReader* CharReaderBuilder::newCharReader() const
{
bool collectComments = settings_["collectComments"].asBool();
OurFeatures features = OurFeatures::all();
features.allowComments_ = settings_["allowComments"].asBool();
features.strictRoot_ = settings_["strictRoot"].asBool();
features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
features.stackLimit_ = settings_["stackLimit"].asInt();
features.failIfExtra_ = settings_["failIfExtra"].asBool();
features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
return new OurCharReader(collectComments, features);
}
static void getValidReaderKeys(std::set<JSONCPP_STRING>* valid_keys)
{
valid_keys->clear();
valid_keys->insert("collectComments");
valid_keys->insert("allowComments");
valid_keys->insert("strictRoot");
valid_keys->insert("allowDroppedNullPlaceholders");
valid_keys->insert("allowNumericKeys");
valid_keys->insert("allowSingleQuotes");
valid_keys->insert("stackLimit");
valid_keys->insert("failIfExtra");
valid_keys->insert("rejectDupKeys");
valid_keys->insert("allowSpecialFloats");
}
bool CharReaderBuilder::validate(Json::Value* invalid) const
{
Json::Value my_invalid;
if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
Json::Value& inv = *invalid;
std::set<JSONCPP_STRING> valid_keys;
getValidReaderKeys(&valid_keys);
Value::Members keys = settings_.getMemberNames();
size_t n = keys.size();
for (size_t i = 0; i < n; ++i) {
JSONCPP_STRING const& key = keys[i];
if (valid_keys.find(key) == valid_keys.end()) {
inv[key] = settings_[key];
}
}
return 0u == inv.size();
}
Value& CharReaderBuilder::operator[](JSONCPP_STRING key)
{
return settings_[key];
}
// static
void CharReaderBuilder::strictMode(Json::Value* settings)
{
//! [CharReaderBuilderStrictMode]
(*settings)["allowComments"] = false;
(*settings)["strictRoot"] = true;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
(*settings)["allowSingleQuotes"] = false;
(*settings)["stackLimit"] = 1000;
(*settings)["failIfExtra"] = true;
(*settings)["rejectDupKeys"] = true;
(*settings)["allowSpecialFloats"] = false;
//! [CharReaderBuilderStrictMode]
}
// static
void CharReaderBuilder::setDefaults(Json::Value* settings)
{
//! [CharReaderBuilderDefaults]
(*settings)["collectComments"] = true;
(*settings)["allowComments"] = true;
(*settings)["strictRoot"] = false;
(*settings)["allowDroppedNullPlaceholders"] = false;
(*settings)["allowNumericKeys"] = false;
(*settings)["allowSingleQuotes"] = false;
(*settings)["stackLimit"] = 1000;
(*settings)["failIfExtra"] = false;
(*settings)["rejectDupKeys"] = false;
(*settings)["allowSpecialFloats"] = false;
//! [CharReaderBuilderDefaults]
}
//////////////////////////////////
// global functions
bool parseFromStream(
CharReader::Factory const& fact, JSONCPP_ISTREAM& sin,
Value* root, JSONCPP_STRING* errs)
{
JSONCPP_OSTRINGSTREAM ssin;
ssin << sin.rdbuf();
JSONCPP_STRING doc = ssin.str();
char const* begin = doc.data();
char const* end = begin + doc.size();
// Note that we do not actually need a null-terminator.
CharReaderPtr const reader(fact.newCharReader());
return reader->parse(begin, end, root, errs);
}
JSONCPP_ISTREAM& operator>>(JSONCPP_ISTREAM& sin, Value& root) {
CharReaderBuilder b;
JSONCPP_STRING errs;
bool ok = parseFromStream(b, sin, &root, &errs);
if (!ok) {
fprintf(stderr,
"Error from reader: %s",
errs.c_str());
throwRuntimeError(errs);
}
return sin;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_reader.cpp
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_valueiterator.inl
// //////////////////////////////////////////////////////////////////////
// Copyright 2007-2010 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
// included by json_value.cpp
namespace Json {
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueIteratorBase
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueIteratorBase::ValueIteratorBase()
: current_(), isNull_(true) {
}
ValueIteratorBase::ValueIteratorBase(
const Value::ObjectValues::iterator& current)
: current_(current), isNull_(false) {}
Value& ValueIteratorBase::deref() const {
return current_->second;
}
void ValueIteratorBase::increment() {
++current_;
}
void ValueIteratorBase::decrement() {
--current_;
}
ValueIteratorBase::difference_type
ValueIteratorBase::computeDistance(const SelfType& other) const {
#ifdef JSON_USE_CPPTL_SMALLMAP
return other.current_ - current_;
#else
// Iterator for null value are initialized using the default
// constructor, which initialize current_ to the default
// std::map::iterator. As begin() and end() are two instance
// of the default std::map::iterator, they can not be compared.
// To allow this, we handle this comparison specifically.
if (isNull_ && other.isNull_) {
return 0;
}
// Usage of std::distance is not portable (does not compile with Sun Studio 12
// RogueWave STL,
// which is the one used by default).
// Using a portable hand-made version for non random iterator instead:
// return difference_type( std::distance( current_, other.current_ ) );
difference_type myDistance = 0;
for (Value::ObjectValues::iterator it = current_; it != other.current_;
++it) {
++myDistance;
}
return myDistance;
#endif
}
bool ValueIteratorBase::isEqual(const SelfType& other) const {
if (isNull_) {
return other.isNull_;
}
return current_ == other.current_;
}
void ValueIteratorBase::copy(const SelfType& other) {
current_ = other.current_;
isNull_ = other.isNull_;
}
Value ValueIteratorBase::key() const {
const Value::CZString czstring = (*current_).first;
if (czstring.data()) {
if (czstring.isStaticString())
return Value(StaticString(czstring.data()));
return Value(czstring.data(), czstring.data() + czstring.length());
}
return Value(czstring.index());
}
UInt ValueIteratorBase::index() const {
const Value::CZString czstring = (*current_).first;
if (!czstring.data())
return czstring.index();
return Value::UInt(-1);
}
JSONCPP_STRING ValueIteratorBase::name() const {
char const* keey;
char const* end;
keey = memberName(&end);
if (!keey) return JSONCPP_STRING();
return JSONCPP_STRING(keey, end);
}
char const* ValueIteratorBase::memberName() const {
const char* cname = (*current_).first.data();
return cname ? cname : "";
}
char const* ValueIteratorBase::memberName(char const** end) const {
const char* cname = (*current_).first.data();
if (!cname) {
*end = NULL;
return NULL;
}
*end = cname + (*current_).first.length();
return cname;
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueConstIterator
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueConstIterator::ValueConstIterator() {}
ValueConstIterator::ValueConstIterator(
const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
ValueConstIterator::ValueConstIterator(ValueIterator const& other)
: ValueIteratorBase(other) {}
ValueConstIterator& ValueConstIterator::
operator=(const ValueIteratorBase& other) {
copy(other);
return *this;
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class ValueIterator
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
ValueIterator::ValueIterator() {}
ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
: ValueIteratorBase(current) {}
ValueIterator::ValueIterator(const ValueConstIterator& other)
: ValueIteratorBase(other) {
throwRuntimeError("ConstIterator to Iterator should never be allowed.");
}
ValueIterator::ValueIterator(const ValueIterator& other)
: ValueIteratorBase(other) {}
ValueIterator& ValueIterator::operator=(const SelfType& other) {
copy(other);
return *this;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_valueiterator.inl
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_value.cpp
// //////////////////////////////////////////////////////////////////////
// Copyright 2011 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include <json/assertions.h>
#include <json/value.h>
#include <json/writer.h>
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <math.h>
#include <sstream>
#include <utility>
#include <cstring>
#include <cassert>
#ifdef JSON_USE_CPPTL
#include <cpptl/conststring.h>
#endif
#include <cstddef> // size_t
#include <algorithm> // min()
#define JSON_ASSERT_UNREACHABLE assert(false)
namespace Json {
// This is a walkaround to avoid the static initialization of Value::null.
// kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
// 8 (instead of 4) as a bit of future-proofing.
#if defined(__ARMEL__)
#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
#else
#define ALIGNAS(byte_alignment)
#endif
//static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 };
//const unsigned char& kNullRef = kNull[0];
//const Value& Value::null = reinterpret_cast<const Value&>(kNullRef);
//const Value& Value::nullRef = null;
// static
static Value nullStatic;
Value const& Value::nullSingleton()
{
return nullStatic;
}
// for backwards compatibility, we'll leave these global references around, but DO NOT
// use them in JSONCPP library code any more!
Value const& Value::null = Value::nullSingleton();
Value const& Value::nullRef = Value::nullSingleton();
const Int Value::minInt = Int(~(UInt(-1) / 2));
const Int Value::maxInt = Int(UInt(-1) / 2);
const UInt Value::maxUInt = UInt(-1);
#if defined(JSON_HAS_INT64)
const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2));
const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2);
const UInt64 Value::maxUInt64 = UInt64(-1);
// The constant is hard-coded because some compiler have trouble
// converting Value::maxUInt64 to a double correctly (AIX/xlC).
// Assumes that UInt64 is a 64 bits integer.
static const double maxUInt64AsDouble = 18446744073709551615.0;
#endif // defined(JSON_HAS_INT64)
const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
template <typename T, typename U>
static inline bool InRange(double d, T min, U max) {
// The casts can lose precision, but we are looking only for
// an approximate range. Might fail on edge cases though. ~cdunn
//return d >= static_cast<double>(min) && d <= static_cast<double>(max);
return d >= min && d <= max;
}
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
static inline double integerToDouble(Json::UInt64 value) {
return static_cast<double>(Int64(value / 2)) * 2.0 + static_cast<double>(Int64(value & 1));
}
template <typename T> static inline double integerToDouble(T value) {
return static_cast<double>(value);
}
template <typename T, typename U>
static inline bool InRange(double d, T min, U max) {
return d >= integerToDouble(min) && d <= integerToDouble(max);
}
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
/** Duplicates the specified string value.
* @param value Pointer to the string to duplicate. Must be zero-terminated if
* length is "unknown".
* @param length Length of the value. if equals to unknown, then it will be
* computed using strlen(value).
* @return Pointer on the duplicate instance of string.
*/
static inline char* duplicateStringValue(const char* value,
size_t length)
{
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
if (length >= static_cast<size_t>(Value::maxInt))
length = Value::maxInt - 1;
char* newString = static_cast<char*>(malloc(length + 1));
if (newString == NULL) {
throwRuntimeError(
"in Json::Value::duplicateStringValue(): "
"Failed to allocate string value buffer");
}
memcpy(newString, value, length);
newString[length] = 0;
return newString;
}
/* Record the length as a prefix.
*/
static inline char* duplicateAndPrefixStringValue(
const char* value,
unsigned int length)
{
// Avoid an integer overflow in the call to malloc below by limiting length
// to a sane value.
JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) - sizeof(unsigned) - 1U,
"in Json::Value::duplicateAndPrefixStringValue(): "
"length too big for prefixing");
unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
char* newString = static_cast<char*>(malloc(actualLength));
if (newString == 0) {
throwRuntimeError(
"in Json::Value::duplicateAndPrefixStringValue(): "
"Failed to allocate string value buffer");
}
*reinterpret_cast<unsigned*>(newString) = length;
memcpy(newString + sizeof(unsigned), value, length);
newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later
return newString;
}
inline static void decodePrefixedString(
bool isPrefixed, char const* prefixed,
unsigned* length, char const** value)
{
if (!isPrefixed) {
*length = static_cast<unsigned>(strlen(prefixed));
*value = prefixed;
} else {
*length = *reinterpret_cast<unsigned const*>(prefixed);
*value = prefixed + sizeof(unsigned);
}
}
/** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
*/
#if JSONCPP_USING_SECURE_MEMORY
static inline void releasePrefixedStringValue(char* value) {
unsigned length = 0;
char const* valueDecoded;
decodePrefixedString(true, value, &length, &valueDecoded);
size_t const size = sizeof(unsigned) + length + 1U;
memset(value, 0, size);
free(value);
}
static inline void releaseStringValue(char* value, unsigned length) {
// length==0 => we allocated the strings memory
size_t size = (length==0) ? strlen(value) : length;
memset(value, 0, size);
free(value);
}
#else // !JSONCPP_USING_SECURE_MEMORY
static inline void releasePrefixedStringValue(char* value) {
free(value);
}
static inline void releaseStringValue(char* value, unsigned) {
free(value);
}
#endif // JSONCPP_USING_SECURE_MEMORY
} // namespace Json
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// ValueInternals...
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
#if !defined(JSON_IS_AMALGAMATION)
#include "json_valueiterator.inl"
#endif // if !defined(JSON_IS_AMALGAMATION)
namespace Json {
Exception::Exception(JSONCPP_STRING const& msg)
: msg_(msg)
{}
Exception::~Exception() throw()
{}
char const* Exception::what() const throw()
{
return msg_.c_str();
}
RuntimeError::RuntimeError(JSONCPP_STRING const& msg)
: Exception(msg)
{}
LogicError::LogicError(JSONCPP_STRING const& msg)
: Exception(msg)
{}
JSONCPP_NORETURN void throwRuntimeError(JSONCPP_STRING const& msg)
{
throw RuntimeError(msg);
}
JSONCPP_NORETURN void throwLogicError(JSONCPP_STRING const& msg)
{
throw LogicError(msg);
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CommentInfo
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
Value::CommentInfo::CommentInfo() : comment_(0)
{}
Value::CommentInfo::~CommentInfo() {
if (comment_)
releaseStringValue(comment_, 0u);
}
void Value::CommentInfo::setComment(const char* text, size_t len) {
if (comment_) {
releaseStringValue(comment_, 0u);
comment_ = 0;
}
JSON_ASSERT(text != 0);
JSON_ASSERT_MESSAGE(
text[0] == '\0' || text[0] == '/',
"in Json::Value::setComment(): Comments must start with /");
// It seems that /**/ style comments are acceptable as well.
comment_ = duplicateStringValue(text, len);
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CZString
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// Notes: policy_ indicates if the string was allocated when
// a string is stored.
Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
: cstr_(str) {
// allocate != duplicate
storage_.policy_ = allocate & 0x3;
storage_.length_ = ulength & 0x3FFFFFFF;
}
Value::CZString::CZString(const CZString& other) {
cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != 0
? duplicateStringValue(other.cstr_, other.storage_.length_)
: other.cstr_);
storage_.policy_ = static_cast<unsigned>(other.cstr_
? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
? noDuplication : duplicate)
: static_cast<DuplicationPolicy>(other.storage_.policy_)) & 3U;
storage_.length_ = other.storage_.length_;
}
#if JSON_HAS_RVALUE_REFERENCES
Value::CZString::CZString(CZString&& other)
: cstr_(other.cstr_), index_(other.index_) {
other.cstr_ = nullptr;
}
#endif
Value::CZString::~CZString() {
if (cstr_ && storage_.policy_ == duplicate) {
releaseStringValue(const_cast<char*>(cstr_), storage_.length_ + 1u); //+1 for null terminating character for sake of completeness but not actually necessary
}
}
void Value::CZString::swap(CZString& other) {
std::swap(cstr_, other.cstr_);
std::swap(index_, other.index_);
}
Value::CZString& Value::CZString::operator=(CZString other) {
swap(other);
return *this;
}
bool Value::CZString::operator<(const CZString& other) const {
if (!cstr_) return index_ < other.index_;
//return strcmp(cstr_, other.cstr_) < 0;
// Assume both are strings.
unsigned this_len = this->storage_.length_;
unsigned other_len = other.storage_.length_;
unsigned min_len = std::min(this_len, other_len);
JSON_ASSERT(this->cstr_ && other.cstr_);
int comp = memcmp(this->cstr_, other.cstr_, min_len);
if (comp < 0) return true;
if (comp > 0) return false;
return (this_len < other_len);
}
bool Value::CZString::operator==(const CZString& other) const {
if (!cstr_) return index_ == other.index_;
//return strcmp(cstr_, other.cstr_) == 0;
// Assume both are strings.
unsigned this_len = this->storage_.length_;
unsigned other_len = other.storage_.length_;
if (this_len != other_len) return false;
JSON_ASSERT(this->cstr_ && other.cstr_);
int comp = memcmp(this->cstr_, other.cstr_, this_len);
return comp == 0;
}
ArrayIndex Value::CZString::index() const { return index_; }
//const char* Value::CZString::c_str() const { return cstr_; }
const char* Value::CZString::data() const { return cstr_; }
unsigned Value::CZString::length() const { return storage_.length_; }
bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; }
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::Value
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
/*! \internal Default constructor initialization must be equivalent to:
* memset( this, 0, sizeof(Value) )
* This optimization is used in ValueInternalMap fast allocator.
*/
Value::Value(ValueType vtype) {
initBasic(vtype);
switch (vtype) {
case nullValue:
break;
case intValue:
case uintValue:
value_.int_ = 0;
break;
case realValue:
value_.real_ = 0.0;
break;
case stringValue:
value_.string_ = 0;
break;
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues();
break;
case booleanValue:
value_.bool_ = false;
break;
default:
JSON_ASSERT_UNREACHABLE;
}
}
Value::Value(Int value) {
initBasic(intValue);
value_.int_ = value;
}
Value::Value(UInt value) {
initBasic(uintValue);
value_.uint_ = value;
}
#if defined(JSON_HAS_INT64)
Value::Value(Int64 value) {
initBasic(intValue);
value_.int_ = value;
}
Value::Value(UInt64 value) {
initBasic(uintValue);
value_.uint_ = value;
}
#endif // defined(JSON_HAS_INT64)
Value::Value(double value) {
initBasic(realValue);
value_.real_ = value;
}
Value::Value(const char* value) {
initBasic(stringValue, true);
value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
}
Value::Value(const char* beginValue, const char* endValue) {
initBasic(stringValue, true);
value_.string_ =
duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
}
Value::Value(const JSONCPP_STRING& value) {
initBasic(stringValue, true);
value_.string_ =
duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
}
Value::Value(const StaticString& value) {
initBasic(stringValue);
value_.string_ = const_cast<char*>(value.c_str());
}
#ifdef JSON_USE_CPPTL
Value::Value(const CppTL::ConstString& value) {
initBasic(stringValue, true);
value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
}
#endif
Value::Value(bool value) {
initBasic(booleanValue);
value_.bool_ = value;
}
Value::Value(Value const& other)
: type_(other.type_), allocated_(false)
,
comments_(0), start_(other.start_), limit_(other.limit_)
{
switch (type_) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
value_ = other.value_;
break;
case stringValue:
if (other.value_.string_ && other.allocated_) {
unsigned len;
char const* str;
decodePrefixedString(other.allocated_, other.value_.string_,
&len, &str);
value_.string_ = duplicateAndPrefixStringValue(str, len);
allocated_ = true;
} else {
value_.string_ = other.value_.string_;
allocated_ = false;
}
break;
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues(*other.value_.map_);
break;
default:
JSON_ASSERT_UNREACHABLE;
}
if (other.comments_) {
comments_ = new CommentInfo[numberOfCommentPlacement];
for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
const CommentInfo& otherComment = other.comments_[comment];
if (otherComment.comment_)
comments_[comment].setComment(
otherComment.comment_, strlen(otherComment.comment_));
}
}
}
#if JSON_HAS_RVALUE_REFERENCES
// Move constructor
Value::Value(Value&& other) {
initBasic(nullValue);
swap(other);
}
#endif
Value::~Value() {
switch (type_) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue:
if (allocated_)
releasePrefixedStringValue(value_.string_);
break;
case arrayValue:
case objectValue:
delete value_.map_;
break;
default:
JSON_ASSERT_UNREACHABLE;
}
if (comments_)
delete[] comments_;
value_.uint_ = 0;
}
Value& Value::operator=(Value other) {
swap(other);
return *this;
}
void Value::swapPayload(Value& other) {
ValueType temp = type_;
type_ = other.type_;
other.type_ = temp;
std::swap(value_, other.value_);
int temp2 = allocated_;
allocated_ = other.allocated_;
other.allocated_ = temp2 & 0x1;
}
void Value::swap(Value& other) {
swapPayload(other);
std::swap(comments_, other.comments_);
std::swap(start_, other.start_);
std::swap(limit_, other.limit_);
}
ValueType Value::type() const { return type_; }
int Value::compare(const Value& other) const {
if (*this < other)
return -1;
if (*this > other)
return 1;
return 0;
}
bool Value::operator<(const Value& other) const {
int typeDelta = type_ - other.type_;
if (typeDelta)
return typeDelta < 0 ? true : false;
switch (type_) {
case nullValue:
return false;
case intValue:
return value_.int_ < other.value_.int_;
case uintValue:
return value_.uint_ < other.value_.uint_;
case realValue:
return value_.real_ < other.value_.real_;
case booleanValue:
return value_.bool_ < other.value_.bool_;
case stringValue:
{
if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
if (other.value_.string_) return true;
else return false;
}
unsigned this_len;
unsigned other_len;
char const* this_str;
char const* other_str;
decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
unsigned min_len = std::min(this_len, other_len);
JSON_ASSERT(this_str && other_str);
int comp = memcmp(this_str, other_str, min_len);
if (comp < 0) return true;
if (comp > 0) return false;
return (this_len < other_len);
}
case arrayValue:
case objectValue: {
int delta = int(value_.map_->size() - other.value_.map_->size());
if (delta)
return delta < 0;
return (*value_.map_) < (*other.value_.map_);
}
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable
}
bool Value::operator<=(const Value& other) const { return !(other < *this); }
bool Value::operator>=(const Value& other) const { return !(*this < other); }
bool Value::operator>(const Value& other) const { return other < *this; }
bool Value::operator==(const Value& other) const {
// if ( type_ != other.type_ )
// GCC 2.95.3 says:
// attempt to take address of bit-field structure member `Json::Value::type_'
// Beats me, but a temp solves the problem.
int temp = other.type_;
if (type_ != temp)
return false;
switch (type_) {
case nullValue:
return true;
case intValue:
return value_.int_ == other.value_.int_;
case uintValue:
return value_.uint_ == other.value_.uint_;
case realValue:
return value_.real_ == other.value_.real_;
case booleanValue:
return value_.bool_ == other.value_.bool_;
case stringValue:
{
if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
return (value_.string_ == other.value_.string_);
}
unsigned this_len;
unsigned other_len;
char const* this_str;
char const* other_str;
decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
if (this_len != other_len) return false;
JSON_ASSERT(this_str && other_str);
int comp = memcmp(this_str, other_str, this_len);
return comp == 0;
}
case arrayValue:
case objectValue:
return value_.map_->size() == other.value_.map_->size() &&
(*value_.map_) == (*other.value_.map_);
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable
}
bool Value::operator!=(const Value& other) const { return !(*this == other); }
const char* Value::asCString() const {
JSON_ASSERT_MESSAGE(type_ == stringValue,
"in Json::Value::asCString(): requires stringValue");
if (value_.string_ == 0) return 0;
unsigned this_len;
char const* this_str;
decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
return this_str;
}
#if JSONCPP_USING_SECURE_MEMORY
unsigned Value::getCStringLength() const {
JSON_ASSERT_MESSAGE(type_ == stringValue,
"in Json::Value::asCString(): requires stringValue");
if (value_.string_ == 0) return 0;
unsigned this_len;
char const* this_str;
decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
return this_len;
}
#endif
bool Value::getString(char const** str, char const** cend) const {
if (type_ != stringValue) return false;
if (value_.string_ == 0) return false;
unsigned length;
decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
*cend = *str + length;
return true;
}
JSONCPP_STRING Value::asString() const {
switch (type_) {
case nullValue:
return "";
case stringValue:
{
if (value_.string_ == 0) return "";
unsigned this_len;
char const* this_str;
decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
return JSONCPP_STRING(this_str, this_len);
}
case booleanValue:
return value_.bool_ ? "true" : "false";
case intValue:
return valueToString(value_.int_);
case uintValue:
return valueToString(value_.uint_);
case realValue:
return valueToString(value_.real_);
default:
JSON_FAIL_MESSAGE("Type is not convertible to string");
}
}
#ifdef JSON_USE_CPPTL
CppTL::ConstString Value::asConstString() const {
unsigned len;
char const* str;
decodePrefixedString(allocated_, value_.string_,
&len, &str);
return CppTL::ConstString(str, len);
}
#endif
Value::Int Value::asInt() const {
switch (type_) {
case intValue:
JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
return Int(value_.int_);
case uintValue:
JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
return Int(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
"double out of Int range");
return Int(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to Int.");
}
Value::UInt Value::asUInt() const {
switch (type_) {
case intValue:
JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
return UInt(value_.int_);
case uintValue:
JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
return UInt(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
"double out of UInt range");
return UInt(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to UInt.");
}
#if defined(JSON_HAS_INT64)
Value::Int64 Value::asInt64() const {
switch (type_) {
case intValue:
return Int64(value_.int_);
case uintValue:
JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
return Int64(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
"double out of Int64 range");
return Int64(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to Int64.");
}
Value::UInt64 Value::asUInt64() const {
switch (type_) {
case intValue:
JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
return UInt64(value_.int_);
case uintValue:
return UInt64(value_.uint_);
case realValue:
JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
"double out of UInt64 range");
return UInt64(value_.real_);
case nullValue:
return 0;
case booleanValue:
return value_.bool_ ? 1 : 0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to UInt64.");
}
#endif // if defined(JSON_HAS_INT64)
LargestInt Value::asLargestInt() const {
#if defined(JSON_NO_INT64)
return asInt();
#else
return asInt64();
#endif
}
LargestUInt Value::asLargestUInt() const {
#if defined(JSON_NO_INT64)
return asUInt();
#else
return asUInt64();
#endif
}
double Value::asDouble() const {
switch (type_) {
case intValue:
return static_cast<double>(value_.int_);
case uintValue:
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return static_cast<double>(value_.uint_);
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return integerToDouble(value_.uint_);
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
case realValue:
return value_.real_;
case nullValue:
return 0.0;
case booleanValue:
return value_.bool_ ? 1.0 : 0.0;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to double.");
}
float Value::asFloat() const {
switch (type_) {
case intValue:
return static_cast<float>(value_.int_);
case uintValue:
#if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
return static_cast<float>(value_.uint_);
#else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
// This can fail (silently?) if the value is bigger than MAX_FLOAT.
return static_cast<float>(integerToDouble(value_.uint_));
#endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
case realValue:
return static_cast<float>(value_.real_);
case nullValue:
return 0.0;
case booleanValue:
return value_.bool_ ? 1.0f : 0.0f;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to float.");
}
bool Value::asBool() const {
switch (type_) {
case booleanValue:
return value_.bool_;
case nullValue:
return false;
case intValue:
return value_.int_ ? true : false;
case uintValue:
return value_.uint_ ? true : false;
case realValue:
// This is kind of strange. Not recommended.
return (value_.real_ != 0.0) ? true : false;
default:
break;
}
JSON_FAIL_MESSAGE("Value is not convertible to bool.");
}
bool Value::isConvertibleTo(ValueType other) const {
switch (other) {
case nullValue:
return (isNumeric() && asDouble() == 0.0) ||
(type_ == booleanValue && value_.bool_ == false) ||
(type_ == stringValue && asString() == "") ||
(type_ == arrayValue && value_.map_->size() == 0) ||
(type_ == objectValue && value_.map_->size() == 0) ||
type_ == nullValue;
case intValue:
return isInt() ||
(type_ == realValue && InRange(value_.real_, minInt, maxInt)) ||
type_ == booleanValue || type_ == nullValue;
case uintValue:
return isUInt() ||
(type_ == realValue && InRange(value_.real_, 0, maxUInt)) ||
type_ == booleanValue || type_ == nullValue;
case realValue:
return isNumeric() || type_ == booleanValue || type_ == nullValue;
case booleanValue:
return isNumeric() || type_ == booleanValue || type_ == nullValue;
case stringValue:
return isNumeric() || type_ == booleanValue || type_ == stringValue ||
type_ == nullValue;
case arrayValue:
return type_ == arrayValue || type_ == nullValue;
case objectValue:
return type_ == objectValue || type_ == nullValue;
}
JSON_ASSERT_UNREACHABLE;
return false;
}
/// Number of values in array or object
ArrayIndex Value::size() const {
switch (type_) {
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
case stringValue:
return 0;
case arrayValue: // size of the array is highest index + 1
if (!value_.map_->empty()) {
ObjectValues::const_iterator itLast = value_.map_->end();
--itLast;
return (*itLast).first.index() + 1;
}
return 0;
case objectValue:
return ArrayIndex(value_.map_->size());
}
JSON_ASSERT_UNREACHABLE;
return 0; // unreachable;
}
bool Value::empty() const {
if (isNull() || isArray() || isObject())
return size() == 0u;
else
return false;
}
bool Value::operator!() const { return isNull(); }
void Value::clear() {
JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue ||
type_ == objectValue,
"in Json::Value::clear(): requires complex value");
start_ = 0;
limit_ = 0;
switch (type_) {
case arrayValue:
case objectValue:
value_.map_->clear();
break;
default:
break;
}
}
void Value::resize(ArrayIndex newSize) {
JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue,
"in Json::Value::resize(): requires arrayValue");
if (type_ == nullValue)
*this = Value(arrayValue);
ArrayIndex oldSize = size();
if (newSize == 0)
clear();
else if (newSize > oldSize)
(*this)[newSize - 1];
else {
for (ArrayIndex index = newSize; index < oldSize; ++index) {
value_.map_->erase(index);
}
JSON_ASSERT(size() == newSize);
}
}
Value& Value::operator[](ArrayIndex index) {
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == arrayValue,
"in Json::Value::operator[](ArrayIndex): requires arrayValue");
if (type_ == nullValue)
*this = Value(arrayValue);
CZString key(index);
ObjectValues::iterator it = value_.map_->lower_bound(key);
if (it != value_.map_->end() && (*it).first == key)
return (*it).second;
ObjectValues::value_type defaultValue(key, nullSingleton());
it = value_.map_->insert(it, defaultValue);
return (*it).second;
}
Value& Value::operator[](int index) {
JSON_ASSERT_MESSAGE(
index >= 0,
"in Json::Value::operator[](int index): index cannot be negative");
return (*this)[ArrayIndex(index)];
}
const Value& Value::operator[](ArrayIndex index) const {
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == arrayValue,
"in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
if (type_ == nullValue)
return nullSingleton();
CZString key(index);
ObjectValues::const_iterator it = value_.map_->find(key);
if (it == value_.map_->end())
return nullSingleton();
return (*it).second;
}
const Value& Value::operator[](int index) const {
JSON_ASSERT_MESSAGE(
index >= 0,
"in Json::Value::operator[](int index) const: index cannot be negative");
return (*this)[ArrayIndex(index)];
}
void Value::initBasic(ValueType vtype, bool allocated) {
type_ = vtype;
allocated_ = allocated;
comments_ = 0;
start_ = 0;
limit_ = 0;
}
// Access an object value by name, create a null member if it does not exist.
// @pre Type of '*this' is object or null.
// @param key is null-terminated.
Value& Value::resolveReference(const char* key) {
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == objectValue,
"in Json::Value::resolveReference(): requires objectValue");
if (type_ == nullValue)
*this = Value(objectValue);
CZString actualKey(
key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
ObjectValues::value_type defaultValue(actualKey, nullSingleton());
it = value_.map_->insert(it, defaultValue);
Value& value = (*it).second;
return value;
}
// @param key is not null-terminated.
Value& Value::resolveReference(char const* key, char const* cend)
{
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == objectValue,
"in Json::Value::resolveReference(key, end): requires objectValue");
if (type_ == nullValue)
*this = Value(objectValue);
CZString actualKey(
key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
if (it != value_.map_->end() && (*it).first == actualKey)
return (*it).second;
ObjectValues::value_type defaultValue(actualKey, nullSingleton());
it = value_.map_->insert(it, defaultValue);
Value& value = (*it).second;
return value;
}
Value Value::get(ArrayIndex index, const Value& defaultValue) const {
const Value* value = &((*this)[index]);
return value == &nullSingleton() ? defaultValue : *value;
}
bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
Value const* Value::find(char const* key, char const* cend) const
{
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == objectValue,
"in Json::Value::find(key, end, found): requires objectValue or nullValue");
if (type_ == nullValue) return NULL;
CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
ObjectValues::const_iterator it = value_.map_->find(actualKey);
if (it == value_.map_->end()) return NULL;
return &(*it).second;
}
const Value& Value::operator[](const char* key) const
{
Value const* found = find(key, key + strlen(key));
if (!found) return nullSingleton();
return *found;
}
Value const& Value::operator[](JSONCPP_STRING const& key) const
{
Value const* found = find(key.data(), key.data() + key.length());
if (!found) return nullSingleton();
return *found;
}
Value& Value::operator[](const char* key) {
return resolveReference(key, key + strlen(key));
}
Value& Value::operator[](const JSONCPP_STRING& key) {
return resolveReference(key.data(), key.data() + key.length());
}
Value& Value::operator[](const StaticString& key) {
return resolveReference(key.c_str());
}
#ifdef JSON_USE_CPPTL
Value& Value::operator[](const CppTL::ConstString& key) {
return resolveReference(key.c_str(), key.end_c_str());
}
Value const& Value::operator[](CppTL::ConstString const& key) const
{
Value const* found = find(key.c_str(), key.end_c_str());
if (!found) return nullSingleton();
return *found;
}
#endif
Value& Value::append(const Value& value) { return (*this)[size()] = value; }
Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
{
Value const* found = find(key, cend);
return !found ? defaultValue : *found;
}
Value Value::get(char const* key, Value const& defaultValue) const
{
return get(key, key + strlen(key), defaultValue);
}
Value Value::get(JSONCPP_STRING const& key, Value const& defaultValue) const
{
return get(key.data(), key.data() + key.length(), defaultValue);
}
bool Value::removeMember(const char* key, const char* cend, Value* removed)
{
if (type_ != objectValue) {
return false;
}
CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
ObjectValues::iterator it = value_.map_->find(actualKey);
if (it == value_.map_->end())
return false;
*removed = it->second;
value_.map_->erase(it);
return true;
}
bool Value::removeMember(const char* key, Value* removed)
{
return removeMember(key, key + strlen(key), removed);
}
bool Value::removeMember(JSONCPP_STRING const& key, Value* removed)
{
return removeMember(key.data(), key.data() + key.length(), removed);
}
Value Value::removeMember(const char* key)
{
JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
"in Json::Value::removeMember(): requires objectValue");
if (type_ == nullValue)
return nullSingleton();
Value removed; // null
removeMember(key, key + strlen(key), &removed);
return removed; // still null if removeMember() did nothing
}
Value Value::removeMember(const JSONCPP_STRING& key)
{
return removeMember(key.c_str());
}
bool Value::removeIndex(ArrayIndex index, Value* removed) {
if (type_ != arrayValue) {
return false;
}
CZString key(index);
ObjectValues::iterator it = value_.map_->find(key);
if (it == value_.map_->end()) {
return false;
}
*removed = it->second;
ArrayIndex oldSize = size();
// shift left all items left, into the place of the "removed"
for (ArrayIndex i = index; i < (oldSize - 1); ++i){
CZString keey(i);
(*value_.map_)[keey] = (*this)[i + 1];
}
// erase the last one ("leftover")
CZString keyLast(oldSize - 1);
ObjectValues::iterator itLast = value_.map_->find(keyLast);
value_.map_->erase(itLast);
return true;
}
#ifdef JSON_USE_CPPTL
Value Value::get(const CppTL::ConstString& key,
const Value& defaultValue) const {
return get(key.c_str(), key.end_c_str(), defaultValue);
}
#endif
bool Value::isMember(char const* key, char const* cend) const
{
Value const* value = find(key, cend);
return NULL != value;
}
bool Value::isMember(char const* key) const
{
return isMember(key, key + strlen(key));
}
bool Value::isMember(JSONCPP_STRING const& key) const
{
return isMember(key.data(), key.data() + key.length());
}
#ifdef JSON_USE_CPPTL
bool Value::isMember(const CppTL::ConstString& key) const {
return isMember(key.c_str(), key.end_c_str());
}
#endif
Value::Members Value::getMemberNames() const {
JSON_ASSERT_MESSAGE(
type_ == nullValue || type_ == objectValue,
"in Json::Value::getMemberNames(), value must be objectValue");
if (type_ == nullValue)
return Value::Members();
Members members;
members.reserve(value_.map_->size());
ObjectValues::const_iterator it = value_.map_->begin();
ObjectValues::const_iterator itEnd = value_.map_->end();
for (; it != itEnd; ++it) {
members.push_back(JSONCPP_STRING((*it).first.data(),
(*it).first.length()));
}
return members;
}
//
//# ifdef JSON_USE_CPPTL
// EnumMemberNames
// Value::enumMemberNames() const
//{
// if ( type_ == objectValue )
// {
// return CppTL::Enum::any( CppTL::Enum::transform(
// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
// MemberNamesTransform() ) );
// }
// return EnumMemberNames();
//}
//
//
// EnumValues
// Value::enumValues() const
//{
// if ( type_ == objectValue || type_ == arrayValue )
// return CppTL::Enum::anyValues( *(value_.map_),
// CppTL::Type<const Value &>() );
// return EnumValues();
//}
//
//# endif
static bool IsIntegral(double d) {
double integral_part;
return modf(d, &integral_part) == 0.0;
}
bool Value::isNull() const { return type_ == nullValue; }
bool Value::isBool() const { return type_ == booleanValue; }
bool Value::isInt() const {
switch (type_) {
case intValue:
return value_.int_ >= minInt && value_.int_ <= maxInt;
case uintValue:
return value_.uint_ <= UInt(maxInt);
case realValue:
return value_.real_ >= minInt && value_.real_ <= maxInt &&
IsIntegral(value_.real_);
default:
break;
}
return false;
}
bool Value::isUInt() const {
switch (type_) {
case intValue:
return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
case uintValue:
return value_.uint_ <= maxUInt;
case realValue:
return value_.real_ >= 0 && value_.real_ <= maxUInt &&
IsIntegral(value_.real_);
default:
break;
}
return false;
}
bool Value::isInt64() const {
#if defined(JSON_HAS_INT64)
switch (type_) {
case intValue:
return true;
case uintValue:
return value_.uint_ <= UInt64(maxInt64);
case realValue:
// Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
// double, so double(maxInt64) will be rounded up to 2^63. Therefore we
// require the value to be strictly less than the limit.
return value_.real_ >= double(minInt64) &&
value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
default:
break;
}
#endif // JSON_HAS_INT64
return false;
}
bool Value::isUInt64() const {
#if defined(JSON_HAS_INT64)
switch (type_) {
case intValue:
return value_.int_ >= 0;
case uintValue:
return true;
case realValue:
// Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
// double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
// require the value to be strictly less than the limit.
return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
IsIntegral(value_.real_);
default:
break;
}
#endif // JSON_HAS_INT64
return false;
}
bool Value::isIntegral() const {
#if defined(JSON_HAS_INT64)
return isInt64() || isUInt64();
#else
return isInt() || isUInt();
#endif
}
bool Value::isDouble() const { return type_ == realValue || isIntegral(); }
bool Value::isNumeric() const { return isIntegral() || isDouble(); }
bool Value::isString() const { return type_ == stringValue; }
bool Value::isArray() const { return type_ == arrayValue; }
bool Value::isObject() const { return type_ == objectValue; }
void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
if (!comments_)
comments_ = new CommentInfo[numberOfCommentPlacement];
if ((len > 0) && (comment[len-1] == '\n')) {
// Always discard trailing newline, to aid indentation.
len -= 1;
}
comments_[placement].setComment(comment, len);
}
void Value::setComment(const char* comment, CommentPlacement placement) {
setComment(comment, strlen(comment), placement);
}
void Value::setComment(const JSONCPP_STRING& comment, CommentPlacement placement) {
setComment(comment.c_str(), comment.length(), placement);
}
bool Value::hasComment(CommentPlacement placement) const {
return comments_ != 0 && comments_[placement].comment_ != 0;
}
JSONCPP_STRING Value::getComment(CommentPlacement placement) const {
if (hasComment(placement))
return comments_[placement].comment_;
return "";
}
void Value::setOffsetStart(ptrdiff_t start) { start_ = start; }
void Value::setOffsetLimit(ptrdiff_t limit) { limit_ = limit; }
ptrdiff_t Value::getOffsetStart() const { return start_; }
ptrdiff_t Value::getOffsetLimit() const { return limit_; }
JSONCPP_STRING Value::toStyledString() const {
StyledWriter writer;
return writer.write(*this);
}
Value::const_iterator Value::begin() const {
switch (type_) {
case arrayValue:
case objectValue:
if (value_.map_)
return const_iterator(value_.map_->begin());
break;
default:
break;
}
return const_iterator();
}
Value::const_iterator Value::end() const {
switch (type_) {
case arrayValue:
case objectValue:
if (value_.map_)
return const_iterator(value_.map_->end());
break;
default:
break;
}
return const_iterator();
}
Value::iterator Value::begin() {
switch (type_) {
case arrayValue:
case objectValue:
if (value_.map_)
return iterator(value_.map_->begin());
break;
default:
break;
}
return iterator();
}
Value::iterator Value::end() {
switch (type_) {
case arrayValue:
case objectValue:
if (value_.map_)
return iterator(value_.map_->end());
break;
default:
break;
}
return iterator();
}
// class PathArgument
// //////////////////////////////////////////////////////////////////
PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {}
PathArgument::PathArgument(ArrayIndex index)
: key_(), index_(index), kind_(kindIndex) {}
PathArgument::PathArgument(const char* key)
: key_(key), index_(), kind_(kindKey) {}
PathArgument::PathArgument(const JSONCPP_STRING& key)
: key_(key.c_str()), index_(), kind_(kindKey) {}
// class Path
// //////////////////////////////////////////////////////////////////
Path::Path(const JSONCPP_STRING& path,
const PathArgument& a1,
const PathArgument& a2,
const PathArgument& a3,
const PathArgument& a4,
const PathArgument& a5) {
InArgs in;
in.push_back(&a1);
in.push_back(&a2);
in.push_back(&a3);
in.push_back(&a4);
in.push_back(&a5);
makePath(path, in);
}
void Path::makePath(const JSONCPP_STRING& path, const InArgs& in) {
const char* current = path.c_str();
const char* end = current + path.length();
InArgs::const_iterator itInArg = in.begin();
while (current != end) {
if (*current == '[') {
++current;
if (*current == '%')
addPathInArg(path, in, itInArg, PathArgument::kindIndex);
else {
ArrayIndex index = 0;
for (; current != end && *current >= '0' && *current <= '9'; ++current)
index = index * 10 + ArrayIndex(*current - '0');
args_.push_back(index);
}
if (current == end || *current++ != ']')
invalidPath(path, int(current - path.c_str()));
} else if (*current == '%') {
addPathInArg(path, in, itInArg, PathArgument::kindKey);
++current;
} else if (*current == '.') {
++current;
} else {
const char* beginName = current;
while (current != end && !strchr("[.", *current))
++current;
args_.push_back(JSONCPP_STRING(beginName, current));
}
}
}
void Path::addPathInArg(const JSONCPP_STRING& /*path*/,
const InArgs& in,
InArgs::const_iterator& itInArg,
PathArgument::Kind kind) {
if (itInArg == in.end()) {
// Error: missing argument %d
} else if ((*itInArg)->kind_ != kind) {
// Error: bad argument type
} else {
args_.push_back(**itInArg);
}
}
void Path::invalidPath(const JSONCPP_STRING& /*path*/, int /*location*/) {
// Error: invalid path.
}
const Value& Path::resolve(const Value& root) const {
const Value* node = &root;
for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
const PathArgument& arg = *it;
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray() || !node->isValidIndex(arg.index_)) {
// Error: unable to resolve path (array value expected at position...
}
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject()) {
// Error: unable to resolve path (object value expected at position...)
}
node = &((*node)[arg.key_]);
if (node == &Value::nullSingleton()) {
// Error: unable to resolve path (object has no member named '' at
// position...)
}
}
}
return *node;
}
Value Path::resolve(const Value& root, const Value& defaultValue) const {
const Value* node = &root;
for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
const PathArgument& arg = *it;
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray() || !node->isValidIndex(arg.index_))
return defaultValue;
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject())
return defaultValue;
node = &((*node)[arg.key_]);
if (node == &Value::nullSingleton())
return defaultValue;
}
}
return *node;
}
Value& Path::make(Value& root) const {
Value* node = &root;
for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
const PathArgument& arg = *it;
if (arg.kind_ == PathArgument::kindIndex) {
if (!node->isArray()) {
// Error: node is not an array at position ...
}
node = &((*node)[arg.index_]);
} else if (arg.kind_ == PathArgument::kindKey) {
if (!node->isObject()) {
// Error: node is not an object at position...
}
node = &((*node)[arg.key_]);
}
}
return *node;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_value.cpp
// //////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////
// Beginning of content of file: src/lib_json/json_writer.cpp
// //////////////////////////////////////////////////////////////////////
// Copyright 2011 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
#include <json/writer.h>
#include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include <set>
#include <cassert>
#include <cstring>
#include <cstdio>
#if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
#include <float.h>
#define isfinite _finite
#elif defined(__sun) && defined(__SVR4) //Solaris
#if !defined(isfinite)
#include <ieeefp.h>
#define isfinite finite
#endif
#elif defined(_AIX)
#if !defined(isfinite)
#include <math.h>
#define isfinite finite
#endif
#elif defined(__hpux)
#if !defined(isfinite)
#if defined(__ia64) && !defined(finite)
#define isfinite(x) ((sizeof(x) == sizeof(float) ? \
_Isfinitef(x) : _IsFinite(x)))
#else
#include <math.h>
#define isfinite finite
#endif
#endif
#else
#include <cmath>
#if !(defined(__QNXNTO__)) // QNX already defines isfinite
#define isfinite std::isfinite
#endif
#endif
#if defined(_MSC_VER)
#if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
#define snprintf sprintf_s
#elif _MSC_VER >= 1900 // VC++ 14.0 and above
#define snprintf std::snprintf
#else
#define snprintf _snprintf
#endif
#elif defined(__ANDROID__) || defined(__QNXNTO__)
#define snprintf snprintf
#elif __cplusplus >= 201103L
#if !defined(__MINGW32__) && !defined(__CYGWIN__)
#define snprintf std::snprintf
#endif
#endif
#if defined(__BORLANDC__)
#include <float.h>
#define isfinite _finite
#define snprintf _snprintf
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
// Disable warning about strdup being deprecated.
#pragma warning(disable : 4996)
#endif
namespace Json {
#if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520)
typedef std::unique_ptr<StreamWriter> StreamWriterPtr;
#else
typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
#endif
static bool containsControlCharacter(const char* str) {
while (*str) {
if (isControlCharacter(*(str++)))
return true;
}
return false;
}
static bool containsControlCharacter0(const char* str, unsigned len) {
char const* end = str + len;
while (end != str) {
if (isControlCharacter(*str) || 0==*str)
return true;
++str;
}
return false;
}
JSONCPP_STRING valueToString(LargestInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
if (value == Value::minLargestInt) {
uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
*--current = '-';
} else if (value < 0) {
uintToString(LargestUInt(-value), current);
*--current = '-';
} else {
uintToString(LargestUInt(value), current);
}
assert(current >= buffer);
return current;
}
JSONCPP_STRING valueToString(LargestUInt value) {
UIntToStringBuffer buffer;
char* current = buffer + sizeof(buffer);
uintToString(value, current);
assert(current >= buffer);
return current;
}
#if defined(JSON_HAS_INT64)
JSONCPP_STRING valueToString(Int value) {
return valueToString(LargestInt(value));
}
JSONCPP_STRING valueToString(UInt value) {
return valueToString(LargestUInt(value));
}
#endif // # if defined(JSON_HAS_INT64)
namespace {
JSONCPP_STRING valueToString(double value, bool useSpecialFloats, unsigned int precision) {
// Allocate a buffer that is more than large enough to store the 16 digits of
// precision requested below.
char buffer[32];
int len = -1;
char formatString[6];
sprintf(formatString, "%%.%dg", precision);
// Print into the buffer. We need not request the alternative representation
// that always has a decimal point because JSON doesn't distingish the
// concepts of reals and integers.
if (isfinite(value)) {
len = snprintf(buffer, sizeof(buffer), formatString, value);
} else {
// IEEE standard states that NaN values will not compare to themselves
if (value != value) {
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
} else if (value < 0) {
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
} else {
len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
}
// For those, we do not need to call fixNumLoc, but it is fast.
}
assert(len >= 0);
fixNumericLocale(buffer, buffer + len);
return buffer;
}
}
JSONCPP_STRING valueToString(double value) { return valueToString(value, false, 17); }
JSONCPP_STRING valueToString(bool value) { return value ? "true" : "false"; }
JSONCPP_STRING valueToQuotedString(const char* value) {
if (value == NULL)
return "";
// Not sure how to handle unicode...
if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
!containsControlCharacter(value))
return JSONCPP_STRING("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to JSONCPP_STRING is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
JSONCPP_STRING::size_type maxsize =
strlen(value) * 2 + 3; // allescaped+quotes+NULL
JSONCPP_STRING result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
for (const char* c = value; *c != 0; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default:
if (isControlCharacter(*c)) {
JSONCPP_OSTRINGSTREAM oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
} else {
result += *c;
}
break;
}
}
result += "\"";
return result;
}
// https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
static char const* strnpbrk(char const* s, char const* accept, size_t n) {
assert((s || !n) && accept);
char const* const end = s + n;
for (char const* cur = s; cur < end; ++cur) {
int const c = *cur;
for (char const* a = accept; *a; ++a) {
if (*a == c) {
return cur;
}
}
}
return NULL;
}
static JSONCPP_STRING valueToQuotedStringN(const char* value, unsigned length) {
if (value == NULL)
return "";
// Not sure how to handle unicode...
if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
!containsControlCharacter0(value, length))
return JSONCPP_STRING("\"") + value + "\"";
// We have to walk value and escape any special characters.
// Appending to JSONCPP_STRING is not efficient, but this should be rare.
// (Note: forward slashes are *not* rare, but I am not escaping them.)
JSONCPP_STRING::size_type maxsize =
length * 2 + 3; // allescaped+quotes+NULL
JSONCPP_STRING result;
result.reserve(maxsize); // to avoid lots of mallocs
result += "\"";
char const* end = value + length;
for (const char* c = value; c != end; ++c) {
switch (*c) {
case '\"':
result += "\\\"";
break;
case '\\':
result += "\\\\";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
// case '/':
// Even though \/ is considered a legal escape in JSON, a bare
// slash is also legal, so I see no reason to escape it.
// (I hope I am not misunderstanding something.)
// blep notes: actually escaping \/ may be useful in javascript to avoid </
// sequence.
// Should add a flag to allow this compatibility mode and prevent this
// sequence from occurring.
default:
if ((isControlCharacter(*c)) || (*c == 0)) {
JSONCPP_OSTRINGSTREAM oss;
oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
<< std::setw(4) << static_cast<int>(*c);
result += oss.str();
} else {
result += *c;
}
break;
}
}
result += "\"";
return result;
}
// Class Writer
// //////////////////////////////////////////////////////////////////
Writer::~Writer() {}
// Class FastWriter
// //////////////////////////////////////////////////////////////////
FastWriter::FastWriter()
: yamlCompatiblityEnabled_(false), dropNullPlaceholders_(false),
omitEndingLineFeed_(false) {}
void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; }
void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; }
JSONCPP_STRING FastWriter::write(const Value& root) {
document_ = "";
writeValue(root);
if (!omitEndingLineFeed_)
document_ += "\n";
return document_;
}
void FastWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
if (!dropNullPlaceholders_)
document_ += "null";
break;
case intValue:
document_ += valueToString(value.asLargestInt());
break;
case uintValue:
document_ += valueToString(value.asLargestUInt());
break;
case realValue:
document_ += valueToString(value.asDouble());
break;
case stringValue:
{
// Is NULL possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
break;
}
case booleanValue:
document_ += valueToString(value.asBool());
break;
case arrayValue: {
document_ += '[';
ArrayIndex size = value.size();
for (ArrayIndex index = 0; index < size; ++index) {
if (index > 0)
document_ += ',';
writeValue(value[index]);
}
document_ += ']';
} break;
case objectValue: {
Value::Members members(value.getMemberNames());
document_ += '{';
for (Value::Members::iterator it = members.begin(); it != members.end();
++it) {
const JSONCPP_STRING& name = *it;
if (it != members.begin())
document_ += ',';
document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
document_ += yamlCompatiblityEnabled_ ? ": " : ":";
writeValue(value[name]);
}
document_ += '}';
} break;
}
}
// Class StyledWriter
// //////////////////////////////////////////////////////////////////
StyledWriter::StyledWriter()
: rightMargin_(74), indentSize_(3), addChildValues_() {}
JSONCPP_STRING StyledWriter::write(const Value& root) {
document_ = "";
addChildValues_ = false;
indentString_ = "";
writeCommentBeforeValue(root);
writeValue(root);
writeCommentAfterValueOnSameLine(root);
document_ += "\n";
return document_;
}
void StyledWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
pushValue("null");
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
{
// Is NULL possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
Value::Members::iterator it = members.begin();
for (;;) {
const JSONCPP_STRING& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
document_ += " : ";
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
document_ += ',';
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void StyledWriter::writeArrayValue(const Value& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isArrayMultiLine = isMultineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
writeIndent();
writeValue(childValue);
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
document_ += ',';
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
} else // output on a single line
{
assert(childValues_.size() == size);
document_ += "[ ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
document_ += ", ";
document_ += childValues_[index];
}
document_ += " ]";
}
}
}
bool StyledWriter::isMultineArray(const Value& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void StyledWriter::pushValue(const JSONCPP_STRING& value) {
if (addChildValues_)
childValues_.push_back(value);
else
document_ += value;
}
void StyledWriter::writeIndent() {
if (!document_.empty()) {
char last = document_[document_.length() - 1];
if (last == ' ') // already indented
return;
if (last != '\n') // Comments may add new-line
document_ += '\n';
}
document_ += indentString_;
}
void StyledWriter::writeWithIndent(const JSONCPP_STRING& value) {
writeIndent();
document_ += value;
}
void StyledWriter::indent() { indentString_ += JSONCPP_STRING(indentSize_, ' '); }
void StyledWriter::unindent() {
assert(indentString_.size() >= indentSize_);
indentString_.resize(indentString_.size() - indentSize_);
}
void StyledWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
document_ += "\n";
writeIndent();
const JSONCPP_STRING& comment = root.getComment(commentBefore);
JSONCPP_STRING::const_iterator iter = comment.begin();
while (iter != comment.end()) {
document_ += *iter;
if (*iter == '\n' &&
(iter != comment.end() && *(iter + 1) == '/'))
writeIndent();
++iter;
}
// Comments are stripped of trailing newlines, so add one here
document_ += "\n";
}
void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
document_ += " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
document_ += "\n";
document_ += root.getComment(commentAfter);
document_ += "\n";
}
}
bool StyledWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
// Class StyledStreamWriter
// //////////////////////////////////////////////////////////////////
StyledStreamWriter::StyledStreamWriter(JSONCPP_STRING indentation)
: document_(NULL), rightMargin_(74), indentation_(indentation),
addChildValues_() {}
void StyledStreamWriter::write(JSONCPP_OSTREAM& out, const Value& root) {
document_ = &out;
addChildValues_ = false;
indentString_ = "";
indented_ = true;
writeCommentBeforeValue(root);
if (!indented_) writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*document_ << "\n";
document_ = NULL; // Forget the stream, for safety.
}
void StyledStreamWriter::writeValue(const Value& value) {
switch (value.type()) {
case nullValue:
pushValue("null");
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble()));
break;
case stringValue:
{
// Is NULL possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
Value::Members::iterator it = members.begin();
for (;;) {
const JSONCPP_STRING& name = *it;
const Value& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedString(name.c_str()));
*document_ << " : ";
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void StyledStreamWriter::writeArrayValue(const Value& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isArrayMultiLine = isMultineArray(value);
if (isArrayMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
const Value& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_) writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*document_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
} else // output on a single line
{
assert(childValues_.size() == size);
*document_ << "[ ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*document_ << ", ";
*document_ << childValues_[index];
}
*document_ << " ]";
}
}
}
bool StyledStreamWriter::isMultineArray(const Value& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
const Value& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void StyledStreamWriter::pushValue(const JSONCPP_STRING& value) {
if (addChildValues_)
childValues_.push_back(value);
else
*document_ << value;
}
void StyledStreamWriter::writeIndent() {
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
*document_ << '\n' << indentString_;
}
void StyledStreamWriter::writeWithIndent(const JSONCPP_STRING& value) {
if (!indented_) writeIndent();
*document_ << value;
indented_ = false;
}
void StyledStreamWriter::indent() { indentString_ += indentation_; }
void StyledStreamWriter::unindent() {
assert(indentString_.size() >= indentation_.size());
indentString_.resize(indentString_.size() - indentation_.size());
}
void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
if (!root.hasComment(commentBefore))
return;
if (!indented_) writeIndent();
const JSONCPP_STRING& comment = root.getComment(commentBefore);
JSONCPP_STRING::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*document_ << *iter;
if (*iter == '\n' &&
(iter != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would include newline
*document_ << indentString_;
++iter;
}
indented_ = false;
}
void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
if (root.hasComment(commentAfterOnSameLine))
*document_ << ' ' << root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
writeIndent();
*document_ << root.getComment(commentAfter);
}
indented_ = false;
}
bool StyledStreamWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
//////////////////////////
// BuiltStyledStreamWriter
/// Scoped enums are not available until C++11.
struct CommentStyle {
/// Decide whether to write comments.
enum Enum {
None, ///< Drop all comments.
Most, ///< Recover odd behavior of previous versions (not implemented yet).
All ///< Keep all comments.
};
};
struct BuiltStyledStreamWriter : public StreamWriter
{
BuiltStyledStreamWriter(
JSONCPP_STRING const& indentation,
CommentStyle::Enum cs,
JSONCPP_STRING const& colonSymbol,
JSONCPP_STRING const& nullSymbol,
JSONCPP_STRING const& endingLineFeedSymbol,
bool useSpecialFloats,
unsigned int precision);
int write(Value const& root, JSONCPP_OSTREAM* sout) JSONCPP_OVERRIDE;
private:
void writeValue(Value const& value);
void writeArrayValue(Value const& value);
bool isMultineArray(Value const& value);
void pushValue(JSONCPP_STRING const& value);
void writeIndent();
void writeWithIndent(JSONCPP_STRING const& value);
void indent();
void unindent();
void writeCommentBeforeValue(Value const& root);
void writeCommentAfterValueOnSameLine(Value const& root);
static bool hasCommentForValue(const Value& value);
typedef std::vector<JSONCPP_STRING> ChildValues;
ChildValues childValues_;
JSONCPP_STRING indentString_;
unsigned int rightMargin_;
JSONCPP_STRING indentation_;
CommentStyle::Enum cs_;
JSONCPP_STRING colonSymbol_;
JSONCPP_STRING nullSymbol_;
JSONCPP_STRING endingLineFeedSymbol_;
bool addChildValues_ : 1;
bool indented_ : 1;
bool useSpecialFloats_ : 1;
unsigned int precision_;
};
BuiltStyledStreamWriter::BuiltStyledStreamWriter(
JSONCPP_STRING const& indentation,
CommentStyle::Enum cs,
JSONCPP_STRING const& colonSymbol,
JSONCPP_STRING const& nullSymbol,
JSONCPP_STRING const& endingLineFeedSymbol,
bool useSpecialFloats,
unsigned int precision)
: rightMargin_(74)
, indentation_(indentation)
, cs_(cs)
, colonSymbol_(colonSymbol)
, nullSymbol_(nullSymbol)
, endingLineFeedSymbol_(endingLineFeedSymbol)
, addChildValues_(false)
, indented_(false)
, useSpecialFloats_(useSpecialFloats)
, precision_(precision)
{
}
int BuiltStyledStreamWriter::write(Value const& root, JSONCPP_OSTREAM* sout)
{
sout_ = sout;
addChildValues_ = false;
indented_ = true;
indentString_ = "";
writeCommentBeforeValue(root);
if (!indented_) writeIndent();
indented_ = true;
writeValue(root);
writeCommentAfterValueOnSameLine(root);
*sout_ << endingLineFeedSymbol_;
sout_ = NULL;
return 0;
}
void BuiltStyledStreamWriter::writeValue(Value const& value) {
switch (value.type()) {
case nullValue:
pushValue(nullSymbol_);
break;
case intValue:
pushValue(valueToString(value.asLargestInt()));
break;
case uintValue:
pushValue(valueToString(value.asLargestUInt()));
break;
case realValue:
pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
break;
case stringValue:
{
// Is NULL is possible for value.string_?
char const* str;
char const* end;
bool ok = value.getString(&str, &end);
if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
else pushValue("");
break;
}
case booleanValue:
pushValue(valueToString(value.asBool()));
break;
case arrayValue:
writeArrayValue(value);
break;
case objectValue: {
Value::Members members(value.getMemberNames());
if (members.empty())
pushValue("{}");
else {
writeWithIndent("{");
indent();
Value::Members::iterator it = members.begin();
for (;;) {
JSONCPP_STRING const& name = *it;
Value const& childValue = value[name];
writeCommentBeforeValue(childValue);
writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
*sout_ << colonSymbol_;
writeValue(childValue);
if (++it == members.end()) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*sout_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("}");
}
} break;
}
}
void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
unsigned size = value.size();
if (size == 0)
pushValue("[]");
else {
bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
if (isMultiLine) {
writeWithIndent("[");
indent();
bool hasChildValue = !childValues_.empty();
unsigned index = 0;
for (;;) {
Value const& childValue = value[index];
writeCommentBeforeValue(childValue);
if (hasChildValue)
writeWithIndent(childValues_[index]);
else {
if (!indented_) writeIndent();
indented_ = true;
writeValue(childValue);
indented_ = false;
}
if (++index == size) {
writeCommentAfterValueOnSameLine(childValue);
break;
}
*sout_ << ",";
writeCommentAfterValueOnSameLine(childValue);
}
unindent();
writeWithIndent("]");
} else // output on a single line
{
assert(childValues_.size() == size);
*sout_ << "[";
if (!indentation_.empty()) *sout_ << " ";
for (unsigned index = 0; index < size; ++index) {
if (index > 0)
*sout_ << ", ";
*sout_ << childValues_[index];
}
if (!indentation_.empty()) *sout_ << " ";
*sout_ << "]";
}
}
}
bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
ArrayIndex const size = value.size();
bool isMultiLine = size * 3 >= rightMargin_;
childValues_.clear();
for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) {
Value const& childValue = value[index];
isMultiLine = ((childValue.isArray() || childValue.isObject()) &&
childValue.size() > 0);
}
if (!isMultiLine) // check if line length > max line length
{
childValues_.reserve(size);
addChildValues_ = true;
ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
for (ArrayIndex index = 0; index < size; ++index) {
if (hasCommentForValue(value[index])) {
isMultiLine = true;
}
writeValue(value[index]);
lineLength += static_cast<ArrayIndex>(childValues_[index].length());
}
addChildValues_ = false;
isMultiLine = isMultiLine || lineLength >= rightMargin_;
}
return isMultiLine;
}
void BuiltStyledStreamWriter::pushValue(JSONCPP_STRING const& value) {
if (addChildValues_)
childValues_.push_back(value);
else
*sout_ << value;
}
void BuiltStyledStreamWriter::writeIndent() {
// blep intended this to look at the so-far-written string
// to determine whether we are already indented, but
// with a stream we cannot do that. So we rely on some saved state.
// The caller checks indented_.
if (!indentation_.empty()) {
// In this case, drop newlines too.
*sout_ << '\n' << indentString_;
}
}
void BuiltStyledStreamWriter::writeWithIndent(JSONCPP_STRING const& value) {
if (!indented_) writeIndent();
*sout_ << value;
indented_ = false;
}
void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
void BuiltStyledStreamWriter::unindent() {
assert(indentString_.size() >= indentation_.size());
indentString_.resize(indentString_.size() - indentation_.size());
}
void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
if (cs_ == CommentStyle::None) return;
if (!root.hasComment(commentBefore))
return;
if (!indented_) writeIndent();
const JSONCPP_STRING& comment = root.getComment(commentBefore);
JSONCPP_STRING::const_iterator iter = comment.begin();
while (iter != comment.end()) {
*sout_ << *iter;
if (*iter == '\n' &&
(iter != comment.end() && *(iter + 1) == '/'))
// writeIndent(); // would write extra newline
*sout_ << indentString_;
++iter;
}
indented_ = false;
}
void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
if (cs_ == CommentStyle::None) return;
if (root.hasComment(commentAfterOnSameLine))
*sout_ << " " + root.getComment(commentAfterOnSameLine);
if (root.hasComment(commentAfter)) {
writeIndent();
*sout_ << root.getComment(commentAfter);
}
}
// static
bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
return value.hasComment(commentBefore) ||
value.hasComment(commentAfterOnSameLine) ||
value.hasComment(commentAfter);
}
///////////////
// StreamWriter
StreamWriter::StreamWriter()
: sout_(NULL)
{
}
StreamWriter::~StreamWriter()
{
}
StreamWriter::Factory::~Factory()
{}
StreamWriterBuilder::StreamWriterBuilder()
{
setDefaults(&settings_);
}
StreamWriterBuilder::~StreamWriterBuilder()
{}
StreamWriter* StreamWriterBuilder::newStreamWriter() const
{
JSONCPP_STRING indentation = settings_["indentation"].asString();
JSONCPP_STRING cs_str = settings_["commentStyle"].asString();
bool eyc = settings_["enableYAMLCompatibility"].asBool();
bool dnp = settings_["dropNullPlaceholders"].asBool();
bool usf = settings_["useSpecialFloats"].asBool();
unsigned int pre = settings_["precision"].asUInt();
CommentStyle::Enum cs = CommentStyle::All;
if (cs_str == "All") {
cs = CommentStyle::All;
} else if (cs_str == "None") {
cs = CommentStyle::None;
} else {
throwRuntimeError("commentStyle must be 'All' or 'None'");
}
JSONCPP_STRING colonSymbol = " : ";
if (eyc) {
colonSymbol = ": ";
} else if (indentation.empty()) {
colonSymbol = ":";
}
JSONCPP_STRING nullSymbol = "null";
if (dnp) {
nullSymbol = "";
}
if (pre > 17) pre = 17;
JSONCPP_STRING endingLineFeedSymbol = "";
return new BuiltStyledStreamWriter(
indentation, cs,
colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
}
static void getValidWriterKeys(std::set<JSONCPP_STRING>* valid_keys)
{
valid_keys->clear();
valid_keys->insert("indentation");
valid_keys->insert("commentStyle");
valid_keys->insert("enableYAMLCompatibility");
valid_keys->insert("dropNullPlaceholders");
valid_keys->insert("useSpecialFloats");
valid_keys->insert("precision");
}
bool StreamWriterBuilder::validate(Json::Value* invalid) const
{
Json::Value my_invalid;
if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
Json::Value& inv = *invalid;
std::set<JSONCPP_STRING> valid_keys;
getValidWriterKeys(&valid_keys);
Value::Members keys = settings_.getMemberNames();
size_t n = keys.size();
for (size_t i = 0; i < n; ++i) {
JSONCPP_STRING const& key = keys[i];
if (valid_keys.find(key) == valid_keys.end()) {
inv[key] = settings_[key];
}
}
return 0u == inv.size();
}
Value& StreamWriterBuilder::operator[](JSONCPP_STRING key)
{
return settings_[key];
}
// static
void StreamWriterBuilder::setDefaults(Json::Value* settings)
{
//! [StreamWriterBuilderDefaults]
(*settings)["commentStyle"] = "All";
(*settings)["indentation"] = "\t";
(*settings)["enableYAMLCompatibility"] = false;
(*settings)["dropNullPlaceholders"] = false;
(*settings)["useSpecialFloats"] = false;
(*settings)["precision"] = 17;
//! [StreamWriterBuilderDefaults]
}
JSONCPP_STRING writeString(StreamWriter::Factory const& builder, Value const& root) {
JSONCPP_OSTRINGSTREAM sout;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
return sout.str();
}
JSONCPP_OSTREAM& operator<<(JSONCPP_OSTREAM& sout, Value const& root) {
StreamWriterBuilder builder;
StreamWriterPtr const writer(builder.newStreamWriter());
writer->write(root, &sout);
return sout;
}
} // namespace Json
// //////////////////////////////////////////////////////////////////////
// End of content of file: src/lib_json/json_writer.cpp
// //////////////////////////////////////////////////////////////////////
| mit |
EricSzla/Android-Apps | Weather-App/app/src/main/java/erpam/weatherapp/MainActivity.java | 6061 | package erpam.weatherapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
EditText text;
TextView weatheroutput;
RelativeLayout downloadedImg = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (EditText) findViewById(R.id.cityName);
weatheroutput = (TextView) findViewById(R.id.output);
downloadedImg = (RelativeLayout) findViewById(R.id.mainLayout);
downloadImage(downloadedImg);
}
public void findWeather(View view){
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(text.getWindowToken(),0);
Log.i("City name",text.getText().toString());
try {
weatheroutput.setAlpha(0f);
String encodedCityName = URLEncoder.encode(text.getText().toString(), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName + "&appid=21683d9217a6653a3b9d92111ecb61d4");
weatheroutput.animate().alpha(1f).setDuration(1000);
} catch (UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(),"Could not find the weather", Toast.LENGTH_LONG).show();
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Could not find the weather", Toast.LENGTH_LONG).show();
}
return "Failed";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String weatherinfo = "";
try {
String message = "";
JSONObject jsonObject = new JSONObject(s);
weatherinfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherinfo);
for(int i = 0; i < arr.length(); i++){
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != ""){
message+= main + ": " + description + "\r\n";
}
}
if(message != ""){
weatheroutput.setText(message);
}else{
weatheroutput.setText("");
Toast.makeText(getApplicationContext(),"Could not find the weather", Toast.LENGTH_LONG).show();
}
}catch (JSONException e) {
weatheroutput.setText("");
Toast.makeText(getApplicationContext(),"Could not find the weather", Toast.LENGTH_LONG).show();
}
Log.i("Website content", weatherinfo);
}
}
public class ImageDownloader extends AsyncTask<String,Void,Bitmap>{
@Override
protected Bitmap doInBackground(String... urls) {
try{
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitMap = BitmapFactory.decodeStream(inputStream);
return myBitMap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
public void downloadImage(View view) {
ImageDownloader task = new ImageDownloader();
try {
Bitmap myImage = task.execute("https://images.unsplash.com/photo-1434434319959-1f886517e1fe?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&s=218dfdd2c0735dbd6ca0f718064a748b").get();
Drawable d = new BitmapDrawable(getResources(),myImage);
downloadedImg.setBackground(d);
Log.i("Done","Done");
}catch (Exception e) {
e.printStackTrace();
}
}
}
| mit |
ottohernandezgarzon/tanks-colored-of-war | programar/node_modules/phaser-ce/tasks/options/copy.js | 208 | module.exports = {
custom: {
expand: true,
flatten: true,
cwd: '<%= compile_dir %>/',
src: [ '*.js', '*.map' ],
dest: '<%= target_dir %>/'
}
};
| mit |
emmertf/OpenBlocks | src/main/java/openblocks/common/entity/EntityCartographer.java | 8321 | package openblocks.common.entity;
import com.google.common.collect.ImmutableSet;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Random;
import java.util.Set;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import openblocks.OpenBlocks.Items;
import openblocks.client.renderer.entity.EntitySelectionHandler.ISelectAware;
import openblocks.common.MapDataBuilder;
import openblocks.common.MapDataBuilder.ChunkJob;
import openblocks.common.item.ItemCartographer;
import openblocks.common.item.ItemEmptyMap;
import openblocks.common.item.ItemHeightMap;
import openmods.Log;
import openmods.api.VisibleForDocumentation;
import openmods.sync.ISyncMapProvider;
import openmods.sync.SyncMap;
import openmods.sync.SyncMapEntity;
import openmods.sync.SyncObjectScanner;
import openmods.sync.SyncableBoolean;
import openmods.sync.SyncableInt;
import openmods.sync.SyncableObjectBase;
import openmods.utils.BitSet;
import openmods.utils.ByteUtils;
import openmods.utils.ItemUtils;
@VisibleForDocumentation
public class EntityCartographer extends EntityAssistant implements ISelectAware, ISyncMapProvider {
private static final int MAP_JOB_DELAY = 5;
private static final int MOVE_DELAY = 35;
public static final Random RANDOM = new Random();
@SideOnly(Side.CLIENT)
public float eyeYaw, eyePitch, targetYaw, targetPitch;
public static class MapJobs extends SyncableObjectBase {
private BitSet bits = new BitSet();
private Set<ChunkJob> jobs;
private int size;
public boolean test(int bit) {
return bits.testBit(bit);
}
@Override
public void readFromStream(DataInputStream input) throws IOException {
size = ByteUtils.readVLI(input);
bits.readFromStream(input);
}
@Override
public void writeToStream(DataOutputStream output) throws IOException {
ByteUtils.writeVLI(output, size);
bits.writeToStream(output);
}
@Override
public void writeToNBT(NBTTagCompound tag, String name) {
NBTTagCompound result = new NBTTagCompound();
bits.writeToNBT(result);
tag.setTag(name, result);
}
@Override
public void readFromNBT(NBTTagCompound tag, String name) {
NBTTagCompound info = tag.getCompoundTag(name);
bits.readFromNBT(info);
}
public void runJob(World world, int x, int z) {
if (jobs == null) {
Log.severe("STOP ABUSING CARTOGRAPHER RIGHT NOW! YOU BROKE IT!");
jobs = ImmutableSet.of();
}
ChunkJob job = MapDataBuilder.doNextChunk(world, x, z, jobs);
if (job != null) {
jobs.remove(job);
bits.setBit(job.bitNum);
markDirty();
}
}
public void resumeMapping(World world, int mapId) {
MapDataBuilder builder = new MapDataBuilder(mapId);
builder.loadMap(world);
builder.resizeIfNeeded(bits); // better to lost progress than to break world
size = builder.size();
jobs = builder.createJobs(bits);
markDirty();
}
public void startMapping(World world, int mapId, int x, int z) {
MapDataBuilder builder = new MapDataBuilder(mapId);
builder.resetMap(world, x, z);
builder.resize(bits);
size = builder.size();
jobs = builder.createJobs(bits);
markDirty();
}
public void stopMapping() {
jobs.clear();
bits.resize(0);
size = 0;
markDirty();
}
public int size() {
return size;
}
}
public final SyncableInt scale = new SyncableInt(2);
public final SyncableBoolean isMapping = new SyncableBoolean(false);
public final MapJobs jobs = new MapJobs();
private ItemStack mapItem;
private int mappingDimension;
private int countdownToAction = MAP_JOB_DELAY;
private int countdownToMove = MOVE_DELAY;
private float randomDelta;
private final SyncMapEntity<EntityCartographer> syncMap = new SyncMapEntity<EntityCartographer>(this);
{
SyncObjectScanner.INSTANCE.registerAllFields(syncMap, this);
setSize(0.2f, 0.2f);
}
public EntityCartographer(World world) {
super(world, null);
}
public EntityCartographer(World world, EntityPlayer owner, ItemStack stack) {
super(world, owner);
setSpawnPosition(owner);
NBTTagCompound tag = ItemUtils.getItemTag(stack);
readOwnDataFromNBT(tag);
}
@Override
protected void entityInit() {}
@Override
public void onUpdate() {
if (!worldObj.isRemote) {
float yaw = 0;
if (isMapping.get()) {
if (countdownToMove-- <= 0) {
countdownToMove = MOVE_DELAY;
randomDelta = 2 * (float)Math.PI * RANDOM.nextFloat();
}
yaw = randomDelta;
} else {
EntityPlayer owner = findOwner();
if (owner != null) yaw = (float)Math.toRadians(owner.rotationYaw);
}
ownerOffsetX = MathHelper.sin(-yaw);
ownerOffsetZ = MathHelper.cos(-yaw);
}
super.onUpdate();
if (!worldObj.isRemote) {
if (worldObj.provider.dimensionId == mappingDimension && isMapping.get() && countdownToAction-- <= 0) {
jobs.runJob(worldObj, (int)posX, (int)posZ);
countdownToAction = MAP_JOB_DELAY;
}
syncMap.sync();
}
}
@Override
protected void readEntityFromNBT(NBTTagCompound tag) {
super.readEntityFromNBT(tag);
readOwnDataFromNBT(tag);
}
private void readOwnDataFromNBT(NBTTagCompound tag) {
syncMap.readFromNBT(tag);
if (tag.hasKey("MapItem")) {
NBTTagCompound mapItem = tag.getCompoundTag("MapItem");
this.mapItem = ItemUtils.readStack(mapItem);
if (this.mapItem != null && isMapping.get()) {
int mapId = this.mapItem.getItemDamage();
jobs.resumeMapping(worldObj, mapId);
}
mappingDimension = tag.getInteger("Dimension");
}
}
@Override
protected void writeEntityToNBT(NBTTagCompound tag) {
super.writeEntityToNBT(tag);
writeOwnDataToNBT(tag);
}
private void writeOwnDataToNBT(NBTTagCompound tag) {
syncMap.writeToNBT(tag);
if (mapItem != null) {
NBTTagCompound mapItem = ItemUtils.writeStack(this.mapItem);
tag.setTag("MapItem", mapItem);
tag.setInteger("Dimension", mappingDimension);
}
}
@Override
public ItemStack toItemStack() {
ItemStack result = Items.cartographer.createStack(ItemCartographer.AssistantType.CARTOGRAPHER);
NBTTagCompound tag = ItemUtils.getItemTag(result);
writeOwnDataToNBT(tag);
return result;
}
@Override
public boolean interactFirst(EntityPlayer player) {
if (player instanceof EntityPlayerMP && player.isSneaking() && getDistanceToEntity(player) < 3) {
ItemStack holding = player.getHeldItem();
if (holding == null && mapItem != null) {
player.setCurrentItemOrArmor(0, mapItem);
mapItem = null;
isMapping.toggle();
jobs.stopMapping();
} else if (holding != null && mapItem == null) {
Item itemType = holding.getItem();
if (itemType instanceof ItemHeightMap || itemType instanceof ItemEmptyMap) {
ItemStack inserted = holding.splitStack(1);
if (holding.stackSize <= 0) player.setCurrentItemOrArmor(0, null);
mapItem = inserted;
mappingDimension = worldObj.provider.dimensionId;
isMapping.toggle();
mapItem = MapDataBuilder.upgradeToMap(worldObj, mapItem);
int mapId = mapItem.getItemDamage();
jobs.startMapping(worldObj, mapId, getNewMapCenterX(), getNewMapCenterZ());
}
}
return true;
}
return false;
}
@Override
@SideOnly(Side.CLIENT)
public boolean canRenderOnFire() {
return false;
}
@Override
public boolean canBeCollidedWith() {
return true;
}
@Override
public SyncMap<EntityCartographer> getSyncMap() {
return syncMap;
}
public int getNewMapCenterX() {
return ((int)posX) & ~0x0F;
}
public int getNewMapCenterZ() {
return ((int)posZ) & ~0x0F;
}
@SideOnly(Side.CLIENT)
public void updateEye() {
float diffYaw = (targetYaw - eyeYaw) % (float)Math.PI;
float diffPitch = (targetPitch - eyePitch) % (float)Math.PI;
if (Math.abs(diffYaw) + Math.abs(diffPitch) < 0.0001) {
targetPitch = RANDOM.nextFloat() * 2 * (float)Math.PI;
targetYaw = RANDOM.nextFloat() * 2 * (float)Math.PI;
} else {
// No, it's not supposed to be correct
eyeYaw = eyeYaw - diffYaw / 50.0f; // HERP
eyePitch = eyePitch - diffPitch / 50.0f; // DERP
}
}
}
| mit |
KonstantinFilin/RandData | tests/src/RandData/Set/ParagraphTest.php | 3667 | <?php
namespace RandData\Set;
/**
* Generated by PHPUnit_SkeletonGenerator on 2017-05-29 at 13:14:11.
*/
class ParagraphTest extends \PHPUnit_Framework_TestCase {
/**
* @var Paragraph
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp() {
$this->object = new Paragraph;
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() {
}
/**
* @covers RandData\Set\Paragraph::__construct
* @covers RandData\Set\Paragraph::getWordsMin
* @covers RandData\Set\Paragraph::setWordsMin
*/
public function testGetWordsMin() {
$this->assertEquals(3, $this->object->getWordsMin());
$val1 = 4;
$this->object->setWordsMin($val1);
$this->assertEquals($val1, $this->object->getWordsMin());
}
/**
* @covers RandData\Set\Paragraph::getWordsMax
* @covers RandData\Set\Paragraph::setWordsMax
*/
public function testGetWordsMax() {
$this->assertEquals(100, $this->object->getWordsMax());
$val1 = 60;
$this->object->setWordsMax($val1);
$this->assertEquals($val1, $this->object->getWordsMax());
}
/**
* @covers RandData\Set\Paragraph::__construct
* @covers RandData\Set\Paragraph::get
* @covers RandData\Set\Paragraph::generateLength
*/
public function testGet() {
for ($i = 1; $i <= 10; $i++) {
$paragraph = $this->object->get();
$this->assertNotNull($paragraph);
$this->assertNotEmpty($paragraph);
$this->assertTrue(mb_strlen($paragraph) > 0);
}
$obj2 = new Paragraph(15, 6);
$res2 = $obj2->get();
$this->assertTrue(mb_strlen($res2) > 0);
}
/**
* @covers RandData\Set\Paragraph::init
*/
public function testInit() {
$lenMin1 = 7;
$lenMax1 = 12;
$lenMin2 = 5;
$lenMax2 = 9;
$charList1 = "abcdefghi";
$charList2 = "xyzfs";
$wordsAmountMin1 = 13;
$wordsAmountMax1 = 19;
$wordsAmountMin2 = 16;
$wordsAmountMax2 = 23;
$params1 = [
"length_min" => $lenMin1,
"length_max" => $lenMax1,
"char_list" => $charList1,
"words_min" => $wordsAmountMin1,
"words_max" => $wordsAmountMax1
];
$params2 = [
"length_min" => $lenMin2,
"length_max" => $lenMax2,
"char_list" => $charList2,
"words_min" => $wordsAmountMin2,
"words_max" => $wordsAmountMax2
];
$this->object->init($params1);
$this->assertEquals($lenMin1, $this->object->getLengthMin());
$this->assertEquals($lenMax1, $this->object->getLengthMax());
$this->assertEquals($wordsAmountMin1, $this->object->getWordsMin());
$this->assertEquals($wordsAmountMax1, $this->object->getWordsMax());
$this->assertEquals($charList1, $this->object->getChars());
$this->object->init($params2);
$this->assertEquals($lenMin2, $this->object->getLengthMin());
$this->assertEquals($lenMax2, $this->object->getLengthMax());
$this->assertEquals($wordsAmountMin2, $this->object->getWordsMin());
$this->assertEquals($wordsAmountMax2, $this->object->getWordsMax());
$this->assertEquals($charList2, $this->object->getChars());
}
}
| mit |
notthetup/ical-generator | example/example_toString.js | 403 | var ical = require('../lib/ical-generator.js'),
cal = ical();
cal.setDomain('example.com');
cal.addEvent({
start: new Date(new Date().getTime() + 3600000),
end: new Date(new Date().getTime() + 7200000),
summary: 'Example Event',
description: 'It works ;)',
organizer: {
name: 'Organizer\'s Name',
email: '[email protected]'
},
url: 'http://sebbo.net/'
});
console.log(cal.toString()); | mit |
GTXiee/RosterAdmin | src/controllers/WelcomeTabController.java | 2369 | package controllers;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import datamodel.DialogUtilities;
import datamodel.Datasource;
import datamodel.Roster;
import datamodel.Team;
public class WelcomeTabController {
@FXML
private GridPane mainGridPane;
@FXML
private ComboBox<Roster> rosterComboBox;
@FXML
private Spinner<Integer> spinner;
@FXML
private Button submitButton;
@FXML
private TextField teamNameTextField;
private MainWindowController mainWindowController;
public void initialize() {
rosterComboBox.setItems(Datasource.getInstance().getRosterData());
// prevents naming spaces
teamNameTextField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (newValue.trim().isEmpty()) {
teamNameTextField.setText("");
}
}
});
// change max spinner value depending on roster selected
NewTeamController.setMaxSpinner(spinner, rosterComboBox);
submitButton.disableProperty().bind(
teamNameTextField.textProperty().isEmpty()
.or(rosterComboBox.valueProperty().isNull())
);
}
// shows dialog box for to create new roster
@FXML
public void showNewRosterDialog() {
Roster newRoster = DialogUtilities.showRosterDialog(mainGridPane);
if (newRoster != null) {
Datasource.getInstance().insertRosterFull(newRoster);
rosterComboBox.getSelectionModel().select(newRoster);
}
}
// creates new team & tab
@FXML
public void handleSubmit() {
String teamName = teamNameTextField.getText();
Roster roster = rosterComboBox.getValue();
int startWeek = spinner.getValue();
Team newTeam = new Team(teamName, startWeek, roster);
Datasource.getInstance().insertTeam(newTeam);
mainWindowController.createTeamTab(newTeam);
}
public void setMainWindowController(MainWindowController controller) {
this.mainWindowController = controller;
}
}
| mit |
iamtraviscole/schemer-rails-project | db/migrate/20171005223239_add_color_note_to_color_scheme_colors.rb | 150 | class AddColorNoteToColorSchemeColors < ActiveRecord::Migration[5.1]
def change
add_column :color_scheme_colors, :color_note, :string
end
end
| mit |
Kagami/material-ui | packages/material-ui-icons/src/DialerSipTwoTone.js | 896 | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M15.2 18.21c1.2.41 2.48.67 3.8.75v-1.5c-.88-.06-1.75-.22-2.59-.45l-1.21 1.2zM6.54 5h-1.5c.09 1.32.35 2.59.75 3.79l1.2-1.21c-.24-.83-.39-1.7-.45-2.58z" opacity=".3" /><path d="M16 3h1v5h-1zM12 7v1h3V5h-2V4h2V3h-3v3h2v1zM21 3h-3v5h1V6h2V3zm-1 2h-1V4h1v1z" /><path d="M21 16.5c0-.55-.45-1-1-1-1.25 0-2.45-.2-3.57-.57-.1-.03-.21-.05-.31-.05-.26 0-.51.1-.7.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.27-.26.35-.65.24-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5zM5.03 5h1.5c.07.88.22 1.75.46 2.59L5.79 8.8c-.41-1.21-.67-2.48-.76-3.8zM19 18.97c-1.32-.09-2.59-.35-3.8-.75l1.2-1.2c.85.24 1.71.39 2.59.45v1.5z" /></g></React.Fragment>
, 'DialerSipTwoTone');
| mit |
georgefrick/mafia | src/net/s5games/mafia/beans/scanning/Scanner.java | 16187 | package net.s5games.mafia.beans.scanning;
import java.util.HashMap;
// Public domain, no restrictions, Ian Holyer, University of Bristol.
/**
* <p>A Scanner object provides a lexical analyser and a resulting token array.
* Incremental rescanning is supported, e.g. for use in a token colouring
* editor. This is a base class dealing with plain text, which can be extended
* to support other languages.
*
* <p>The actual text is assumed to be held elsewhere, e.g. in a document. The
* <code>change()</code> method is called to report the position and length of
* a change in the text, and the <code>scan()</code> method is called to
* perform scanning or rescanning. For example, to scan an entire document
* held in a character array <code>text</code> in one go:
*
* <blockquote>
* <pre>
* scanner.change(0, 0, text.length);
* scanner.scan(text, 0, text.length);
* </pre>
* </blockquote>
*
* <p>For incremental scanning, the <code>position()</code> method is used
* to find the text position at which rescanning should start. For example, a
* syntax highlighter might contain this code:
*
* <blockquote>
* <pre>
* // Where to start rehighlighting, and a segment object
* int firstRehighlightToken;
* Segment segment;
*
* ...
*
* // Whenever the text changes, e.g. on an insert or remove or read.
* firstRehighlightToken = scanner.change(offset, oldLength, newLength);
* repaint();
*
* ...
*
* // in repaintComponent
* int offset = scanner.position();
* if (offset < 0) return;
* int tokensToRedo = 0;
* int amount = 100;
* while (tokensToRedo == 0 && offset >= 0)
* {
* int length = doc.getLength() - offset;
* if (length > amount) length = amount;
* try { doc.getText(offset, length, text); }
* catch (BadLocationException e) { return; }
* tokensToRedo = scanner.scan(text.array, text.offset, text.count);
* offset = scanner.position();
* amount = 2*amount;
* }
* for (int i = 0; i < tokensToRedo; i++)
* {
* Token t = scanner.getToken(firstRehighlightToken + i);
* int length = t.symbol.name.length();
* int type = t.symbol.type;
* doc.setCharacterAttributes (t.position, length, styles[type], false);
* }
* firstRehighlightToken += tokensToRedo;
* if (offset >= 0) repaint(2);
* </pre>
* </blockquote>
*
* <p>Note that <code>change</code> can be called at any time, even between
* calls to <code>scan</code>. Only small number of characters are passed to
* <code>scan</code> so that only a small burst of scanning is done, to prevent
* the program's user interface from freezing.
*/
public class Scanner implements TokenTypes
{
/**
* <p>Read one token from the start of the current text buffer, given the
* start offset, end offset, and current scanner state. The method moves
* the start offset past the token, updates the scanner state, and returns
* the type of the token just scanned.
*
* <p>The scanner state is a representative token type. It is either the
* state left after the last call to read, or the type of the old token at
* the same position if rescanning, or WHITESPACE if at the start of a
* document. The method succeeds in all cases, returning whitespace or
* comment or error tokens where necessary. Each line of a multi-line
* comment is treated as a separate token, to improve incremental
* rescanning. If the buffer does not extend to the end of the document,
* the last token returned for the buffer may be incomplete and the caller
* must rescan it. The read method can be overridden to implement
* different languages. The default version splits plain text into words,
* numbers and punctuation.
*/
protected int read()
{
char c = buffer[start];
int type;
// Ignore the state, since there is only one.
if (Character.isWhitespace(c))
{
type = WHITESPACE;
while (++start < end)
{
if (!Character.isWhitespace(buffer[start]))
break;
}
}
else if (Character.isLetter(c))
{
type = WORD;
while (++start < end)
{
c = buffer[start];
if (Character.isLetter(c) || Character.isDigit(c))
continue;
if (c == '-' || c == '\'' || c == '_')
continue;
break;
}
}
else if (Character.isDigit(c))
{
type = NUMBER;
while (++start < end)
{
c = buffer[start];
if (!Character.isDigit(c) && c != '.')
break;
}
}
else if (c >= '!' || c <= '~')
{
type = PUNCTUATION;
start++;
}
else
{
type = UNRECOGNIZED;
start++;
}
// state = WHITESPACE;
return type;
}
/**
* The current buffer of text being scanned.
*/
protected char[] buffer;
/**
* The current offset within the buffer, at which to scan the next token.
*/
protected int start;
/**
* The end offset in the buffer.
*/
protected int end;
/**
* The current scanner state, as a representative token type.
*/
protected int state = WHITESPACE;
// The array of tokens forms a gap buffer. The total length of the text is
// tracked, and tokens after the gap have (negative) positions relative to
// the end of the text. While scanning, the gap represents the area to be
// scanned, no tokens after the gap can be taken as valid, and in
// particular the end-of-text sentinel token is after the gap.
private Token[] tokens;
private int gap, endgap, textLength;
private boolean scanning;
private int position;
/**
* The symbol table can be accessed by <code>initSymbolTable</code> or
* <code>lookup</code>, if they are overridden. Symbols are inserted with
* <code>symbolTable.put(sym,sym)</code> and extracted with
* <code>symbolTable.get(sym)</code>.
*/
protected HashMap symbolTable;
/**
* Create a new Scanner representing an empty text document. For
* non-incremental scanning, use change() to report the document size, then
* pass the entire text to the scan() method in one go, or if coming from
* an input stream, a bufferful at a time.
*/
Scanner()
{
tokens = new Token[1];
gap = 0;
endgap = 0;
textLength = 0;
symbolTable = new HashMap();
initSymbolTable();
Symbol endOfText = new Symbol(WHITESPACE, "");
tokens[0] = new Token(endOfText, 0);
scanning = false;
position = 0;
}
// Move the gap to a new index within the tokens array. When preparing to
// pass a token back to a caller, this is used to ensure that the token's
// position is relative to the start of the text and not the end.
private void moveGap(int newgap)
{
if (scanning)
throw new Error("moveGap called while scanning");
if (newgap < 0 || newgap > gap + tokens.length - endgap)
{
throw new Error("bad argument to moveGap");
}
if (gap < newgap)
{
while (gap < newgap)
{
tokens[endgap].position += textLength;
tokens[gap++] = tokens[endgap++];
}
}
else if (gap > newgap)
{
while (gap > newgap)
{
tokens[--endgap] = tokens[--gap];
tokens[endgap].position -= textLength;
}
}
}
/**
* Find the number of available valid tokens, not counting tokens in or
* after any area yet to be rescanned.
*/
public int size()
{
if (scanning)
return gap;
else
return gap + tokens.length - endgap;
}
/**
* Find the n'th token, or null if it is not currently valid.
*/
public Token getToken(int n)
{
if (n < 0 || n >= gap && scanning)
return null;
if (n >= gap)
moveGap(n + 1);
return tokens[n];
}
/**
* Find the index of the valid token starting before, but nearest to, text
* position p. This uses an O(log(n)) binary chop search.
*/
public int find(int p)
{
int start = 0, end, mid, midpos;
if (!scanning)
moveGap(gap + tokens.length - endgap);
end = gap - 1;
if (p > tokens[end].position)
return end;
while (end > start + 1)
{
mid = (start + end) / 2;
midpos = tokens[mid].position;
if (p > midpos)
{
start = mid;
}
else
{
end = mid;
}
}
return start;
}
/**
* Report the position of an edit, the length of the text being replaced,
* and the length of the replacement text, to prepare for rescanning. The
* call returns the index of the token at which rescanning will start.
*/
public int change(int start, int len, int newLen)
{
if (start < 0 || len < 0 || newLen < 0 || start + len > textLength)
{
throw new Error("change(" + start + "," + len + "," + newLen + ")");
}
textLength += newLen - len;
int end = start + newLen;
if (scanning)
{
while (gap > 0 && tokens[gap - 1].position > start)
gap--;
if (gap > 0)
gap--;
if (gap > 0)
{
gap--;
position = tokens[gap].position;
state = tokens[gap].symbol.type;
}
else
{
position = 0;
state = WHITESPACE;
}
while (tokens[endgap].position + textLength < end)
endgap++;
return gap;
}
if (endgap == tokens.length)
moveGap(gap - 1);
scanning = true;
while (tokens[endgap].position + textLength < start)
{
tokens[endgap].position += textLength;
tokens[gap++] = tokens[endgap++];
}
while (gap > 0 && tokens[gap - 1].position > start)
{
tokens[--endgap] = tokens[--gap];
tokens[endgap].position -= textLength;
}
if (gap > 0)
gap--;
if (gap > 0)
{
gap--;
position = tokens[gap].position;
state = tokens[gap].symbol.type;
}
else
{
position = 0;
state = WHITESPACE;
}
while (tokens[endgap].position + textLength < end)
endgap++;
return gap;
}
/**
* Find out at what text position any remaining scanning work should
* start, or -1 if scanning is complete.
*/
public int position()
{
if (!scanning)
return -1;
else
return position;
}
/**
* Create the initial symbol table. This can be overridden to enter
* keywords, for example. The default implementation does nothing.
*/
protected void initSymbolTable()
{
}
// Reuse this symbol object to create each new symbol, then look it up in
// the symbol table, to replace it by a shared version to minimize space.
private Symbol symbol = new Symbol(0, null);
/**
* Lookup a symbol in the symbol table. This can be overridden to implement
* keyword detection, for example. The default implementation just uses the
* table to ensure that there is only one shared occurrence of each symbol.
*/
protected Symbol lookup(int type, String name)
{
symbol.type = type;
symbol.name = name;
Symbol sym = (Symbol) symbolTable.get(symbol);
if (sym != null)
return sym;
sym = new Symbol(type, name);
symbolTable.put(sym, sym);
return sym;
}
/**
* Scan or rescan a given read-only segment of text. The segment is assumed
* to represent a portion of the document starting at
* <code>position()</code>. Return the number of tokens successfully
* scanned, excluding any partial token at the end of the text segment but
* not at the end of the document. If the result is 0, the call should be
* retried with a longer segment.
*/
public int scan(char[] array, int offset, int length)
{
if (!scanning)
throw new Error("scan called when not scanning");
if (position + length > textLength)
throw new Error("scan too much");
boolean all = position + length == textLength;
end = start + length;
int startGap = gap;
buffer = array;
start = offset;
end = start + length;
while (start < end)
{
int tokenStart = start;
int type = read();
if (start == end && !all)
break;
if (type != WHITESPACE)
{
String name =
new String(buffer, tokenStart, start - tokenStart);
Symbol sym = lookup(type, name);
Token t = new Token(sym, position);
if (gap >= endgap)
checkCapacity(gap + tokens.length - endgap + 1);
tokens[gap++] = t;
}
// Try to synchronise
while (tokens[endgap].position + textLength < position)
endgap++;
if (position + start - tokenStart == textLength)
scanning = false;
else if (
gap > 0
&& tokens[endgap].position + textLength == position
&& tokens[endgap].symbol.type == type)
{
endgap++;
scanning = false;
break;
}
position += start - tokenStart;
}
checkCapacity(gap + tokens.length - endgap);
return gap - startGap;
}
// Change the size of the gap buffer, doubling it if it fills up, and
// halving if it becomes less than a quarter full.
private void checkCapacity(int capacity)
{
int oldCapacity = tokens.length;
if (capacity <= oldCapacity && 4 * capacity >= oldCapacity)
return;
Token[] oldTokens = tokens;
int newCapacity;
if (capacity > oldCapacity)
{
newCapacity = oldCapacity * 2;
if (newCapacity < capacity)
newCapacity = capacity;
}
else
newCapacity = capacity * 2;
tokens = new Token[newCapacity];
System.arraycopy(oldTokens, 0, tokens, 0, gap);
int n = oldCapacity - endgap;
System.arraycopy(oldTokens, endgap, tokens, newCapacity - n, n);
endgap = newCapacity - n;
}
void print()
{
for (int i = 0; i < tokens.length; i++)
{
if (i >= gap && i < endgap)
continue;
if (i == endgap)
System.out.print("... ");
System.out.print("" + i + ":" + tokens[i].position);
System.out.print(
"-" + (tokens[i].position + tokens[i].symbol.name.length()));
System.out.print(" ");
}
System.out.println();
}
} | mit |
levibostian/VSAS | kristenTesting/PreviousRecordingsScreen.py | 4756 | """
Previous Recordings Screen
Author: Kristen Nielsen
Email: [email protected]
Patterned after tkSimpleDialog
This is called by the main screen and calls the screen that lists out the previous events
"""
from Tkinter import *
import tkMessageBox as MsgBox
from PreviousRecordingsListScreen import PreviousRecordingsListScreen
from datetime import date
class PreviousRecordingsScreen(Toplevel):
def __init__(self,parent):
Toplevel.__init__(self,parent,height=400,width=400)
self.transient(parent)
self.title("VSAS - View Previous Recordings")
self._parent = parent
body = Frame(self)
self._initialFocus = self.body(body)
body.pack(padx=5,pady=5)
self.buttonbox()
self.grab_set()
self.bind("<F1>",self.displayHelp)
if not self._initialFocus:
self._initialFocus = self
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
parent.winfo_rooty()+50))
self._initialFocus.focus_set()
self._parent.wait_window(self)
def body(self, master):
self.result = None
self._today = date.today()
MODE =[("One Week", "week"),
("One Month", "month"),
("One Year", "year")]
self._variable = StringVar()
self._variable.set("week")
radioButtonList = []
for text, mode in MODE:
b = Radiobutton(self, text = text, variable=self._variable,
value=mode, indicatoron=0)
b.pack(anchor=W,padx=2,pady=2)
radioButtonList.append(b)
return radioButtonList[0]
def buttonbox(self):
# add standard button box.
box = Frame(self)
w = Button(box, text="OK", width=10, command = self.ok,
default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text="Help", width=10, command=self.displayHelp)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text="Cancel",width=10,command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.cancel)
box.pack()
def validate(self):
if self._variable != None:
return 1
else:
MsgBox.showwarning(
"Invalid choice",
"Please make a selection")
return 0
def calculateDate(self):
monthDict = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31,
8:31, 9:30, 10:31, 11:30, 12:31}
newDay = self._today.day
newMonth = self._today.month
newYear = self._today.year
if self._variable.get() == "week":
newDay -= 7
if newDay <= 0:
newMonth -= 1
if newMonth == 0:
newMonth = 12
newYear -= 1
newDay = monthDict[newMonth] + newDay
elif self._variable.get() == "month":
newMonth -= 1
if newMonth == 0:
newMonth = 12
newYear -= 1
else:
newYear -= 1
self.result = str(date(newYear,newMonth,newDay))
def displayHelp(self, event=None):
helpText = open("PreviousRecordingsHelp.txt","r").read()
MsgBox.showinfo(title="VSAS Previous Events - Help", message=helpText)
def ok(self, event=None):
if not self.validate():
self.initial_focus.focus_set() # put focus back
return
self.withdraw()
self.update_idletasks()
self.apply()
self.cancel()
def apply(self):
self.calculateDate()
previousRecordingsList = open("testPreviousRecordings.txt","r").readlines() # change filename when before actual file is created
listOfEvents = []
for item in previousRecordingsList:
index = previousRecordingsList.index(item)
item = item[ :-1].split(",")
dateOfInterest=item[0]
if (dateOfInterest[0:10] >= self.result and
dateOfInterest[0:10] <= str(self._today)):
listOfEvents.append(item)
if len(listOfEvents) == 0:
MsgBox.showinfo("No Events",
"There are currently no events to show for this time period.")
else:
PreviousRecordingsListScreen(self._parent, listOfEvents, self._variable.get())
def cancel(self, event = None):
self._parent.focus_set()
self.destroy()
| mit |
ogawatti/gcevent | lib/google/service_account.rb | 627 | module Google
class ServiceAccount
SCOPE = 'https://www.googleapis.com/auth/calendar'
attr_reader :auth_uri, :token_uri
attr_reader :client_id, :client_email
attr_reader :auth_provider_x509_cert_url, :client_x509_cert_url
attr_reader :project_id
attr_reader :scope
def initialize(secret_path, email)
JSON.parse(File.read(secret_path)).each do |key, secret|
secret.each do |k, v|
instance_varialbe_name = "@#{k}".to_sym
instance_variable_set(instance_varialbe_name, v)
end
end
@client_email ||= email
@scope = SCOPE
end
end
end
| mit |
oliwierptak/Everon-Example-Mvc | Module/Auth/View/Error.php | 340 | <?php
namespace Everon\Module\Auth\View;
use Everon\View;
use Everon\Dependency;
use Everon\View as DefaultView;
class Error extends DefaultView
{
public function show()
{
$this->set('error', 'the error message');
}
public function test()
{
$this->set('View.Body', 'no template: test error');
}
}
| mit |
gameknife/electron-shadermonki | lib/gk-component.js | 9519 | /**
* Created by kaimingyi on 2016/11/18.
*/
const math = require("gl-matrix");
const mathext = require('./util/gl-matrix-extension.js');
const gkCore = window.gkCore;
class Component {
constructor() {
this._host = null;
}
get host()
{
return this._host;
}
set host( target )
{
this._host = target;
this.onStart();
}
onStart() {
}
onUpdate() {
//console.info( this );
}
onRender() {
}
}
class Transform extends Component {
constructor() {
super();
this._position = math.vec3.fromValues(0,0,0);
this._rotation = math.quat.identity(math.quat.create());
this._scale = math.vec3.fromValues(1,1,1);
this._dirty = true;
this._localToWorldMatrx = math.mat4.identity(math.mat4.create());
this._parent = null;
this.children = new Set();
this._worldposition = math.vec3.create();
this._worldrotation = math.quat.create();
}
_markDirty()
{
this._dirtyComp = true;
this._dirty = true;
// all children mark dirty
this.children.forEach( child => {
child._markDirty();
} );
}
get parent()
{
return this._parent;
}
set parent( target )
{
// detach
if(this._parent !== null) {
this._parent._removeChild(this);
}
this._parent = target;
if( target instanceof Transform)
{
// attach
this._parent._addChild(this);
}
this._markDirty();
}
_addChild( target )
{
this.children.add( target );
}
_removeChild( target )
{
if(this.children.has( target )) {
this.children.delete(target);
}
}
CheckCompDirty() {
if (this._dirtyComp === true) {
if(this._parent !== null)
{
this._worldposition = math.vec3.add(math.vec3.create(), this._parent.position, math.vec3.transformQuat(
math.vec3.create(), this.localPosition, this._parent.rotation));
this._worldrotation = math.quat.mul(math.quat.create(), this._parent.rotation, this.localRotation);
}
else
{
this._worldposition = this.localPosition;
this._worldrotation = this.localRotation;
}
this._dirtyComp = false;
}
}
get position() {
if( this._parent === null )
{
return this._position;
}
this.CheckCompDirty();
return this._worldposition;
}
get rotation() {
if( this._parent === null )
{
return this._rotation;
}
this.CheckCompDirty();
return this._worldrotation;
}
set position(value) {
this._worldposition = value;
if( this._parent !== null)
{
let distance = math.vec3.sub(math.vec3.create(), this._worldposition, this._parent.position);
let invRotParent = math.quat.invert( math.quat.create(), this._parent.rotation );
this.localPosition = math.vec3.transformQuat( math.vec3.create(), distance, invRotParent );
}
else
{
this.localPosition = this._worldposition;
}
}
set rotation(value) {
this._worldrotation = value;
if( this._parent !== null) {
let invRotParent = math.quat.invert(math.quat.create(), this._parent.rotation);
this.localRotation = math.quat.mul(math.quat.create(), invRotParent, this._worldrotation);
}
else
{
this.localRotation = this._worldrotation;
}
}
// native propery setter/getter
get localPosition() {
return this._position;
}
set localPosition(value) {
this._markDirty();
this._position = value;
}
get localRotation() {
return this._rotation;
}
set localRotation(value) {
this._markDirty();
this._rotation = value;
}
get localScale() {
return this._scale;
}
set localScale(value) {
this._markDirty();
this._scale = value;
}
// matrix access
get localToWorldMatrix() {
if(this._dirty)
{
this._dirty = false;
let childmatrix = math.mat4.fromRotationTranslationScale(math.mat4.create(), this._rotation, this._position, this._scale );
if(this._parent !== null)
{
this._localToWorldMatrx = math.mat4.mul( this._localToWorldMatrx, this._parent.localToWorldMatrix, childmatrix );
}
else
{
this._localToWorldMatrx = childmatrix;
}
}
return this._localToWorldMatrx;
}
get forward() {
// TODO
return math.vec3.transformQuat(math.vec3.create(), math.vec3.fromValues(0,0,1), this.rotation );
}
get up() {
// TODO
return math.vec3.transformQuat(math.vec3.create(), math.vec3.fromValues(0,1,0), this.rotation );
}
get left() {
// TODO
return math.vec3.transformQuat(math.vec3.create(), math.vec3.fromValues(1,0,0), this.rotation );
}
// other method
lookAt( target ) {
// rebuild the quat axes with forward and up
let forward = math.vec3.sub(math.vec3.create(), target, this.position);
forward = math.vec3.normalize(forward, forward);
let up = math.vec3.fromValues(0,1,0);
let left = math.vec3.cross(math.vec3.create(), up, forward );
left = math.vec3.normalize(left,left);
up = math.vec3.cross(math.vec3.create(), forward, left );
up = math.vec3.normalize(up, up);
let matr = math.mat3.create();
matr[0] = -left[0];
matr[1] = -left[1];
matr[2] = -left[2];
matr[3] = up[0];
matr[4] = up[1];
matr[5] = up[2];
matr[6] = -forward[0];
matr[7] = -forward[1];
matr[8] = -forward[2];
this.rotation = math.quat.fromMat3(math.quat.create(), matr);
}
/**
* Transforms in localspace
*
* @param {vec3} vector
*/
translateLocal( vec ) {
let trans = math.vec3.transformQuat( math.vec3.create(), vec, this.localRotation );
this.localPosition = math.vec3.add( this.localPosition, this.localPosition, trans );
}
/**
* Transforms in worldspace
*
* @param {vec3} vector
*/
translateWorld( vec ) {
let trans = math.vec3.transformQuat( math.vec3.create(), vec, this.rotation );
this.position = math.vec3.add( math.vec3.create(), this.position, trans );
}
getComponent( comp ) {
let returnArray = [];
let component = this.host.components.get( comp );
if(component)
{
returnArray.push(component);
}
this.children.forEach( child => {
returnArray = returnArray.concat( child.getComponent( comp ) );
});
return returnArray;
}
onStart() {
this.host.transform = this;
}
}
class MeshFilter extends Component {
constructor() {
super();
this._mesh = null;
this._aabb = mathext.aabb.create();
}
set mesh(value) {
this._mesh = value;
// for each vertice in mesh
// compare with _lbb & _rtf
let vbo = this._mesh.vboForReadback;
let size = this._mesh.vertexSize / 4;
let vertCount = vbo.length / size ;
//console.log(vbo.length + ' / ' + size);
for( let i=0; i < vertCount; ++i) {
let position = math.vec3.fromValues(this._mesh.vboForReadback[i * size + 0], this._mesh.vboForReadback[i * size + 1], this._mesh.vboForReadback[i * size + 2]);
mathext.aabb.addPoint( this._aabb, position);
}
// complete
}
get mesh() {
return this._mesh;
}
}
class MeshRenderer extends Component {
constructor() {
super();
this.material = null;
}
get bounds() {
let mf = this.host.components.get(MeshFilter);
// transform mesh bounds to world,
let tmpaabb = mathext.aabb.create();
mathext.aabb.mergeOBB( tmpaabb, mf._aabb, this.host.transform.localToWorldMatrix );
// return the new bounds
return tmpaabb;
}
}
class Camera extends Component {
constructor() {
super();
}
onUpdate() {
super.onUpdate();
}
onRender() {
// prepare render queue
let queue = gkCore.renderer.getOrCreateRenderQueue(0);
// send per queue parameter set to queue
queue.setupCamera( this );
// push target mr to renderqueue
let mrs = gkCore.sceneMgr.getMeshRenderers();
mrs.forEach( mr => {
// doing culling here
queue.addRenderer( mr );
});
}
}
class Light extends Component {
constructor() {
super();
this.intensity = 1.0;
}
onUpdate() {
super.onUpdate();
}
onRender() {
// TODO: add to everyqueue
// prepare render queue
let queue = gkCore.renderer.getOrCreateRenderQueue(0);
// send per queue parameter set to queue
queue.setupLight( this );
}
}
module.exports = {Component, Transform, MeshFilter, MeshRenderer, Camera, Light};
| mit |
Iran/CnCMemoryWatchTool | Properties/Resources.Designer.cs | 2795 | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CnCMemoryWatchTool.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("CnCMemoryWatchTool.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| mit |
mleczek/cbuilder | src/Dependency/Resolver.php | 4653 | <?php
namespace Mleczek\CBuilder\Dependency;
use Mleczek\CBuilder\Dependency\Entities\Factory;
use Mleczek\CBuilder\Package\Package;
use Mleczek\CBuilder\Package\Remote;
use Mleczek\CBuilder\Repository\Collection;
use Mleczek\CBuilder\Repository\Exceptions\PackageNotFoundException;
use Mleczek\CBuilder\Repository\Factory as RepositoriesFactory;
use Mleczek\CBuilder\Dependency\Entities\Factory as TreeNodeFactory;
/**
* Resolve dependencies tree from cbuilder.json file
* (include nested dependencies with loops detection).
*
* Repositories defined in the cbuilder.json file are skipped for the dependencies.
* This prevents packages names conflicts, realize the situation when A has 2 dependencies:
* B and C, the B also has the C dependency (but due to the specific repositories definition
* the C package is resolved from the other repository).
*
* There are 2 major use cases of the repositories:
* - to register private repository shared between all company packages,
* - and to improve development process experience.
*/
class Resolver
{
/**
* Dependencies tree.
*
* @var object[] Each object contains remote, constraints and dependencies key.
*/
private $tree = [];
/**
* Dependencies list.
*
* @var object[] Package name (key) with object (value) containing remote and constraints key.
*/
private $list = [];
/**
* @var RepositoriesFactory
*/
private $repositoriesFactory;
/**
* @var TreeNodeFactory
*/
private $treeNodeFactory;
/**
* Repositories for the latest resolved package.
*
* @var Collection
*/
private $repositories;
/**
* Resolver constructor.
*
* @param RepositoriesFactory $repositoriesFactory
* @param TreeNodeFactory $treeNodeFactory
*/
public function __construct(RepositoriesFactory $repositoriesFactory, TreeNodeFactory $treeNodeFactory)
{
$this->repositoriesFactory = $repositoriesFactory;
$this->treeNodeFactory = $treeNodeFactory;
}
/**
* Get dependencies tree.
*
* @return object[] Each object contains remote, constraints and dependencies key.
*/
public function getTree()
{
return $this->tree;
}
/**
* Get dependencies list.
*
* @return object[] Each object contains remote and constraints key.
*/
public function getList()
{
return $this->list;
}
/**
* @param Package $package
* @return $this
* @throws PackageNotFoundException
*/
public function resolve(Package $package)
{
// Get repositories only for this package
// in which dependencies will be searched.
$plainRepositories = $package->getRepositories();
$this->repositories = $this->repositoriesFactory->hydrate($plainRepositories);
// For root package always get all
// dependencies including dev ones.
$dependencies = array_merge(
$package->getDependencies(),
$package->getDevDependencies()
);
// Register each dependency in tree and list.
foreach ($dependencies as $dependency) {
$remote = $this->repositories->find($dependency->name);
$this->registerTree($remote, $dependency->version);
$this->registerList($remote, $dependency->version);
}
return $this;
}
/**
* @param Remote $dependency
* @param string $constraint
* @see $list
*/
private function registerList(Remote $dependency, $constraint)
{
$packageName = $dependency->getPackage()->getName();
// Initialize new dependency in the list.
if (!isset($this->list[$packageName])) {
$this->list[$packageName] = (object)[
'remote' => $dependency,
'constraints' => [],
];
}
// Add new constraints.
$entry = $this->list[$packageName];
$entry->constraints[] = $constraint;
// Register nested dependencies.
$dependencies = $dependency->getPackage()->getDependencies();
foreach ($dependencies as $dependency) {
$remote = $this->repositories->find($dependency->name);
$this->registerList($remote, $dependency->version);
}
}
/**
* @param Remote $dependency
* @param string $constraint
* @see $tree
*/
private function registerTree(Remote $dependency, $constraint)
{
$this->tree[] = $this->treeNodeFactory->makeTreeNode($this->repositories, null, $dependency, $constraint);
}
}
| mit |
whoGloo/nodespeed | test/fixtures/simple-integration-app/sdk/services/custom/Patient.ts | 13425 | /* tslint:disable */
import { Injectable, Inject, Optional } from '@angular/core';
import { Http, Response } from '@angular/http';
import { SDKModels } from './SDKModels';
import { BaseLoopBackApi } from '../core/base.service';
import { LoopBackConfig } from '../../lb.config';
import { LoopBackAuth } from '../core/auth.service';
import { LoopBackFilter, } from '../../models/BaseModels';
import { JSONSearchParams } from '../core/search.params';
import { ErrorHandler } from '../core/error.service';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Rx';
import { Patient } from '../../models/Patient';
import { Physician } from '../../models/Physician';
/**
* Api services for the `Patient` model.
*/
@Injectable()
export class PatientApi extends BaseLoopBackApi {
constructor(
@Inject(Http) protected http: Http,
@Inject(SDKModels) protected models: SDKModels,
@Inject(LoopBackAuth) protected auth: LoopBackAuth,
@Inject(JSONSearchParams) protected searchParams: JSONSearchParams,
@Optional() @Inject(ErrorHandler) protected errorHandler: ErrorHandler
) {
super(http, models, auth, searchParams, errorHandler);
}
/**
* Find a related item by id for physicians.
*
* @param {any} id patient id
*
* @param {any} fk Foreign key for physicians
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public findByIdPhysicians(id: any, fk: any): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Delete a related item by id for physicians.
*
* @param {any} id patient id
*
* @param {any} fk Foreign key for physicians
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public destroyByIdPhysicians(id: any, fk: any): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Update a related item by id for physicians.
*
* @param {any} id patient id
*
* @param {any} fk Foreign key for physicians
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public updateByIdPhysicians(id: any, fk: any, data: any = {}): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Add a related item by id for physicians.
*
* @param {any} id patient id
*
* @param {any} fk Foreign key for physicians
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public linkPhysicians(id: any, fk: any, data: any = {}): Observable<any> {
let _method: string = "PUT";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/rel/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Remove the physicians relation to an item by id.
*
* @param {any} id patient id
*
* @param {any} fk Foreign key for physicians
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public unlinkPhysicians(id: any, fk: any): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/rel/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Check the existence of physicians relation to an item by id.
*
* @param {any} id patient id
*
* @param {any} fk Foreign key for physicians
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public existsPhysicians(id: any, fk: any): Observable<any> {
let _method: string = "HEAD";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/rel/:fk";
let _routeParams: any = {
id: id,
fk: fk
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Queries physicians of patient.
*
* @param {any} id patient id
*
* @param {object} filter
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public getPhysicians(id: any, filter: LoopBackFilter = {}): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (filter) _urlParams.filter = filter;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Creates a new instance in physicians of this model.
*
* @param {any} id patient id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public createPhysicians(id: any, data: any = {}): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Deletes all physicians of this model.
*
* @param {any} id patient id
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* This method returns no data.
*/
public deletePhysicians(id: any): Observable<any> {
let _method: string = "DELETE";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Counts physicians of patient.
*
* @param {any} id patient id
*
* @param {object} where Criteria to match model instances
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* Data properties:
*
* - `count` – `{number}` -
*/
public countPhysicians(id: any, where: any = {}): Observable<any> {
let _method: string = "GET";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians/count";
let _routeParams: any = {
id: id
};
let _postBody: any = {};
let _urlParams: any = {};
if (where) _urlParams.where = where;
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Patch an existing model instance or insert a new one into the data source.
*
* @param {object} data Request data.
*
* - `data` – `{object}` - Model instance data
*
* - `options` – `{object}` -
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public patchOrCreate(data: any = {}, options: any = {}): Observable<any> {
let _method: string = "PATCH";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients";
let _routeParams: any = {};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Patch attributes for a model instance and persist it into the data source.
*
* @param {any} id patient id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public patchAttributes(id: any, data: any = {}): Observable<any> {
let _method: string = "PATCH";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* Creates a new instance in physicians of this model.
*
* @param {any} id patient id
*
* @param {object} data Request data.
*
* This method expects a subset of model properties as request parameters.
*
* @returns {object[]} An empty reference that will be
* populated with the actual data once the response is returned
* from the server.
*
* <em>
* (The remote method definition does not provide any description.
* This usually means the response is a `Patient` object.)
* </em>
*/
public createManyPhysicians(id: any, data: any[] = []): Observable<any> {
let _method: string = "POST";
let _url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() +
"/patients/:id/physicians";
let _routeParams: any = {
id: id
};
let _postBody: any = {
data: data
};
let _urlParams: any = {};
let result = this.request(_method, _url, _routeParams, _urlParams, _postBody);
return result;
}
/**
* The name of the model represented by this $resource,
* i.e. `Patient`.
*/
public getModelName() {
return "Patient";
}
}
| mit |
bigmountainideas/socializr | lib/providers/facebook.js | 6071 | var debug = require('debug')('socializr:provider:facebook')
, stream = require('stream')
, util = require('util')
, request = require('superagent')
, uuid = require('node-uuid')
, _ = require('underscore')
, oauth1a = require('../auth/oauth1a')
, PubSubConnection = require('../auth/pubsub')
, Message = require('../message')
, Transform = stream.Transform
, FB_GRAPH_URL = 'https://graph.facebook.com/v2.2/'
, FB_DEFAULT_PAGE_SUBSCRIBED_FIELDS = [
'feed'
]
;
function Facebook(options){
options = _.extend({
filters: []
},options);
Transform.call(this, {
objectMode: true
});
this.appId = options.appId;
this.appSecret = options.appSecret;
this.appAccessToken = this.getApplicationToken();
this.subscriptionCallbackURL = options.subscriptionCallbackURL;
this.pubsub = options.pubsub || new PubSubConnection( this.appSecret, this);
this.uuid = uuid.v1();
this._filters = options.filters || [];
this._pages = [];
};
util.inherits(Facebook, Transform);
Facebook.prototype.stream = function(request, auth, socializr){
if( !this._piped){
this._piped = true;
this.pubsub
.pipe( this)
.pipe( socializr);
this.on('warning', socializr._onError.bind(socializr));
var data, i;
this._pages = this._pages.concat( request.pages);
for( i=0; i<request.pages.length; i++){
data = request.pages[i];
debug('Subscribing to [ %s ]',data.name);
this.subscribeTo( data.page, data.access_token, function(res){
debug('Subscription responded %s',res.error||res.text);
});
}
}
return this;
};
Facebook.prototype.unstream = function(request, auth, socializr){
return this;
};
Facebook.prototype.auth = function(auth){
auth._provider = this;
return auth;
};
Facebook.prototype.getApplicationToken = function(cb){
if( cb){
this._graphRequest( 'oauth/access_token', 'GET', {
client_id: this.appId,
client_secret: this.appSecret,
grant_type: 'client_credentials'
}, function(res){
cb&&cb(res);
});
}
return [
this.appId,
this.appSecret
].join('|');
};
Facebook.prototype.getTokenInfo = function(token, cb){
this._graphRequest( 'debug_token', 'GET', {
input_token: token,
access_token: this.appAccessToken
}, function(res){
cb&&cb(res);
});
};
Facebook.prototype.exchangeToken = function(token, cb){
this._graphRequest( 'oauth/access_token', 'GET', {
grant_type: 'fb_exchange_token',
client_id: this.appId,
client_secret: this.appSecret,
fb_exchange_token: token
}, function(res){
cb&&cb(res);
});
};
Facebook.prototype.subscribeTo = function(id,token,cb){
this._graphRequest( id + '/subscribed_apps', 'POST', {
access_token: token
},function(res){
cb&&cb(res);
});
};
Facebook.prototype.unsubscribe = function(id,token,cb){
this._graphRequest( id + '/subscribed_apps', 'DELETE', {
access_token: token
},function(res){
cb&&cb(res);
});
};
Facebook.prototype.subscribe = function(type,cb){
this.subscribedFields = FB_DEFAULT_PAGE_SUBSCRIBED_FIELDS;
var verify_token = this.pubsub.verifyToken();
this._graphRequest( this.appId + '/subscriptions', 'POST', {
object: type || 'page',
callback_url: this.subscriptionCallbackURL,
fields: this.subscribedFields.join(','),
verify_token: verify_token,
access_token: this.appAccessToken
},function(res){
cb&&cb(res);
});
};
Facebook.prototype.getUserAccounts = function(user, token, cb){
this._graphRequest( user + '/accounts', 'GET', {
access_token: token
}, function(res){
cb&&cb(res);
});
};
Facebook.prototype.install = function(pageId, token, cb){
this._graphRequest( pageId + '/tabs', 'POST', {
app_id: this.appId,
access_token: token
}, function(res){
cb&&cb(res);
});
};
Facebook.prototype.uninstall = function(pageId, token, cb){
var self = this;
this._graphRequest( pageId + '/tabs/app_' + this.appId, 'DELETE', {
access_token: token
}, function(res){
cb&&cb(res);
});
};
Facebook.prototype._transform = function(chunk, encoding, done){
var expected = 0
, stream = this
;
for( var i in chunk.entry){
for( var j in chunk.entry[i].changes){
expected++;
this._graphRequest( chunk.entry[i].changes[j].value.post_id, 'GET', {}, function(res){
expected--;
if( res.error){
debug('Error requesting data. Server responded %s', res.error);
}else{
try {
var data = JSON.parse(res.text);
}catch(err){
debug('Error parsing chunk. Parser threw error %j',err);
}
if( data && stream.include(data)) {
stream.push(
new Message( stream, data )
);
}
}
if( !expected){
done();
}
})
}
}
};
Facebook.prototype.include = function(data){
if(this._filters){
var pass = true;
this._filters.forEach( function(cb){
if( !cb(data)){
pass = false;
return false;
}
});
return pass;
}
return true;
};
Facebook.prototype._graphRequest = function(endpoint, method, data, cb){
var url = FB_GRAPH_URL + endpoint
, req
;
if( !data.hasOwnProperty('access_token')){
data.access_token = this.appAccessToken;
}
switch( method.toUpperCase()){
case 'GET':
req = request.get(url)
.query(data)
.end( function(res){
cb&&cb( res);
})
break;
case 'POST':
req = request.post(url)
.send(data)
.end( function(res){
cb&&cb( res);
})
break;
case 'DELETE':
req = request.del(url)
.query(data)
.send(data)
.end( function(res){
cb&&cb( res);
})
break;
}
};
module.exports = Facebook;
| mit |
DDuarte/feup-sope-unix | Proj/2/docs/html/search/functions_70.js | 1424 | var searchData=
[
['parsearguments',['ParseArguments',['../a00018.html#a912fd970d2f8667272597122b5d9fe89',1,'tpc.c']]],
['play',['Play',['../a00018.html#a209335d248e70fbe25a751fe6fad2a27',1,'tpc.c']]],
['player_5finit',['player_init',['../a00025.html#ga5c83feea6dbd6e2448404261375365e3',1,'player_init(player *p): player.c'],['../a00025.html#ga5c83feea6dbd6e2448404261375365e3',1,'player_init(player *p): player.c']]],
['player_5fnew',['player_new',['../a00025.html#ga75b1ecd76f93fa8893c4f2bab9fbf03b',1,'player_new(): player.c'],['../a00025.html#ga75b1ecd76f93fa8893c4f2bab9fbf03b',1,'player_new(void): player.c']]],
['player_5fset_5ffifo_5fname',['player_set_fifo_name',['../a00025.html#ga2d7b416518d58ac941d831b808273f2c',1,'player_set_fifo_name(player *p, const char newFifoName[STRING_MAX_LENGTH]): player.c'],['../a00025.html#ga2d7b416518d58ac941d831b808273f2c',1,'player_set_fifo_name(player *p, const char newFifoName[STRING_MAX_LENGTH]): player.c']]],
['player_5fset_5fname',['player_set_name',['../a00025.html#ga761441bacf27fb156667785386ad8f21',1,'player_set_name(player *p, const char newName[STRING_MAX_LENGTH]): player.c'],['../a00025.html#ga761441bacf27fb156667785386ad8f21',1,'player_set_name(player *p, const char newName[STRING_MAX_LENGTH]): player.c']]],
['printusage',['PrintUsage',['../a00018.html#a9550e83ca945ade9a0832dd373fac74e',1,'tpc.c']]]
];
| mit |
mzdunek93/volt | lib/volt/server/template_handlers/view_processor.rb | 2512 | require 'volt/server/component_templates'
require 'opal/sprockets/processor'
require 'sprockets'
require 'tilt'
require 'opal/sprockets/processor'
module Volt
class ViewProcessor < ::Opal::TiltTemplate
def initialize(client)
@client = client
end
def app_reference
if @client
'Volt.current_app'
else
'volt_app'
end
end
def cache_key
@cache_key ||= "#{self.class.name}:0.2".freeze
end
# def evaluate(context, locals, &block)
# binding.pry
# @data = compile(@data)
# super
# end
def call(input)
context = input[:environment].context_class.new(input)
# context.link_asset('main/assets/images/lombard.jpg')
# puts context.asset_path('main/assets/images/lombard.jpg').inspect
# pp input
data = input[:data]
# input[:accept] = 'application/javascript'
# input[:content_type] = 'application/javascript'
# input[:environment].content_type = 'application/javascript'
compiled = false
data, links = input[:cache].fetch([self.cache_key, data]) do
compiled = true
filename = input[:filename]
# puts input[:data].inspect
# Remove all semicolons from source
# input[:content_type] = 'application/javascript'
compile(filename, input[:data], context)
end
unless compiled
links.each do |link|
context.link_asset(link)
end
end
context.metadata.merge(data: data.to_str)
end
def compile(view_path, html, context)
exts = ComponentTemplates::Preprocessors.extensions
template_path = view_path.split('/')[-4..-1].join('/').gsub('/views/', '/').gsub(/[.](#{exts.join('|')})$/, '')
exts = ComponentTemplates::Preprocessors.extensions
format = File.extname(view_path).downcase.delete('.').to_sym
code = ''
# Process template if we have a handler for this file type
if handler = ComponentTemplates.handler_for_extension(format)
html = handler.call(html)
parser = ViewParser.new(html, template_path, context)
code = parser.code(app_reference)
end
return [Opal.compile(code), parser.links]
end
def self.setup(sprockets=$volt_app.sprockets)
sprockets.register_mime_type 'application/vtemplate', extensions: ['.html', '.email']
sprockets.register_transformer 'application/vtemplate', 'application/javascript', Volt::ViewProcessor.new(true)
end
end
end
| mit |
agc93/Cake.VisualStudio | src/Cake.VisualStudio.Shared/Menus/InstallDotNetFrameworkBashBootstrapperCommand.cs | 4149 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Design;
using Cake.VisualStudio.Helpers;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Constants = Cake.VisualStudio.Helpers.Constants;
namespace Cake.VisualStudio.Menus
{
/// <summary>
/// Command handler
/// </summary>
internal sealed class InstallDotNetFrameworkBashBootstrapperCommand
{
/// <summary>
/// Command ID.
/// </summary>
public const int CommandId = PackageIds.cmdidInstallDotNetFrameworkBashBootstrapperCommand;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
public static readonly Guid CommandSet = new Guid("6003519f-6876-4db3-ad29-8d5379949869");
/// <summary>
/// VS Package that provides this command, not null.
/// </summary>
private readonly Package _package;
/// <summary>
/// Initializes a new instance of the <see cref="InstallDotNetFrameworkBashBootstrapperCommand"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner _package, not null.</param>
private InstallDotNetFrameworkBashBootstrapperCommand(Package package)
{
_package = package ?? throw new ArgumentNullException("package");
var commandService = ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (commandService != null)
{
var menuCommandID = new CommandID(CommandSet, CommandId);
var menuItem = new MenuCommand(MenuItemCallback, menuCommandID);
commandService.AddCommand(menuItem);
}
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
public static InstallDotNetFrameworkBashBootstrapperCommand Instance
{
get;
private set;
}
/// <summary>
/// Gets the service provider from the owner _package.
/// </summary>
private IServiceProvider ServiceProvider
{
get
{
return _package;
}
}
/// <summary>
/// Initializes the singleton instance of the command.
/// </summary>
/// <param name="package">Owner _package, not null.</param>
public static void Initialize(Package package)
{
Instance = new InstallDotNetFrameworkBashBootstrapperCommand(package);
}
/// <summary>
/// This function is the callback used to execute the command when the menu item is clicked.
/// See the constructor to see how the menu item is associated with this function using
/// OleMenuCommandService service and MenuCommand class.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event args.</param>
private void MenuItemCallback(object sender, EventArgs e)
{
var dte = CakePackage.Dte;
if (dte == null)
{
return;
}
if (dte.Solution == null || dte.Solution.Count == 0)
{
ServiceProvider.ShowMessageBox("No solution opened");
}
else
{
if (MenuHelpers.DownloadFileToProject(Constants.DotNetFrameworkBashUri, "build.sh"))
{
VsShellUtilities.LogMessage(Constants.PackageName, ".NET Framework Bash bootstrapper installed into solution", __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION);
ServiceProvider.ShowMessageBox(".NET Framework Bash bootstrapper script successfully downloaded.");
}
}
// Show a message box to prove we were here
}
}
} | mit |
rksdna/mobuco | application/functions/FunctionType.cpp | 367 | #include "FunctionType.h"
FunctionType::FunctionType(int code, const QString &title)
: m_code(code),
m_title(title)
{
types().insert(code, this);
}
int FunctionType::code() const
{
return m_code;
}
QString FunctionType::title() const
{
return m_title;
}
FunctionType::Hash &FunctionType::types()
{
static Hash types;
return types;
}
| mit |
monsieurgustav/2DBoard | src/Level.cpp | 1566 | //
// Level.cpp
// Labyrinth
//
// Created by Guillaume on 12/10/13.
//
//
#include "Level.h"
#include "cinder/app/App.h"
#include "fmod.hpp"
Level::Level(Board && b, Actor && p, Drawer && d, EventManager && m)
: board(b), player(p), drawer(d), eventManager(m), current(0)
{ }
Level::Level(Level && other)
: board(std::move(other.board)),
player(std::move(other.player)),
drawer(std::move(other.drawer)),
eventManager(std::move(other.eventManager)),
widgets(std::move(other.widgets)),
current(0)
{ }
Level::~Level()
{
std::for_each(sounds.begin(), sounds.end(),
[] (decltype(*sounds.begin()) & v)
{
v.second.channel->stop();
v.second.sound->release();
});
}
Level & Level::operator=(Level && other)
{
board = std::move(other.board);
player = std::move(other.player);
drawer = std::move(other.drawer);
eventManager = std::move(other.eventManager);
pendingWidgets = std::move(other.widgets);
++current;
return *this;
}
void Level::prepare(ci::app::App * app)
{
player.setFinishMoveCallback([app, this] (ci::Vec2i position)
{
int trigger = board.cell(position.x, position.y).triggerId();
eventManager.runEvent(trigger, app, *this);
});
drawer.setWindowSize(app->getWindowSize());
// run the initial event.
eventManager.runEvent(0, app, *this);
}
void Level::destroy(ci::app::App * app)
{
}
| mit |
lelenaic/Paradox | pages/website-take-course.php | 21286 | <div class="parallax bg-white page-section third">
<div class="container parallax-layer" data-opacity="true">
<div class="media v-middle media-overflow-visible">
<div class="media-left">
<span class="icon-block s30 bg-lightred"><i class="fa fa-github"></i></span>
</div>
<div class="media-body">
<div class="text-headline">Github Webhooks for Beginners</div>
</div>
<div class="media-right">
<div class="dropdown">
<a class="btn btn-white dropdown-toggle" data-toggle="dropdown" href="#">Course <span class="caret"></span></a>
<ul class="dropdown-menu pull-right">
<li><a href="">Something</a></li>
<li><a href="">Something else</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="page-section">
<div class="row">
<div class="col-md-9">
<div class="page-section padding-top-none">
<div class="media media-grid v-middle">
<div class="media-left">
<span class="icon-block half bg-blue-300 text-white">2</span>
</div>
<div class="media-body">
<h1 class="text-display-1 margin-none">The MVC architectural pattern</h1>
</div>
</div>
<br/>
<p class="text-body-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cum dicta eius enim inventore minus optio ratione veritatis. Beatae deserunt illum ipsam magni minima mollitia officiis quia tempora! Aliquid autem beatae, dignissimos exercitationem illum, incidunt itaque libero, minima molestiae necessitatibus perferendis quae quas quidem recusandae sit! Esse maxime porro provident quasi?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Architecto assumenda aut debitis, ducimus, ea eaque earum eius enim eos explicabo facilis harum impedit natus nemo, nobis obcaecati omnis perspiciatis praesentium quaerat quas quod reprehenderit sapiente temporibus vel voluptatem voluptates voluptatibus?</p>
</div>
<h5 class="text-subhead-2 text-light">Curriculum</h5>
<div class="panel panel-default curriculum open paper-shadow" data-z="0.5">
<div class="panel-heading panel-heading-gray" data-toggle="collapse" data-target="#curriculum-1">
<div class="media">
<div class="media-left">
<span class="icon-block img-circle bg-indigo-300 half text-white"><i class="fa fa-graduation-cap"></i></span>
</div>
<div class="media-body">
<h4 class="text-headline">Chapter 1</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores cumque minima nemo repudiandae rerum! Aspernatur at, autem expedita id illum laudantium molestias officiis quaerat, rem sapiente sint totam velit. Enim.</p>
</div>
</div>
<span class="collapse-status collapse-open">Open</span>
<span class="collapse-status collapse-close">Close</span>
</div>
<div class="list-group collapse in" id="curriculum-1">
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">1.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-green-300"></i>
Installation
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">2:03 min</div>
</div>
</div>
<div class="list-group-item media active" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">2.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-blue-300"></i>
The MVC architectural pattern
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">25:01 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">3.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Database Models
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">12:10 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">4.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Database Access
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">1:25 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">5.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Eloquent Basics
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">22:30 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-quiz.html">
<div class="media-left">
<div class="text-crt">6.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Take Quiz
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">10:00 min</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default curriculum paper-shadow" data-z="0.5">
<div class="panel-heading panel-heading-gray" data-toggle="collapse" data-target="#curriculum-2">
<div class="media">
<div class="media-left">
<span class="icon-block half img-circle bg-orange-300 text-white"><i class="fa fa-graduation-cap"></i></span>
</div>
<div class="media-body">
<h4 class="text-headline">Chapter 2</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores cumque minima nemo repudiandae rerum! Aspernatur at, autem expedita id illum laudantium molestias officiis quaerat, rem sapiente sint totam velit. Enim.</p>
</div>
</div>
<span class="collapse-status collapse-open">Open</span>
<span class="collapse-status collapse-close">Close</span>
</div>
<div class="list-group collapse" id="curriculum-2">
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">1.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Installation
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">2:03 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">2.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
The MVC architectural pattern
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">25:01 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">3.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Database Models
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">12:10 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">4.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Database Access
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">1:25 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">5.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Eloquent Basics
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">22:30 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-quiz.html">
<div class="media-left">
<div class="text-crt">6.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Take Quiz
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">10:00 min</div>
</div>
</div>
</div>
</div>
<div class="panel panel-default curriculum paper-shadow" data-z="0.5">
<div class="panel-heading panel-heading-gray" data-toggle="collapse" data-target="#curriculum-3">
<div class="media">
<div class="media-left">
<span class="icon-block half img-circle bg-green-300 text-white"><i class="fa fa-graduation-cap"></i></span>
</div>
<div class="media-body">
<h4 class="text-headline">Chapter 3</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores cumque minima nemo repudiandae rerum! Aspernatur at, autem expedita id illum laudantium molestias officiis quaerat, rem sapiente sint totam velit. Enim.</p>
</div>
</div>
<span class="collapse-status collapse-open">Open</span>
<span class="collapse-status collapse-close">Close</span>
</div>
<div class="list-group collapse" id="curriculum-3">
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">1.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Installation
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">2:03 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">2.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
The MVC architectural pattern
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">25:01 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">3.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Database Models
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">12:10 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">4.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Database Access
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">1:25 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-course.html">
<div class="media-left">
<div class="text-crt">5.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Eloquent Basics
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">22:30 min</div>
</div>
</div>
<div class="list-group-item media" data-target="website-take-quiz.html">
<div class="media-left">
<div class="text-crt">6.</div>
</div>
<div class="media-body">
<i class="fa fa-fw fa-circle text-grey-200"></i>
Take Quiz
</div>
<div class="media-right">
<div class="width-100 text-right text-caption">10:00 min</div>
</div>
</div>
</div>
</div>
<br/>
<br/>
</div>
<div class="col-md-3">
<div class="panel panel-default" data-toggle="panel-collapse" data-open="true">
<div class="panel-heading panel-collapse-trigger">
<h4 class="panel-title">Resources</h4>
</div>
<div class="panel-body list-group">
<ul class="list-group list-group-menu">
<li class="list-group-item active"><a class="link-text-color" href="website-take-course.html">Curriculum</a></li>
<li class="list-group-item"><a class="link-text-color" href="website-course-forums.html">Course Forums</a></li>
<li class="list-group-item"><a class="link-text-color" href="website-take-quiz.html">Take Quiz</a></li>
<li class="list-group-item"><a class="link-text-color" href="website-quiz-results.html">Quiz Results</a></li>
</ul>
</div>
</div>
<div class="panel panel-default" data-toggle="panel-collapse" data-open="true">
<div class="panel-heading panel-collapse-trigger">
<h4 class="panel-title">Instructor</h4>
</div>
<div class="panel-body">
<div class="media v-middle">
<div class="media-left">
<img src="images/people/110/guy-6.jpg" alt="About Adrian" width="60" class="img-circle"/>
</div>
<div class="media-body">
<h4 class="text-title margin-none"><a href="#">Adrian Demian</a></h4>
<span class="caption text-light">Biography</span>
</div>
</div>
<br/>
<div class="expandable expandable-indicator-white expandable-trigger">
<div class="expandable-content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A accusamus aut consectetur
consequatur cum cupiditate debitis doloribus, error ex explicabo harum illum minima
mollitia nisi nostrum officiis omnis optio qui quisquam saepe sit sunt totam vel velit
voluptatibus? Adipisci ducimus expedita id nostrum quas quia!</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div> | mit |
mr-rampage/reactive-boids | src/js/app.js | 238 | 'use strict';
(function () {
var ToggleStream = require('./stream/toggle-stream.js');
require('./model/Entity.js');
var $ = require('jqlite');
$(document).ready(function () {
ToggleStream.create(null, $('body'));
});
})();
| mit |
wael-Fadlallah/overflow | asset/tinymce/src/core/src/main/js/init/Render.js | 6980 | /**
* Render.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
define(
'tinymce.core.init.Render',
[
'ephox.katamari.api.Type',
'global!window',
'tinymce.core.api.NotificationManager',
'tinymce.core.api.WindowManager',
'tinymce.core.dom.DOMUtils',
'tinymce.core.dom.EventUtils',
'tinymce.core.dom.ScriptLoader',
'tinymce.core.Env',
'tinymce.core.ErrorReporter',
'tinymce.core.init.Init',
'tinymce.core.PluginManager',
'tinymce.core.ThemeManager',
'tinymce.core.util.Tools'
],
function (Type, window, NotificationManager, WindowManager, DOMUtils, EventUtils, ScriptLoader, Env, ErrorReporter, Init, PluginManager, ThemeManager, Tools) {
var DOM = DOMUtils.DOM;
var hasSkipLoadPrefix = function (name) {
return name.charAt(0) === '-';
};
var loadLanguage = function (scriptLoader, editor) {
var settings = editor.settings;
if (settings.language && settings.language !== 'en' && !settings.language_url) {
settings.language_url = editor.editorManager.baseURL + '/langs/' + settings.language + '.js';
}
if (settings.language_url) {
scriptLoader.add(settings.language_url);
}
};
var loadTheme = function (scriptLoader, editor, suffix, callback) {
var settings = editor.settings, theme = settings.theme;
if (Type.isString(theme)) {
if (!hasSkipLoadPrefix(theme) && !ThemeManager.urls.hasOwnProperty(theme)) {
var themeUrl = settings.theme_url;
if (themeUrl) {
ThemeManager.load(theme, editor.documentBaseURI.toAbsolute(themeUrl));
} else {
ThemeManager.load(theme, 'themes/' + theme + '/theme' + suffix + '.js');
}
}
scriptLoader.loadQueue(function () {
ThemeManager.waitFor(theme, callback);
});
} else {
callback();
}
};
var loadPlugins = function (settings, suffix) {
if (Tools.isArray(settings.plugins)) {
settings.plugins = settings.plugins.join(' ');
}
Tools.each(settings.external_plugins, function (url, name) {
PluginManager.load(name, url);
settings.plugins += ' ' + name;
});
Tools.each(settings.plugins.split(/[ ,]/), function (plugin) {
plugin = Tools.trim(plugin);
if (plugin && !PluginManager.urls[plugin]) {
if (hasSkipLoadPrefix(plugin)) {
plugin = plugin.substr(1, plugin.length);
var dependencies = PluginManager.dependencies(plugin);
Tools.each(dependencies, function (dep) {
var defaultSettings = {
prefix: 'plugins/',
resource: dep,
suffix: '/plugin' + suffix + '.js'
};
dep = PluginManager.createUrl(defaultSettings, dep);
PluginManager.load(dep.resource, dep);
});
} else {
PluginManager.load(plugin, {
prefix: 'plugins/',
resource: plugin,
suffix: '/plugin' + suffix + '.js'
});
}
}
});
};
var loadScripts = function (editor, suffix) {
var scriptLoader = ScriptLoader.ScriptLoader;
loadTheme(scriptLoader, editor, suffix, function () {
loadLanguage(scriptLoader, editor);
loadPlugins(editor.settings, suffix);
scriptLoader.loadQueue(function () {
if (!editor.removed) {
Init.init(editor);
}
}, editor, function (urls) {
ErrorReporter.pluginLoadError(editor, urls[0]);
if (!editor.removed) {
Init.init(editor);
}
});
});
};
var render = function (editor) {
var settings = editor.settings, id = editor.id;
function readyHandler() {
DOM.unbind(window, 'ready', readyHandler);
editor.render();
}
// Page is not loaded yet, wait for it
if (!EventUtils.Event.domLoaded) {
DOM.bind(window, 'ready', readyHandler);
return;
}
// Element not found, then skip initialization
if (!editor.getElement()) {
return;
}
// No editable support old iOS versions etc
if (!Env.contentEditable) {
return;
}
// Hide target element early to prevent content flashing
if (!settings.inline) {
editor.orgVisibility = editor.getElement().style.visibility;
editor.getElement().style.visibility = 'hidden';
} else {
editor.inline = true;
}
var form = editor.getElement().form || DOM.getParent(id, 'form');
if (form) {
editor.formElement = form;
// Add hidden input for non input elements inside form elements
if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(editor.getElement().nodeName)) {
DOM.insertAfter(DOM.create('input', { type: 'hidden', name: id }), id);
editor.hasHiddenInput = true;
}
// Pass submit/reset from form to editor instance
editor.formEventDelegate = function (e) {
editor.fire(e.type, e);
};
DOM.bind(form, 'submit reset', editor.formEventDelegate);
// Reset contents in editor when the form is reset
editor.on('reset', function () {
editor.setContent(editor.startContent, { format: 'raw' });
});
// Check page uses id="submit" or name="submit" for it's submit button
if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
form._mceOldSubmit = form.submit;
form.submit = function () {
editor.editorManager.triggerSave();
editor.setDirty(false);
return form._mceOldSubmit(form);
};
}
}
editor.windowManager = new WindowManager(editor);
editor.notificationManager = new NotificationManager(editor);
if (settings.encoding === 'xml') {
editor.on('GetContent', function (e) {
if (e.save) {
e.content = DOM.encode(e.content);
}
});
}
if (settings.add_form_submit_trigger) {
editor.on('submit', function () {
if (editor.initialized) {
editor.save();
}
});
}
if (settings.add_unload_trigger) {
editor._beforeUnload = function () {
if (editor.initialized && !editor.destroyed && !editor.isHidden()) {
editor.save({ format: 'raw', no_events: true, set_dirty: false });
}
};
editor.editorManager.on('BeforeUnload', editor._beforeUnload);
}
editor.editorManager.add(editor);
loadScripts(editor, editor.suffix);
};
return {
render: render
};
}
);
| mit |
pleary/inaturalist | tools/frequency_cells_populate.rb | 2920 | OPTS = Optimist::options do
banner <<-EOS
Create a FrequencyCell grid of the globe and populate each cell with its respective
FrequencyCellMonthTaxon, broken out by month observed. The all_taxa_counts API will
return leaf-style counts, and will include accumulation counts for all ancestors
up the taxonomic tree. This can generate 3 times as much data compared to just storing
leaves, so there is a final step to only keep counts of species and non-species
leaf taxa included in a vision export
Usage:
rails runner tools/frequency_cells_populate.rb
EOS
end
PSQL = ActiveRecord::Base.connection
CELL_SIZE = 1 # degrees
# create an empty FrequencyCell grid of the globe
# this only needs to be run the first time, or if cell size changes
PSQL.execute( "TRUNCATE TABLE frequency_cells RESTART IDENTITY" )
Benchmark.measure do
lat = -90
while lat <= ( 90 - CELL_SIZE )
lng = -180
lat_cells = []
while lng <= ( 180 - CELL_SIZE )
lat_cells << "(#{lat},#{lng})"
lng += CELL_SIZE
end
sql = "INSERT INTO frequency_cells (swlat, swlng) VALUES " + lat_cells.join( "," )
PSQL.execute( sql )
lat += CELL_SIZE
end
end
# iterate through the grid and populate with FrequencyCellMonthTaxa
PSQL.execute( "TRUNCATE TABLE frequency_cell_month_taxa RESTART IDENTITY" )
start_time = Time.now
cells_counted = 0
Benchmark.measure do
lat = -90
while lat <= ( 90 - CELL_SIZE )
lng = -180
FrequencyCellMonthTaxon.transaction do
while lng <= ( 180 - CELL_SIZE )
params = {
swlat: lat,
swlng: lng,
nelat: lat + CELL_SIZE,
nelng: lng + CELL_SIZE,
quality_grade: "research,needs_id",
taxon_is_active: "true",
identifications: "most_agree"
}
response = INatAPIService.get( "/observations/taxa_counts_by_month",
params, { retry_delay: 2.0, retries: 30, json: true }
)
month_of_year = response && response["results"] && response["results"]["month_of_year"]
if month_of_year && !month_of_year.blank?
frequency_cell = FrequencyCell.where( swlat: lat, swlng: lng ).first
month_of_year.each do |month, leaf_counts|
sql = "INSERT INTO frequency_cell_month_taxa (frequency_cell_id, month, taxon_id, count) VALUES " +
leaf_counts.filter{ |r| !r["taxon_id"].blank? }.map {|r| "(#{frequency_cell.id},#{month},#{r["taxon_id"]},#{r["count"]})" }.join( "," )
PSQL.execute( sql )
end
puts "Inserted #{lat},#{lng} :: #{month_of_year.map{ |m,v| v.length }.inject(:+)}"
end
lng += CELL_SIZE
cells_counted += 1
total_time = Time.now - start_time
if cells_counted % 100 === 0
puts "#{cells_counted} cells in #{total_time}s, #{( cells_counted / total_time ).round( 2 )}cells/s"
end
end
end
lat += CELL_SIZE
end
end
| mit |
arapovavikka/InstaKiller | InstaKiller.Wpf/HttpClientWrapper.cs | 1016 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using InstaKiller.Model;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http.Formatting;
namespace InstaKiller.Wpf
{
class HttpClientWrapper
{
private readonly string _connectionString;
private readonly HttpClient _client;
public HttpClientWrapper(string connectionString)
{
_connectionString = connectionString;
_client = new HttpClient
{
BaseAddress = new Uri(connectionString)
};
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public Person GetUserByEmail(string email)
{
var result = _client.GetAsync(string.Format("{0}api/v1/user/email/{1}", _connectionString, email)).Result;
return result.Content.ReadAsAsync<Person>().Result;
}
}
}
| mit |
lsadam0/BEx | BEx/Transaction.cs | 3375 | // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using BEx.ExchangeEngine;
using BEx.ExchangeEngine.Utilities;
using BEx.ExchangeEngine.API;
namespace BEx
{
public struct Transaction : IEquatable<Transaction>, IExchangeResult
{
internal Transaction(
string amount,
TradingPair pair,
DateTime exchangeTimestamp,
int transactionId,
string price,
ExchangeType sourceExchange)
: this()
{
Amount = Conversion.ToDecimalInvariant(amount);
Pair = pair;
CompletedTime = exchangeTimestamp;
UnixCompletedTimeStamp = (long) CompletedTime.ToUnixTime();
ExchangeTimeStampUTC = CompletedTime;
LocalTimeStampUTC = DateTime.UtcNow;
Price = Conversion.ToDecimalInvariant(price);
SourceExchange = sourceExchange;
TransactionId = transactionId;
}
internal Transaction(
string amount,
TradingPair pair,
long unixTimeStamp,
int transactionId,
string price,
ExchangeType sourceExchange)
: this()
{
Amount = Conversion.ToDecimalInvariant(amount);
Pair = pair;
UnixCompletedTimeStamp = unixTimeStamp;
CompletedTime = unixTimeStamp.ToDateTimeUTC();
ExchangeTimeStampUTC = CompletedTime;
LocalTimeStampUTC = DateTime.UtcNow;
Price = Conversion.ToDecimalInvariant(price);
SourceExchange = sourceExchange;
TransactionId = transactionId;
}
public decimal Amount { get; }
public DateTime CompletedTime { get; }
public DateTime ExchangeTimeStampUTC { get; }
public DateTime LocalTimeStampUTC { get; }
public TradingPair Pair { get; }
public decimal Price { get; }
public ExchangeType SourceExchange { get; }
public long TransactionId { get; }
public long UnixCompletedTimeStamp { get; }
public static bool operator !=(Transaction a, Transaction b) => !(a == b);
public static bool operator ==(Transaction a, Transaction b)
{
return
a.Amount == b.Amount
&& a.UnixCompletedTimeStamp == b.UnixCompletedTimeStamp
&& a.Pair == b.Pair
&& a.Price == b.Price
&& a.SourceExchange == b.SourceExchange
&& a.TransactionId == b.TransactionId;
}
public override bool Equals(object obj)
{
if (!(obj is Transaction))
{
return false;
}
return this == (Transaction) obj;
}
public bool Equals(Transaction b) => this == b;
public override int GetHashCode()
{
return
Amount.GetHashCode()
^ CompletedTime.GetHashCode()
^ Pair.GetHashCode()
^ UnixCompletedTimeStamp.GetHashCode()
^ TransactionId.GetHashCode()
^ SourceExchange.GetHashCode();
}
public override string ToString() => $"{SourceExchange} {Pair} - Price: {Price} - Amount: {Amount}";
}
} | mit |
angularcolombia/angularcolombia.com | src/app/shared/components/user-auth/user-auth.component.spec.ts | 643 | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { UserAuthComponent } from './user-auth.component';
describe('UserAuthComponent', () => {
let component: UserAuthComponent;
let fixture: ComponentFixture<UserAuthComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UserAuthComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserAuthComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| mit |
polypodes/EuradioNantes.eu | src/RadioSolution/ProgramBundle/Controller/EmissionController.php | 5508 | <?php
namespace RadioSolution\ProgramBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use RadioSolution\ProgramBundle\Entity\Emission;
/**
* Emission controller.
*
* @Route("/")
*/
class EmissionController extends Controller
{
/**
* Lists all Emission entities.
*
* @Route("/", name="")
* @Template()
*/
public function indexAction()
{
$breadcrumbs = $this->get("white_october_breadcrumbs");
$breadcrumbs->addItem('Les émissions');
$breadcrumbs->addItem('Les émissions de A à Z');
if (!empty($_GET['emission'])) {
$this->redirect($_GET['emission']);
}
$em = $this->getDoctrine()->getManager();
$query = $this
->getDoctrine()
->getRepository('ProgramBundle:Emission')
->createQueryBuilder('e')
->where('e.published = 1')
->orderBy('e.name', 'ASC')
;
if (!empty($_GET['theme'])) {
$query = $query
->andWhere('e.collection = :theme')
->setParameter('theme', $_GET['theme'])
;
}
if (!empty($_GET['frequency'])) {
$query = $query
->andWhere('e.frequency = :frequency')
->setParameter('frequency', $_GET['frequency'])
;
}
if (!empty($_GET['archive'])) {
$query = $query
->andWhere('e.archive = :archive')
->setParameter('archive', $_GET['archive'])
;
} else{
$query = $query->andWhere('e.archive = 0');
}
$query = $query->getQuery();
$paginator = $this->get('knp_paginator');
$entities = $paginator->paginate(
$query,
$this->get('request')->query->get('page', 1),
6
);
$themes = $this
->getDoctrine()
->getRepository('ApplicationSonataClassificationBundle:Collection')
->createQueryBuilder('c')
->where('c.context = :context')
->setParameter('context', 'emission')
->getQuery()
->getResult()
;
$emissions = $this
->getDoctrine()
->getRepository('ProgramBundle:Emission')
->createQueryBuilder('e')
->where('e.published = 1')
->andWhere('e.archive = 0')
->orderBy('e.name', 'ASC')
->getQuery()
->getResult()
;
$frequencies = $this
->getDoctrine()
->getRepository('ProgramBundle:EmissionFrequency')
->findAll()
;
return $this->render('ProgramBundle:Emission:index.html.twig', compact('entities', 'emissions', 'frequencies', 'themes'));
}
/**
* Finds and displays a Emission entity.
*
* @Route("/{id}/show", name="_show")
* @Template()
*/
public function showAction($name)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ProgramBundle:Emission')->findOneBySlug($name);
if (!$entity) {
throw $this->createNotFoundException('L’émission est introuvable.');
}
// hide content if not published and user not logged
if (!$entity->getPublished() && !$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
throw $this->createNotFoundException('L’émission est indisponible.');
}
if ($seoPage = $this->get('sonata.seo.page')) {
$seoPage
->addTitle($entity->getName())
->addMeta('name', 'description', $entity->getDescription())
->addMeta('property', 'og:title', $entity->getName())
->addMeta('property', 'og:type', 'article')
->addMeta('property', 'og:url', $this->generateUrl('emission', array(
'name' => $entity->getSlug()
), true))
->addMeta('property', 'og:description', $entity->getDescription())
;
}
$breadcrumbs = $this->get("white_october_breadcrumbs");
$breadcrumbs->addRouteItem('Les émissions de A à Z', 'emissions');
$breadcrumbs->addItem($entity->getName());
return $this->render('ProgramBundle:Emission:show.html.twig', array(
'entity' => $entity
));
}
public function showRssAction($name)
{
$dateNow =new \DateTime();
$domain = $this->get('request')->server->get('HTTP_HOST');
$em = $this->getDoctrine()->getManager();
if (!$emission = $em->getRepository('ProgramBundle:Emission')->findOneBySlug($name)) {
throw $this->createNotFoundException('Unable to find Emission entity.');
}
$query = $em
->createQuery("SELECT p FROM PodcastBundle:Podcast p JOIN p.program pr WHERE p.real_time_start < :dateNow AND pr.emission = :idEmission ORDER BY p.real_time_start DESC")
->setMaxResults(10)
->setParameter('dateNow', $dateNow)
->setParameter('idEmission',$emission->getId())
;
$podcasts = $query->getResult();
return $this->render('ProgramBundle:Emission:show.rss.twig', compact('emission','podcasts','domain'));
}
}
| mit |
distributions-io/laplace-random | test/test.typedarray.js | 2537 | /* global describe, it, require */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Module to be tested:
random = require( './../lib/typedarray.js' ),
// Module to calculate the mean
mean = require( 'compute-mean' ),
// Kolmogorov-Smirnov test
kstest = require( 'compute-kstest' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'random typed array', function tests() {
this.timeout( 50000 );
it( 'should export a function', function test() {
expect( random ).to.be.a( 'function' );
});
it( 'should generate samples which pass mean test when mu = 0 and b = 1', function test() {
var out,
mu = 0,
b = 1,
sampleMean,
n = 50000,
iTotal = 400,
s,
ci,
outside = 0,
i;
// Mean test
s = Math.sqrt( 2 * Math.pow( b, 2 ) ) / Math.sqrt( n );
// CI
ci = [ mu - 2 * s, mu + 2 * s ];
for ( i = 0; i < iTotal; i++ ) {
out = random( n, 'float64', mu, b );
sampleMean = mean( out );
if ( sampleMean < ci[ 0 ] || sampleMean > ci[ 1 ] ) {
outside += 1;
}
}
assert.isBelow( outside / iTotal, 0.05 + 0.025 );
});
it( 'should generate samples which pass Kolmogorov-Smirnov test when mu = 0 and b = 1', function test() {
var data,
i,
notpassed = 0,
mu = 0,
b = 1;
for ( i = 0; i < 100; i++ ) {
data = random( 500, 'float64', mu, b );
if ( kstest( data, 'laplace' ).pValue < 0.05 ) {
notpassed += 1;
}
}
assert.isBelow( notpassed / 100, 0.15 );
});
it( 'should generate samples which pass mean test when mu = -2, b = 4', function test() {
var out,
mu = -2,
b = 4,
sampleMean,
n = 50000,
iTotal = 400,
s,
ci,
outside = 0,
i;
// Mean test
s = Math.sqrt( 2 * Math.pow( b, 2 ) ) / Math.sqrt( n );
// CI
ci = [ mu - 2 * s, mu + 2 * s ];
for ( i = 0; i < iTotal; i++ ) {
out = random( n, 'float64', mu, b );
sampleMean = mean( out );
if ( sampleMean < ci[ 0 ] || sampleMean > ci[ 1 ] ) {
outside += 1;
}
}
assert.isBelow( outside / iTotal, 0.05 + 0.025 );
});
it( 'should generate samples which pass Kolmogorov-Smirnov test when mu = -2 and b = 4', function test() {
var data,
i,
notpassed = 0,
mu = -2,
b = 4,
pval;
for ( i = 0; i < 100; i++ ) {
data = random( 500, 'float64', mu, b );
pval = kstest( data, 'laplace', {
'mu': mu,
'b': b
}).pValue;
if ( pval < 0.05 ) {
notpassed += 1;
}
}
assert.isBelow( notpassed / 100, 0.15 );
});
});
| mit |
xyproto/algernon | vendor/github.com/caddyserver/certmagic/cache.go | 11897 | // Copyright 2015 Matthew Holt
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package certmagic
import (
"fmt"
weakrand "math/rand" // seeded elsewhere
"strings"
"sync"
"time"
"go.uber.org/zap"
)
// Cache is a structure that stores certificates in memory.
// A Cache indexes certificates by name for quick access
// during TLS handshakes, and avoids duplicating certificates
// in memory. Generally, there should only be one per process.
// However, that is not a strict requirement; but using more
// than one is a code smell, and may indicate an
// over-engineered design.
//
// An empty cache is INVALID and must not be used. Be sure
// to call NewCache to get a valid value.
//
// These should be very long-lived values and must not be
// copied. Before all references leave scope to be garbage
// collected, ensure you call Stop() to stop maintenance on
// the certificates stored in this cache and release locks.
//
// Caches are not usually manipulated directly; create a
// Config value with a pointer to a Cache, and then use
// the Config to interact with the cache. Caches are
// agnostic of any particular storage or ACME config,
// since each certificate may be managed and stored
// differently.
type Cache struct {
// User configuration of the cache
options CacheOptions
// The cache is keyed by certificate hash
cache map[string]Certificate
// cacheIndex is a map of SAN to cache key (cert hash)
cacheIndex map[string][]string
// Protects the cache and index maps
mu sync.RWMutex
// Close this channel to cancel asset maintenance
stopChan chan struct{}
// Used to signal when stopping is completed
doneChan chan struct{}
logger *zap.Logger
}
// NewCache returns a new, valid Cache for efficiently
// accessing certificates in memory. It also begins a
// maintenance goroutine to tend to the certificates
// in the cache. Call Stop() when you are done with the
// cache so it can clean up locks and stuff.
//
// Most users of this package will not need to call this
// because a default certificate cache is created for you.
// Only advanced use cases require creating a new cache.
//
// This function panics if opts.GetConfigForCert is not
// set. The reason is that a cache absolutely needs to
// be able to get a Config with which to manage TLS
// assets, and it is not safe to assume that the Default
// config is always the correct one, since you have
// created the cache yourself.
//
// See the godoc for Cache to use it properly. When
// no longer needed, caches should be stopped with
// Stop() to clean up resources even if the process
// is being terminated, so that it can clean up
// any locks for other processes to unblock!
func NewCache(opts CacheOptions) *Cache {
// assume default options if necessary
if opts.OCSPCheckInterval <= 0 {
opts.OCSPCheckInterval = DefaultOCSPCheckInterval
}
if opts.RenewCheckInterval <= 0 {
opts.RenewCheckInterval = DefaultRenewCheckInterval
}
if opts.Capacity < 0 {
opts.Capacity = 0
}
// this must be set, because we cannot not
// safely assume that the Default Config
// is always the correct one to use
if opts.GetConfigForCert == nil {
panic("cache must be initialized with a GetConfigForCert callback")
}
c := &Cache{
options: opts,
cache: make(map[string]Certificate),
cacheIndex: make(map[string][]string),
stopChan: make(chan struct{}),
doneChan: make(chan struct{}),
logger: opts.Logger,
}
go c.maintainAssets(0)
return c
}
// Stop stops the maintenance goroutine for
// certificates in certCache. It blocks until
// stopping is complete. Once a cache is
// stopped, it cannot be reused.
func (certCache *Cache) Stop() {
close(certCache.stopChan) // signal to stop
<-certCache.doneChan // wait for stop to complete
}
// CacheOptions is used to configure certificate caches.
// Once a cache has been created with certain options,
// those settings cannot be changed.
type CacheOptions struct {
// REQUIRED. A function that returns a configuration
// used for managing a certificate, or for accessing
// that certificate's asset storage (e.g. for
// OCSP staples, etc). The returned Config MUST
// be associated with the same Cache as the caller.
//
// The reason this is a callback function, dynamically
// returning a Config (instead of attaching a static
// pointer to a Config on each certificate) is because
// the config for how to manage a domain's certificate
// might change from maintenance to maintenance. The
// cache is so long-lived, we cannot assume that the
// host's situation will always be the same; e.g. the
// certificate might switch DNS providers, so the DNS
// challenge (if used) would need to be adjusted from
// the last time it was run ~8 weeks ago.
GetConfigForCert ConfigGetter
// How often to check certificates for renewal;
// if unset, DefaultOCSPCheckInterval will be used.
OCSPCheckInterval time.Duration
// How often to check certificates for renewal;
// if unset, DefaultRenewCheckInterval will be used.
RenewCheckInterval time.Duration
// Maximum number of certificates to allow in the cache.
// If reached, certificates will be randomly evicted to
// make room for new ones. 0 means unlimited.
Capacity int
// Set a logger to enable logging
Logger *zap.Logger
}
// ConfigGetter is a function that returns a prepared,
// valid config that should be used when managing the
// given certificate or its assets.
type ConfigGetter func(Certificate) (*Config, error)
// cacheCertificate calls unsyncedCacheCertificate with a write lock.
//
// This function is safe for concurrent use.
func (certCache *Cache) cacheCertificate(cert Certificate) {
certCache.mu.Lock()
certCache.unsyncedCacheCertificate(cert)
certCache.mu.Unlock()
}
// unsyncedCacheCertificate adds cert to the in-memory cache unless
// it already exists in the cache (according to cert.Hash). It
// updates the name index.
//
// This function is NOT safe for concurrent use. Callers MUST acquire
// a write lock on certCache.mu first.
func (certCache *Cache) unsyncedCacheCertificate(cert Certificate) {
// no-op if this certificate already exists in the cache
if _, ok := certCache.cache[cert.hash]; ok {
if certCache.logger != nil {
certCache.logger.Debug("certificate already cached",
zap.Strings("subjects", cert.Names),
zap.Time("expiration", cert.Leaf.NotAfter),
zap.Bool("managed", cert.managed),
zap.String("issuer_key", cert.issuerKey),
zap.String("hash", cert.hash))
}
return
}
// if the cache is at capacity, make room for new cert
cacheSize := len(certCache.cache)
if certCache.options.Capacity > 0 && cacheSize >= certCache.options.Capacity {
// Go maps are "nondeterministic" but not actually random,
// so although we could just chop off the "front" of the
// map with less code, that is a heavily skewed eviction
// strategy; generating random numbers is cheap and
// ensures a much better distribution.
rnd := weakrand.Intn(cacheSize)
i := 0
for _, randomCert := range certCache.cache {
if i == rnd {
if certCache.logger != nil {
certCache.logger.Debug("cache full; evicting random certificate",
zap.Strings("removing_subjects", randomCert.Names),
zap.String("removing_hash", randomCert.hash),
zap.Strings("inserting_subjects", cert.Names),
zap.String("inserting_hash", cert.hash))
}
certCache.removeCertificate(randomCert)
break
}
i++
}
}
// store the certificate
certCache.cache[cert.hash] = cert
// update the index so we can access it by name
for _, name := range cert.Names {
certCache.cacheIndex[name] = append(certCache.cacheIndex[name], cert.hash)
}
if certCache.logger != nil {
certCache.logger.Debug("added certificate to cache",
zap.Strings("subjects", cert.Names),
zap.Time("expiration", cert.Leaf.NotAfter),
zap.Bool("managed", cert.managed),
zap.String("issuer_key", cert.issuerKey),
zap.String("hash", cert.hash),
zap.Int("cache_size", len(certCache.cache)),
zap.Int("cache_capacity", certCache.options.Capacity))
}
}
// removeCertificate removes cert from the cache.
//
// This function is NOT safe for concurrent use; callers
// MUST first acquire a write lock on certCache.mu.
func (certCache *Cache) removeCertificate(cert Certificate) {
// delete all mentions of this cert from the name index
for _, name := range cert.Names {
keyList := certCache.cacheIndex[name]
for i := 0; i < len(keyList); i++ {
if keyList[i] == cert.hash {
keyList = append(keyList[:i], keyList[i+1:]...)
i--
}
}
if len(keyList) == 0 {
delete(certCache.cacheIndex, name)
} else {
certCache.cacheIndex[name] = keyList
}
}
// delete the actual cert from the cache
delete(certCache.cache, cert.hash)
if certCache.logger != nil {
certCache.logger.Debug("removed certificate from cache",
zap.Strings("subjects", cert.Names),
zap.Time("expiration", cert.Leaf.NotAfter),
zap.Bool("managed", cert.managed),
zap.String("issuer_key", cert.issuerKey),
zap.String("hash", cert.hash),
zap.Int("cache_size", len(certCache.cache)),
zap.Int("cache_capacity", certCache.options.Capacity))
}
}
// replaceCertificate atomically replaces oldCert with newCert in
// the cache.
//
// This method is safe for concurrent use.
func (certCache *Cache) replaceCertificate(oldCert, newCert Certificate) {
certCache.mu.Lock()
certCache.removeCertificate(oldCert)
certCache.unsyncedCacheCertificate(newCert)
certCache.mu.Unlock()
if certCache.logger != nil {
certCache.logger.Info("replaced certificate in cache",
zap.Strings("subjects", newCert.Names),
zap.Time("new_expiration", newCert.Leaf.NotAfter))
}
}
func (certCache *Cache) getAllMatchingCerts(name string) []Certificate {
certCache.mu.RLock()
defer certCache.mu.RUnlock()
allCertKeys := certCache.cacheIndex[name]
certs := make([]Certificate, len(allCertKeys))
for i := range allCertKeys {
certs[i] = certCache.cache[allCertKeys[i]]
}
return certs
}
func (certCache *Cache) getAllCerts() []Certificate {
certCache.mu.RLock()
defer certCache.mu.RUnlock()
certs := make([]Certificate, 0, len(certCache.cache))
for _, cert := range certCache.cache {
certs = append(certs, cert)
}
return certs
}
func (certCache *Cache) getConfig(cert Certificate) (*Config, error) {
cfg, err := certCache.options.GetConfigForCert(cert)
if err != nil {
return nil, err
}
if cfg.certCache != nil && cfg.certCache != certCache {
return nil, fmt.Errorf("config returned for certificate %v is not nil and points to different cache; got %p, expected %p (this one)",
cert.Names, cfg.certCache, certCache)
}
return cfg, nil
}
// AllMatchingCertificates returns a list of all certificates that could
// be used to serve the given SNI name, including exact SAN matches and
// wildcard matches.
func (certCache *Cache) AllMatchingCertificates(name string) []Certificate {
// get exact matches first
certs := certCache.getAllMatchingCerts(name)
// then look for wildcard matches by replacing each
// label of the domain name with wildcards
labels := strings.Split(name, ".")
for i := range labels {
labels[i] = "*"
candidate := strings.Join(labels, ".")
certs = append(certs, certCache.getAllMatchingCerts(candidate)...)
}
return certs
}
var (
defaultCache *Cache
defaultCacheMu sync.Mutex
)
| mit |
HenryHarper/Acquire-Reboot | gradle/src/language-scala/org/gradle/language/scala/internal/toolchain/DefaultScalaToolProvider.java | 3238 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.language.scala.internal.toolchain;
import org.gradle.api.internal.tasks.compile.daemon.CompilerDaemonManager;
import org.gradle.api.internal.tasks.scala.DaemonScalaCompiler;
import org.gradle.api.internal.tasks.scala.NormalizingScalaCompiler;
import org.gradle.api.internal.tasks.scala.ScalaJavaJointCompileSpec;
import org.gradle.api.internal.tasks.scala.ZincScalaCompiler;
import org.gradle.language.base.internal.compile.CompileSpec;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.platform.base.internal.toolchain.ToolProvider;
import org.gradle.util.TreeVisitor;
import java.io.File;
import java.util.Set;
public class DefaultScalaToolProvider implements ToolProvider {
public static final String DEFAULT_ZINC_VERSION = "0.3.7";
private final File gradleUserHomeDir;
private final File rootProjectDir;
private final CompilerDaemonManager compilerDaemonManager;
private final Set<File> resolvedScalaClasspath;
private final Set<File> resolvedZincClasspath;
public DefaultScalaToolProvider(File gradleUserHomeDir, File rootProjectDir, CompilerDaemonManager compilerDaemonManager, Set<File> resolvedScalaClasspath, Set<File> resolvedZincClasspath) {
this.gradleUserHomeDir = gradleUserHomeDir;
this.rootProjectDir = rootProjectDir;
this.compilerDaemonManager = compilerDaemonManager;
this.resolvedScalaClasspath = resolvedScalaClasspath;
this.resolvedZincClasspath = resolvedZincClasspath;
}
@Override
@SuppressWarnings("unchecked")
public <T extends CompileSpec> org.gradle.language.base.internal.compile.Compiler<T> newCompiler(Class<T> spec) {
if (ScalaJavaJointCompileSpec.class.isAssignableFrom(spec)) {
Compiler<ScalaJavaJointCompileSpec> scalaCompiler = new ZincScalaCompiler(resolvedScalaClasspath, resolvedZincClasspath, gradleUserHomeDir);
return (Compiler<T>) new NormalizingScalaCompiler(new DaemonScalaCompiler<ScalaJavaJointCompileSpec>(rootProjectDir, scalaCompiler, compilerDaemonManager, resolvedZincClasspath));
}
throw new IllegalArgumentException(String.format("Cannot create Compiler for unsupported CompileSpec type '%s'", spec.getSimpleName()));
}
@Override
public <T> T get(Class<T> toolType) {
throw new IllegalArgumentException(String.format("Don't know how to provide tool of type %s.", toolType.getSimpleName()));
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void explain(TreeVisitor<? super String> visitor) {
}
}
| mit |
happylindz/algorithms-tutorial | lintcode/Backpack/backpack.py | 2416 | # coding: utf8
'''
LintCode: http://www.lintcode.com/zh-cn/problem/backpack/
92.背包问题:
在n个物品中挑选若干物品装入背包,最多能装多满?假设背包的大小为m,每个物品的大小为A[i]
注意事项:
你不可以将物品进行切割。
样例:
如果有4个物品[2, 3, 5, 7]
如果背包的大小为11,可以选择[2, 3, 5]装入背包,最多可以装满10的空间。
如果背包的大小为12,可以选择[2, 3, 7]装入背包,最多可以装满12的空间。
函数需要返回最多能装满的空间大小。
'''
# 法一: 动态规划
# 状态: res[i][S] 表示前i个物品,取出一些物品能否组成体积和为S的背包
# 状态转移方程: f[i][S]=f[i−1][S−A[i]] or f[i−1][S]
# 欲从前i个物品中取出一些组成体积和为S的背包,可从两个状态转换得到。
# f[i−1][S−A[i]]: 放入第i个物品,前 i−1 个物品能否取出一些体积和为 S−A[i] 的背包。
# f[i−1][S]: 不放入第i个物品,前 i−1 个物品能否取出一些组成体积和为S的背包。
# 状态初始化: f[1⋯n][0]=true; f[0][1⋯m]=false. 前1~n个物品组成体积和为0的背包始终为真,其他情况为假。
# 返回结果: 寻找使 f[n][S] 值为true的最大S (1≤S≤m)
def backPack1(m, A):
# write your code here
lenA = len(A)
if m < 1 or lenA == 0:
return 0
res = [[False for i in range(m + 1)] for j in range(lenA + 1)]
res[0][0] = True
for i in range(1, lenA + 1):
for j in range(m + 1):
if j < A[i - 1]:
res[i][j] = res[i - 1][j]
else:
res[i][j] = res[i - 1][j] or res[i - 1][j - A[i - 1]]
for i in range(m, -1, -1):
if res[lenA][i] == True:
return i
# 每次 res[i][j] 都会一来到 res[i - 1][j] 的结果, 那么如果仅仅使用一维数组的话, 那么我们每次在添加一个商品的时候,我们倒序遍历这个数组,
# 保证每次 res[i] 都能用到上次的 res[i]
def backPack2(m, A):
# write your code here
lenA = len(A)
if m < 1 or lenA == 0:
return 0
res = [False for i in range(m + 1)]
res[0] = True
for i in range(lenA):
for j in range(m, 0, -1):
if j >= A[i] and res[j - A[i]]:
res[j] = True
for i in range(m, -1, -1):
if res[i] == True:
return i
| mit |
vuetifyjs/vuetify | ecosystem-win.config.js | 1045 | // PM2 process file
// http://pm2.keymetrics.io/docs/usage/application-declaration/
const fs = require('fs')
const separator = process.platform === 'win32' ? ';' : ':'
const paths = process.env.PATH.split(separator).map(p => `${p}/yarn.js`)
const yarnjsPaths = [
'c:/Program Files (x86)/yarn/bin/yarn.js',
'c:/Program Files/yarn/bin/yarn.js',
].concat(paths)
const yarnjsPath = yarnjsPaths.find(fs.existsSync)
if (!yarnjsPath) {
const checkedPaths = yarnjsPaths.reduce((prev, curr) => `${prev}\n${curr}`)
throw new Error(`Yarn.js not found in any of these paths:\n${checkedPaths}`)
}
module.exports = {
apps: [
{
name: 'vuetify-dev',
script: yarnjsPath,
cwd: './packages/vuetify/',
args: 'dev',
},
{
name: 'vuetify-build',
script: yarnjsPath,
cwd: './packages/vuetify/',
args: 'watch',
env: {
NODE_ENV: 'production',
},
},
{
name: 'vuetify-docs',
script: yarnjsPath,
cwd: './packages/docs/',
args: 'dev',
},
],
}
| mit |
danydunk/Augusto | resources/test/rft/Refinement_upmfull_crudHelper.java | 1434 | // DO NOT EDIT: This file is automatically generated.
//
// Only the associated template file should be edited directly.
// Helper class files are automatically regenerated from the template
// files at various times, including record actions and test object
// insertion actions. Any changes made directly to a helper class
// file will be lost when automatically updated.
package resources.test.rft;
import com.rational.test.ft.object.interfaces.*;
import com.rational.test.ft.object.interfaces.SAP.*;
import com.rational.test.ft.object.interfaces.WPF.*;
import com.rational.test.ft.object.interfaces.siebel.*;
import com.rational.test.ft.object.interfaces.flex.*;
import com.rational.test.ft.object.interfaces.dojo.*;
import com.rational.test.ft.object.interfaces.generichtmlsubdomain.*;
import com.rational.test.ft.script.*;
import com.rational.test.ft.vp.IFtVerificationPoint;
import com.ibm.rational.test.ft.object.interfaces.sapwebportal.*;
/**
* Script Name : <b>Refinement_upmfull_crud</b><br>
* Generated : <b>2016/10/24 7:03:25 AM</b><br>
* Description : Helper class for script<br>
* Original Host : Windows 7 amd64 6.1 <br>
*
* @since October 24, 2016
* @author usi
*/
public abstract class Refinement_upmfull_crudHelper extends RationalTestScript
{
protected Refinement_upmfull_crudHelper()
{
setScriptName("test.rft.Refinement_upmfull_crud");
}
}
| mit |
ruthlesshelp/Presentations | NDbUnit/4_Unit_Finish/Tests.Unit.Lender.Slos.Database/Bases/SurfaceTestingBase.cs | 1087 | using System;
using System.Diagnostics.CodeAnalysis;
namespace Tests.Unit.Lender.Slos.Database.Bases
{
[ExcludeFromCodeCoverage]
public class SurfaceTestingBase<TContext> : IDisposable
where TContext : TestContextBase, new()
{
~SurfaceTestingBase()
{
Dispose(false);
}
protected TContext TestFixtureContext { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Clean up all managed resources
if (TestFixtureContext != null) TestFixtureContext.Dispose();
}
// Clean up any unmanaged resources here.
}
protected void SetUpTestFixture(
TContext context = null,
bool buildSchema = false)
{
TestFixtureContext = context ?? new TContext();
TestFixtureContext.InitializeConnection();
}
}
} | mit |
scottbrenneman/auto-wrapper | AutoWrapper/AutoWrapper/CodeGen/ContractGenerator.cs | 2531 | using AutoWrapper.CodeGen.Contracts;
using System;
using System.CodeDom;
using System.Linq;
using System.Reflection;
namespace AutoWrapper.CodeGen
{
public sealed class ContractGenerator : GeneratorBase
{
private readonly IContractGeneratorOptions _contractGeneratorOptions;
private readonly MemberGenerator _memberGenerator;
public ContractGenerator(IWrappedTypeDictionary wrappedTypeDictionary) : this(null, wrappedTypeDictionary) { }
public ContractGenerator(IContractGeneratorOptions contractGeneratorOptions, IWrappedTypeDictionary wrappedTypeDictionary)
: base(wrappedTypeDictionary)
{
_contractGeneratorOptions = contractGeneratorOptions ?? new ContractGeneratorOptionsBuilder().Build();
_memberGenerator = new MemberGenerator(wrappedTypeDictionary);
}
public override CodeTypeDeclaration GenerateDeclaration(Type type)
{
ValidateTypeBeforeGeneration(type);
var contract = new CodeTypeDeclaration(WrappedTypeDictionary.GetContractNameFor(type))
{
TypeAttributes = _contractGeneratorOptions.GetTypeAttributes(),
IsInterface = true,
IsPartial = _contractGeneratorOptions.UsePartial
};
contract.CustomAttributes.AddGeneratedCode();
contract.Comments.Add(new CodeCommentStatement($"Interface for {WrappedTypeDictionary.GetTypeNameFor(type)}"));
if (type.GetInterfaces().Contains(typeof(IDisposable)))
contract.BaseTypes.Add("System.IDisposable");
GenerateMethods(type, contract);
GenerateProperties(type, contract);
contract.Members.Add(CreateWrappedProperty(type, GenerateAs.Contract));
return contract;
}
private void GenerateProperties(IReflect type, CodeTypeDeclaration contract)
{
var properties = type
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => _contractGeneratorOptions.IsExcluded(p) == false);
foreach (var property in properties)
contract.Members.Add(_memberGenerator.GeneratePropertyDeclaration(property));
}
private void GenerateMethods(IReflect type, CodeTypeDeclaration contract)
{
var methods = type
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => IsExcluded(m) == false);
foreach (var method in methods)
contract.Members.Add(_memberGenerator.GenerateMethodDeclaration(method));
}
private bool IsExcluded(MethodInfo method)
{
return
_contractGeneratorOptions.IsExcluded(method) ||
method.IsSpecialName ||
method.Name == "Dispose";
}
}
} | mit |
astral-keks/powershell-workbench | src/Core/Models/Command.cs | 840 |
using System.Collections.Generic;
namespace AstralKeks.Workbench.Models
{
public class Command
{
public const string Default = "Default";
public const string Workspace = "Workspace";
public string Name { get; set; }
public List<string> Arguments { get; set; }
public string[] DeleteVariables { get; set; }
public bool RereadCurrentVariables { get; set; }
public bool RereadMachineVariables { get; set; }
public bool RereadUserVariables { get; set; }
public bool ResetVariables { get; set; }
public bool UseShellExecute { get; set; }
public bool WaitForExit { get; set; }
public bool NoWindow { get; set; }
#region Unsupported
//public bool RunAs { get; set; }
#endregion
}
}
| mit |
pankleks/TypeScriptBuilder | src/TypeScriptBuilder/TypeScriptGenerator.cs | 12333 | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
namespace TypeScriptBuilder
{
public class TypeScriptGenerator
{
readonly HashSet<Type>
_defined = new HashSet<Type>();
readonly Stack<Type>
_toDefine = new Stack<Type>();
readonly SortedDictionary<string, CodeTextBuilder>
_builder = new SortedDictionary<string, CodeTextBuilder>();
readonly TypeScriptGeneratorOptions _options;
readonly HashSet<Type>
_exclude;
public TypeScriptGenerator(TypeScriptGeneratorOptions options = null)
{
_exclude = new HashSet<Type>();
_options = options ?? new TypeScriptGeneratorOptions();
}
public TypeScriptGenerator ExcludeType(Type type)
{
_exclude.Add(type);
return this;
}
public TypeScriptGenerator AddCSType(Type type)
{
if (_defined.Add(type))
_toDefine.Push(type);
return this;
}
static string WithoutGeneric(Type type)
{
return type.Name.Split('`')[0];
}
public string TypeName(Type type, bool forceClass = false)
{
var
ti = type.GetTypeInfo();
if (ti.IsGenericParameter)
return type.Name;
var
map = type.GetTypeInfo().GetCustomAttribute<TSMap>(false);
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
if (ti.IsEnum)
{
AddCSType(type);
return map == null ? type.Name : map.Name;
}
return "number";
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return "number";
case TypeCode.Boolean:
return "boolean";
case TypeCode.String:
return "string";
case TypeCode.DateTime:
return "Date";
case TypeCode.Object:
if (type.IsArray)
return TypeName(type.GetElementType()) + "[]";
if (type == typeof(Guid))
return "string";
if (type == typeof(object))
return "any";
if (ti.IsGenericType)
{
var
genericType = ti.GetGenericTypeDefinition();
var
generics = ti.GetGenericArguments();
if (genericType == typeof(Dictionary<,>))
{
if (generics[0] == typeof(int) || generics[0] == typeof(string))
return $"{{ [index: {TypeName(generics[0])}]: {TypeName(generics[1])} }}";
return "{}";
}
// any other enumerable
if (genericType.GetInterfaces().Any(e => e.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
return TypeName(generics[0]) + "[]";
AddCSType(genericType);
map = genericType.GetTypeInfo().GetCustomAttribute<TSMap>(false);
return $"{NamespacePrefix(genericType)}{NormalizeInterface(map == null ? WithoutGeneric(genericType) : map.Name, forceClass)}<{string.Join(", ", generics.Select(e => TypeName(e)))}>";
}
AddCSType(type);
return NamespacePrefix(type) + NormalizeInterface(map == null ? type.Name : map.Name, forceClass);
default:
return $"any /* {type.FullName} */";
}
}
string NamespacePrefix(Type type)
{
return type.Namespace == _namespace || _options.IgnoreNamespaces ? "" : (type.Namespace + '.');
}
string _namespace = "";
CodeTextBuilder Builder
{
get { return _builder[_namespace]; }
}
void SetNamespace(Type type)
{
_namespace = type.Namespace;
if (!_builder.ContainsKey(_namespace))
_builder[_namespace] = new CodeTextBuilder();
}
void GenerateTypeDefinition(Type type)
{
var
ti = type.GetTypeInfo();
if (ti.GetCustomAttribute<TSExclude>() != null || _exclude.Contains(type))
return;
SetNamespace(type);
CommentClass(type);
if (ti.IsEnum)
{
Builder.AppendLine($"export enum {TypeName(type)}");
Builder.OpenScope();
foreach (var e in Enum.GetValues(type))
Builder.AppendLine($"{e} = {Convert.ToInt32(e)},");
Builder.CloseScope();
return;
}
bool
forceClass = ti.GetCustomAttribute<TSClass>() != null,
flat = ti.GetCustomAttribute<TSFlat>() != null;
Builder.Append($"export {(forceClass ? "class" : "interface")} {TypeName(type, forceClass)}");
var
baseType = ti.BaseType;
if (ti.IsClass && !flat && baseType != null && baseType != typeof(object))
Builder.AppendLine($" extends {TypeName(baseType)}");
Builder.OpenScope();
var
flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static;
if (!flat)
flags |= BindingFlags.DeclaredOnly;
// fields
GenerateFields(
type,
type.GetFields(flags),
f => f.FieldType,
f => f.IsInitOnly,
f => f.IsStatic,
forceClass);
// properties
GenerateFields(
type,
type.GetProperties(flags),
f => f.PropertyType,
f => false,
f => f.GetGetMethod().IsStatic,
forceClass
);
Builder.CloseScope();
}
void GenerateFields<T>(Type type, T[] fields, Func<T, Type> getType, Func<T, bool> getReadonly, Func<T, bool> getStatic, bool forceClass) where T : MemberInfo
{
foreach (var f in fields)
{
if (f.GetCustomAttribute<TSExclude>() == null) // only fields defined in that type
{
var fieldType = getType(f);
CommentMember(fieldType, f);
var nullable = Nullable.GetUnderlyingType(fieldType);
if (nullable != null)
fieldType = getType(f).GetGenericArguments()[0];
var optional = f.GetCustomAttribute<TSOptional>() != null;
// If not the attribute was used, check if the type is nullable
if (!optional)
{
// Needs to fetch the Type from the PropertyInfo or FieldInfo-objects, for some resone
// the fieldType-variable does not contain this info.
Type realType = null;
if (f is PropertyInfo pInfo)
{
realType = pInfo.PropertyType;
}
else if (f is FieldInfo fInfo)
{
realType = fInfo.FieldType;
}
if (realType != null)
{
if (realType.IsGenericType && realType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
optional = true;
}
}
}
if (getStatic(f))
Builder.Append("static ");
if (_options.EmitReadonly && getReadonly(f))
Builder.Append("readonly ");
Builder.Append(NormalizeField(f.Name));
Builder.Append(optional ? "?" : "");
Builder.Append(": ");
Builder.Append(f.GetCustomAttribute<TSAny>() == null ? TypeName(fieldType) : "any");
var
init = f.GetCustomAttribute<TSInitialize>();
if (forceClass && init != null)
Builder.Append($" = {GenerateBody(init, f)}");
Builder.AppendLine(";");
}
}
}
private string GenerateBody(TSInitialize attribute, MemberInfo info)
{
if (attribute.Body != null)
return attribute.Body;
if (info is FieldInfo)
{
FieldInfo field = info as FieldInfo;
return JsonConvert.SerializeObject(field.GetRawConstantValue());
}
else
{
PropertyInfo property = info as PropertyInfo;
return JsonConvert.SerializeObject(property.GetRawConstantValue());
}
}
private void CommentClass(Type type)
{
var summery = "";
if (_options.EmitDocumentation)
{
summery = type.GetSummary();
}
AppendComment(summery,type.ToString());
}
private void CommentMember<T>(Type type, T memberInfo) where T : MemberInfo
{
var methodSummary = "";
if (_options.EmitDocumentation)
{
methodSummary = memberInfo.GetSummary();
}
AppendComment(methodSummary,type.ToString());
}
private void AppendComment(string commentText, string type)
{
if(_options.EmitComments && _options.EmitDocumentation)
{
Builder.AppendLine($"/** {commentText} ({type}) */");
}
else if (_options.EmitComments && !string.IsNullOrEmpty(type))
{
Builder.AppendLine($"/** {type} */");
}
else if (_options.EmitDocumentation && !string.IsNullOrEmpty(commentText))
{
Builder.AppendLine($"/** {commentText} */");
}
}
public string NormalizeField(string name)
{
if (!_options.UseCamelCase)
return name;
return char.ToLower(name[0]) + name.Substring(1);
}
public string NormalizeInterface(string name, bool forceClass)
{
if (forceClass || !_options.EmitIinInterface)
return name;
return 'I' + name;
}
public override string ToString()
{
while (_toDefine.Count > 0)
GenerateTypeDefinition(_toDefine.Pop());
var builder = new CodeTextBuilder();
builder.AppendLine("// NOTE: This file is auto-generated. Any changes will be overwritten.");
foreach (var e in _builder)
{
if (!_options.IgnoreNamespaces)
{
builder.AppendLine($"namespace {e.Key}");
builder.OpenScope();
}
builder.AppendLine(e.Value.ToString());
if (!_options.IgnoreNamespaces)
builder.CloseScope();
}
return builder.ToString();
}
public void Store(string file)
{
File.WriteAllText(file, ToString());
}
}
}
| mit |
conanite/sepa | lib/sepa/payments_initiation/financial_identification_scheme_name_1_choice.rb | 173 | class Sepa::PaymentsInitiation::FinancialIdentificationSchemeName1Choice < Sepa::Base
code_or_proprietary
def empty?
[code, proprietary].join.strip == ""
end
end
| mit |
merorafael/DelphiCompat | src/Mero/DelphiCompat/TColor.php | 1670 | <?php
namespace Mero\DelphiCompat;
class TColor
{
/**
* @var string Color in TColor format
*/
private $tcolor;
/**
* @var array Color in RGB format
*/
private $rgb;
/**
* @var string Color in hex format
*/
private $hex;
/**
* TColor constructor.
*
* @param string $color Color in TColor format
*/
public function __construct($color)
{
$this->setColor($color);
}
/**
* Define color using TColor format.
*
* @param string $color Color in TColor format
*
* @return TColor
*/
public function setColor($color)
{
$this->tcolor = $color;
$this->rgb = [
'r' => $color & 0xFF,
'g' => ($color >> 8) & 0xFF,
'b' => ($color >> 16) & 0xFF,
];
$hexRed = str_pad(dechex($this->rgb['r']), 2, '0', STR_PAD_LEFT);
$hexGreen = str_pad(dechex($this->rgb['g']), 2, '0', STR_PAD_LEFT);
$hexBlue = str_pad(dechex($this->rgb['b']), 2, '0', STR_PAD_LEFT);
$this->hex = '#'.$hexRed.$hexGreen.$hexBlue;
return $this;
}
/**
* Return color in TColor format.
*
* @return string Color in TColor format string
*/
public function getTColor()
{
return $this->tcolor;
}
/**
* Return color in RGB format.
*
* @return array Color in RGB format
*/
public function getRGB()
{
return $this->rgb;
}
/**
* Return color in hex format.
*
* @return string Color in hex format
*/
public function getHex()
{
return $this->hex;
}
}
| mit |
novuso/service | src/Novuso/Component/Service/Exception/ServiceNotFoundException.php | 363 | <?php
/**
* This file is part of the Novuso Framework
*
* @author John Nickell
* @copyright Copyright (c) 2013, Novuso. (http://novuso.com)
* @license http://opensource.org/licenses/MIT The MIT License
*/
namespace Novuso\Component\Service\Exception;
use InvalidArgumentException;
class ServiceNotFoundException extends InvalidArgumentException
{
}
| mit |
intothevoid/bosskey | BossKee/BossKeeDlg.cpp | 7309 |
// BossKeeDlg.cpp : implementation file
//
#include "stdafx.h"
#include "BossKee.h"
#include "BossKeeDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//Constants
const int HOTKEY_ID = 100;
//Global mappings of window titles and handles
map<CString,HWND> g_mapMain;
//Global window name to set
CString g_csWindowTitle = _T("");
//Global hide/unhide flag
BOOL g_bHide = 0;
//User message
#define WM_MYMESSAGE (WM_USER + 1)
//User notification structure
NOTIFYICONDATA nid;
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CBossKeeDlg dialog
CBossKeeDlg::CBossKeeDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CBossKeeDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CBossKeeDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_lstMain);
DDX_Control(pDX, IDC_BUTTON3, m_cmdApply);
}
BEGIN_MESSAGE_MAP(CBossKeeDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON3, &CBossKeeDlg::OnBnClickedButton3)
//Hotkey Handler
ON_MESSAGE(WM_HOTKEY, OnHotKey)
ON_MESSAGE(WM_MYMESSAGE, OnMyMessage)
ON_WM_CLOSE()
ON_LBN_SELCHANGE(IDC_LIST1, &CBossKeeDlg::OnLbnSelchangeList1)
ON_BN_CLICKED(IDC_BUTTON4, &CBossKeeDlg::OnBnClickedButton4)
ON_BN_CLICKED(IDC_BUTTON2, &CBossKeeDlg::OnBnClickedButton2)
END_MESSAGE_MAP()
// CBossKeeDlg message handlers
BOOL CBossKeeDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
//Clear main handle title map
g_mapMain.clear();
//Intial Apply button disabled
m_cmdApply.EnableWindow(FALSE);
//Setup our hotkey
if(!RegisterHotKey(m_hWnd, HOTKEY_ID, MOD_CONTROL, VK_SPACE))
{
DWORD dwError = ::GetLastError();
TRACE(_T("RegisterHotKeys() Failed Code: %ld"),dwError);
MessageBox(_T("BossKee: Failed to register hotkey!"));
}
//Populate list
RefreshList();
return TRUE; // return TRUE unless you set the focus to a control
}
void CBossKeeDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CBossKeeDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CBossKeeDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
BOOL CALLBACK CBossKeeDlg::EnumWindowsCallback(HWND hwndWindow, LPARAM lpParam)
{
TCHAR lpszBuff[1024];
memset(lpszBuff,0,1024);
int nCnt = 0;
::GetWindowText(hwndWindow,lpszBuff,(int)(_tcslen(lpszBuff) - 1));
CBossKeeDlg *myObj = (CBossKeeDlg *)lpParam;
//Only add valid window titles
if(0 != _tcscmp(lpszBuff,_T("")))
{
myObj->m_lstMain.AddString(lpszBuff);
g_mapMain[lpszBuff] = hwndWindow;
nCnt = g_mapMain.size();
}
//To continue enumeration, we return TRUE
return TRUE;
}
void CBossKeeDlg::OnBnClickedButton3()
{
//Get the current selected Window title from list
//and save it to our global location
int nSel = m_lstMain.GetCurSel();
m_lstMain.GetText(nSel,g_csWindowTitle);
//Disable command button
m_cmdApply.EnableWindow(FALSE);
}
LRESULT CBossKeeDlg::OnHotKey(WPARAM wParam, LPARAM lParam)
{
HWND hndWindow = NULL;
hndWindow = g_mapMain[g_csWindowTitle];
//Window is visible
if(0 == g_bHide)
{
::ShowWindow(hndWindow,SW_HIDE);
//Window is now hidden
g_bHide = 1;
}
else
{
//Window is not visible
::ShowWindow(hndWindow,SW_SHOWNORMAL);
//Window is now visible
g_bHide = 0;
}
return TRUE;
}
void CBossKeeDlg::OnClose()
{
// TODO: Add your message handler code here and/or call default
//Unregister hotkey
if(!UnregisterHotKey(m_hWnd, HOTKEY_ID))
{
DWORD dwError = ::GetLastError();
TRACE(_T("UnRegisterHotKeys() Failed Code: %ld"),dwError);
MessageBox(_T("BossKee: Failed to unregister hotkey!"));
}
CDialogEx::OnClose();
}
void CBossKeeDlg::OnLbnSelchangeList1()
{
// TODO: Add your control notification handler code here
//Enable apply button
m_cmdApply.EnableWindow();
}
void CBossKeeDlg::OnBnClickedButton4()
{
// TODO: Add your control notification handler code here
//Refresh the list
RefreshList();
}
void CBossKeeDlg::RefreshList()
{
//Clear list
m_lstMain.ResetContent();
//Clear our map
g_mapMain.clear();
//Start the enumeration
BOOL bRetVal = FALSE;
bRetVal = EnumWindows(EnumWindowsCallback,(LPARAM)this);
if(FALSE == bRetVal)
{
DWORD dwError = ::GetLastError();
TRACE(_T("Enumwindows Failed Code: %ld"),dwError);
MessageBox(_T("BossKee: Window Enumeration failed!"));
}
}
void CBossKeeDlg::OnBnClickedButton2()
{
// TODO: Add your control notification handler code here
//Minimize to System Tray
//Show the notification icon
ZeroMemory(&nid,sizeof(nid));
nid.cbSize = sizeof(NOTIFYICONDATA);
nid.hWnd = m_hWnd;
nid.uID = 0;
nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
nid.uCallbackMessage = WM_USER+1;
nid.hIcon = LoadIcon(AfxGetInstanceHandle() ,MAKEINTRESOURCE(IDI_ICON2));
_tcscpy(nid.szTip, _T("BossKey - I have your back!\n\nClick me to restore."));
Shell_NotifyIcon(NIM_ADD,&nid);
//Hide me
ShowWindow(SW_HIDE);
}
LRESULT CBossKeeDlg::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
switch(lParam)
{
case WM_LBUTTONUP:
ShowWindow(SW_SHOWNORMAL);
Shell_NotifyIcon(NIM_DELETE,&nid);
return true;
}
return TRUE;
} | mit |
tatemae/muck-activities | test/app/controllers/default_controller.rb | 100 | class DefaultController < ApplicationController
def index
@user = current_user
end
end | mit |
lytics/ember-components | addon/components/lio-option.js | 3198 | import { tagForType } from '../util/namespace';
import ChildComponentMixin from '../mixins/child';
import ActiveStateMixin from '../mixins/active-state';
import TransitionMixin from '../mixins/transition';
import Ember from 'ember';
const Component = Ember.Component;
const get = Ember.get;
const set = Ember.set;
const computed = Ember.computed;
const uuid = Ember.uuid;
const typeKey = 'option';
/**
Option Component
This component represents an option that the user can choose from. The value
of the option is set through its `value` attribute, which defaults to the
template's context if omitted (this makes looping over options easy). Options
have a 'selected' state which is managed by the parent component, and an
optional 'unselect' attribute which effectively makes the option a 'remove'
button (with a value). When clicked, options send the 'select' event to their
parent with its value, which can be disabled using the 'disabled' state.
Options also have a class binding for an intelligent string representation of
its value.
*/
export default Component.extend(ChildComponentMixin, ActiveStateMixin, TransitionMixin, {
//
// HTML Properties
//
tagName: tagForType(typeKey),
classNameBindings: [ 'valueClass', 'disabled', 'selected', 'unselect', 'filtered' ],
//
// Handlebars Attributes
//
option: null,
value: computed(function() {
// The 'content' path is the current context
const path = this.get('valuePath');
const option = this.get('option');
return option && get(option, path);
}).property('option', 'valuePath'),
valuePath: computed.oneWay('parent.optionValuePath'),
selected: false,
unselect: false,
disabled: computed.oneWay('parent.disabled'),
filtered: false,
//
// Internal Properties
//
typeKey: typeKey,
isSelected: computed.readOnly('selected'),
isUnselect: computed.readOnly('unselect'),
isDisabled: computed.readOnly('disabled'),
isFiltered: computed.readOnly('filtered'),
valueClass: computed(function() {
let value = get(this, 'value');
const type = Ember.typeOf(value);
// Avoid '[Object object]' classes and complex toString'd values
if (type === 'object' || type === 'instance') {
// Look for an identifier, fall back on a uuid
value = get(value, 'id') || ('option-' + get(this, 'uuid'));
}
return '' + value;
}).property('value'),
uuid: computed(function() {
return uuid();
}).property(),
// Override the active state mixin's property to use the parent's value
isActive: computed(function() {
return get(this, 'value') === get(this, 'parent.value');
}).property('value', 'parent.value'),
//
// Event Handlers
//
click: function() {
// Do not perform the action if the component is disabled
if (get(this, 'isDisabled')) { return; }
const parent = get(this, 'parent');
const isUnselect = get(this, 'isUnselect');
const isSelected = get(this, 'isSelected');
const value = get(this, 'value');
// Don't set the select state directly; let the parent manage the state
parent.send('select', value, isUnselect ? false : !isSelected);
}
});
| mit |
pchrysa/Memento-Calendar | android_mobile/src/main/java/com/alexstyl/specialdates/upcoming/widget/today/UserOptions.java | 473 | package com.alexstyl.specialdates.upcoming.widget.today;
final class UserOptions {
private final float opacityLevel;
private final WidgetVariant widgetVariant;
UserOptions(float opacityLevel, WidgetVariant widgetVariant) {
this.opacityLevel = opacityLevel;
this.widgetVariant = widgetVariant;
}
float getOpacityLevel() {
return opacityLevel;
}
WidgetVariant getWidgetVariant() {
return widgetVariant;
}
}
| mit |
AstramMC/ArcadeAPI | src/me/astramg/arcadeapi/api/Game.java | 87 | package me.astramg.arcadeapi.api;
public class Game {
public int x = 0;
}
| mit |
markwylde/Symfony-CookBook | app/cache/dev/appDevUrlMatcher.php | 12822 | <?php
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;
/**
* appDevUrlMatcher
*
* This class has been auto-generated
* by the Symfony Routing Component.
*/
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
/**
* Constructor.
*/
public function __construct(RequestContext $context)
{
$this->context = $context;
}
public function match($pathinfo)
{
$allow = array();
$pathinfo = rawurldecode($pathinfo);
$context = $this->context;
$request = $this->request;
if (0 === strpos($pathinfo, '/_')) {
// _wdt
if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
}
if (0 === strpos($pathinfo, '/_profiler')) {
// _profiler_home
if (rtrim($pathinfo, '/') === '/_profiler') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_profiler_home');
}
return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',);
}
if (0 === strpos($pathinfo, '/_profiler/search')) {
// _profiler_search
if ($pathinfo === '/_profiler/search') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',);
}
// _profiler_search_bar
if ($pathinfo === '/_profiler/search_bar') {
return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',);
}
}
// _profiler_purge
if ($pathinfo === '/_profiler/purge') {
return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',);
}
if (0 === strpos($pathinfo, '/_profiler/i')) {
// _profiler_info
if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',));
}
// _profiler_import
if ($pathinfo === '/_profiler/import') {
return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',);
}
}
// _profiler_export
if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',));
}
// _profiler_phpinfo
if ($pathinfo === '/_profiler/phpinfo') {
return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',);
}
// _profiler_search_results
if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
}
// _profiler
if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',));
}
// _profiler_router
if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',));
}
// _profiler_exception
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',));
}
// _profiler_exception_css
if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',));
}
}
if (0 === strpos($pathinfo, '/_configurator')) {
// _configurator_home
if (rtrim($pathinfo, '/') === '/_configurator') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_configurator_home');
}
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',);
}
// _configurator_step
if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',));
}
// _configurator_final
if ($pathinfo === '/_configurator/final') {
return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',);
}
}
}
// baker_recipe_about
if (rtrim($pathinfo, '/') === '/about') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'baker_recipe_about');
}
return array ( '_controller' => 'Baker\\RecipeBundle\\Controller\\PageController::aboutAction', '_route' => 'baker_recipe_about',);
}
if (0 === strpos($pathinfo, '/recipe')) {
// baker_recipe_list
if ($pathinfo === '/recipes') {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_baker_recipe_list;
}
return array ( '_controller' => 'Baker\\RecipeBundle\\Controller\\RecipeController::listAction', '_route' => 'baker_recipe_list',);
}
not_baker_recipe_list:
// baker_recipe_create
if ($pathinfo === '/recipe/submit') {
if (!in_array($this->context->getMethod(), array('GET', 'POST', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'POST', 'HEAD'));
goto not_baker_recipe_create;
}
return array ( '_controller' => 'Baker\\RecipeBundle\\Controller\\RecipeController::createAction', '_route' => 'baker_recipe_create',);
}
not_baker_recipe_create:
// baker_recipe_read
if (preg_match('#^/recipe/(?P<id>\\d+)$#s', $pathinfo, $matches)) {
if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
$allow = array_merge($allow, array('GET', 'HEAD'));
goto not_baker_recipe_read;
}
return $this->mergeDefaults(array_replace($matches, array('_route' => 'baker_recipe_read')), array ( '_controller' => 'Baker\\RecipeBundle\\Controller\\RecipeController::readAction',));
}
not_baker_recipe_read:
}
// _welcome
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_welcome');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',);
}
if (0 === strpos($pathinfo, '/demo')) {
if (0 === strpos($pathinfo, '/demo/secured')) {
if (0 === strpos($pathinfo, '/demo/secured/log')) {
if (0 === strpos($pathinfo, '/demo/secured/login')) {
// _demo_login
if ($pathinfo === '/demo/secured/login') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',);
}
// _security_check
if ($pathinfo === '/demo/secured/login_check') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',);
}
}
// _demo_logout
if ($pathinfo === '/demo/secured/logout') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',);
}
}
if (0 === strpos($pathinfo, '/demo/secured/hello')) {
// acme_demo_secured_hello
if ($pathinfo === '/demo/secured/hello') {
return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => 'acme_demo_secured_hello',);
}
// _demo_secured_hello
if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',));
}
// _demo_secured_hello_admin
if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello_admin')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',));
}
}
}
// _demo
if (rtrim($pathinfo, '/') === '/demo') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', '_demo');
}
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',);
}
// _demo_hello
if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',));
}
// _demo_contact
if ($pathinfo === '/demo/contact') {
return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',);
}
}
throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
}
}
| mit |