code
stringlengths
5
1.01M
repo_name
stringlengths
5
84
path
stringlengths
4
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
5
1.01M
input_ids
listlengths
502
502
token_type_ids
listlengths
502
502
attention_mask
listlengths
502
502
labels
listlengths
502
502
<div> <?php $labo_id = $current_user->get_preferred_labo(); $events = Sim::get_sim_changes($labo_id); $events_count = mysql_num_rows($events); ?> <h2>SIM changes</h2> <b>for <?php echo get_lab_name($labo_id); ?></b> <?php if($events_count) { ?> <table class="display display-medium-nospace"> <thead> <tr> <th>MSISDN</th> <th>owner</th> <th>start date</th> <th>end date</th> </tr> </thead> <tbody> <?php // vars for switching tr background $i = 1; $tr_class = array("", "odd"); while($event = mysql_fetch_array($events)) { echo '<tr class="'.$tr_class[$i%2].'">'; echo '<td>'.$event['sim_msisdn'].'</td>'; echo '<td>'.format_name($event['prenom'], $event['nom']).'</td>'; echo '<td>'.$event['date_begin'].'</td>'; echo '<td>'.$event['date_end'].'</td>'; echo '</tr>'; $i++; } ?> </tbody> </table> <?php } ?> </div>
Wohlraj/devices-management-tool
view/sim_history.php
PHP
apache-2.0
941
[ 30522, 1026, 4487, 2615, 1028, 1026, 1029, 25718, 1002, 6845, 2080, 1035, 8909, 1027, 1002, 2783, 1035, 5310, 1011, 1028, 2131, 1035, 6871, 1035, 6845, 2080, 1006, 1007, 1025, 1002, 2824, 1027, 21934, 1024, 1024, 2131, 1035, 21934, 1035, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class RubyXL::VectorValue - rubyXL 3.4.21</title> <script type="text/javascript"> var rdoc_rel_prefix = "../"; var index_rel_prefix = "../"; </script> <script src="../js/navigation.js" defer></script> <script src="../js/search.js" defer></script> <script src="../js/search_index.js" defer></script> <script src="../js/searcher.js" defer></script> <script src="../js/darkfish.js" defer></script> <link href="../css/fonts.css" rel="stylesheet"> <link href="../css/rdoc.css" rel="stylesheet"> <body id="top" role="document" class="class"> <nav role="navigation"> <div id="project-navigation"> <div id="home-section" role="region" title="Quick navigation" class="nav-section"> <h2> <a href="../index.html" rel="home">Home</a> </h2> <div id="table-of-contents-navigation"> <a href="../table_of_contents.html#pages">Pages</a> <a href="../table_of_contents.html#classes">Classes</a> <a href="../table_of_contents.html#methods">Methods</a> </div> </div> <div id="search-section" role="search" class="project-section initially-hidden"> <form action="#" method="get" accept-charset="utf-8"> <div id="search-field-wrapper"> <input id="search-field" role="combobox" aria-label="Search" aria-autocomplete="list" aria-controls="search-results" type="text" name="search" placeholder="Search" spellcheck="false" title="Type to search, Up and Down to navigate, Enter to load"> </div> <ul id="search-results" aria-label="Search Results" aria-busy="false" aria-expanded="false" aria-atomic="false" class="initially-hidden"></ul> </form> </div> </div> <div id="class-metadata"> <div id="parent-class-section" class="nav-section"> <h3>Parent</h3> <p class="link">OOXMLObject </div> </div> </nav> <main role="main" aria-labelledby="class-RubyXL::VectorValue"> <h1 id="class-RubyXL::VectorValue" class="class"> class RubyXL::VectorValue </h1> <section class="description"> </section> <section id="5Buntitled-5D" class="documentation-section"> </section> </main> <footer id="validator-badges" role="contentinfo"> <p><a href="https://validator.w3.org/check/referer">Validate</a> <p>Generated by <a href="https://ruby.github.io/rdoc/">RDoc</a> 6.4.0. <p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>. </footer>
weshatheleopard/rubyXL
rdoc/RubyXL/VectorValue.html
HTML
mit
2,534
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 2516, 1028, 2465, 10090, 2595, 2140, 1024, 1024, 9207, 10175, 5657, 1011, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php // (c) Copyright 2002-2013 by authors of the Tiki Wiki CMS Groupware Project // // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. // $Id: Div.php 45445 2013-04-11 20:54:04Z lphuberdeau $ class Math_Formula_Function_Div extends Math_Formula_Function { function evaluate( $element ) { $elements = array(); foreach ( $element as $child ) { $elements[] = $this->evaluateChild($child); } $out = array_shift($elements); foreach ($elements as $element) { $out /= $element; } return $out; } }
reneejustrenee/tikiwikitest
lib/core/Math/Formula/Function/Div.php
PHP
lgpl-2.1
643
[ 30522, 1026, 1029, 25718, 1013, 1013, 1006, 1039, 1007, 9385, 2526, 1011, 2286, 2011, 6048, 1997, 1996, 14841, 3211, 15536, 3211, 4642, 2015, 2177, 8059, 2622, 1013, 1013, 1013, 1013, 2035, 2916, 9235, 1012, 2156, 9385, 1012, 19067, 2102, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 2003 MaxSt ( maxst@hiend3d.com ) * * Adapted for Exult: 4/7/07 - JSF * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #ifdef USE_HQ4X_SCALER #include "SDL_video.h" #include "imagewin.h" #include <cstdlib> #include <cstring> #include "exult_types.h" #include "manip.h" #include "scale_hq4x.h" // // Hq4x Filtering // void Image_window::show_scaled8to16_Hq4x( int x, int y, int w, int h // Area to show. ) { Manip8to16 manip(paletted_surface->format->palette->colors, inter_surface->format); Scale_Hq4x<uint16, Manip8to16> (reinterpret_cast<uint8 *>(draw_surface->pixels), x + guard_band, y + guard_band, w, h, ibuf->line_width, ibuf->height + guard_band, reinterpret_cast<uint16 *>(inter_surface->pixels), inter_surface->pitch / inter_surface->format->BytesPerPixel, manip); } void Image_window::show_scaled8to555_Hq4x( int x, int y, int w, int h // Area to show. ) { Manip8to555 manip(paletted_surface->format->palette->colors, inter_surface->format); Scale_Hq4x<uint16, Manip8to555> (reinterpret_cast<uint8 *>(draw_surface->pixels), x + guard_band, y + guard_band, w, h, ibuf->line_width, ibuf->height + guard_band, reinterpret_cast<uint16 *>(inter_surface->pixels), inter_surface->pitch / inter_surface->format->BytesPerPixel, manip); } void Image_window::show_scaled8to565_Hq4x( int x, int y, int w, int h // Area to show. ) { Manip8to565 manip(paletted_surface->format->palette->colors, inter_surface->format); Scale_Hq4x<uint16, Manip8to565> (reinterpret_cast<uint8 *>(draw_surface->pixels), x + guard_band, y + guard_band, w, h, ibuf->line_width, ibuf->height + guard_band, reinterpret_cast<uint16 *>(inter_surface->pixels), inter_surface->pitch / inter_surface->format->BytesPerPixel, manip); } void Image_window::show_scaled8to32_Hq4x( int x, int y, int w, int h // Area to show. ) { Manip8to32 manip(paletted_surface->format->palette->colors, inter_surface->format); Scale_Hq4x<uint32, Manip8to32> (reinterpret_cast<uint8 *>(draw_surface->pixels), x + guard_band, y + guard_band, w, h, ibuf->line_width, ibuf->height + guard_band, reinterpret_cast<uint32 *>(inter_surface->pixels), inter_surface->pitch / inter_surface->format->BytesPerPixel, manip); } #endif //USE_HQ4X_SCALER
slashman/exult-tbc
imagewin/scale_hq4x.cc
C++
gpl-2.0
3,125
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2494, 4098, 3367, 1006, 4098, 3367, 1030, 7632, 10497, 29097, 1012, 4012, 1007, 1008, 1008, 5967, 2005, 4654, 11314, 1024, 1018, 1013, 1021, 1013, 5718, 1011, 1046, 22747, 1008, 1008, 2023, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
function getFunction(f,b){ return function myNextTick(){ console.log(f + " " + b); }; } process.nextTick(getFunction("foo", "bar"));
marcos-goes/livro_node
04/next-tick-gambi.js
JavaScript
apache-2.0
146
[ 30522, 3853, 2131, 11263, 27989, 1006, 1042, 1010, 1038, 1007, 1063, 2709, 3853, 2026, 2638, 18413, 26348, 1006, 1007, 1063, 10122, 1012, 8833, 1006, 1042, 1009, 1000, 1000, 1009, 1038, 1007, 1025, 1065, 1025, 1065, 2832, 1012, 2279, 26348,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- simple-qml.qdoc --> <title>Qt 3D: Simple QML Example | Qt 3D 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qt3d-index.html">Qt 3D</a></td><td >Qt 3D: Simple QML Example</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#running-the-example">Running the Example</a></li> <li class="level1"><a href="#setting-up-the-scene">Setting Up the Scene</a></li> <li class="level1"><a href="#specifying-settings-and-axes">Specifying Settings and Axes</a></li> <li class="level1"><a href="#specifying-settings-and-axes">Specifying Settings and Axes</a></li> </ul> </div> <div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">Qt 3D: Simple QML Example</h1> <span class="subtitle"></span> <!-- $$$simple-qml-description --> <div class="descr"> <a name="details"></a> <p class="centerAlign"><img src="images/simple-qml.png" alt="" /></p><p><i>Simple</i> demonstrates how to render a scene in Qt 3D.</p> <a name="running-the-example"></a> <h2 id="running-the-example">Running the Example</h2> <p>To run the example from <a href="http://doc.qt.io/qtcreator/index.html">Qt Creator</a>, open the <b>Welcome</b> mode and select the example from <b>Examples</b>. For more information, visit <a href="http://doc.qt.io/qtcreator/creator-build-example-application.html">Building and Running an Example</a>.</p> <a name="setting-up-the-scene"></a> <h2 id="setting-up-the-scene">Setting Up the Scene</h2> <p>We set up the entire scene in the <i>main.qml</i> file.</p> <p>To be able to use the types in the Q3D and Q3D Render modules, we must import the modules:</p> <pre class="qml"> import Qt3D.Core 2.0 import Qt3D.Render 2.0 </pre> <p>The first entities we create are a <a href="qml-qt3d-render-camera.html">Camera</a>, which represents the camera used for the final rendering, and a camera controller, which allows us to control this camera using the keyboard or the mouse:</p> <pre class="qml"> <span class="type"><a href="qml-qt3d-render-camera.html">Camera</a></span> { <span class="name">id</span>: <span class="name">camera</span> <span class="name">projectionType</span>: <span class="name">CameraLens</span>.<span class="name">PerspectiveProjection</span> <span class="name">fieldOfView</span>: <span class="number">45</span> <span class="name">aspectRatio</span>: <span class="number">16</span><span class="operator">/</span><span class="number">9</span> <span class="name">nearPlane</span> : <span class="number">0.1</span> <span class="name">farPlane</span> : <span class="number">1000.0</span> <span class="name">position</span>: <span class="name">Qt</span>.<span class="name">vector3d</span>( <span class="number">0.0</span>, <span class="number">0.0</span>, -<span class="number">40.0</span> ) <span class="name">upVector</span>: <span class="name">Qt</span>.<span class="name">vector3d</span>( <span class="number">0.0</span>, <span class="number">1.0</span>, <span class="number">0.0</span> ) <span class="name">viewCenter</span>: <span class="name">Qt</span>.<span class="name">vector3d</span>( <span class="number">0.0</span>, <span class="number">0.0</span>, <span class="number">0.0</span> ) } <span class="type">OrbitCameraController</span> { <span class="name">camera</span>: <span class="name">camera</span> } </pre> <p>A RenderSettings entity specifies a ForwardRenderer as the active framegraph:</p> <pre class="qml"> <span class="name">components</span>: [ <span class="type">RenderSettings</span> { <span class="name">activeFrameGraph</span>: <span class="name">ForwardRenderer</span> { <span class="name">clearColor</span>: <span class="name">Qt</span>.<span class="name">rgba</span>(<span class="number">0</span>, <span class="number">0.5</span>, <span class="number">1</span>, <span class="number">1</span>) <span class="name">camera</span>: <span class="name">camera</span> } }, </pre> <p>The event source is set by the Qt3DQuickWindow:</p> <pre class="qml"> <span class="type"><a href="qml-qt3d-input-inputsettings.html">InputSettings</a></span> { } </pre> <a name="specifying-settings-and-axes"></a> <a name="specifying-settings-and-axes"></a> <h2 id="specifying-settings-and-axes">Specifying Settings and Axes</h2> <p>In the <i>CameraController.qml</i> file, we use the <a href="qml-qt3d-input-logicaldevice.html">LogicalDevice</a> type to define a set of actions and axes to use within the application:</p> <pre class="qml"> <span class="type"><a href="qml-qt3d-input-logicaldevice.html">LogicalDevice</a></span> { <span class="name">id</span>: <span class="name">cameraControlDevice</span> <span class="name">actions</span>: [ <span class="type"><a href="qml-qt3d-input-action.html">Action</a></span> { <span class="name">name</span>: <span class="string">&quot;LMB&quot;</span> <span class="name">inputs</span>: [ <span class="type"><a href="qml-qt3d-input-actioninput.html">ActionInput</a></span> { <span class="name">sourceDevice</span>: <span class="name">mouseSourceDevice</span> <span class="name">buttons</span>: [<span class="name">MouseEvent</span>.<span class="name">LeftButton</span>] ... <span class="name">axes</span>: [ <span class="comment">// Rotation</span> <span class="type"><a href="qml-qt3d-input-axis.html">Axis</a></span> { <span class="name">name</span>: <span class="string">&quot;RX&quot;</span> <span class="name">inputs</span>: [ <span class="type"><a href="qml-qt3d-input-analogaxisinput.html">AnalogAxisInput</a></span> { <span class="name">sourceDevice</span>: <span class="name">mouseSourceDevice</span> <span class="name">axis</span>: <span class="name">MouseDevice</span>.<span class="name">X</span> } ] ... </pre> <p>Files:</p> <ul> <li><a href="qt3d-simple-qml-cameracontroller-qml.html">simple-qml/CameraController.qml</a></li> <li><a href="qt3d-simple-qml-main-qml.html">simple-qml/main.qml</a></li> <li><a href="qt3d-simple-qml-main-cpp.html">simple-qml/main.cpp</a></li> <li><a href="qt3d-simple-qml-simple-qml-pro.html">simple-qml/simple-qml.pro</a></li> <li><a href="qt3d-simple-qml-simple-qml-qrc.html">simple-qml/simple-qml.qrc</a></li> </ul> </div> <!-- @@@simple-qml --> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
angeloprudentino/QtNets
Doc/qt3d/qt3d-simple-qml-example.html
HTML
gpl-3.0
8,281
[ 30522, 1026, 1029, 20950, 2544, 1027, 1000, 1015, 1012, 1014, 1000, 17181, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1029, 1028, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * This file adds the main menu, free version must be under appearance, this file is NOT in the free version. * @package PageLines DMS * @since 1.0.1 * * // set memory limit * // dashboard menus * // shortcodes extended */ add_filter( 'pagelines_global_notification', 'pagelines_check_pro_nag' ); function pagelines_check_pro_nag( $note ) { if( pl_is_pro_check() ) return $note; ob_start(); ?> <div class="alert editor-alert"> <button type="button" class="close" data-dismiss="alert" href="#">&times;</button> <strong><i class="icon icon-star"></i> <?php _e( 'Upgrade to Pro!', 'pagelines' ); ?> </strong> <br/> <?php _e( 'You are currently using the basic DMS version. Pro activate this site for tons more features and support.', 'pagelines' ); ?> <a href="http://www.pagelines.com/DMS" class="btn btn-mini" target="_blank"><i class="icon icon-thumbs-up"></i> <?php _e( 'Learn More About Pro', 'pagelines' ); ?> </a> </div> <?php $note .= ob_get_clean(); return $note; } add_filter( 'pl_is_activated', 'pl_is_activated_check' ); add_filter( 'pl_is_pro', 'pl_is_pro_check' ); add_filter( 'pl_pro_text', 'pl_pro_text_check' ); add_filter( 'pl_pro_disable_class', 'pl_pro_disable_class_check' ); function pl_is_pro_check() { return true; } function pl_is_activated_check(){ // AP stop putting return true here!! $status = get_option( 'dms_activation', array( 'active' => false, 'key' => '', 'message' => '', 'email' => '' ) ); $pro = (isset($status['active']) && true === $status['active']) ? true : false; return $pro; } function pl_pro_text_check(){ return ( ! pl_is_pro_check()) ? __('(Pro Edition Only)', 'pagelines') : ''; } function pl_pro_disable_class_check(){ return ( ! pl_is_pro_check()) ? 'pro-only-disabled' : ''; } /** * Boost memory for LESS compile * @package PageLines DMS * @since 1.2 * */ add_action( 'pagelines_max_mem', create_function('',"@ini_set('memory_limit',WP_MAX_MEMORY_LIMIT);") ); /** * Dashboard menus * @package PageLines DMS * @since 1.2 * */ function pagelines_add_admin_menus() { global $_pagelines_account_hook; $_pagelines_account_hook = pagelines_insert_menu( PL_MAIN_DASH, __( 'Dashboard', 'pagelines' ), 'edit_theme_options', PL_MAIN_DASH, 'pagelines_build_account_interface' ); } /** * * PageLines menu wrapper */ function pagelines_insert_menu( $page_title, $menu_title, $capability, $menu_slug, $function ) { return add_submenu_page( PL_MAIN_DASH, $page_title, $menu_title, $capability, $menu_slug, $function ); } /** * Full version menu wrapper. * */ function pagelines_add_admin_menu() { global $menu; // Create the new separator $menu['2.995'] = array( '', 'edit_theme_options', 'separator-pagelines', '', 'wp-menu-separator' ); // Create the new top-level Menu add_menu_page( 'PageLines', 'PageLines', 'edit_theme_options', PL_MAIN_DASH, 'pagelines_build_account_interface', PL_PARENT_URL . '/images/admin-icon.png', '2.996' ); } /** * The bulk of the PL Shortcodes. * @package PageLines DMS * @since 1.2 * */ class PL_ShortCodes_Libs extends PageLines_ShortCodes { // 1. Return link in page based on Bookmark // USAGE : [bookmark id="21" text="Link Text"] function bookmark_link( $atts ) { //extract page name from the shortcode attributes extract( shortcode_atts( array( 'id' => '0', 'text' => '' ), $atts ) ); //convert the page name to a page ID $bookmark = get_bookmark( $id ); if( isset( $text ) ) $ltext = $text; else $ltext = $bookmark->link_name; $pagelink = "<a href=\"".$bookmark->link_url."\" target=\"".$bookmark->link_target."\">".$ltext."</a>"; return $pagelink; } // 2. Function for creating a link from a page name // USAGE : [link pagename="My Example Page" linktext="Link Text"] function create_pagelink( $atts ) { //extract page name from the shortcode attributes extract( shortcode_atts( array( 'pagename' => 'home', 'linktext' => '' ), $atts ) ); //convert the page name to a page ID $page = get_page_by_title( $pagename ); //use page ID to get the permalink for the page $link = get_permalink( $page ); //create the link and output $pagelink = "<a href=\"".$link."\">".$linktext."</a>"; return $pagelink; } // 4. GOOGLE MAPS ////////////////////////////////////////////////// // you can use the default width and height // The only requirement is to add the address of the map // Example: // [googlemap address="san diego, ca"] // or with options // [googlemap width="200" height="200" address="San Francisco, CA 92109"] function googleMaps( $atts, $content = null ) { extract( shortcode_atts( array( 'width' => '480', 'height' => '480', 'locale' => 'en', 'address' => '' ), $atts ) ); $src = "http://maps.google.com/maps?f=q&source=s_q&hl=".$locale."&q=".$address; return '<iframe width="'.$width.'" height="'.$height.'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'.$src.'&amp;output=embed"></iframe>'; } // 5. GOOGLE CHARTS ////////////////////////////////////////////////// // Gets Google charts // USAGE // [chart data="0,12,24,26,32,64,54,24,22,20,8,2,0,0,3" bg="F7F9FA" size="200x100" type="sparkline"] // [chart data="41.52,37.79,20.67,0.03" bg="F7F9FA" labels="Reffering+sites|Search+Engines|Direct+traffic|Other" colors="058DC7,50B432,ED561B,EDEF00" size="488x200" title="Traffic Sources" type="pie"] function chart_shortcode( $atts ) { extract( shortcode_atts( array( 'data' => '', 'colors' => '', 'size' => '400x200', 'bg' => 'ffffff', 'title' => '', 'labels' => '', 'advanced' => '', 'type' => 'pie' ), $atts ) ); switch ( $type ) { case 'line' : $charttype = 'lc'; break; case 'xyline' : $charttype = 'lxy'; break; case 'sparkline' : $charttype = 'ls'; break; case 'meter' : $charttype = 'gom'; break; case 'scatter' : $charttype = 's'; break; case 'venn' : $charttype = 'v'; break; case 'pie' : $charttype = 'p3'; break; case 'pie2d' : $charttype = 'p'; break; default : $charttype = $type; break; } $string = ''; if ( $title ) $string .= '&chtt='.$title.''; if ( $labels ) $string .= '&chl='.$labels.''; if ( $colors ) $string .= '&chco='.$colors.''; $string .= '&chs='.$size.''; $string .= '&chd=t:'.$data.''; $string .= '&chf=bg,s,'.$bg.''; return '<img title="'.$title.'" src="http://chart.apis.google.com/chart?cht='.$charttype.''.$string.$advanced.'" alt="'.$title.'" />'; } // 6. GET POST FIELD BY OFFSET ////////////////////////////////////////////////// // Get a post based on offset from the last post published (0 for last post) // USAGE: [postfeed field="post_title" offset="0" customfield="true" ] function get_postfeed( $atts ) { //extract page name from the shortcode attributes extract( shortcode_atts( array( 'field' => 'post_title', 'offset' => '0', 'customfield' => "" ), $atts ) ); //returns an array of objects $thepost = get_posts( 'numberposts=1&offset='.$offset ); if( $customfield == 'true' ){ $postfield = get_post_meta( $thepost[0]->ID, $field, true ); }else{ $postfield = $thepost[0]->$field; } return $postfield; } // 7. Created a container for dynamic html layout // USAGE: [cbox width="50%" leftgutter="15px" rightgutter="0px"] html box content[/cbox] function dynamic_box( $atts, $content = null ) { //extract page name from the shortcode attributes extract( shortcode_atts( array( 'width' => '30%', 'leftgutter' => '10px', 'rightgutter' => '0px' ), $atts ) ); $cbox = '<div class="cbox" style="float:left;width:'.$width.';"><div class="cbox_pad" style="margin: 0px '.$rightgutter.' 0px '.$leftgutter.'">'.do_shortcode( $content ).'</div></div>'; return $cbox; } // 8. Created a container for dynamic html layout // USAGE: [container id="mycontainer" class="myclass"] 'cboxes' see shortcode below [/container] function dynamic_container( $atts, $content = null ) { //extract page name from the shortcode attributes extract( shortcode_atts( array( 'id' => 'container', 'class' => '' ), $atts ) ); $container = '<div style="width: 100%;" class="container">'.do_shortcode( $content ).'<div class="clear"></div></div>'; return $container; } /** * 18.Shortcode to display Pinterest button * * @example <code>[pinterest_button img=""]</code> is the default usage * @example <code>[pinterest_button img=""]</code> */ function pl_pinterest_button( $atts ){ $defaults = array( 'url' => get_permalink(), 'img' => '', 'title' => urlencode( the_title_attribute( array( 'echo' => false ) ) ), ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<a href="http://pinterest.com/pin/create/button/?url=%s&amp;media=%s&amp;description=%s" class="pin-it-button" count-layout="horizontal"><img style="border:0px;" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>', $atts['url'], $atts['img'], $atts['title'] ); global $shortcode_js; $shortcode_js['pinterest'] = '<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>'; return $out; } /** * 1X.Shortcode to display Google Plus 1 Button * * @example <code>[googleplus]</code> is the default usage * @example <code>[googleplus size="" count=""]</code> * @example available attributes for size include small, medium, and tall * @example avialable counts include inline, and bubble */ function pl_googleplus_button ( $atts ) { $defaults = array( 'size' => 'medium', 'count' => '', 'url' => get_permalink() ); $atts = shortcode_atts($defaults, $atts); ob_start(); printf( '<div class="g-plusone" data-size="%s" data-href="%s"></div>', $atts['size'], $atts['count'], $atts['url'] ); global $shortcode_js; ob_start(); ?> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/platform.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> <?php $shortcode_js['gplus'] = ob_get_clean(); return ob_get_clean(); } /** * . Shortcode to display Linkedin Share Button * * @example <code>[linkedin]</code> is the default usage * @example <code>[linkedin count="vertical"]</code> */ function pl_linkedinshare_button ($atts) { $defaults = array( 'url' => get_permalink(), 'count' => 'horizontal' ); $atts = wp_parse_args( $atts, $defaults ); $out = sprintf( '<script type="IN/Share" data-url="%s" data-counter="%s"></script>', $atts['url'], $atts['count'] ); global $shortcode_js; $shortcode_js['linkedin'] = '<script src="//platform.linkedin.com/in.js" type="text/javascript"></script>'; return $out; } /** * 19. Shortcode to display Tweet button * * @example <code>[twitter_button type=""]</code> is the default usage * @example <code>[twitter_button type="follow"]</code> */ function pl_twitter_button( $args ){ $defaults = array( 'type' => '', 'permalink' => get_permalink(), 'handle' => ( pl_setting( 'twittername' ) ) ? pl_setting( 'twittername' ) : 'PageLines' , 'title' => '' ); $a = wp_parse_args( $args, $defaults ); if ($a['type'] == 'follow') { $out = sprintf( '<a href="https://twitter.com/%1$s" class="twitter-follow-button" data-show-count="true" data-show-screen-name="false">Follow @%1$s</a>', $a['handle'] ); } else { $out = sprintf( '<a href="https://twitter.com/share" class="twitter-share-button" data-url="%s" data-text="%s" data-via="%s">Tweet</a>', $a['type'], $a['permalink'], $a['title'], $a['handle'] ); } global $shortcode_js; $shortcode_js['twitter'] = '<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>'; return $out; } /** * 20. Shortcode to display Facebook Like button * * @example <code>[like_button]</code> is the default usage * @example <code>[like_button]</code> */ function pl_facebook_shortcode( $args ){ $defaults = array( 'url' => get_permalink(), 'width' => '80', ); $a = wp_parse_args( $args, $defaults ); $app_id = ''; if( pl_setting( 'facebook_app_id' ) ) $app_id = sprintf( '&appId=%s', pl_setting( 'facebook_app_id' ) ); ob_start(); ?> <div id="fb-root" style="display: none;"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1<?php echo $app_id; ?>"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <?php $facebook_js = ob_get_clean(); global $shortcode_js; $shortcode_js['facebook'] = $facebook_js; return sprintf( '<div class="fb-like" style="vertical-align: top;" data-href="%s" data-width="%s" data-layout="button_count" data-action="like" data-show-faces="true" data-share="false"></div>', $a['url'], $a['width'] ); } /** * 21. This function/shortcode will show all authors on a post * * @example <code>[show_authors]</code> is the default usage * @example <code>[show_authors]</code> */ function show_multiple_authors() { if( class_exists( 'CoAuthorsIterator' ) ) { $i = new CoAuthorsIterator(); $return = ''; $i->iterate(); $return .= '<a href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ).'">'.get_the_author_meta( 'display_name' ).'</a>'; while( $i->iterate() ){ $return.= $i->is_last() ? ' and ' : ', '; $return .= '<a href="'.get_author_posts_url( get_the_author_meta( 'ID' ) ).'">'.get_the_author_meta( 'display_name' ).'</a>'; } return $return; } else { //fallback } } /** * 22.Bootstrap Code Shortcode * * @example <code>[pl_codebox]...[/pl_codebox]</code> is the default usage * @example <code>[pl_codebox scrollable="yes"].box{margin:0 auto;}[/pl_codebox]</code> for lots of code */ function pl_codebox_shortcode ( $atts, $content = null ) { extract( shortcode_atts( array( 'scrollable' => 'no', 'linenums' => 'yes', 'language' => 'html' ), $atts ) ); $scrollable = ( $scrollable == 'yes' ) ? 'pre-scrollable' : ''; $linenums = ( $linenums == 'yes' ) ? 'linenums' : ''; $language = 'lang-'.$language; // Grab Shortcodes $pattern = array( '#([a-z]+\=[\'|"][^\'|"]*[\'|"])#m', '#(\[[^]]*])#m', ); $replace = array( '<span class="sc_var">$1</span>', '<span class="sc_code">$1</span>' ); $code = preg_replace( $pattern, $replace, esc_html( $content ) ); $out = sprintf( '<pre class="%s prettyprint %s %s">%s</pre>', $scrollable, $language, $linenums, $code ); return $out; } /** * 23. Bootstrap Labels Shortcode * * @example <code>[pl_label type=""]My Label[/pl_label]</code> is the default usage * @example <code>[pl_label type="info"]label[/pl_label]</code> * @example Available types include info, success, warning, error */ function pl_label_shortcode( $atts, $content = null ) { $defaults = array( 'type' => 'info', ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<span class="label label-%s">%s</span>', $atts['type'], do_shortcode( $content ) ); return $out; } /** * 24. Bootstrap Badges Shortcode * * @example <code>[pl_badge type="info"]My badge[/pl_badge]</code> is the default usage * @example <code>[pl_badge type="info"]badge[/pl_badge]</code> * @example Available types include info, success, warning, error */ function pl_badge_shortcode( $atts, $content = null ) { $defaults = array( 'type' => 'info', ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<span class="badge badge-%s">%s</span>', $atts['type'], do_shortcode( $content ) ); return $out; } /** * 25. Bootstrap Alertbox Shortcode * * @example <code>[pl_alertbox type="info"]My alert[/pl_alertbox]</code> is the default usage * @example <code>[pl_alertbox type="info" closable="yes"]My alert[/pl_alertbox]</code> makes an alert that can be toggled away with a close button * @example <code>[pl_alertbox type="info"]<h4 class="pl-alert-heading">Heading</h4>My alert[/pl_alertbox]</code> * @example Available types include info, success, warning, error */ function pl_alertbox_shortcode( $atts, $content = null ) { $content = str_replace( '<br />', '', str_replace( '<br>', '', $content ) ); $defaults = array( 'type' => 'info', 'closable' =>'no', ); $atts = shortcode_atts( $defaults, $atts ); $closed = sprintf( '<div class="alert alert-%s"><a class="close" data-dismiss="alert" href="#">×</a>%s</div>', $atts['type'], do_shortcode( $content ) ); if ( $atts['closable'] === 'yes' ) { return $closed; } $out = sprintf( '<div class="alert alert-%s alert-block">%2$s</div>', $atts['type'], do_shortcode( $content ) ); return $out; } /** * 26. Bootstrap Blockquote Shortcode * * @example <code>[pl_blockquote pull="" cite=""]My quote[/pl_blockquote]</code> is the default usage * @example <code>[pl_blockquote pull="right" cite="Someone Famous"]My quote pulled right with source[/pl_blockquote]</code> */ function pl_blockquote_shortcode( $atts, $content = null) { $defaults = array( 'pull' => '', 'cite' => '' ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<blockquote class="side-%1$s"><p>%3$s<small>%2$s</small></p></blockquote>', $atts['pull'], $atts['cite'], do_shortcode( $content ) ); return $out; } /** * 27. Bootstrap Button Shortcode * * @example <code>[pl_button type="" size="" link="" target=""]...[/pl_button]</code> is the default usage * @example <code>[pl_button type="info" size="small" link="#" target="blank"]My Button[/pl_button]</code> * @example Available types include info, success, warning, danger, inverse * @example Available sizes include large, medium, and mini */ function pl_button_shortcode( $atts, $content = null, $target = null ) { $defaults = array( 'type' => 'info', 'size' => 'small', 'link' => '#', 'target' => '_self' ); $atts = shortcode_atts( $defaults, $atts ); $target = ( $target == 'blank' ) ? '_blank' : ''; $out = sprintf( '<a href="%1$s" target="%2$s" class="btn btn-%3$s btn-%4$s">%5$s</a>', $atts['link'], $atts['target'], $atts['type'], $atts['size'], do_shortcode( $content ) ); return $out; } /** * 28. Bootstrap Button Group Shortcode - Builds a group of buttons as a menu * * @example <code>[pl_buttongroup]<a href="#" class="btn btn-info">...[/pl_buttongroup]</code> is the default usage * @example <code>[pl_buttongroup]<a href="#" class="btn btn-info"><a href="#" class="btn btn-info"><a href="#" class="btn btn-info">[/pl_button]</code> * @example Available types include info, success, warning, danger, inverse */ function pl_buttongroup_shortcode( $atts, $content = null ) { $content = str_replace( '<br />', '', str_replace( '<br>', '', $content ) ); return sprintf( '<div class="btn-group">%s</div>', do_shortcode( $content ) ); } /** * 29. Bootstrap Dropdown Button Shortcode - Builds a button with contained dropdown menu * * @example <code>[pl_buttondropdown size="" type="" label=""]<li><a href="#">...</a></li>[/pl_buttondropdown]</code> is the default usage * @example <code>[pl_buttondropdown size="large" type="info" label="button"]<li><a href="#"></li><li><a href="#"></li><li><a href="#"></li>[/pl_buttondropdown]</code> * @example Available types include info, success, warning, danger, inverse */ function pl_buttondropdown_shortcode( $atts, $content = null ) { $defaults = array( 'size' => '', 'type' => '', 'label' => '' ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<div class="btn-group"><button class="btn btn-%s btn-%s dropdown-toggle" data-toggle="dropdown" href="#">%s <span class="caret"></span></button><ul class="dropdown-menu">%s</ul></div>', $atts['size'], $atts['type'], $atts['label'], do_shortcode( $content ) ); return $out; } /** * 30. Bootstrap Split Button Dropdown - Builds a button with split button dropdown caret * * @example <code>[pl_splitbuttondropdown size="" type="" label=""]<li><a href="#">...</a></li>[/pl_splitbuttondropdown]</code> is the default usage * @example <code>[pl_splitbuttondropdown size="large" type="info" label="button"]<li><a href="#"></li><li><a href="#"></li><li><a href="#"></li>[/pl_splitbuttondropdown]</code> * @example Available types include info, success, warning, danger, inverse */ function pl_splitbuttondropdown_shortcode( $atts, $content = null ) { $defaults = array( 'size' => '', 'type' => '', 'label' => '' ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<div class="btn-group"><a class="btn btn-%1$s btn-%2$s" >%3$s</a><a class="btn btn-%1$s btn-%2$s dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></a><ul class="dropdown-menu">%4$s</ul></div>', $atts['size'], $atts['type'], $atts['label'], do_shortcode( $content ) ); return $out; } /** * 31. Bootstrap Tooltips * * @example <code>[pl_tooltip tip=""]...[/pl_tooltip]</code> is the default usage * @example <code>This is a [pl_tooltip tip="Cool"]tooltip[/pl_tooltip] example.</code> */ function pl_tooltip_shortcode( $atts, $content = null ) { $defaults = array( 'tip' => 'Tip', 'position' => 'right' ); $atts = shortcode_atts( $defaults, $atts ); global $shortcode_js; $shortcode_js['tooltips'] = '<script> jQuery(function(){ jQuery("a[rel=tooltip]").tooltip();}); </script>'; ob_start(); printf( '<a href="#" rel="tooltip" title="%s" data-placement="%s">%s</a>', $atts['tip'], $atts['position'], do_shortcode( $content ) ); return ob_get_clean(); } /** * 32. Bootstrap Popovers * * @example <code>[pl_popover title="" content=""]...[/pl_popover]</code> is the default usage * @example <code>This is a [pl_popover title="Popover Title" content="Some content that you can have inside the Popover"]popover[/pl_popover] example.</code> */ function pl_popover_shortcode( $atts, $content = null ) { $defaults = array( 'title' => 'Popover Title', 'content' => 'Content', 'position' => 'right' ); $atts = shortcode_atts( $defaults, $atts ); global $shortcode_js; $shortcode_js['popover'] = '<script> jQuery(function(){ jQuery("a[rel=popover]").popover({ html:true, trigger: "hover" }).click(function(e) { e.preventDefault() }); }); </script>'; ob_start(); printf( '<a href="#" rel="popover" title="%s" data-content="%s" data-placement="%s">%s</a>', $atts['title'], $atts['content'], $atts['position'], do_shortcode( $content ) ); return ob_get_clean(); } /** * 33. Bootstrap Accordion - Collapsable Content * * @example <code>[pl_accordion name="accordion"] [accordioncontent name="accordion" number="1" heading="Tile 1"]Content 1 [/accordioncontent] [accordioncontent name="accordion" number="2" heading="Title 2"]Content 2 [/accordioncontent] [/pl_accordion]</code> is the default usage */ function pl_accordion_shortcode( $atts, $content = null ) { $defaults = array( 'name' => '', ); $atts = shortcode_atts( $defaults, $atts ); $out = sprintf( '<div id="%s" class="accordion">%s</div>', $atts['name'], do_shortcode( $content ) ); return $out; } //Accordion Content function pl_accordioncontent_shortcode( $atts, $content = null, $open = null ) { $defaults = array( 'name' => '', 'heading' => '', 'number' => '', 'open' => '' ); $atts = shortcode_atts( $defaults, $atts ); $open = ( $atts['open'] == 'yes' ) ? 'in' : ''; $out = sprintf( '<div class="accordion-group"><div class="accordion-heading pl-contrast"><a class="accordion-toggle" data-toggle="collapse" data-parent="#%1$s" href="#collapse%3$s">%2$s</a></div><div id="collapse%3$s" class="accordion-body collapse %4$s"><div class="accordion-inner">%5$s</div></div></div>', $atts['name'], $atts['heading'], $atts['number'], $open, do_shortcode( $content ) ); return $out; } /** * 34. Bootstrap Carousel * * @example <code>[pl_carousel name=""][pl_carouselimage first="yes" title="" imageurl="" ]Caption[/pl_carouselimage][pl_carouselimage title="" imageurl="" ]Caption[/pl_carouselimage][/pl_carousel]</code> is the default usage * @example <code>[pl_carousel name="PageLinesCarousel"][pl_carouselimage first="yes" title="Feature 1" imageurl="" ]Image 1 Caption[/pl_carouselimage][pl_carouselimage title="Feature 2" imageurl=""]Image 2 Caption[/pl_carouselimage][pl_carouselimage title="Feature 3" imageurl=""]Image 3 Caption[/pl_carouselimage][/pl_carousel]</code> */ function pl_carousel_shortcode( $atts, $content = null ) { global $carousel_js; if ( isset($atts['speed']) && '0' === $atts['speed'] ) $atts['speed'] = 'pause'; // 0 will be striped by array_filter // remove any empty array keys that have empty values to enforce defaults (eg: name="" or speed="") that would otherwise break things $atts = array_filter($atts); $defaults = array( 'name' => 'PageLines Carousel', 'speed' => 5000 // default bootstrap transition time ); $atts = shortcode_atts( $defaults, $atts ); $carousel_id = sanitize_title_with_dashes( $atts['name'], null, 'save' ); // convert it to a valid id attribute if it isn't. $speed = absint($atts['speed']); if ( ! isset($carousel_js) ) $carousel_js = array(); else { if ( array_key_exists($carousel_id, $carousel_js) ) $carousel_id = $carousel_id.'-'.count($carousel_js); } // store away the values for consolidated output in the footer $carousel_js[$carousel_id] = array( 'id' => $carousel_id, 'speed' => $speed ); return sprintf( '<div id="%2$s" class="carousel slide"><div class="carousel-inner">%1$s</div><a class="carousel-control left" href="#%2$s" data-slide="prev">&lsaquo;</a><a class="carousel-control right" href="#%2$s" data-slide="next">&rsaquo;</a></div>', do_shortcode( $content ), $carousel_id ); } //Carousel Images function pl_carouselimage_shortcode( $atts, $content = null ) { // remove any empty string attributes to use defaults $atts = array_filter($atts); extract( shortcode_atts( array( 'first' => '', 'title' => '', 'imageurl' => sprintf( '%s/screenshot.png', PL_PARENT_URL ), // fallback "reminder" image 'caption' => '', ), $atts ) ); $first = ( $first == 'yes' ) ? 'active' : ''; $content = ( $content <> '' ) ? "<div class='carousel-caption'><h4>$title</h4><p>$content</p></div>" : ''; // changed to work without captions return sprintf( '<div class="item %s"><img src="%s">%s</div>', // changed to work without captions $first, $imageurl, do_shortcode( $content ) ); } /** * 35. Bootstrap Tabs * * @example <code>[pl_tabs][pl_tabtitlesection type=""][pl_tabtitle active="" number="1"]...[/pl_tabtitle][pl_tabtitle number="2"]...[/pl_tabtitle][/pl_tabtitlesection][pl_tabcontentsection][pl_tabcontent active="" number="1"]...[/pl_tabcontent][pl_tabcontent number=""]...[/pl_tabcontent][/pl_tabcontentsection][/pl_tabs]</code> is the default usage * @example <code>[pl_tabs][pl_tabtitlesection type="tabs"][pl_tabtitle active="yes" number="1"]Title 1[/pl_tabtitle][pl_tabtitle number="2"]Title 2[/pl_tabtitle][/pl_tabtitlesection][pl_tabcontentsection][pl_tabcontent active="yes" number="1"]Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque ac mi enim, at consectetur justo.[/pl_tabcontent][pl_tabcontent number="2"]Second content there.[/pl_tabcontent][/pl_tabcontentsection][/pl_tabs]</code> * @example Available types include tabs, pills */ function pl_tabs_shortcode( $atts, $content = null ) { return sprintf( '<div class="tabs">%s</div>', do_shortcode( $content ) ); } //Tab Titles Section function pl_tabtitlesection_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'type' => '', ), $atts ) ); ob_start(); ?> <script> jQuery(function(){ jQuery('a[data-toggle="tab"]').on('shown', function (e) { e.target // activated tab e.relatedTarget // previous tab }) }); </script><?php printf( '<ul class="nav nav-%s">%s</ul>', $type, do_shortcode( $content ) ); return ob_get_clean(); } //Tab Titles function pl_tabtitle_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'active' => '', 'number' => '' ), $atts ) ); $active = ( $active == 'yes' ) ? "class='active'" : ''; $out = sprintf( '<li %s><a href="#%s" data-toggle="tab">%s</a></li>', $active, $number, do_shortcode( $content ) ); return $out; } //Tab Content Section function pl_tabcontentsection_shortcode( $atts, $content = null ) { return '<div class="tab-content">'.do_shortcode( $content ).'</div>'; } //Tab Content function pl_tabcontent_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'active' => '', 'number' => '' ), $atts ) ); $active = ( $active == 'yes' ) ? "active" : ''; return sprintf( '<div class="tab-pane %s" id="%s"><p>%s</p></div>', $active, $number, do_shortcode( apply_filters( 'the_content',$content ) ) ); } /** * 36. Bootstrap Modal Popup Window * * @example <code>[pl_modal title="" type="" colortype="" label=""]...[/pl_modal]</code> * @example <code>[pl_modal title="Title" type="label" colortype="info" label="Click Me!"]Some content here for the cool modal pop up. You can have all kinds of cool stuff in here.[/pl_modal]</code> * @example available types include button, label, and badge * @example available color types include default, success, warning, important, info, and inverse */ function pl_modal_shortcode( $atts, $content = null ) { extract( shortcode_atts( array( 'title' => '', 'type' => '', 'colortype' => '', 'label' => '', 'show' => 'false', 'hash' => rand() ), $atts ) ); ob_start(); ?> <script> jQuery(function(){ jQuery('#modal_<?php echo $hash; ?>').appendTo(jQuery('body')).modal({ keyboard: true , show: <?php echo $show; ?> }); }); </script><?php printf( '<a data-toggle="modal" role="button" href="#modal_%6$s" class="%2$s %2$s-%3$s">%5$s</a><div id="modal_%6$s" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-header"><a class="close" data-dismiss="modal" aria-hidden="true">×</a><h3>%s</h3></div><div class="modal-body"><p>%4$s</p></div><div class="modal-footer"><a href="#" class="btn btn-%3$s" data-dismiss="modal" aria-hidden="true">%7$s</a></div></div>', $title, $type, $colortype, do_shortcode( $content ), $label, $hash, __( 'Close', 'pagelines' ) ); return ob_get_clean(); } /** * 38. Used to create general buttons and button links * * @example <code>[button]</code> is the default usage * @example <code>[button format="edit_post" before="<b>" after="</b>"]</code> */ function pagelines_button_shortcode( $atts ) { $defaults = array( 'color' => 'grey', 'size' => 'normal', 'align' => 'right', 'style' => '', 'type' => 'button', 'text' => '&nbsp;', 'pid' => 0, 'class' => null, ); $atts = shortcode_atts( $defaults, $atts ); $button = sprintf( '<div class="blink"><div class="blink-pad">%s</div></div>', $text ); $output = sprintf( '<div class="%s %s %s blink-wrap">%s</div>', $special, $size, $color, $button ); return apply_filters( 'pagelines_button_shortcode', $output, $atts ); } /** * XX. Responsive Videos * * @example <code>[pl_video]</code> is the default usage * @example <code>[pl_video type="youtube" url="urltovideo"]</code> */ function pl_video_shortcode ($atts) { extract( shortcode_atts( array( 'type' =>'', 'id' =>'', 'width' => '100%', 'height' => '100%', 'related' => '', ), $atts ) ); if ( $related ) $related = '?rel=0'; switch( $type ) { case 'vimeo': $out = sprintf( '<div class="pl-video vimeo"><iframe src="http://player.vimeo.com/video/%s" width="%s" height="%s" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen wmode="transparent"></iframe></div>',$id, $width, $height ); break; case 'dailymotion': $out = sprintf( '<div class="pl-video dailymotion"><iframe src="http://www.dailymotion.com/embed/video/%s" width="%s" height="%s" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen wmode="transparent"></iframe></div>',$id, $width, $height ); break; default: $out = sprintf('<div class="pl-video youtube"><iframe src="http://www.youtube.com/embed/%s%s" width="%s" height="%s" frameborder="0" allowfullscreen wmode="transparent"></iframe></div>', $id, $related, $width, $height); } return $out; } } new PL_ShortCodes_Libs;
benpeck/experticity-fools
wp-content/themes/dms/dms/includes/library.pagelines.php
PHP
gpl-2.0
34,533
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 2023, 5371, 9909, 1996, 2364, 12183, 1010, 2489, 2544, 2442, 2022, 2104, 3311, 1010, 2023, 5371, 2003, 2025, 1999, 1996, 2489, 2544, 1012, 1008, 1030, 7427, 3931, 12735, 1040, 5244, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#4.2 Reaction Paper# "puts" returns nil, and then prints the outcome to the console with a line break after it. An integer is any number that doesn't end with a decimal point, like 89 or 3. Floats end with a decimal point, e.g. 1.2, 7.9999999999 or 45.0. Integer division is the kind we learn in school, float division rounds the output up or down (usually down) to an integer. I would explain that computers are dumb, they need two categories to understand numbers, and they cannot conceptualize that all numbers can be reprented as both integers and floats. And that all operations can change the value of the number, but the computer won't change what kind of number it is unless it's specifically told. ___ ```ruby hours_in_year = 24*365.25 puts "There are #{hours_in_year} hours in a year" minutes_in_decade= 60*24*365.25*10 print "There are #{minutes_in_decade} minutes in a decade" ``` ___ My code for the following exercises: *[Defining Variables](defining_variables.rb) *[Simple String Methods](simple-string.rb) *[Local Variables and Basic Arithmetical Operations](basic-math.rb) ___ *How does Ruby handle addition, subtraction, multiplication, and division of numbers?* Ruby stores integers and floats(numbers with decimals) as different categories. One can add, subtract, and multiply integers and receive integers, and floats as floats. Division, on the other hand, returns numbers that would be characterized as floats when two integers are divided. Ruby rounds quotients unless either number is changed or re-represented as a float. *What are strings? Why and when would you use them?* Ruby encodes information in different ways, different kinds of information merits different kinds of methods. And it's easier to group methods conceptually based on what kind of information they act upon. Strings are a grouping of characters, including integers, spaces, punctuation, etc. They can be broken into substrings and searched for their information. An address in a database could be stored as a string, a list of addresses with the same zip code would not. My name on Facebook could be stored as a string, the number of times I've looked at Elon Musk's profile could not. *What are local variables? Why and when would you use them?* Their names start with lower cases or underscores, they act as temporary placeholders for the information being manipulated within the steps of a method. You cannot access (in trying to call or use their values) them outside of the method in which they "live". *How was this challenge? Did you get a good review of some of the basics?* I have some experience with Ruby, so it wasn't too hard. And it felt good compared to git, with which I had no experience. But I want to guard myself against an illusion of competence in my understanding of Ruby. Building a poor understanding of a big thing based on poor understanding of basic concepts is 1) easy to prevent/change and 2) super common.
almightyboz/phase-0
week-4/nums-letters.md
Markdown
mit
2,947
[ 30522, 1001, 1018, 1012, 1016, 4668, 3259, 1001, 1000, 8509, 1000, 5651, 9152, 2140, 1010, 1998, 2059, 11204, 1996, 9560, 2000, 1996, 10122, 2007, 1037, 2240, 3338, 2044, 2009, 1012, 2019, 16109, 2003, 2151, 2193, 2008, 2987, 1005, 1056, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "skia/ext/skia_trace_memory_dump_impl.h" #include "base/trace_event/memory_allocator_dump.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/process_memory_dump.h" #include "skia/ext/SkDiscardableMemory_chrome.h" namespace skia { namespace { const char kMallocBackingType[] = "malloc"; } SkiaTraceMemoryDumpImpl::SkiaTraceMemoryDumpImpl( base::trace_event::MemoryDumpLevelOfDetail level_of_detail, base::trace_event::ProcessMemoryDump* process_memory_dump) : SkiaTraceMemoryDumpImpl("", level_of_detail, process_memory_dump) {} SkiaTraceMemoryDumpImpl::SkiaTraceMemoryDumpImpl( const std::string& dump_name_prefix, base::trace_event::MemoryDumpLevelOfDetail level_of_detail, base::trace_event::ProcessMemoryDump* process_memory_dump) : dump_name_prefix_(dump_name_prefix), process_memory_dump_(process_memory_dump), request_level_( level_of_detail == base::trace_event::MemoryDumpLevelOfDetail::LIGHT ? SkTraceMemoryDump::kLight_LevelOfDetail : SkTraceMemoryDump::kObjectsBreakdowns_LevelOfDetail) {} SkiaTraceMemoryDumpImpl::~SkiaTraceMemoryDumpImpl() = default; void SkiaTraceMemoryDumpImpl::dumpNumericValue(const char* dumpName, const char* valueName, const char* units, uint64_t value) { auto* dump = process_memory_dump_->GetOrCreateAllocatorDump(dumpName); dump->AddScalar(valueName, units, value); } void SkiaTraceMemoryDumpImpl::dumpStringValue(const char* dump_name, const char* value_name, const char* value) { auto* dump = process_memory_dump_->GetOrCreateAllocatorDump(dump_name); dump->AddString(value_name, "", value); } void SkiaTraceMemoryDumpImpl::setMemoryBacking(const char* dumpName, const char* backingType, const char* backingObjectId) { if (strcmp(backingType, kMallocBackingType) == 0) { auto* dump = process_memory_dump_->GetOrCreateAllocatorDump(dumpName); const char* system_allocator_name = base::trace_event::MemoryDumpManager::GetInstance() ->system_allocator_pool_name(); if (system_allocator_name) { process_memory_dump_->AddSuballocation(dump->guid(), system_allocator_name); } } else { NOTREACHED(); } } void SkiaTraceMemoryDumpImpl::setDiscardableMemoryBacking( const char* dumpName, const SkDiscardableMemory& discardableMemoryObject) { std::string name = dump_name_prefix_ + dumpName; DCHECK(!process_memory_dump_->GetAllocatorDump(name)); const SkDiscardableMemoryChrome& discardable_memory_obj = static_cast<const SkDiscardableMemoryChrome&>(discardableMemoryObject); auto* dump = discardable_memory_obj.CreateMemoryAllocatorDump( name.c_str(), process_memory_dump_); DCHECK(dump); } SkTraceMemoryDump::LevelOfDetail SkiaTraceMemoryDumpImpl::getRequestedDetails() const { return request_level_; } bool SkiaTraceMemoryDumpImpl::shouldDumpWrappedObjects() const { // Chrome already dumps objects it imports into Skia. Avoid duplicate dumps // by asking Skia not to dump them. return false; } } // namespace skia
scheib/chromium
skia/ext/skia_trace_memory_dump_impl.cc
C++
bsd-3-clause
3,620
[ 30522, 1013, 1013, 9385, 2325, 1996, 10381, 21716, 5007, 6048, 1012, 2035, 2916, 9235, 1012, 1013, 1013, 2224, 1997, 2023, 3120, 3642, 2003, 9950, 2011, 1037, 18667, 2094, 1011, 2806, 6105, 2008, 2064, 2022, 1013, 1013, 2179, 1999, 1996, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<html> <head> <title>User agent detail - Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>ua-parser/uap-core<br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td> </td><td> </td><td style="border-left: 1px solid #555">Nokia</td><td>6720c-1b</td><td></td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a> <!-- Modal Structure --> <div id="modal-test" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Testsuite result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile [family] => Nokia 6720c-1b [brand] => Nokia [model] => 6720c-1b ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Nokia </td><td> </td><td> </td><td style="border-left: 1px solid #555">Nokia</td><td></td><td>Mobile Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.158</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-215ac98d-ccf8-4615-916e-5a819d6a59c9">Detail</a> <!-- Modal Structure --> <div id="modal-215ac98d-ccf8-4615-916e-5a819d6a59c9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^.*nokia.*$/ [browser_name_pattern] => *nokia* [parent] => Nokia [comment] => Nokia [browser] => Nokia [browser_type] => Browser [browser_bits] => 0 [browser_maker] => Nokia [browser_modus] => unknown [version] => 0.0 [majorver] => 0 [minorver] => 0 [platform] => unknown [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [cssversion] => 0 [aolversion] => 0 [device_name] => general Mobile Device [device_maker] => Nokia [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => general Mobile Device [device_brand_name] => Nokia [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>AppleWebKit 530.13</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661">Detail</a> <!-- Modal Structure --> <div id="modal-f1436016-fdf1-4aea-b4be-1d7c99ab0661" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => [browser] => AppleWebKit [version] => 530.13 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small></td><td>Mobile Safari </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.18202</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc">Detail</a> <!-- Modal Structure --> <div id="modal-9b0fa449-ec1b-40c8-8b1c-9486eb3b9cbc" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 90 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => [mobile_model] => [version] => [is_android] => [browser_name] => Mobile Safari [operating_system_family] => unknown [operating_system_version] => [is_ios] => [producer] => Apple Inc. [operating_system] => unknown [mobile_screen_width] => 90 [mobile_browser] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.2</small></td><td>UC Browser 8.7</td><td>WebKit </td><td>Symbian OS Series 60 V3</td><td style="border-left: 1px solid #555">Nokia</td><td>6720c-1b</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.008</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-21638055-738d-46ba-a1b1-f5114bc26475">Detail</a> <!-- Modal Structure --> <div id="modal-21638055-738d-46ba-a1b1-f5114bc26475" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => UC Browser [short_name] => UC [version] => 8.7 [engine] => WebKit ) [operatingSystem] => Array ( [name] => Symbian OS Series 60 [short_name] => S60 [version] => V3 [platform] => ) [device] => Array ( [brand] => NK [brandName] => Nokia [model] => 6720c-1b [device] => 1 [deviceName] => smartphone ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => 1 [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Nokia S60 OSS Browser 530.13</td><td><i class="material-icons">close</i></td><td>Nokia </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c">Detail</a> <!-- Modal Structure --> <div id="modal-5415e7f2-ef7b-434c-abe0-b71ba9f6707c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile ) [name:Sinergi\BrowserDetector\Browser:private] => Nokia S60 OSS Browser [version:Sinergi\BrowserDetector\Browser:private] => 530.13 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => Nokia [version:Sinergi\BrowserDetector\Os:private] => unknown [isMobile:Sinergi\BrowserDetector\Os:private] => 1 [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>UC Browser 8.7.1</td><td><i class="material-icons">close</i></td><td>Symbian OS </td><td style="border-left: 1px solid #555">Nokia</td><td>6720c-1b</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.008</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b">Detail</a> <!-- Modal Structure --> <div id="modal-346c1a98-5fd3-454f-b6c8-350f2f505d8b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 8 [minor] => 7 [patch] => 1 [family] => UC Browser ) [os] => UAParser\Result\OperatingSystem Object ( [major] => [minor] => [patch] => [patchMinor] => [family] => Symbian OS ) [device] => UAParser\Result\Device Object ( [brand] => Nokia [model] => 6720c-1b [family] => Nokia 6720c-1b ) [originalUserAgent] => Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small></td><td>UC Browser </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.045</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4">Detail</a> <!-- Modal Structure --> <div id="modal-9cdd8b45-a2eb-406b-bd27-7e48af38ffd4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Mobile Browser [agent_name] => UC Browser [agent_version] => -- [os_type] => unknown [os_name] => unknown [os_versionName] => [os_versionNumber] => [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => English - United States [agent_languageTag] => en-us ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small></td><td>UC Browser 8.7.1.234</td><td>WebKit 530.13</td><td> </td><td style="border-left: 1px solid #555">Nokia</td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.40104</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-9795f66f-7271-430e-973a-a5c0e14dc35a">Detail</a> <!-- Modal Structure --> <div id="modal-9795f66f-7271-430e-973a-a5c0e14dc35a" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => [simple_sub_description_string] => [simple_browser_string] => UC Browser 8.7 on Mobile [browser_version] => 8.7 [extra_info] => Array ( ) [operating_platform] => Mobile [extra_info_table] => Array ( ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => uc-browser [operating_system_version] => [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 530.13 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => Nokia [operating_system] => [operating_system_version_full] => [operating_platform_code] => [browser_name] => UC Browser [operating_system_name_code] => [user_agent] => Mozilla/5.0 (S60V3; U; en-us; NOKIA6720c-1b) AppleWebKit/530.13 (KHTML, like Gecko) UCBrowser/8.7.1.234/28/352/UCWEB Mobile [browser_version_full] => 8.7.1.234 [browser] => UC Browser 8.7 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>2.0.10</small></td><td>UC Browser 8.7</td><td>Gecko </td><td>Series60 3</td><td style="border-left: 1px solid #555">Nokia</td><td>6720 classic</td><td>mobile:smart</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.007</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4">Detail</a> <!-- Modal Structure --> <div id="modal-342c8d32-4765-40a8-8a5c-af3a38d19ae4" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => UC Browser [version] => 8.7 [type] => browser ) [engine] => Array ( [name] => Gecko ) [os] => Array ( [name] => Series60 [family] => Symbian [version] => 3 ) [device] => Array ( [type] => mobile [subtype] => smart [manufacturer] => Nokia [model] => 6720 classic ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td> <td colspan="12" class="center-align red lighten-1"> <strong>No result found</strong> </td> </tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>UC Browser 8</td><td><i class="material-icons">close</i></td><td>Android 4.0</td><td style="border-left: 1px solid #555"></td><td></td><td>Feature Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.021</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-1a1aee36-7ce7-4111-a391-8e2c501f1532">Detail</a> <!-- Modal Structure --> <div id="modal-1a1aee36-7ce7-4111-a391-8e2c501f1532" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => false [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => false [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => false [is_wml_preferred] => false [is_xhtmlmp_preferred] => true [is_html_preferred] => false [advertised_device_os] => Android [advertised_device_os_version] => 4.0 [advertised_browser] => UC Browser [advertised_browser_version] => 8 [complete_device_name] => [form_factor] => Feature Phone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => [model_name] => [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => false [has_qwerty_keyboard] => false [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => [mobile_browser] => UCWeb [mobile_browser_version] => browser_root_ucweb [device_os_version] => [pointing_method] => [release_date] => 2002_july [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => false [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => false [xhtml_supports_forms_in_table] => false [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => false [xhtml_supports_css_cell_table_coloring] => false [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => false [xhtml_document_title_support] => true [xhtml_preferred_charset] => utf8 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => application/vnd.wap.xhtml+xml [xhtml_table_support] => true [xhtml_send_sms_string] => none [xhtml_send_mms_string] => none [xhtml_file_upload] => not_supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => none [xhtml_avoid_accesskeys] => false [xhtml_can_embed_video] => none [ajax_support_javascript] => false [ajax_manipulate_css] => false [ajax_support_getelementbyid] => false [ajax_support_inner_html] => false [ajax_xhr_type] => none [ajax_manipulate_dom] => false [ajax_support_events] => false [ajax_support_event_listener] => false [ajax_preferred_geoloc_api] => none [xhtml_support_level] => 1 [preferred_markup] => html_wi_oma_xhtmlmp_1_0 [wml_1_1] => true [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => false [html_web_4_0] => false [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 128 [resolution_height] => 92 [columns] => 11 [max_image_width] => 120 [max_image_height] => 92 [rows] => 6 [physical_screen_width] => 27 [physical_screen_height] => 27 [dual_orientation] => false [density_class] => 1.0 [wbmp] => true [bmp] => false [epoc_bmp] => false [gif_animated] => true [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => false [transparent_png_index] => false [svgt_1_1] => false [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 256 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 9 [wifi] => false [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 10000 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => false [inline_support] => false [oma_support] => false [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => false [streaming_3gpp] => false [streaming_mp4] => false [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => -1 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => -1 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => -1 [streaming_acodec_amr] => none [streaming_acodec_aac] => none [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => none [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => false [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => false [mp3] => false [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => false [css_supports_width_as_percentage] => true [css_border_image] => none [css_rounded_corners] => none [css_gradient] => none [css_spriting] => false [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => false [progressive_download] => false [playback_vcodec_h263_0] => -1 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => -1 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => -1 [playback_real_media] => none [playback_3gpp] => false [playback_3g2] => false [playback_mp4] => false [playback_mov] => false [playback_acodec_amr] => none [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => false [html_preferred_dtd] => xhtml_mp1 [viewport_supported] => false [viewport_width] => [viewport_userscalable] => [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => none [image_inlining] => false [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => none [is_sencha_touch_ok] => false [controlcap_is_smartphone] => default [controlcap_is_ios] => default [controlcap_is_android] => default [controlcap_is_robot] => default [controlcap_is_app] => default [controlcap_advertised_device_os] => default [controlcap_advertised_device_os_version] => default [controlcap_advertised_browser] => default [controlcap_advertised_browser_version] => default [controlcap_is_windows_phone] => default [controlcap_is_full_desktop] => default [controlcap_is_largescreen] => default [controlcap_is_mobile] => default [controlcap_is_touchscreen] => default [controlcap_is_wml_preferred] => default [controlcap_is_xhtmlmp_preferred] => default [controlcap_is_html_preferred] => default [controlcap_form_factor] => default [controlcap_complete_device_name] => default ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-02-13 13:29:03</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
ThaDafinser/UserAgentParserComparison
v4/user-agent-detail/35/aa/35aa65e9-0e3a-4bfc-93e0-670d97b21017.html
HTML
mit
44,678
[ 30522, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 2516, 1028, 5310, 4005, 6987, 1011, 9587, 5831, 4571, 1013, 1019, 1012, 1014, 1006, 1055, 16086, 2615, 2509, 1025, 1057, 1025, 4372, 1011, 2149, 1025, 22098, 2575, 30524, 22018, 1013, 2654, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName /** * Crowdsignal (PollDaddy) shortcode. * * Formats: * [polldaddy type="iframe" survey="EB151947E5950FCF" height="auto" domain="jeherve" id="a-survey-with-branches"] * [crowdsignal type="iframe" survey="EB151947E5950FCF" height="auto" domain="jeherve" id="a-survey-with-branches"] * https://polldaddy.com/poll/7910844/ * https://jeherve.survey.fm/a-survey * https://jeherve.survey.fm/a-survey-with-branches * [crowdsignal type="iframe" survey="7676FB1FF2B56CE9" height="auto" domain="jeherve" id="a-survey"] * [crowdsignal survey="7676FB1FF2B56CE9"] * [polldaddy survey="7676FB1FF2B56CE9"] * [crowdsignal poll=9541291] * [crowdsignal poll=9541291 type=slider] * [crowdsignal rating=8755352] * * @package Jetpack */ use Automattic\Jetpack\Assets; use Automattic\Jetpack\Constants; // Keep compatibility with the PollDaddy plugin. if ( ! class_exists( 'CrowdsignalShortcode' ) && ! class_exists( 'PolldaddyShortcode' ) ) { /** * Class wrapper for Crowdsignal shortcodes */ class CrowdsignalShortcode { /** * Should the Crowdsignal JavaScript be added to the page? * * @var bool */ private static $add_script = false; /** * Array of Polls / Surveys present on the page, and that need to be added. * * @var bool|array */ private static $scripts = false; /** * Add all the actions & register the shortcode. */ public function __construct() { add_action( 'init', array( $this, 'register_scripts' ) ); add_shortcode( 'crowdsignal', array( $this, 'crowdsignal_shortcode' ) ); add_shortcode( 'polldaddy', array( $this, 'polldaddy_shortcode' ) ); add_filter( 'pre_kses', array( $this, 'crowdsignal_embed_to_shortcode' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'check_infinite' ) ); add_action( 'infinite_scroll_render', array( $this, 'crowdsignal_shortcode_infinite' ), 11 ); } /** * Register scripts that may be enqueued later on by the shortcode. */ public static function register_scripts() { wp_register_script( 'crowdsignal-shortcode', Assets::get_file_url_for_environment( '_inc/build/crowdsignal-shortcode.min.js', '_inc/crowdsignal-shortcode.js' ), array( 'jquery' ), JETPACK__VERSION, true ); wp_register_script( 'crowdsignal-survey', Assets::get_file_url_for_environment( '_inc/build/crowdsignal-survey.min.js', '_inc/crowdsignal-survey.js' ), array(), JETPACK__VERSION, true ); wp_register_script( 'crowdsignal-rating', 'https://polldaddy.com/js/rating/rating.js', array(), JETPACK__VERSION, true ); } /** * JavaScript code for a specific survey / poll. * * @param array $settings Array of information about a survey / poll. * @param string $survey_link HTML link tag for a specific survey or poll. * @param string $survey_url Link to the survey or poll. */ private function get_async_code( array $settings, $survey_link, $survey_url ) { wp_enqueue_script( 'crowdsignal-survey' ); if ( 'button' === $settings['type'] ) { $placeholder = sprintf( '<a class="cs-embed pd-embed" href="%1$s" data-settings="%2$s">%3$s</a>', esc_url( $survey_url ), esc_attr( wp_json_encode( $settings ) ), esc_html( $settings['title'] ) ); } else { $placeholder = sprintf( '<div class="cs-embed pd-embed" data-settings="%1$s"></div><noscript>%2$s</noscript>', esc_attr( wp_json_encode( $settings ) ), $survey_link ); } return $placeholder; } /** * Crowdsignal Poll Embed script - transforms code that looks like that: * <script type="text/javascript" charset="utf-8" async src="http://static.polldaddy.com/p/123456.js"></script> * <noscript><a href="http://polldaddy.com/poll/123456/">What is your favourite color?</a></noscript> * into the [crowdsignal poll=...] shortcode format * * @param string $content Post content. */ public function crowdsignal_embed_to_shortcode( $content ) { if ( ! is_string( $content ) || false === strpos( $content, 'polldaddy.com/p/' ) ) { return $content; } $regexes = array(); $regexes[] = '#<script[^>]+?src="https?://(secure|static)\.polldaddy\.com/p/([0-9]+)\.js"[^>]*+>\s*?</script>\r?\n?(<noscript>.*?</noscript>)?#i'; $regexes[] = '#&lt;script(?:[^&]|&(?!gt;))+?src="https?://(secure|static)\.polldaddy\.com/p/([0-9]+)\.js"(?:[^&]|&(?!gt;))*+&gt;\s*?&lt;/script&gt;\r?\n?(&lt;noscript&gt;.*?&lt;/noscript&gt;)?#i'; foreach ( $regexes as $regex ) { if ( ! preg_match_all( $regex, $content, $matches, PREG_SET_ORDER ) ) { continue; } foreach ( $matches as $match ) { if ( ! isset( $match[2] ) ) { continue; } $id = (int) $match[2]; if ( $id > 0 ) { $content = str_replace( $match[0], " [crowdsignal poll=$id]", $content ); /** This action is documented in modules/shortcodes/youtube.php */ do_action( 'jetpack_embed_to_shortcode', 'crowdsignal', $id ); } } } return $content; } /** * Support for legacy Polldaddy shortcode. * * @param array $atts Shortcode attributes. */ public function polldaddy_shortcode( $atts ) { if ( ! is_array( $atts ) ) { return '<!-- Polldaddy shortcode passed invalid attributes -->'; } $atts['site'] = 'polldaddy.com'; return $this->crowdsignal_shortcode( $atts ); } /** * Shortcode for Crowdsignal * [crowdsignal poll|survey|rating="123456"] * * @param array $atts Shortcode attributes. */ public function crowdsignal_shortcode( $atts ) { global $post; global $content_width; if ( ! is_array( $atts ) ) { return '<!-- Crowdsignal shortcode passed invalid attributes -->'; } $attributes = shortcode_atts( array( 'survey' => null, 'link_text' => esc_html__( 'Take Our Survey', 'jetpack' ), 'poll' => 'empty', 'rating' => 'empty', 'unique_id' => null, 'item_id' => null, 'title' => null, 'permalink' => null, 'cb' => 0, // cache buster. Helps with testing. 'type' => 'button', 'body' => '', 'button' => '', 'text_color' => '000000', 'back_color' => 'FFFFFF', 'align' => '', 'style' => '', 'width' => $content_width, 'height' => floor( $content_width * 3 / 4 ), 'delay' => 100, 'visit' => 'single', 'domain' => '', 'id' => '', 'site' => 'crowdsignal.com', ), $atts, 'crowdsignal' ); $inline = ! in_the_loop() && ! Constants::is_defined( 'TESTING_IN_JETPACK' ); $no_script = false; $infinite_scroll = false; if ( is_home() && current_theme_supports( 'infinite-scroll' ) ) { $infinite_scroll = true; } if ( function_exists( 'get_option' ) && get_option( 'polldaddy_load_poll_inline' ) ) { $inline = true; } if ( is_feed() || ( defined( 'DOING_AJAX' ) && ! $infinite_scroll ) ) { $no_script = false; } self::$add_script = $infinite_scroll; /* * Rating embed. */ if ( (int) $attributes['rating'] > 0 && ! $no_script ) { if ( empty( $attributes['unique_id'] ) ) { $attributes['unique_id'] = is_page() ? 'wp-page-' . $post->ID : 'wp-post-' . $post->ID; } if ( empty( $attributes['item_id'] ) ) { $attributes['item_id'] = is_page() ? '_page_' . $post->ID : '_post_' . $post->ID; } if ( empty( $attributes['title'] ) ) { /** This filter is documented in core/src/wp-includes/general-template.php */ $attributes['title'] = apply_filters( 'wp_title', $post->post_title, '', '' ); } if ( empty( $attributes['permalink'] ) ) { $attributes['permalink'] = get_permalink( $post->ID ); } $rating = (int) $attributes['rating']; $unique_id = preg_replace( '/[^\-_a-z0-9]/i', '', wp_strip_all_tags( $attributes['unique_id'] ) ); $item_id = wp_strip_all_tags( $attributes['item_id'] ); $item_id = preg_replace( '/[^_a-z0-9]/i', '', $item_id ); $settings = wp_json_encode( array( 'id' => $rating, 'unique_id' => $unique_id, 'title' => rawurlencode( trim( $attributes['title'] ) ), 'permalink' => esc_url( $attributes['permalink'] ), 'item_id' => $item_id, ) ); $item_id = esc_js( $item_id ); if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) { return sprintf( '<a href="%s" target="_blank">%s</a>', esc_url( $attributes['permalink'] ), esc_html( trim( $attributes['title'] ) ) ); } elseif ( $inline ) { $rating_js = "<!--//--><![CDATA[//><!--\n"; $rating_js .= "PDRTJS_settings_{$rating}{$item_id}={$settings};"; $rating_js .= "\n//--><!]]>"; wp_enqueue_script( 'crowdsignal-rating' ); wp_add_inline_script( 'crowdsignal-rating', $rating_js, 'before' ); return sprintf( '<div class="cs-rating pd-rating" id="pd_rating_holder_%1$d%2$s"></div>', absint( $rating ), esc_attr( $item_id ) ); } else { if ( false === self::$scripts ) { self::$scripts = array(); } $data = array( 'id' => $rating, 'item_id' => $item_id, 'settings' => $settings, ); self::$scripts['rating'][] = $data; add_action( 'wp_footer', array( $this, 'generate_scripts' ) ); if ( $infinite_scroll ) { return sprintf( '<div class="cs-rating pd-rating" id="pd_rating_holder_%1$d%2$s" data-settings="%3$s"></div>', absint( $rating ), esc_attr( $item_id ), esc_attr( wp_json_encode( $data ) ) ); } else { return sprintf( '<div class="cs-rating pd-rating" id="pd_rating_holder_%1$d%2$s"></div>', absint( $rating ), esc_attr( $item_id ) ); } } } elseif ( (int) $attributes['poll'] > 0 ) { /* * Poll embed. */ if ( empty( $attributes['title'] ) ) { $attributes['title'] = esc_html__( 'Take Our Poll', 'jetpack' ); } $poll = (int) $attributes['poll']; if ( 'crowdsignal.com' === $attributes['site'] ) { $poll_url = sprintf( 'https://poll.fm/%d', $poll ); } else { $poll_url = sprintf( 'https://polldaddy.com/p/%d', $poll ); } $poll_js = sprintf( 'https://secure.polldaddy.com/p/%d.js', $poll ); $poll_link = sprintf( '<a href="%s" target="_blank">%s</a>', esc_url( $poll_url ), esc_html( $attributes['title'] ) ); if ( $no_script || ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) ) { return $poll_link; } else { /* * Slider poll. */ if ( 'slider' === $attributes['type'] && ! $inline ) { if ( ! in_array( $attributes['visit'], array( 'single', 'multiple' ), true ) ) { $attributes['visit'] = 'single'; } $settings = array( 'type' => 'slider', 'embed' => 'poll', 'delay' => (int) $attributes['delay'], 'visit' => $attributes['visit'], 'id' => (int) $poll, 'site' => $attributes['site'], ); return $this->get_async_code( $settings, $poll_link, $poll_url ); } else { if ( 1 === $attributes['cb'] ) { $attributes['cb'] = '?cb=' . time(); } else { $attributes['cb'] = false; } $margins = ''; $float = ''; if ( in_array( $attributes['align'], array( 'right', 'left' ), true ) ) { $float = sprintf( 'float: %s;', $attributes['align'] ); if ( 'left' === $attributes['align'] ) { $margins = 'margin: 0px 10px 0px 0px;'; } elseif ( 'right' === $attributes['align'] ) { $margins = 'margin: 0px 0px 0px 10px'; } } /* * Force the normal style embed on single posts/pages * otherwise it's not rendered on infinite scroll themed blogs * ('infinite_scroll_render' isn't fired) */ if ( is_singular() ) { $inline = true; } if ( false === $attributes['cb'] && ! $inline ) { if ( false === self::$scripts ) { self::$scripts = array(); } $data = array( 'url' => $poll_js ); self::$scripts['poll'][ (int) $poll ] = $data; add_action( 'wp_footer', array( $this, 'generate_scripts' ) ); wp_enqueue_script( 'crowdsignal-shortcode' ); wp_localize_script( 'crowdsignal-shortcode', 'crowdsignal_shortcode_options', array( 'script_url' => esc_url_raw( Assets::get_file_url_for_environment( '_inc/build/polldaddy-shortcode.min.js', '_inc/polldaddy-shortcode.js' ) ), ) ); /** * Hook into the Crowdsignal shortcode before rendering. * * @since 8.4.0 * * @param int $poll Poll ID. */ do_action( 'crowdsignal_shortcode_before', (int) $poll ); return sprintf( '<a name="pd_a_%1$d"></a><div class="CSS_Poll PDS_Poll" id="PDI_container%1$d" data-settings="%2$s" style="%3$s%4$s"></div><div id="PD_superContainer"></div><noscript>%5$s</noscript>', absint( $poll ), esc_attr( wp_json_encode( $data ) ), $float, $margins, $poll_link ); } else { if ( $inline ) { $attributes['cb'] = ''; } wp_enqueue_script( 'crowdsignal-' . absint( $poll ), esc_url( $poll_js . $attributes['cb'] ), array(), JETPACK__VERSION, true ); /** This action is already documented in modules/shortcodes/crowdsignal.php */ do_action( 'crowdsignal_shortcode_before', (int) $poll ); return sprintf( '<a id="pd_a_%1$s"></a><div class="CSS_Poll PDS_Poll" id="PDI_container%1$s" style="%2$s%3$s"></div><div id="PD_superContainer"></div><noscript>%4$s</noscript>', absint( $poll ), $float, $margins, $poll_link ); } } } } elseif ( ! empty( $attributes['survey'] ) ) { /* * Survey embed. */ if ( in_array( $attributes['type'], array( 'iframe', 'button', 'banner', 'slider' ), true ) ) { if ( empty( $attributes['title'] ) ) { $attributes['title'] = esc_html__( 'Take Our Survey', 'jetpack' ); if ( ! empty( $attributes['link_text'] ) ) { $attributes['title'] = $attributes['link_text']; } } if ( 'banner' === $attributes['type'] || 'slider' === $attributes['type'] ) { $inline = false; } $survey_url = ''; if ( 'true' !== $attributes['survey'] ) { $survey = preg_replace( '/[^a-f0-9]/i', '', $attributes['survey'] ); if ( 'crowdsignal.com' === $attributes['site'] ) { $survey_url = 'https://survey.fm/' . $survey; } else { $survey_url = 'https://polldaddy.com/s/' . $survey; } } else { if ( isset( $attributes['domain'] ) && isset( $attributes['id'] ) ) { $survey_url = 'https://' . $attributes['domain'] . '.survey.fm/' . $attributes['id']; } } $survey_link = sprintf( '<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>', esc_url( $survey_url ), esc_html( $attributes['title'] ) ); $settings = array(); if ( 'iframe' === $attributes['type'] ) { if ( 'auto' !== $attributes['height'] ) { if ( isset( $content_width ) && is_numeric( $attributes['width'] ) && $attributes['width'] > $content_width ) { $attributes['width'] = $content_width; } if ( ! $attributes['width'] ) { $attributes['width'] = '100%'; } else { $attributes['width'] = (int) $attributes['width']; } if ( ! $attributes['height'] ) { $attributes['height'] = '600'; } else { $attributes['height'] = (int) $attributes['height']; } return sprintf( '<iframe src="%1$s?iframe=1" frameborder="0" width="%2$d" height="%3$d" scrolling="auto" allowtransparency="true" marginheight="0" marginwidth="0">%4$s</iframe>', esc_url( $survey_url ), absint( $attributes['width'] ), absint( $attributes['height'] ), $survey_link ); } elseif ( ! empty( $attributes['domain'] ) && ! empty( $attributes['id'] ) ) { $domain = preg_replace( '/[^a-z0-9\-]/i', '', $attributes['domain'] ); $id = preg_replace( '/[\/\?&\{\}]/', '', $attributes['id'] ); $auto_src = esc_url( "https://{$domain}.survey.fm/{$id}" ); $auto_src = wp_parse_url( $auto_src ); if ( ! is_array( $auto_src ) || 0 === count( $auto_src ) ) { return '<!-- no crowdsignal output -->'; } if ( ! isset( $auto_src['host'] ) || ! isset( $auto_src['path'] ) ) { return '<!-- no crowdsignal output -->'; } $domain = $auto_src['host'] . '/'; $id = ltrim( $auto_src['path'], '/' ); $settings = array( 'type' => $attributes['type'], 'auto' => true, 'domain' => $domain, 'id' => $id, 'site' => $attributes['site'], ); } } else { $text_color = preg_replace( '/[^a-f0-9]/i', '', $attributes['text_color'] ); $back_color = preg_replace( '/[^a-f0-9]/i', '', $attributes['back_color'] ); if ( ! in_array( $attributes['align'], array( 'right', 'left', 'top-left', 'top-right', 'middle-left', 'middle-right', 'bottom-left', 'bottom-right', ), true ) ) { $attributes['align'] = ''; } if ( ! in_array( $attributes['style'], array( 'inline', 'side', 'corner', 'rounded', 'square', ), true ) ) { $attributes['style'] = ''; } $settings = array_filter( array( 'title' => wp_strip_all_tags( $attributes['title'] ), 'type' => $attributes['type'], 'body' => wp_strip_all_tags( $attributes['body'] ), 'button' => wp_strip_all_tags( $attributes['button'] ), 'text_color' => $text_color, 'back_color' => $back_color, 'align' => $attributes['align'], 'style' => $attributes['style'], 'id' => $survey, 'site' => $attributes['site'], ) ); } if ( empty( $settings ) ) { return '<!-- no crowdsignal output -->'; } return $this->get_async_code( $settings, $survey_link, $survey_url ); } } else { return '<!-- no crowdsignal output -->'; } } /** * Enqueue JavaScript containing all ratings / polls on the page. * Hooked into wp_footer */ public function generate_scripts() { if ( is_array( self::$scripts ) ) { if ( isset( self::$scripts['rating'] ) ) { $script = "<!--//--><![CDATA[//><!--\n"; foreach ( self::$scripts['rating'] as $rating ) { $script .= "PDRTJS_settings_{$rating['id']}{$rating['item_id']}={$rating['settings']}; if ( typeof PDRTJS_RATING !== 'undefined' ){if ( typeof PDRTJS_{$rating['id']}{$rating['item_id']} == 'undefined' ){PDRTJS_{$rating['id']}{$rating['item_id']} = new PDRTJS_RATING( PDRTJS_settings_{$rating['id']}{$rating['item_id']} );}}"; } $script .= "\n//--><!]]>"; wp_enqueue_script( 'crowdsignal-rating' ); wp_add_inline_script( 'crowdsignal-rating', $script, 'before' ); } if ( isset( self::$scripts['poll'] ) ) { foreach ( self::$scripts['poll'] as $poll_id => $poll ) { wp_enqueue_script( 'crowdsignal-' . absint( $poll_id ), esc_url( $poll['url'] ), array(), JETPACK__VERSION, true ); } } } self::$scripts = false; } /** * If the theme uses infinite scroll, include jquery at the start */ public function check_infinite() { if ( current_theme_supports( 'infinite-scroll' ) && class_exists( 'The_Neverending_Home_Page' ) && The_Neverending_Home_Page::archive_supports_infinity() ) { wp_enqueue_script( 'jquery' ); } } /** * Dynamically load the .js, if needed * * This hooks in late (priority 11) to infinite_scroll_render to determine * a posteriori if a shortcode has been called. */ public function crowdsignal_shortcode_infinite() { // only try to load if a shortcode has been called and theme supports infinite scroll. if ( self::$add_script ) { wp_enqueue_script( 'crowdsignal-shortcode' ); wp_localize_script( 'crowdsignal-shortcode', 'crowdsignal_shortcode_options', array( 'script_url' => esc_url_raw( Assets::get_file_url_for_environment( '_inc/build/polldaddy-shortcode.min.js', '_inc/polldaddy-shortcode.js' ) ), ) ); } } } // Kick it all off. new CrowdsignalShortcode(); if ( ! function_exists( 'crowdsignal_link' ) ) { /** * Replace link with shortcode. * Examples: https://poll.fm/10499328 | https://7iger.survey.fm/test-embed * * @param string $content Post content. */ function crowdsignal_link( $content ) { if ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() ) { return $content; } // Replace poll links. $content = jetpack_preg_replace_outside_tags( '!(?:\n|\A)https?://(polldaddy\.com/poll|poll\.fm)/([0-9]+?)(/.*)?(?:\n|\Z)!i', '[crowdsignal poll=$2]', $content ); // Replace survey.fm links. $content = preg_replace( '!(?:\n|\A)https?://(.*).survey.fm/(.*)(/.*)?(?:\n|\Z)!i', '[crowdsignal type="iframe" survey="true" height="auto" domain="$1" id="$2"]', $content ); return $content; } // higher priority because we need it before auto-link and autop get to it. add_filter( 'the_content', 'crowdsignal_link', 1 ); add_filter( 'the_content_rss', 'crowdsignal_link', 1 ); } }
Automattic/vip-go-mu-plugins
jetpack-9.4/modules/shortcodes/crowdsignal.php
PHP
gpl-2.0
22,364
[ 30522, 1026, 1029, 25718, 1013, 1013, 25718, 6169, 1024, 8568, 30524, 2828, 1027, 1000, 2065, 6444, 2063, 1000, 5002, 1027, 1000, 1041, 2497, 16068, 16147, 22610, 2063, 28154, 12376, 11329, 2546, 1000, 4578, 1027, 1000, 8285, 1000, 5884, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <linux/soundcard.h> #ifdef HAVE_ALSA #include <alsa/asoundlib.h> #endif #define AUDIO_DEVICE "/dev/dsp" #define ALSA_MAX_BUF_SIZE 655350 #ifdef HAVE_ALSA int play_sound_Alsa(char* filename,int rate,int bits,int channel,int order) { int rc,size; char *buffer; unsigned int val; snd_pcm_t *handle; snd_pcm_hw_params_t *params; snd_pcm_uframes_t frames,periodsize; snd_mixer_t *mixer; snd_mixer_elem_t *pcm_element; struct stat buf; if(stat(filename, &buf)<0) { return -1; } size=(unsigned long)buf.st_size; FILE *fp = fopen(filename,"rb"); if(NULL == fp) { printf("can't open file!\n"); return -1; } rc = snd_pcm_open(&handle,"default",SND_PCM_STREAM_PLAYBACK,0); snd_pcm_hw_params_alloca(&params); snd_pcm_hw_params_any(handle,params); snd_pcm_hw_params_set_access(handle,params,SND_PCM_ACCESS_RW_INTERLEAVED); switch(order){ case 1: snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_LE); break; case 2: snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_BE); break; defualt: break; } snd_pcm_hw_params_set_channels(handle,params,channel); val = rate; snd_pcm_hw_params_set_rate_near(handle,params,&val,0); snd_pcm_hw_params_get_buffer_size_max(params,&frames); frames = frames < ALSA_MAX_BUF_SIZE? frames:ALSA_MAX_BUF_SIZE; rc = snd_pcm_hw_params_set_buffer_size_near(handle,params,&frames); snd_pcm_hw_params_get_period_size_min(params,&periodsize,NULL); if(!periodsize){ periodsize=size/4; } rc = snd_pcm_hw_params_set_period_size_near(handle,params,&periodsize,NULL); rc = snd_pcm_hw_params(handle,params); snd_mixer_open(&mixer,0); snd_mixer_attach(mixer,"default"); snd_mixer_selem_register(mixer,NULL,NULL); snd_mixer_load(mixer); for(pcm_element = snd_mixer_first_elem(mixer);pcm_element;pcm_element=snd_mixer_elem_next(pcm_element)) { if(snd_mixer_elem_get_type(pcm_element)==SND_MIXER_ELEM_SIMPLE && snd_mixer_selem_is_active(pcm_element)) { if(!strcmp(snd_mixer_selem_get_name(pcm_element),"Master")) { snd_mixer_selem_set_playback_volume_range(pcm_element,0,100); snd_mixer_selem_set_playback_volume_all(pcm_element,(long)100); } } } buffer = (char*)malloc(size); rc = fread(buffer,1,size,fp); if(0== rc) return -1; snd_pcm_writei(handle,buffer,size); snd_pcm_prepare(handle); snd_pcm_hw_params_free(params); snd_mixer_close(mixer); snd_pcm_close(handle); free(buffer); fclose(fp); return 0; } #endif int play_sound_OSS(char *filename,int rate,int bits){ struct stat stat_buf; unsigned char *buf = NULL; int result,arg,status,handler,fd; fd = open(filename,O_RDONLY); if(fd<0) return -1; if(fstat(fd,&stat_buf)) { close(fd); return -1; } if(!stat_buf.st_size) { close(fd); return -1; } buf=malloc(stat_buf.st_size); if(!buf){ close(fd); return -1; } if(read(fd,buf,stat_buf.st_size)<0){ free(buf); close(fd); return -1; } handler = open(AUDIO_DEVICE,O_WRONLY); if(-1 == handler){ return -1; } arg = rate*2; status = ioctl(handler,SOUND_PCM_WRITE_RATE,&arg); if(-1 == status) return -1; arg = bits; status = ioctl(handler,SOUND_PCM_WRITE_BITS,&arg); if(-1 == status) return -1; result = write(handler,buf,stat_buf.st_size); if(-1 == result) return -1; free(buf); close(fd); close(handler); return result; } /*中文显示乱码问题*/ int main(int argc,char** argv){ if(*argv[4] == '1') play_sound_OSS(argv[1],atoi(argv[2]),atoi(argv[3])); #ifdef HAVE_ALSA else play_sound_Alsa(argv[1],atoi(argv[2]),atoi(argv[3]),atoi(argv[5]),atoi(argv[6])); #endif return 0; }
Oxfinder/splayer
playmusic.c
C
gpl-2.0
4,149
[ 30522, 1001, 2421, 1026, 2358, 20617, 1012, 1044, 1028, 1001, 2421, 1026, 2358, 19422, 12322, 1012, 1044, 1028, 1001, 2421, 1026, 4895, 2923, 2094, 1012, 1044, 1028, 1001, 2421, 1026, 4429, 3372, 2140, 1012, 1044, 1028, 1001, 2421, 1026, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Miracode\StripeBundle\Model; use Miracode\StripeBundle\Annotation\StripeObjectParam; abstract class AbstractSubscriptionModel extends StripeModel { /** * @StripeObjectParam(name="application_fee_percent") * * @var float */ protected $applicationFeePercent; /** * @StripeObjectParam * * @var string */ protected $billing; /** * @StripeObjectParam(name="cancel_at_period_end") * * @var bool */ protected $cancelAtPeriodEnd; /** * @StripeObjectParam(name="canceled_at") * * @var int */ protected $canceledAt; /** * @StripeObjectParam(name="discount", embeddedId="coupon.id") * * @var string */ protected $coupon; /** * @StripeObjectParam * * @var int */ protected $created; /** * @StripeObjectParam(name="current_period_end") * * @var int */ protected $currentPeriodEnd; /** * @StripeObjectParam(name="current_period_start") * * @var int */ protected $currentPeriodStart; /** * @StripeObjectParam * * @var string */ protected $customer; /** * @StripeObjectParam(name="days_until_due") * * @var int */ protected $daysUntilDue; /** * @StripeObjectParam(name="ended_at") * * @var int */ protected $endedAt; /** * @StripeObjectParam * * @var array */ protected $items; /** * @StripeObjectParam * * @var bool */ protected $livemode; /** * @StripeObjectParam * * @var array */ protected $metadata; /** * @StripeObjectParam(embeddedId="id") * * @var string */ protected $plan; /** * @StripeObjectParam * * @var int */ protected $quantity; /** * @StripeObjectParam * * @var int */ protected $start; /** * @StripeObjectParam * * @var string */ protected $status; /** * @StripeObjectParam(name="tax_percent") * * @var float */ protected $taxPercent; /** * @StripeObjectParam(name="trial_end") * * @var int */ protected $trialEnd; /** * @StripeObjectParam(name="trial_start") * * @var int */ protected $trialStart; /** * @return float */ public function getApplicationFeePercent() { return $this->applicationFeePercent; } /** * @param float $applicationFeePercent * * @return $this */ public function setApplicationFeePercent($applicationFeePercent) { $this->applicationFeePercent = $applicationFeePercent; return $this; } /** * @return string */ public function getBilling() { return $this->billing; } /** * @param string $billing * * @return $this */ public function setBilling($billing) { $this->billing = $billing; return $this; } /** * @return bool */ public function isCancelAtPeriodEnd() { return $this->cancelAtPeriodEnd; } /** * @param bool $cancelAtPeriodEnd * * @return $this */ public function setCancelAtPeriodEnd($cancelAtPeriodEnd) { $this->cancelAtPeriodEnd = $cancelAtPeriodEnd; return $this; } /** * @return int */ public function getCanceledAt() { return $this->canceledAt; } /** * @param int $canceledAt * * @return $this */ public function setCanceledAt($canceledAt) { $this->canceledAt = $canceledAt; return $this; } /** * @return string */ public function getCoupon() { return $this->coupon; } /** * @param string $coupon * * @return $this */ public function setCoupon($coupon) { $this->coupon = $coupon; return $this; } /** * @return int */ public function getCreated() { return $this->created; } /** * @param int $created * * @return $this */ public function setCreated($created) { $this->created = $created; return $this; } /** * @return int */ public function getCurrentPeriodEnd() { return $this->currentPeriodEnd; } /** * @param int $currentPeriodEnd * * @return $this */ public function setCurrentPeriodEnd($currentPeriodEnd) { $this->currentPeriodEnd = $currentPeriodEnd; return $this; } /** * @return int */ public function getCurrentPeriodStart() { return $this->currentPeriodStart; } /** * @param int $currentPeriodStart * * @return $this */ public function setCurrentPeriodStart($currentPeriodStart) { $this->currentPeriodStart = $currentPeriodStart; return $this; } /** * @return string */ public function getCustomer() { return $this->customer; } /** * @param string $customer * * @return $this */ public function setCustomer($customer) { $this->customer = $customer; return $this; } /** * @return int */ public function getDaysUntilDue() { return $this->daysUntilDue; } /** * @param int $daysUntilDue * * @return $this */ public function setDaysUntilDue($daysUntilDue) { $this->daysUntilDue = $daysUntilDue; return $this; } /** * @return int */ public function getEndedAt() { return $this->endedAt; } /** * @param int $endedAt * * @return $this */ public function setEndedAt($endedAt) { $this->endedAt = $endedAt; return $this; } /** * @return array */ public function getItems() { return $this->items; } /** * @param array $items * * @return $this */ public function setItems($items) { $this->items = $items; return $this; } /** * @return bool */ public function isLivemode() { return $this->livemode; } /** * @param bool $livemode * * @return $this */ public function setLivemode($livemode) { $this->livemode = $livemode; return $this; } /** * @return array */ public function getMetadata() { return $this->metadata; } /** * @param array $metadata * * @return $this */ public function setMetadata($metadata) { $this->metadata = $metadata; return $this; } /** * @return string */ public function getPlan() { return $this->plan; } /** * @param string $plan * * @return $this */ public function setPlan($plan) { $this->plan = $plan; return $this; } /** * @return int */ public function getQuantity() { return $this->quantity; } /** * @param int $quantity * * @return $this */ public function setQuantity($quantity) { $this->quantity = $quantity; return $this; } /** * @return int */ public function getStart() { return $this->start; } /** * @param int $start * * @return $this */ public function setStart($start) { $this->start = $start; return $this; } /** * @return string */ public function getStatus() { return $this->status; } /** * @param string $status * * @return $this */ public function setStatus($status) { $this->status = $status; return $this; } /** * @return float */ public function getTaxPercent() { return $this->taxPercent; } /** * @param float $taxPercent * * @return $this */ public function setTaxPercent($taxPercent) { $this->taxPercent = $taxPercent; return $this; } /** * @return int */ public function getTrialEnd() { return $this->trialEnd; } /** * @param int $trialEnd * * @return $this */ public function setTrialEnd($trialEnd) { $this->trialEnd = $trialEnd; return $this; } /** * @return int */ public function getTrialStart() { return $this->trialStart; } /** * @param int $trialStart * * @return $this */ public function setTrialStart($trialStart) { $this->trialStart = $trialStart; return $this; } }
aimir/stripe-bundle
Model/AbstractSubscriptionModel.php
PHP
mit
9,051
[ 30522, 1026, 1029, 25718, 3415, 15327, 18062, 16044, 1032, 18247, 27265, 2571, 1032, 2944, 1025, 2224, 18062, 16044, 1032, 18247, 27265, 2571, 1032, 5754, 17287, 30524, 9247, 8908, 18247, 5302, 9247, 1063, 1013, 1008, 1008, 1008, 1030, 18247,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module.exports = function (app) { // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // development error handler // will print stacktrace app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('errors/generic', { message: err.message, error: err }); }); // production error handler // no stacktraces leaked to user // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('partials/error', { // message: err.message, // error: {} // }); // }); }
RandomVision/darkchess
backend/lib/error_handlers.js
JavaScript
gpl-3.0
686
[ 30522, 11336, 1012, 14338, 1027, 3853, 1006, 10439, 1007, 1063, 1013, 1013, 4608, 24837, 1998, 2830, 2000, 7561, 28213, 10439, 1012, 30524, 7561, 1006, 1005, 2025, 2179, 1005, 1007, 1025, 9413, 2099, 1012, 3570, 1027, 24837, 1025, 2279, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
const Comparator = require('../../util/comparator'); /** * Swaps two elements in the array */ const swap = (array, x, y) => { const tmp = array[y]; array[y] = array[x]; array[x] = tmp; }; /** * Chooses a pivot and makes every element that is * lower than the pivot move to its left, and every * greater element moves to its right * * @return Number the positon of the pivot */ const partition = (a, comparator, lo, hi) => { // pick a random element, swap with the rightmost and // use it as pivot swap(a, Math.floor(Math.random() * (hi - lo)) + lo, hi); const pivot = hi; // dividerPosition keeps track of the position // where the pivot should be inserted let dividerPosition = lo; for (let i = lo; i < hi; i++) { if (comparator.lessThan(a[i], a[pivot])) { swap(a, i, dividerPosition); dividerPosition++; } } swap(a, dividerPosition, pivot); return dividerPosition; }; /** * Quicksort recursively sorts parts of the array in * O(n.lg n) */ const quicksortInit = (array, comparatorFn) => { const comparator = new Comparator(comparatorFn); return (function quicksort(array, lo, hi) { while (lo < hi) { const p = partition(array, comparator, lo, hi); // Chooses only the smallest partition to use recursion on and // tail-optimize the other. This guarantees O(log n) space in worst case. if (p - lo < hi - p) { quicksort(array, lo, p - 1); lo = p + 1; } else { quicksort(array, p + 1, hi); hi = p - 1; } } return array; })(array, 0, array.length - 1); }; module.exports = quicksortInit;
felipernb/algorithms.js
src/algorithms/sorting/quicksort.js
JavaScript
mit
1,638
[ 30522, 9530, 3367, 4012, 28689, 4263, 1027, 5478, 1006, 1005, 1012, 1012, 1013, 1012, 1012, 1013, 21183, 4014, 1013, 4012, 28689, 4263, 1005, 1007, 1025, 1013, 1008, 1008, 1008, 19948, 2015, 2048, 3787, 1999, 1996, 9140, 1008, 1013, 9530, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.rpereira.mineteam.client.gui; import com.rpereira.mineteam.common.packets.Packets; import com.rpereira.mineteam.common.packets.client.PacketTeamInvitation; import com.rpereira.mineteam.common.packets.server.PacketTeamAcceptInvitation; import com.rpereira.mineteam.common.packets.server.PacketTeamRefuseInvitation; import com.rpereira.mineutils.ChatColor; import cpw.mods.fml.common.network.simpleimpl.IMessage; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; public class GuiInvitation extends GuiScreen { private PacketTeamInvitation message; public GuiInvitation(PacketTeamInvitation message) { this.message = message; } @SuppressWarnings("unchecked") @Override public void initGui() { this.buttonList.add( new GuiButton(42, this.width / 4, this.height - 80, this.width / 2, 20, ChatColor.RESET + "Accept")); this.buttonList.add( new GuiButton(43, this.width / 4, this.height - 40, this.width / 2, 20, ChatColor.RESET + "Decline")); } /** * Draws the screen and all the components in it. */ @Override public void drawScreen(int x, int y, float useless) { this.drawCenteredString(this.fontRendererObj, ChatColor.UNDERLINE + this.message.inviter + " has invited you in his team: " + this.message.teamName, this.width / 2, 14, Integer.MAX_VALUE); super.drawScreen(x, y, useless); } @Override public boolean doesGuiPauseGame() { return false; } @Override protected void actionPerformed(GuiButton b) { if (b.id == 42) { // accept IMessage packet = new PacketTeamAcceptInvitation(this.message.token); Packets.network.sendToServer(packet); this.mc.displayGuiScreen((GuiScreen) null); this.mc.setIngameFocus(); } else if (b.id == 43) { // refuses IMessage packet = new PacketTeamRefuseInvitation(this.message.token); Packets.network.sendToServer(packet); this.mc.displayGuiScreen((GuiScreen) null); this.mc.setIngameFocus(); } } }
rpereira-dev/MineMods_1_7_10
MineTeam/src/main/java/com/rpereira/mineteam/client/gui/GuiInvitation.java
Java
gpl-3.0
2,029
[ 30522, 7427, 4012, 1012, 1054, 4842, 21302, 1012, 3067, 27058, 2213, 1012, 7396, 1012, 26458, 1025, 12324, 4012, 1012, 1054, 4842, 21302, 1012, 3067, 27058, 2213, 1012, 2691, 1012, 23730, 1012, 23730, 1025, 12324, 4012, 1012, 1054, 4842, 21...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// // MainWindow.h // fakeThunder // // Created by Martian on 12-8-15. // Copyright (c) 2012年 MartianZ. All rights reserved. // #import <Cocoa/Cocoa.h> @interface MainWindow : NSWindowController @end
yangchenghu/fakeThunder
fakeThunder/fakeThunder/MainWindow.h
C
gpl-3.0
209
[ 30522, 1013, 1013, 1013, 1013, 2364, 11101, 5004, 1012, 1044, 1013, 1013, 8275, 2705, 20824, 1013, 1013, 1013, 1013, 2580, 2011, 20795, 2006, 2260, 1011, 1022, 1011, 2321, 1012, 1013, 1013, 9385, 1006, 1039, 1007, 2262, 1840, 20795, 2480, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from scapy.all import * from scapy.layers import dhcp6 from time import time def duid(ll_addr): return DUID_LLT(lladdr=ll_addr, timeval=time()) def ias(requested, iface, T1=None, T2=None): return map(lambda r: __build_ia(r, iface, T1, T2), requested) def options(requested): return map(__build_option_by_code, requested) def __build_ia(request, iface, T1=None, T2=None): ia = request.__class__(iaid=request.iaid, T1=(T1 == None and request.T1 or T1), T2=(T2 == None and request.T2 or T2)) ia.ianaopts.append(DHCP6OptIAAddress(addr=str(iface.global_ip()), preflft=300, validlft=300)) return ia def __build_option_by_code(code): opt = __option_klass_by_code(code)() if isinstance(opt, DHCP6OptClientFQDN): opt.fqdn = 'testhost.local.' elif isinstance(opt, DHCP6OptDNSDomains): pass elif isinstance(opt, DHCP6OptDNSServers): opt.dnsservers.append('2001:500:88:200::10') elif isinstance(opt, DHCP6OptSNTPServers): opt.sntpservers.append('2001:500:88:200::10') return opt def __option_klass_by_code(code): return getattr(dhcp6, dhcp6.dhcp6opts_by_code[code])
mwrlabs/veripy
contrib/rfc3736/builder.py
Python
gpl-3.0
1,149
[ 30522, 2013, 8040, 9331, 2100, 1012, 2035, 12324, 1008, 2013, 8040, 9331, 2100, 1012, 9014, 12324, 28144, 21906, 2575, 2013, 2051, 12324, 2051, 13366, 4241, 3593, 1006, 2222, 1035, 5587, 2099, 1007, 1024, 2709, 4241, 3593, 1035, 2222, 2102,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Generated by asn1c-0.9.28 (http://lionet.info/asn1c) * From ASN.1 module "ACSE-1" * found in "../../../dumpvdl2.asn1/atn-b1_ulcs.asn1" * `asn1c -fcompound-names -fincludes-quoted -gen-PER` */ #include "ACSE-apdu.h" static asn_per_constraints_t asn_PER_type_ACSE_apdu_constr_1 GCC_NOTUSED = { { APC_CONSTRAINED | APC_EXTENSIBLE, 3, 3, 0, 4 } /* (0..4,...) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_ACSE_apdu_1[] = { { ATF_NOFLAGS, 0, offsetof(struct ACSE_apdu, choice.aarq), (ASN_TAG_CLASS_APPLICATION | (0 << 2)), 0, &asn_DEF_AARQ_apdu, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "aarq" }, { ATF_NOFLAGS, 0, offsetof(struct ACSE_apdu, choice.aare), (ASN_TAG_CLASS_APPLICATION | (1 << 2)), 0, &asn_DEF_AARE_apdu, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "aare" }, { ATF_NOFLAGS, 0, offsetof(struct ACSE_apdu, choice.rlrq), (ASN_TAG_CLASS_APPLICATION | (2 << 2)), 0, &asn_DEF_RLRQ_apdu, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "rlrq" }, { ATF_NOFLAGS, 0, offsetof(struct ACSE_apdu, choice.rlre), (ASN_TAG_CLASS_APPLICATION | (3 << 2)), 0, &asn_DEF_RLRE_apdu, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "rlre" }, { ATF_NOFLAGS, 0, offsetof(struct ACSE_apdu, choice.abrt), (ASN_TAG_CLASS_APPLICATION | (4 << 2)), 0, &asn_DEF_ABRT_apdu, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "abrt" }, }; static const asn_TYPE_tag2member_t asn_MAP_ACSE_apdu_tag2el_1[] = { { (ASN_TAG_CLASS_APPLICATION | (0 << 2)), 0, 0, 0 }, /* aarq */ { (ASN_TAG_CLASS_APPLICATION | (1 << 2)), 1, 0, 0 }, /* aare */ { (ASN_TAG_CLASS_APPLICATION | (2 << 2)), 2, 0, 0 }, /* rlrq */ { (ASN_TAG_CLASS_APPLICATION | (3 << 2)), 3, 0, 0 }, /* rlre */ { (ASN_TAG_CLASS_APPLICATION | (4 << 2)), 4, 0, 0 } /* abrt */ }; static asn_CHOICE_specifics_t asn_SPC_ACSE_apdu_specs_1 = { sizeof(struct ACSE_apdu), offsetof(struct ACSE_apdu, _asn_ctx), offsetof(struct ACSE_apdu, present), sizeof(((struct ACSE_apdu *)0)->present), asn_MAP_ACSE_apdu_tag2el_1, 5, /* Count of tags in the map */ 0, 5 /* Extensions start */ }; asn_TYPE_descriptor_t asn_DEF_ACSE_apdu = { "ACSE-apdu", "ACSE-apdu", CHOICE_free, CHOICE_print, CHOICE_constraint, CHOICE_decode_ber, CHOICE_encode_der, CHOICE_decode_xer, CHOICE_encode_xer, CHOICE_decode_uper, CHOICE_encode_uper, CHOICE_outmost_tag, 0, /* No effective tags (pointer) */ 0, /* No effective tags (count) */ 0, /* No tags (pointer) */ 0, /* No tags (count) */ &asn_PER_type_ACSE_apdu_constr_1, asn_MBR_ACSE_apdu_1, 5, /* Elements count */ &asn_SPC_ACSE_apdu_specs_1 /* Additional specs */ };
szpajder/dumpvdl2
src/asn1/ACSE-apdu.c
C
gpl-3.0
2,962
[ 30522, 1013, 1008, 1008, 7013, 2011, 2004, 2078, 2487, 2278, 1011, 1014, 1012, 1023, 1012, 2654, 1006, 8299, 1024, 1013, 1013, 7006, 3388, 1012, 18558, 1013, 2004, 2078, 2487, 2278, 1007, 1008, 2013, 2004, 2078, 1012, 1015, 11336, 1000, 9...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<a href="https://github.com/php-in-a-tweet/php-in-a-tweet.github.io"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>
php-in-a-tweet/php-in-a-tweet.github.io
_includes/fork-me-ribbon.html
HTML
mit
481
[ 30522, 1026, 1037, 17850, 12879, 1027, 1000, 16770, 1024, 1013, 1013, 21025, 2705, 12083, 1012, 4012, 1013, 25718, 1011, 1999, 1011, 1037, 1011, 1056, 28394, 2102, 1013, 25718, 1011, 1999, 1011, 1037, 1011, 1056, 28394, 2102, 1012, 21025, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * JDIVisitor * Copyright (C) 2014 Adrian Herrera * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jdivisitor.debugger.launcher; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import org.apache.commons.lang3.Validate; import com.sun.jdi.Bootstrap; import com.sun.jdi.VirtualMachine; import com.sun.jdi.connect.AttachingConnector; import com.sun.jdi.connect.Connector; /** * Attach (via a socket) to a listening virtual machine in debug mode. * * @author Adrian Herrera * */ public class RemoteVMConnector extends VMConnector { /** * Socket connection details. */ private final InetSocketAddress socketAddress; /** * Constructor. * * @param hostname Name of the host to connect to * @param port Port number the virtual machine is listening on */ public RemoteVMConnector(String hostname, int port) { this(new InetSocketAddress(hostname, port)); } /** * Constructor. * * @param sockAddr Socket address structure to connect to. */ public RemoteVMConnector(InetSocketAddress sockAddr) { socketAddress = Validate.notNull(sockAddr); } @Override public VirtualMachine connect() throws Exception { List<AttachingConnector> connectors = Bootstrap.virtualMachineManager() .attachingConnectors(); AttachingConnector connector = findConnector( "com.sun.jdi.SocketAttach", connectors); Map<String, Connector.Argument> arguments = connectorArguments(connector); VirtualMachine vm = connector.attach(arguments); // TODO - redirect stdout and stderr? return vm; } /** * Set the socket-attaching connector's arguments. * * @param connector A socket-attaching connector * @return The socket-attaching connector's arguments */ private Map<String, Connector.Argument> connectorArguments( AttachingConnector connector) { Map<String, Connector.Argument> arguments = connector .defaultArguments(); arguments.get("hostname").setValue(socketAddress.getHostName()); arguments.get("port").setValue( Integer.toString(socketAddress.getPort())); return arguments; } }
adrianherrera/jdivisitor
src/main/java/org/jdivisitor/debugger/launcher/RemoteVMConnector.java
Java
mit
2,991
[ 30522, 1013, 1008, 1008, 26219, 12848, 17417, 4263, 1008, 9385, 1006, 1039, 1007, 2297, 7918, 23527, 1008, 1008, 2023, 2565, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, 1008, 2009, 2104, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require 'bundler/setup' module Bob end require_relative 'bob/config' require_relative 'bob/engine' config = Bob::Config.load engine = Bob::Engine.new(config) engine.run
hcatlin/bob
lib/bob.rb
Ruby
mit
173
[ 30522, 5478, 1005, 14012, 2099, 1013, 16437, 1005, 11336, 3960, 2203, 5478, 1035, 5816, 1005, 3960, 1013, 9530, 8873, 2290, 1005, 5478, 1035, 5816, 1005, 3960, 1013, 3194, 1005, 9530, 8873, 2290, 1027, 3960, 1024, 1024, 9530, 8873, 2290, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include <ctype.h> #include "driver.h" #include "sound/samples.h" #include "info.h" #include "datafile.h" /* Output format indentation */ /* Indentation */ #define INDENT "\t" /* Possible output format */ #define OUTPUT_FORMAT_UNFORMATTED 0 #define OUTPUT_FORMAT_ONE_LEVEL 1 #define OUTPUT_FORMAT_TWO_LEVEL 2 /* Output format */ #define OUTPUT_FORMAT OUTPUT_FORMAT_ONE_LEVEL /* Output format configuration L list 1,2 levels B,S,E Begin, Separator, End */ #if OUTPUT_FORMAT == OUTPUT_FORMAT_UNFORMATTED #define L1B "(" #define L1P " " #define L1N "" #define L1E ")" #define L2B "(" #define L2P " " #define L2N "" #define L2E ")" #elif OUTPUT_FORMAT == OUTPUT_FORMAT_ONE_LEVEL #define L1B " (\n" #define L1P INDENT #define L1N "\n" #define L1E ")\n\n" #define L2B " (" #define L2P " " #define L2N "" #define L2E " )" #elif OUTPUT_FORMAT == OUTPUT_FORMAT_TWO_LEVEL #define L1B " (\n" #define L1P INDENT #define L1N "\n" #define L1E ")\n\n" #define L2B " (\n" #define L2P INDENT INDENT #define L2N "\n" #define L2E INDENT ")" #else #error Wrong OUTPUT_FORMAT #endif /* Print a string in C format */ static void print_c_string(FILE* out, const char* s) { fprintf(out, "\""); if (s) { while (*s) { switch (*s) { case '\a' : fprintf(out, "\\a"); break; case '\b' : fprintf(out, "\\b"); break; case '\f' : fprintf(out, "\\f"); break; case '\n' : fprintf(out, "\\n"); break; case '\r' : fprintf(out, "\\r"); break; case '\t' : fprintf(out, "\\t"); break; case '\v' : fprintf(out, "\\v"); break; case '\\' : fprintf(out, "\\\\"); break; case '\"' : fprintf(out, "\\\""); break; default: if (*s>=' ' && *s<='~') fprintf(out, "%c", *s); else fprintf(out, "\\x%02x", (unsigned)(unsigned char)*s); } ++s; } } fprintf(out, "\""); } /* Print a string in statement format (remove space, parentesis, ") */ static void print_statement_string(FILE* out, const char* s) { if (s) { while (*s) { if (isspace(*s)) { fprintf(out, "_"); } else { switch (*s) { case '(' : case ')' : case '"' : fprintf(out, "_"); break; default: fprintf(out, "%c", *s); } } ++s; } } else { fprintf(out, "null"); } } static void print_game_switch(FILE* out, const struct GameDriver* game) { const struct InputPortTiny* input = game->input_ports; while ((input->type & ~IPF_MASK) != IPT_END) { if ((input->type & ~IPF_MASK)==IPT_DIPSWITCH_NAME) { int def = input->default_value; const char* def_name = 0; fprintf(out, L1P "dipswitch" L2B); fprintf(out, L2P "name " ); print_c_string(out,input->name); fprintf(out, "%s", L2N); ++input; while ((input->type & ~IPF_MASK)==IPT_DIPSWITCH_SETTING) { if (def == input->default_value) def_name = input->name; fprintf(out, L2P "entry " ); print_c_string(out,input->name); fprintf(out, "%s", L2N); ++input; } if (def_name) { fprintf(out, L2P "default "); print_c_string(out,def_name); fprintf(out, "%s", L2N); } fprintf(out, L2E L1N); } else ++input; } } static void print_game_input(FILE* out, const struct GameDriver* game) { const struct InputPortTiny* input = game->input_ports; int nplayer = 0; const char* control = 0; int nbutton = 0; int ncoin = 0; const char* service = 0; const char* tilt = 0; while ((input->type & ~IPF_MASK) != IPT_END) { switch (input->type & IPF_PLAYERMASK) { case IPF_PLAYER1: if (nplayer<1) nplayer = 1; break; case IPF_PLAYER2: if (nplayer<2) nplayer = 2; break; case IPF_PLAYER3: if (nplayer<3) nplayer = 3; break; case IPF_PLAYER4: if (nplayer<4) nplayer = 4; break; } switch (input->type & ~IPF_MASK) { case IPT_JOYSTICK_UP: case IPT_JOYSTICK_DOWN: case IPT_JOYSTICK_LEFT: case IPT_JOYSTICK_RIGHT: if (input->type & IPF_2WAY) control = "joy2way"; else if (input->type & IPF_4WAY) control = "joy4way"; else control = "joy8way"; break; case IPT_JOYSTICKRIGHT_UP: case IPT_JOYSTICKRIGHT_DOWN: case IPT_JOYSTICKRIGHT_LEFT: case IPT_JOYSTICKRIGHT_RIGHT: case IPT_JOYSTICKLEFT_UP: case IPT_JOYSTICKLEFT_DOWN: case IPT_JOYSTICKLEFT_LEFT: case IPT_JOYSTICKLEFT_RIGHT: if (input->type & IPF_2WAY) control = "doublejoy2way"; else if (input->type & IPF_4WAY) control = "doublejoy4way"; else control = "doublejoy8way"; break; case IPT_BUTTON1: if (nbutton<1) nbutton = 1; break; case IPT_BUTTON2: if (nbutton<2) nbutton = 2; break; case IPT_BUTTON3: if (nbutton<3) nbutton = 3; break; case IPT_BUTTON4: if (nbutton<4) nbutton = 4; break; case IPT_BUTTON5: if (nbutton<5) nbutton = 5; break; case IPT_BUTTON6: if (nbutton<6) nbutton = 6; break; case IPT_BUTTON7: if (nbutton<7) nbutton = 7; break; case IPT_BUTTON8: if (nbutton<8) nbutton = 8; break; case IPT_PADDLE: control = "paddle"; break; case IPT_DIAL: control = "dial"; break; case IPT_TRACKBALL_X: case IPT_TRACKBALL_Y: control = "trackball"; break; case IPT_AD_STICK_X: case IPT_AD_STICK_Y: control = "stick"; break; case IPT_COIN1: if (ncoin < 1) ncoin = 1; break; case IPT_COIN2: if (ncoin < 2) ncoin = 2; break; case IPT_COIN3: if (ncoin < 3) ncoin = 3; break; case IPT_COIN4: if (ncoin < 4) ncoin = 4; break; case IPT_SERVICE : service = "yes"; break; case IPT_TILT : tilt = "yes"; break; } ++input; } fprintf(out, L1P "input" L2B); fprintf(out, L2P "players %d" L2N, nplayer ); if (control) fprintf(out, L2P "control %s" L2N, control ); if (nbutton) fprintf(out, L2P "buttons %d" L2N, nbutton ); if (ncoin) fprintf(out, L2P "coins %d" L2N, ncoin ); if (service) fprintf(out, L2P "service %s" L2N, service ); if (tilt) fprintf(out, L2P "tilt %s" L2N, tilt ); fprintf(out, L2E L1N); } static void print_game_rom(FILE* out, const struct GameDriver* game) { const struct RomModule *rom = game->rom, *p_rom = NULL; extern struct GameDriver driver_0; if (!rom) return; if (game->clone_of && game->clone_of != &driver_0) { fprintf(out, L1P "romof %s" L1N, game->clone_of->name); } while (rom->name || rom->offset || rom->length) { int region = rom->crc; rom++; while (rom->length) { char name[100]; int offset, length, crc, in_parent; sprintf(name,rom->name,game->name); offset = rom->offset; crc = rom->crc; in_parent = 0; length = 0; do { if (rom->name == (char *)-1) length = 0; /* restart */ length += rom->length & ~ROMFLAG_MASK; rom++; } while (rom->length && (rom->name == 0 || rom->name == (char *)-1)); if(game->clone_of && crc) { p_rom = game->clone_of->rom; if (p_rom) while( !in_parent && (p_rom->name || p_rom->offset || p_rom->length) ) { p_rom++; while(!in_parent && p_rom->length) { do { if (p_rom->crc == crc) in_parent = 1; else p_rom++; } while (!in_parent && p_rom->length && (p_rom->name == 0 || p_rom->name == (char *)-1)); } } } fprintf(out, L1P "rom" L2B); if (*name) fprintf(out, L2P "name %s" L2N, name); if(in_parent && p_rom && p_rom->name) fprintf(out, L2P "merge %s" L2N, p_rom->name); fprintf(out, L2P "size %d" L2N, length); fprintf(out, L2P "crc %08x" L2N, crc); switch (region & ~REGIONFLAG_MASK) { case REGION_CPU1: fprintf(out, L2P "region cpu1" L2N); break; case REGION_CPU2: fprintf(out, L2P "region cpu2" L2N); break; case REGION_CPU3: fprintf(out, L2P "region cpu3" L2N); break; case REGION_CPU4: fprintf(out, L2P "region cpu4" L2N); break; case REGION_CPU5: fprintf(out, L2P "region cpu5" L2N); break; case REGION_CPU6: fprintf(out, L2P "region cpu6" L2N); break; case REGION_CPU7: fprintf(out, L2P "region cpu7" L2N); break; case REGION_CPU8: fprintf(out, L2P "region cpu8" L2N); break; case REGION_GFX1: fprintf(out, L2P "region gfx1" L2N); break; case REGION_GFX2: fprintf(out, L2P "region gfx2" L2N); break; case REGION_GFX3: fprintf(out, L2P "region gfx3" L2N); break; case REGION_GFX4: fprintf(out, L2P "region gfx4" L2N); break; case REGION_GFX5: fprintf(out, L2P "region gfx5" L2N); break; case REGION_GFX6: fprintf(out, L2P "region gfx6" L2N); break; case REGION_GFX7: fprintf(out, L2P "region gfx7" L2N); break; case REGION_GFX8: fprintf(out, L2P "region gfx8" L2N); break; case REGION_PROMS: fprintf(out, L2P "region proms" L2N); break; case REGION_SOUND1: fprintf(out, L2P "region sound1" L2N); break; case REGION_SOUND2: fprintf(out, L2P "region sound2" L2N); break; case REGION_SOUND3: fprintf(out, L2P "region sound3" L2N); break; case REGION_SOUND4: fprintf(out, L2P "region sound4" L2N); break; case REGION_SOUND5: fprintf(out, L2P "region sound5" L2N); break; case REGION_SOUND6: fprintf(out, L2P "region sound6" L2N); break; case REGION_SOUND7: fprintf(out, L2P "region sound7" L2N); break; case REGION_SOUND8: fprintf(out, L2P "region sound8" L2N); break; case REGION_USER1: fprintf(out, L2P "region user1" L2N); break; case REGION_USER2: fprintf(out, L2P "region user2" L2N); break; case REGION_USER3: fprintf(out, L2P "region user3" L2N); break; case REGION_USER4: fprintf(out, L2P "region user4" L2N); break; case REGION_USER5: fprintf(out, L2P "region user5" L2N); break; case REGION_USER6: fprintf(out, L2P "region user6" L2N); break; case REGION_USER7: fprintf(out, L2P "region user7" L2N); break; case REGION_USER8: fprintf(out, L2P "region user8" L2N); break; default: fprintf(out, L2P "region 0x%x" L2N, region & ~REGIONFLAG_MASK); } switch (region & REGIONFLAG_MASK) { case 0: break; case REGIONFLAG_SOUNDONLY: fprintf(out, L2P "flags soundonly" L2N); break; case REGIONFLAG_DISPOSE: fprintf(out, L2P "flags dispose" L2N); break; default: fprintf(out, L2P "flags 0x%x" L2N, region & REGIONFLAG_MASK); } fprintf(out, L2P "offs %x", offset); fprintf(out, L2E L1N); } } } static void print_game_sample(FILE* out, const struct GameDriver* game) { #if (HAS_SAMPLES) int i; for( i = 0; game->drv->sound[i].sound_type && i < MAX_SOUND; i++ ) { const char **samplenames = NULL; if( game->drv->sound[i].sound_type != SOUND_SAMPLES ) continue; samplenames = ((struct Samplesinterface *)game->drv->sound[i].sound_interface)->samplenames; if (samplenames != 0 && samplenames[0] != 0) { int k = 0; if (samplenames[k][0]=='*') { /* output sampleof only if different from game name */ if (strcmp(samplenames[k] + 1, game->name)!=0) { fprintf(out, L1P "sampleof %s" L1N, samplenames[k] + 1); } ++k; } while (samplenames[k] != 0) { /* Check if is not empty */ if (*samplenames[k]) { /* Check if sample is duplicate */ int l = 0; while (l<k && strcmp(samplenames[k],samplenames[l])!=0) ++l; if (l==k) { fprintf(out, L1P "sample %s" L1N, samplenames[k]); } } ++k; } } } #endif } static void print_game_micro(FILE* out, const struct GameDriver* game) { const struct MachineDriver* driver = game->drv; const struct MachineCPU* cpu = driver->cpu; const struct MachineSound* sound = driver->sound; int j; for(j=0;j<MAX_CPU;++j) { if (cpu[j].cpu_type!=0) { fprintf(out, L1P "chip" L2B); if (cpu[j].cpu_type & CPU_AUDIO_CPU) fprintf(out, L2P "type cpu flags audio" L2N); else fprintf(out, L2P "type cpu" L2N); fprintf(out, L2P "name "); print_statement_string(out, cputype_name(cpu[j].cpu_type)); fprintf(out, "%s", L2N); fprintf(out, L2P "clock %d" L2N, cpu[j].cpu_clock); fprintf(out, L2E L1N); } } for(j=0;j<MAX_SOUND;++j) if (sound[j].sound_type) { if (sound[j].sound_type) { int num = sound_num(&sound[j]); int l; if (num == 0) num = 1; for(l=0;l<num;++l) { fprintf(out, L1P "chip" L2B); fprintf(out, L2P "type audio" L2N); fprintf(out, L2P "name "); print_statement_string(out, sound_name(&sound[j])); fprintf(out, "%s", L2N); if (sound_clock(&sound[j])) fprintf(out, L2P "clock %d" L2N, sound_clock(&sound[j])); fprintf(out, L2E L1N); } } } } static void print_game_video(FILE* out, const struct GameDriver* game) { const struct MachineDriver* driver = game->drv; int dx; int dy; int showxy; int orientation; fprintf(out, L1P "video" L2B); if (driver->video_attributes & VIDEO_TYPE_VECTOR) { fprintf(out, L2P "screen vector" L2N); showxy = 0; } else { fprintf(out, L2P "screen raster" L2N); showxy = 1; } if (game->flags & ORIENTATION_SWAP_XY) { dx = driver->default_visible_area.max_y - driver->default_visible_area.min_y + 1; dy = driver->default_visible_area.max_x - driver->default_visible_area.min_x + 1; orientation = 1; } else { dx = driver->default_visible_area.max_x - driver->default_visible_area.min_x + 1; dy = driver->default_visible_area.max_y - driver->default_visible_area.min_y + 1; orientation = 0; } fprintf(out, L2P "orientation %s" L2N, orientation ? "vertical" : "horizontal" ); if (showxy) { fprintf(out, L2P "x %d" L2N, dx); fprintf(out, L2P "y %d" L2N, dy); } fprintf(out, L2P "colors %d" L2N, driver->total_colors); fprintf(out, L2P "freq %f" L2N, driver->frames_per_second); fprintf(out, L2E L1N); } static void print_game_sound(FILE* out, const struct GameDriver* game) { const struct MachineDriver* driver = game->drv; const struct MachineCPU* cpu = driver->cpu; const struct MachineSound* sound = driver->sound; /* check if the game have sound emulation */ int has_sound = 0; int i; i = 0; while (i < MAX_SOUND && !has_sound) { if (sound[i].sound_type) has_sound = 1; ++i; } i = 0; while (i < MAX_CPU && !has_sound) { if ((cpu[i].cpu_type & CPU_AUDIO_CPU)!=0) has_sound = 1; ++i; } fprintf(out, L1P "sound" L2B); /* sound channel */ if (has_sound) { if (driver->sound_attributes & SOUND_SUPPORTS_STEREO) fprintf(out, L2P "channels 2" L2N); else fprintf(out, L2P "channels 1" L2N); } else fprintf(out, L2P "channels 0" L2N); fprintf(out, L2E L1N); } #define HISTORY_BUFFER_MAX 16384 static void print_game_history(FILE* out, const struct GameDriver* game) { char buffer[HISTORY_BUFFER_MAX]; if (load_driver_history(game,buffer,HISTORY_BUFFER_MAX)==0) { fprintf(out, L1P "history "); print_c_string(out, buffer); fprintf(out, "%s", L1N); } } static void print_game_driver(FILE* out, const struct GameDriver* game) { fprintf(out, L1P "driver" L2B); if (game->flags & GAME_NOT_WORKING) fprintf(out, L2P "status preliminary" L2N); else fprintf(out, L2P "status good" L2N); if (game->flags & GAME_WRONG_COLORS) fprintf(out, L2P "color preliminary" L2N); else if (game->flags & GAME_IMPERFECT_COLORS) fprintf(out, L2P "color imperfect" L2N); else fprintf(out, L2P "color good" L2N); if (game->flags & GAME_NO_SOUND) fprintf(out, L2P "sound preliminary" L2N); else if (game->flags & GAME_IMPERFECT_SOUND) fprintf(out, L2P "sound imperfect" L2N); else fprintf(out, L2P "sound good" L2N); if (game->flags & GAME_REQUIRES_16BIT) fprintf(out, L2P "colordeep 16" L2N); else fprintf(out, L2P "colordeep 8" L2N); fprintf(out, L2E L1N); } /* Print the MAME info record for a game */ static void print_game_info(FILE* out, const struct GameDriver* game) { #ifndef MESS fprintf(out, "game" L1B ); #else fprintf(out, "machine" L1B ); #endif fprintf(out, L1P "name %s" L1N, game->name ); if (game->description) { fprintf(out, L1P "description "); print_c_string(out, game->description ); fprintf(out, "%s", L1N); } /* print the year only if is a number */ if (game->year && strspn(game->year,"0123456789")==strlen(game->year)) { fprintf(out, L1P "year %s" L1N, game->year ); } if (game->manufacturer) { fprintf(out, L1P "manufacturer "); print_c_string(out, game->manufacturer ); fprintf(out, "%s", L1N); } print_game_history(out,game); if (game->clone_of && !(game->clone_of->flags & NOT_A_DRIVER)) { fprintf(out, L1P "cloneof %s" L1N, game->clone_of->name); } print_game_rom(out,game); print_game_sample(out,game); print_game_micro(out,game); print_game_video(out,game); print_game_sound(out,game); print_game_input(out,game); print_game_switch(out,game); print_game_driver(out,game); fprintf(out, L1E); } /* Print all the MAME info database */ void print_mame_info(FILE* out, const struct GameDriver* games[]) { int j; for(j=0;games[j];++j) print_game_info( out, games[j] ); #ifndef MESS /* addictional fixed record */ fprintf(out, "resource" L1B); fprintf(out, L1P "name neogeo" L1N); fprintf(out, L1P "description \"Neo Geo BIOS\"" L1N); fprintf(out, L1P "rom" L2B); fprintf(out, L2P "name neo-geo.rom" L2N); fprintf(out, L2P "size 131072" L2N); fprintf(out, L2P "crc 9036d879" L2N); fprintf(out, L2E L1N); fprintf(out, L1P "rom" L2B); fprintf(out, L2P "name ng-sm1.rom" L2N); fprintf(out, L2P "size 131072" L2N); fprintf(out, L2P "crc 97cf998b" L2N); fprintf(out, L2E L1N); fprintf(out, L1P "rom" L2B); fprintf(out, L2P "name ng-sfix.rom" L2N); fprintf(out, L2P "size 131072" L2N); fprintf(out, L2P "crc 354029fc" L2N); fprintf(out, L2E L1N); fprintf(out, L1E); #endif }
skeezix/compo4all
stevem/mame4all/src/info.cpp
C++
gpl-2.0
18,177
[ 30522, 1001, 2421, 1026, 14931, 18863, 1012, 1044, 1028, 1001, 2421, 1000, 4062, 1012, 1044, 1000, 1001, 2421, 1000, 2614, 1013, 8168, 1012, 1044, 1000, 1001, 2421, 1000, 18558, 1012, 1044, 1000, 1001, 2421, 1000, 2951, 8873, 2571, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace Drupal\Tests\locale\Functional; use Drupal\language\Entity\ConfigurableLanguage; use Drupal\Tests\BrowserTestBase; use Drupal\Tests\RequirementsPageTrait; /** * Adds and configures languages to check field schema definition. * * @group locale */ class LocaleTranslatedSchemaDefinitionTest extends BrowserTestBase { use RequirementsPageTrait; /** * Modules to enable. * * @var array */ public static $modules = ['language', 'locale', 'node']; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); ConfigurableLanguage::createFromLangcode('fr')->save(); $this->config('system.site')->set('default_langcode', 'fr')->save(); // Clear all caches so that the base field definition, its cache in the // entity manager, the t() cache, etc. are all cleared. drupal_flush_all_caches(); } /** * Tests that translated field descriptions do not affect the update system. */ public function testTranslatedSchemaDefinition() { /** @var \Drupal\locale\StringDatabaseStorage $stringStorage */ $stringStorage = \Drupal::service('locale.storage'); $source = $stringStorage->createString([ 'source' => 'Revision ID', ])->save(); $stringStorage->createTranslation([ 'lid' => $source->lid, 'language' => 'fr', 'translation' => 'Translated Revision ID', ])->save(); // Ensure that the field is translated when access through the API. $this->assertEqual('Translated Revision ID', \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('node')['vid']->getLabel()); // Assert there are no updates. $this->assertFalse(\Drupal::service('entity.definition_update_manager')->needsUpdates()); } /** * Tests that translations do not affect the update system. */ public function testTranslatedUpdate() { // Visit the update page to collect any strings that may be translatable. $user = $this->drupalCreateUser(['administer software updates']); $this->drupalLogin($user); $update_url = $GLOBALS['base_url'] . '/update.php'; $this->drupalGet($update_url, ['external' => TRUE]); /** @var \Drupal\locale\StringDatabaseStorage $stringStorage */ $stringStorage = \Drupal::service('locale.storage'); $sources = $stringStorage->getStrings(); // Translate all source strings found. foreach ($sources as $source) { $stringStorage->createTranslation([ 'lid' => $source->lid, 'language' => 'fr', 'translation' => $this->randomMachineName(100), ])->save(); } // Ensure that there are no updates just due to translations. Check for // markup and a link instead of specific text because text may be // translated. $this->drupalGet($update_url . '/selection', ['external' => TRUE]); $this->updateRequirementsProblem(); $this->drupalGet($update_url . '/selection', ['external' => TRUE]); $this->assertRaw('messages--status', 'No pending updates.'); $this->assertNoLinkByHref('fr/update.php/run', 'No link to run updates.'); } }
rsathishkumar/drupal8
core/modules/locale/tests/src/Functional/LocaleTranslatedSchemaDefinitionTest.php
PHP
gpl-2.0
3,095
[ 30522, 1026, 1029, 25718, 3415, 15327, 2852, 6279, 2389, 1032, 5852, 1032, 2334, 2063, 1032, 8360, 1025, 2224, 2852, 6279, 2389, 1032, 2653, 1032, 9178, 1032, 9530, 8873, 27390, 3085, 25023, 6692, 3351, 1025, 2224, 2852, 6279, 2389, 1032, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright (C) 2005-2016 Free Software Foundation, Inc. Contributed by Richard Henderson <rth@redhat.com>. This file is part of the GNU Offloading and Multi Processing Library (libgomp). Libgomp 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 3, or (at your option) any later version. Libgomp 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. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ /* This is the default PTHREADS implementation of the public OpenMP locking primitives. Because OpenMP uses different entry points for normal and recursive locks, and pthreads uses only one entry point, a system may be able to do better and streamline the locking as well as reduce the size of the types exported. */ /* We need UNIX98/XPG5 extensions to get recursive locks. Request XPG6 since Solaris requires this for C99 and later. */ #define _XOPEN_SOURCE 600 #include "libgomp.h" #ifdef HAVE_BROKEN_POSIX_SEMAPHORES void gomp_init_lock_30 (omp_lock_t *lock) { pthread_mutex_init (lock, NULL); } void gomp_destroy_lock_30 (omp_lock_t *lock) { pthread_mutex_destroy (lock); } void gomp_set_lock_30 (omp_lock_t *lock) { pthread_mutex_lock (lock); } void gomp_unset_lock_30 (omp_lock_t *lock) { pthread_mutex_unlock (lock); } int gomp_test_lock_30 (omp_lock_t *lock) { return pthread_mutex_trylock (lock) == 0; } void gomp_init_nest_lock_30 (omp_nest_lock_t *lock) { pthread_mutex_init (&lock->lock, NULL); lock->count = 0; lock->owner = NULL; } void gomp_destroy_nest_lock_30 (omp_nest_lock_t *lock) { pthread_mutex_destroy (&lock->lock); } void gomp_set_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { pthread_mutex_lock (&lock->lock); lock->owner = me; } lock->count++; } void gomp_unset_nest_lock_30 (omp_nest_lock_t *lock) { if (--lock->count == 0) { lock->owner = NULL; pthread_mutex_unlock (&lock->lock); } } int gomp_test_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { if (pthread_mutex_trylock (&lock->lock) != 0) return 0; lock->owner = me; } return ++lock->count; } #else void gomp_init_lock_30 (omp_lock_t *lock) { sem_init (lock, 0, 1); } void gomp_destroy_lock_30 (omp_lock_t *lock) { sem_destroy (lock); } void gomp_set_lock_30 (omp_lock_t *lock) { while (sem_wait (lock) != 0) ; } void gomp_unset_lock_30 (omp_lock_t *lock) { sem_post (lock); } int gomp_test_lock_30 (omp_lock_t *lock) { return sem_trywait (lock) == 0; } void gomp_init_nest_lock_30 (omp_nest_lock_t *lock) { sem_init (&lock->lock, 0, 1); lock->count = 0; lock->owner = NULL; } void gomp_destroy_nest_lock_30 (omp_nest_lock_t *lock) { sem_destroy (&lock->lock); } void gomp_set_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { while (sem_wait (&lock->lock) != 0) ; lock->owner = me; } lock->count++; } void gomp_unset_nest_lock_30 (omp_nest_lock_t *lock) { if (--lock->count == 0) { lock->owner = NULL; sem_post (&lock->lock); } } int gomp_test_nest_lock_30 (omp_nest_lock_t *lock) { void *me = gomp_icv (true); if (lock->owner != me) { if (sem_trywait (&lock->lock) != 0) return 0; lock->owner = me; } return ++lock->count; } #endif #ifdef LIBGOMP_GNU_SYMBOL_VERSIONING void gomp_init_lock_25 (omp_lock_25_t *lock) { pthread_mutex_init (lock, NULL); } void gomp_destroy_lock_25 (omp_lock_25_t *lock) { pthread_mutex_destroy (lock); } void gomp_set_lock_25 (omp_lock_25_t *lock) { pthread_mutex_lock (lock); } void gomp_unset_lock_25 (omp_lock_25_t *lock) { pthread_mutex_unlock (lock); } int gomp_test_lock_25 (omp_lock_25_t *lock) { return pthread_mutex_trylock (lock) == 0; } void gomp_init_nest_lock_25 (omp_nest_lock_25_t *lock) { pthread_mutexattr_t attr; pthread_mutexattr_init (&attr); pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init (&lock->lock, &attr); lock->count = 0; pthread_mutexattr_destroy (&attr); } void gomp_destroy_nest_lock_25 (omp_nest_lock_25_t *lock) { pthread_mutex_destroy (&lock->lock); } void gomp_set_nest_lock_25 (omp_nest_lock_25_t *lock) { pthread_mutex_lock (&lock->lock); lock->count++; } void gomp_unset_nest_lock_25 (omp_nest_lock_25_t *lock) { lock->count--; pthread_mutex_unlock (&lock->lock); } int gomp_test_nest_lock_25 (omp_nest_lock_25_t *lock) { if (pthread_mutex_trylock (&lock->lock) == 0) return ++lock->count; return 0; } omp_lock_symver (omp_init_lock) omp_lock_symver (omp_destroy_lock) omp_lock_symver (omp_set_lock) omp_lock_symver (omp_unset_lock) omp_lock_symver (omp_test_lock) omp_lock_symver (omp_init_nest_lock) omp_lock_symver (omp_destroy_nest_lock) omp_lock_symver (omp_set_nest_lock) omp_lock_symver (omp_unset_nest_lock) omp_lock_symver (omp_test_nest_lock) #else ialias (omp_init_lock) ialias (omp_init_nest_lock) ialias (omp_destroy_lock) ialias (omp_destroy_nest_lock) ialias (omp_set_lock) ialias (omp_set_nest_lock) ialias (omp_unset_lock) ialias (omp_unset_nest_lock) ialias (omp_test_lock) ialias (omp_test_nest_lock) #endif
selmentdev/selment-toolchain
source/gcc-latest/libgomp/config/posix/lock.c
C
gpl-3.0
5,963
[ 30522, 1013, 1008, 9385, 1006, 1039, 1007, 2384, 1011, 2355, 2489, 4007, 3192, 1010, 4297, 1012, 5201, 2011, 2957, 9481, 1026, 19387, 2232, 1030, 2417, 12707, 1012, 4012, 1028, 1012, 2023, 5371, 2003, 2112, 1997, 1996, 27004, 2125, 18570, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * * bttv - Bt848 frame grabber driver * * card ID's and external interfaces of the bttv driver * basically stuff needed by other drivers (i2c, lirc, ...) * and is supported not to change much over time. * * Copyright (C) 1996,97 Ralph Metzler (rjkm@thp.uni-koeln.de) * (c) 1999,2000 Gerd Knorr <kraxel@goldbach.in-berlin.de> * */ #ifndef _BTTV_H_ #define _BTTV_H_ #include <linux/videodev.h> #include <linux/i2c.h> #include <media/ir-common.h> #include <media/ir-kbd-i2c.h> #include <media/i2c-addr.h> /* ---------------------------------------------------------- */ /* exported by bttv-cards.c */ #define BTTV_BOARD_UNKNOWN 0x00 #define BTTV_BOARD_MIRO 0x01 #define BTTV_BOARD_HAUPPAUGE 0x02 #define BTTV_BOARD_STB 0x03 #define BTTV_BOARD_INTEL 0x04 #define BTTV_BOARD_DIAMOND 0x05 #define BTTV_BOARD_AVERMEDIA 0x06 #define BTTV_BOARD_MATRIX_VISION 0x07 #define BTTV_BOARD_FLYVIDEO 0x08 #define BTTV_BOARD_TURBOTV 0x09 #define BTTV_BOARD_HAUPPAUGE878 0x0a #define BTTV_BOARD_MIROPRO 0x0b #define BTTV_BOARD_ADSTECH_TV 0x0c #define BTTV_BOARD_AVERMEDIA98 0x0d #define BTTV_BOARD_VHX 0x0e #define BTTV_BOARD_ZOLTRIX 0x0f #define BTTV_BOARD_PIXVIEWPLAYTV 0x10 #define BTTV_BOARD_WINVIEW_601 0x11 #define BTTV_BOARD_AVEC_INTERCAP 0x12 #define BTTV_BOARD_LIFE_FLYKIT 0x13 #define BTTV_BOARD_CEI_RAFFLES 0x14 #define BTTV_BOARD_CONFERENCETV 0x15 #define BTTV_BOARD_PHOEBE_TVMAS 0x16 #define BTTV_BOARD_MODTEC_205 0x17 #define BTTV_BOARD_MAGICTVIEW061 0x18 #define BTTV_BOARD_VOBIS_BOOSTAR 0x19 #define BTTV_BOARD_HAUPPAUG_WCAM 0x1a #define BTTV_BOARD_MAXI 0x1b #define BTTV_BOARD_TERRATV 0x1c #define BTTV_BOARD_PXC200 0x1d #define BTTV_BOARD_FLYVIDEO_98 0x1e #define BTTV_BOARD_IPROTV 0x1f #define BTTV_BOARD_INTEL_C_S_PCI 0x20 #define BTTV_BOARD_TERRATVALUE 0x21 #define BTTV_BOARD_WINFAST2000 0x22 #define BTTV_BOARD_CHRONOS_VS2 0x23 #define BTTV_BOARD_TYPHOON_TVIEW 0x24 #define BTTV_BOARD_PXELVWPLTVPRO 0x25 #define BTTV_BOARD_MAGICTVIEW063 0x26 #define BTTV_BOARD_PINNACLE 0x27 #define BTTV_BOARD_STB2 0x28 #define BTTV_BOARD_AVPHONE98 0x29 #define BTTV_BOARD_PV951 0x2a #define BTTV_BOARD_ONAIR_TV 0x2b #define BTTV_BOARD_SIGMA_TVII_FM 0x2c #define BTTV_BOARD_MATRIX_VISION2 0x2d #define BTTV_BOARD_ZOLTRIX_GENIE 0x2e #define BTTV_BOARD_TERRATVRADIO 0x2f #define BTTV_BOARD_DYNALINK 0x30 #define BTTV_BOARD_GVBCTV3PCI 0x31 #define BTTV_BOARD_PXELVWPLTVPAK 0x32 #define BTTV_BOARD_EAGLE 0x33 #define BTTV_BOARD_PINNACLEPRO 0x34 #define BTTV_BOARD_TVIEW_RDS_FM 0x35 #define BTTV_BOARD_LIFETEC_9415 0x36 #define BTTV_BOARD_BESTBUY_EASYTV 0x37 #define BTTV_BOARD_FLYVIDEO_98FM 0x38 #define BTTV_BOARD_GRANDTEC 0x39 #define BTTV_BOARD_ASKEY_CPH060 0x3a #define BTTV_BOARD_ASKEY_CPH03X 0x3b #define BTTV_BOARD_MM100PCTV 0x3c #define BTTV_BOARD_GMV1 0x3d #define BTTV_BOARD_BESTBUY_EASYTV2 0x3e #define BTTV_BOARD_ATI_TVWONDER 0x3f #define BTTV_BOARD_ATI_TVWONDERVE 0x40 #define BTTV_BOARD_FLYVIDEO2000 0x41 #define BTTV_BOARD_TERRATVALUER 0x42 #define BTTV_BOARD_GVBCTV4PCI 0x43 #define BTTV_BOARD_VOODOOTV_FM 0x44 #define BTTV_BOARD_AIMMS 0x45 #define BTTV_BOARD_PV_BT878P_PLUS 0x46 #define BTTV_BOARD_FLYVIDEO98EZ 0x47 #define BTTV_BOARD_PV_BT878P_9B 0x48 #define BTTV_BOARD_SENSORAY311 0x49 #define BTTV_BOARD_RV605 0x4a #define BTTV_BOARD_POWERCLR_MTV878 0x4b #define BTTV_BOARD_WINDVR 0x4c #define BTTV_BOARD_GRANDTEC_MULTI 0x4d #define BTTV_BOARD_KWORLD 0x4e #define BTTV_BOARD_DSP_TCVIDEO 0x4f #define BTTV_BOARD_HAUPPAUGEPVR 0x50 #define BTTV_BOARD_GVBCTV5PCI 0x51 #define BTTV_BOARD_OSPREY1x0 0x52 #define BTTV_BOARD_OSPREY1x0_848 0x53 #define BTTV_BOARD_OSPREY101_848 0x54 #define BTTV_BOARD_OSPREY1x1 0x55 #define BTTV_BOARD_OSPREY1x1_SVID 0x56 #define BTTV_BOARD_OSPREY2xx 0x57 #define BTTV_BOARD_OSPREY2x0_SVID 0x58 #define BTTV_BOARD_OSPREY2x0 0x59 #define BTTV_BOARD_OSPREY500 0x5a #define BTTV_BOARD_OSPREY540 0x5b #define BTTV_BOARD_OSPREY2000 0x5c #define BTTV_BOARD_IDS_EAGLE 0x5d #define BTTV_BOARD_PINNACLESAT 0x5e #define BTTV_BOARD_FORMAC_PROTV 0x5f #define BTTV_BOARD_MACHTV 0x60 #define BTTV_BOARD_EURESYS_PICOLO 0x61 #define BTTV_BOARD_PV150 0x62 #define BTTV_BOARD_AD_TVK503 0x63 #define BTTV_BOARD_HERCULES_SM_TV 0x64 #define BTTV_BOARD_PACETV 0x65 #define BTTV_BOARD_IVC200 0x66 #define BTTV_BOARD_XGUARD 0x67 #define BTTV_BOARD_NEBULA_DIGITV 0x68 #define BTTV_BOARD_PV143 0x69 #define BTTV_BOARD_VD009X1_MINIDIN 0x6a #define BTTV_BOARD_VD009X1_COMBI 0x6b #define BTTV_BOARD_VD009_MINIDIN 0x6c #define BTTV_BOARD_VD009_COMBI 0x6d #define BTTV_BOARD_IVC100 0x6e #define BTTV_BOARD_IVC120 0x6f #define BTTV_BOARD_PC_HDTV 0x70 #define BTTV_BOARD_TWINHAN_DST 0x71 #define BTTV_BOARD_WINFASTVC100 0x72 #define BTTV_BOARD_TEV560 0x73 #define BTTV_BOARD_SIMUS_GVC1100 0x74 #define BTTV_BOARD_NGSTV_PLUS 0x75 #define BTTV_BOARD_LMLBT4 0x76 #define BTTV_BOARD_TEKRAM_M205 0x77 #define BTTV_BOARD_CONTVFMI 0x78 #define BTTV_BOARD_PICOLO_TETRA_CHIP 0x79 #define BTTV_BOARD_SPIRIT_TV 0x7a #define BTTV_BOARD_AVDVBT_771 0x7b #define BTTV_BOARD_AVDVBT_761 0x7c #define BTTV_BOARD_MATRIX_VISIONSQ 0x7d #define BTTV_BOARD_MATRIX_VISIONSLC 0x7e #define BTTV_BOARD_APAC_VIEWCOMP 0x7f #define BTTV_BOARD_DVICO_DVBT_LITE 0x80 #define BTTV_BOARD_VGEAR_MYVCD 0x81 #define BTTV_BOARD_SUPER_TV 0x82 #define BTTV_BOARD_TIBET_CS16 0x83 #define BTTV_BOARD_KODICOM_4400R 0x84 #define BTTV_BOARD_KODICOM_4400R_SL 0x85 #define BTTV_BOARD_ADLINK_RTV24 0x86 #define BTTV_BOARD_DVICO_FUSIONHDTV_5_LITE 0x87 #define BTTV_BOARD_ACORP_Y878F 0x88 #define BTTV_BOARD_CONCEPTRONIC_CTVFMI2 0x89 #define BTTV_BOARD_PV_BT878P_2E 0x8a #define BTTV_BOARD_PV_M4900 0x8b #define BTTV_BOARD_OSPREY440 0x8c #define BTTV_BOARD_ASOUND_SKYEYE 0x8d #define BTTV_BOARD_SABRENT_TVFM 0x8e #define BTTV_BOARD_HAUPPAUGE_IMPACTVCB 0x8f #define BTTV_BOARD_MACHTV_MAGICTV 0x90 /* more card-specific defines */ #define PT2254_L_CHANNEL 0x10 #define PT2254_R_CHANNEL 0x08 #define PT2254_DBS_IN_2 0x400 #define PT2254_DBS_IN_10 0x20000 #define WINVIEW_PT2254_CLK 0x40 #define WINVIEW_PT2254_DATA 0x20 #define WINVIEW_PT2254_STROBE 0x80 /* digital_mode */ #define DIGITAL_MODE_VIDEO 1 #define DIGITAL_MODE_CAMERA 2 struct bttv_core { /* device structs */ struct pci_dev *pci; struct i2c_adapter i2c_adap; struct list_head subs; /* struct bttv_sub_device */ /* device config */ unsigned int nr; /* dev nr (for printk("bttv%d: ..."); */ unsigned int type; /* card type (pointer into tvcards[]) */ char name[8]; /* dev name */ }; struct bttv; struct bttv_ir { struct input_dev *dev; struct ir_input_state ir; char name[32]; char phys[32]; /* Usual gpio signalling */ u32 mask_keycode; u32 mask_keydown; u32 mask_keyup; u32 polling; u32 last_gpio; struct work_struct work; struct timer_list timer; /* RC5 gpio */ u32 rc5_gpio; struct timer_list timer_end; /* timer_end for code completion */ struct timer_list timer_keyup; /* timer_end for key release */ u32 last_rc5; /* last good rc5 code */ u32 last_bit; /* last raw bit seen */ u32 code; /* raw code under construction */ struct timeval base_time; /* time of last seen code */ int active; /* building raw code */ }; struct tvcard { char *name; unsigned int video_inputs; unsigned int audio_inputs; unsigned int tuner; unsigned int svhs; unsigned int digital_mode; // DIGITAL_MODE_CAMERA or DIGITAL_MODE_VIDEO u32 gpiomask; u32 muxsel[16]; u32 gpiomux[4]; /* Tuner, Radio, external, internal */ u32 gpiomute; /* GPIO mute setting */ u32 gpiomask2; /* GPIO MUX mask */ /* i2c audio flags */ unsigned int no_msp34xx:1; unsigned int no_tda9875:1; unsigned int no_tda7432:1; unsigned int needs_tvaudio:1; unsigned int msp34xx_alt:1; /* flag: video pci function is unused */ unsigned int no_video:1; unsigned int has_dvb:1; unsigned int has_remote:1; unsigned int no_gpioirq:1; /* other settings */ unsigned int pll; #define PLL_NONE 0 #define PLL_28 1 #define PLL_35 2 unsigned int tuner_type; unsigned int tuner_addr; unsigned int radio_addr; unsigned int has_radio; void (*audio_hook)(struct bttv *btv, struct video_audio *v, int set); void (*muxsel_hook)(struct bttv *btv, unsigned int input); }; extern struct tvcard bttv_tvcards[]; /* identification / initialization of the card */ extern void bttv_idcard(struct bttv *btv); extern void bttv_init_card1(struct bttv *btv); extern void bttv_init_card2(struct bttv *btv); /* card-specific funtions */ extern void tea5757_set_freq(struct bttv *btv, unsigned short freq); extern void bttv_tda9880_setnorm(struct bttv *btv, int norm); /* extra tweaks for some chipsets */ extern void bttv_check_chipset(void); extern int bttv_handle_chipset(struct bttv *btv); /* ---------------------------------------------------------- */ /* exported by bttv-if.c */ /* this obsolete -- please use the sysfs-based interface below for new code */ /* returns card type + card ID (for bt878-based ones) for possible values see lines below beginning with #define BTTV_BOARD_UNKNOWN returns negative value if error occurred */ extern int bttv_get_cardinfo(unsigned int card, int *type, unsigned int *cardid); extern struct pci_dev* bttv_get_pcidev(unsigned int card); /* obsolete, use bttv_get_cardinfo instead */ extern int bttv_get_id(unsigned int card); /* sets GPOE register (BT848_GPIO_OUT_EN) to new value: data | (current_GPOE_value & ~mask) returns negative value if error occurred */ extern int bttv_gpio_enable(unsigned int card, unsigned long mask, unsigned long data); /* fills data with GPDATA register contents returns negative value if error occurred */ extern int bttv_read_gpio(unsigned int card, unsigned long *data); /* sets GPDATA register to new value: (data & mask) | (current_GPDATA_value & ~mask) returns negative value if error occurred */ extern int bttv_write_gpio(unsigned int card, unsigned long mask, unsigned long data); /* returns pointer to task queue which can be used as parameter to interruptible_sleep_on in interrupt handler if BT848_INT_GPINT bit is set - this queue is activated (wake_up_interruptible) and following call to the function bttv_read_gpio should return new value of GPDATA, returns NULL value if error occurred or queue is not available WARNING: because there is no buffer for GPIO data, one MUST process data ASAP */ extern wait_queue_head_t* bttv_get_gpio_queue(unsigned int card); /* call i2c clients */ extern void bttv_i2c_call(unsigned int card, unsigned int cmd, void *arg); /* ---------------------------------------------------------- */ /* sysfs/driver-moded based gpio access interface */ struct bttv_sub_device { struct device dev; struct bttv_core *core; struct list_head list; }; #define to_bttv_sub_dev(x) container_of((x), struct bttv_sub_device, dev) struct bttv_sub_driver { struct device_driver drv; char wanted[BUS_ID_SIZE]; int (*probe)(struct bttv_sub_device *sub); void (*remove)(struct bttv_sub_device *sub); void (*gpio_irq)(struct bttv_sub_device *sub); }; #define to_bttv_sub_drv(x) container_of((x), struct bttv_sub_driver, drv) int bttv_sub_register(struct bttv_sub_driver *drv, char *wanted); int bttv_sub_unregister(struct bttv_sub_driver *drv); /* gpio access functions */ void bttv_gpio_inout(struct bttv_core *core, u32 mask, u32 outbits); u32 bttv_gpio_read(struct bttv_core *core); void bttv_gpio_write(struct bttv_core *core, u32 value); void bttv_gpio_bits(struct bttv_core *core, u32 mask, u32 bits); #define gpio_inout(mask,bits) bttv_gpio_inout(&btv->c, mask, bits) #define gpio_read() bttv_gpio_read(&btv->c) #define gpio_write(value) bttv_gpio_write(&btv->c, value) #define gpio_bits(mask,bits) bttv_gpio_bits(&btv->c, mask, bits) /* ---------------------------------------------------------- */ /* i2c */ extern void bttv_call_i2c_clients(struct bttv *btv, unsigned int cmd, void *arg); extern int bttv_I2CRead(struct bttv *btv, unsigned char addr, char *probe_for); extern int bttv_I2CWrite(struct bttv *btv, unsigned char addr, unsigned char b1, unsigned char b2, int both); extern void bttv_readee(struct bttv *btv, unsigned char *eedata, int addr); extern int bttv_input_init(struct bttv *dev); extern void bttv_input_fini(struct bttv *dev); extern void bttv_input_irq(struct bttv *dev); #endif /* _BTTV_H_ */ /* * Local variables: * c-basic-offset: 8 * End: */
zrafa/linuxkernel
linux-2.6.17.new/drivers/media/video/bt8xx/bttv.h
C
gpl-2.0
14,583
[ 30522, 1013, 1008, 1008, 1008, 18411, 9189, 1011, 18411, 2620, 18139, 4853, 6723, 5677, 4062, 1008, 1008, 4003, 8909, 1005, 1055, 1998, 6327, 19706, 1997, 1996, 18411, 9189, 4062, 1008, 10468, 4933, 2734, 2011, 2060, 6853, 30524, 1030, 1621...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.istic.synthlab.core.modules.whitenoise; import org.istic.synthlab.components.IComponent; import org.istic.synthlab.core.modules.io.IOutput; import org.istic.synthlab.core.services.Factory; import org.istic.synthlab.core.services.Register; public class WhiteNoise implements IWhiteNoise { private com.jsyn.unitgen.WhiteNoise whiteNoise; private IOutput output; public WhiteNoise(IComponent component) { super(); whiteNoise = new com.jsyn.unitgen.WhiteNoise(); Register.declare(component, whiteNoise); whiteNoise.output.setName("noise_output"); output = Factory.createOutput("Out", component, this.whiteNoise.output); } @Override public IOutput getOutput() { return this.output; } public void activate() { whiteNoise.setEnabled(true); } public void deactivate() { whiteNoise.setEnabled(false); } public boolean isActivated() { return whiteNoise.isEnabled(); } }
StephaneMangin/Synth
src/main/java/org/istic/synthlab/core/modules/whitenoise/WhiteNoise.java
Java
gpl-3.0
1,003
[ 30522, 7427, 8917, 1012, 21541, 2594, 1012, 24203, 20470, 1012, 4563, 1012, 14184, 1012, 2317, 3630, 5562, 1025, 12324, 8917, 1012, 21541, 2594, 1012, 24203, 20470, 1012, 6177, 1012, 24582, 25377, 5643, 3372, 1025, 12324, 8917, 1012, 21541, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Template Source: BaseEntityCollectionRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.Site; import com.microsoft.graph.models.ItemActivityStat; import com.microsoft.graph.models.ContentType; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.options.QueryOption; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseEntityCollectionRequest; import com.microsoft.graph.requests.SiteCollectionResponse; import com.microsoft.graph.requests.SiteCollectionRequestBuilder; import com.microsoft.graph.requests.SiteCollectionRequest; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Site Collection Request. */ public class SiteCollectionRequest extends BaseEntityCollectionRequest<Site, SiteCollectionResponse, SiteCollectionPage> { /** * The request builder for this collection of Site * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public SiteCollectionRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, SiteCollectionResponse.class, SiteCollectionPage.class, SiteCollectionRequestBuilder.class); } /** * Creates a new Site * @param newSite the Site to create * @return a future with the created object */ @Nonnull public java.util.concurrent.CompletableFuture<Site> postAsync(@Nonnull final Site newSite) { final String requestUrl = getBaseRequest().getRequestUrl().toString(); return new SiteRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null) .buildRequest(getBaseRequest().getHeaders()) .postAsync(newSite); } /** * Creates a new Site * @param newSite the Site to create * @return the newly created object */ @Nonnull public Site post(@Nonnull final Site newSite) throws ClientException { final String requestUrl = getBaseRequest().getRequestUrl().toString(); return new SiteRequestBuilder(requestUrl, getBaseRequest().getClient(), /* Options */ null) .buildRequest(getBaseRequest().getHeaders()) .post(newSite); } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public SiteCollectionRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } /** * Sets the filter clause for the request * * @param value the filter clause * @return the updated request */ @Nonnull public SiteCollectionRequest filter(@Nonnull final String value) { addFilterOption(value); return this; } /** * Sets the order by clause for the request * * @param value the order by clause * @return the updated request */ @Nonnull public SiteCollectionRequest orderBy(@Nonnull final String value) { addOrderByOption(value); return this; } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public SiteCollectionRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the top value for the request * * @param value the max number of items to return * @return the updated request */ @Nonnull public SiteCollectionRequest top(final int value) { addTopOption(value); return this; } /** * Sets the count value for the request * * @param value whether or not to return the count of objects with the request * @return the updated request */ @Nonnull public SiteCollectionRequest count(final boolean value) { addCountOption(value); return this; } /** * Sets the count value to true for the request * * @return the updated request */ @Nonnull public SiteCollectionRequest count() { addCountOption(true); return this; } /** * Sets the skip value for the request * * @param value of the number of items to skip * @return the updated request */ @Nonnull public SiteCollectionRequest skip(final int value) { addSkipOption(value); return this; } /** * Add Skip token for pagination * @param skipToken - Token for pagination * @return the updated request */ @Nonnull public SiteCollectionRequest skipToken(@Nonnull final String skipToken) { addSkipTokenOption(skipToken); return this; } }
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/SiteCollectionRequest.java
Java
mit
5,493
[ 30522, 1013, 1013, 23561, 3120, 1024, 2918, 4765, 3012, 26895, 18491, 2890, 15500, 1012, 9262, 1012, 23746, 1013, 1013, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * The DOM Element unit handling * * Copyright (C) 2008-2011 Nikolay Nemshilov */ var Element = RightJS.Element = new Class(Wrapper, { /** * constructor * * NOTE: this constructor will dynamically typecast * the wrappers depending on the element tag-name * * @param String element tag name or an HTMLElement instance * @param Object options * @return Element element */ initialize: function(element, options) { Element_initialize(this, element, options); } }, Element_Klass), Element_wrappers = Element.Wrappers = {}, elements_cache = {}, /** * bulds dom-elements * * @param String element tag name * @param Object options * @return HTMLElement */ make_element = function (tag, options) { return (tag in elements_cache ? elements_cache[tag] : ( elements_cache[tag] = document.createElement(tag) )).cloneNode(false); }; // // IE 6,7,8 (not 9!) browsers have a bug with checkbox and radio input elements // it doesn't place the 'checked' property correctly, plus there are some issues // with clonned SELECT objects, so we are replaceing the elements maker in here // if (IE8_OR_LESS) { make_element = function(tag, options) { if (options !== undefined && (tag === 'input' || tag === 'button')) { tag = '<'+ tag +' name="'+ options.name + '" type="'+ options.type +'"'+ (options.checked ? ' checked' : '') + ' />'; delete(options.name); delete(options.type); } return document.createElement(tag); }; } /** * Basic element's constructor * * @param Element wrapper instance * @param mixed raw dom element of a string tag name * @param Object options * @return void */ function Element_initialize(inst, element, options) { if (typeof element === 'string') { inst._ = make_element(element, options); if (options !== undefined) { for (var key in options) { switch (key) { case 'id': inst._.id = options[key]; break; case 'html': inst._.innerHTML = options[key]; break; case 'class': inst._.className = options[key]; break; case 'on': inst.on(options[key]); break; default: inst.set(key, options[key]); } } } } else { inst._ = element; } }
rightjs/rightjs-core
src/dom/element.js
JavaScript
mit
2,291
[ 30522, 1013, 1008, 1008, 1008, 1996, 14383, 5783, 3131, 8304, 1008, 1008, 9385, 1006, 1039, 1007, 2263, 1011, 2249, 28494, 11265, 5244, 19466, 4492, 1008, 1013, 13075, 5783, 1027, 2157, 22578, 1012, 5783, 1027, 2047, 2465, 1006, 10236, 4842...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright (c) 2012- PPSSPP Project. // 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, version 2.0 or later versions. // 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 2.0 for more details. // A copy of the GPL 2.0 should have been included with the program. // If not, see http://www.gnu.org/licenses/ // Official git repository and contact information can be found at // https://github.com/hrydgard/ppsspp and http://www.ppsspp.org/. #include "Core/MIPS/MIPS.h" #include "Core/MIPS/MIPSTables.h" #include "Core/MIPS/MIPSAnalyst.h" #include "Core/MIPS/x86/Jit.h" #include "Core/MIPS/x86/Asm.h" #include "Core/MIPS/x86/RegCache.h" using namespace Gen; static const int allocationOrder[] = { // R12, when used as base register, for example in a LEA, can generate bad code! Need to look into this. #ifdef _M_X64 #ifdef _WIN32 RSI, RDI, R13, R14, R8, R9, R10, R11, R12, //, RCX #else RBP, R13, R14, R8, R9, R10, R11, R12, //, RCX #endif #elif _M_IX86 ESI, EDI, EBP, EDX, ECX, // Let's try to free up EBX as well. #endif }; GPRRegCache::GPRRegCache() : emit(0), mips(0) { memset(regs, 0, sizeof(regs)); memset(xregs, 0, sizeof(xregs)); } void GPRRegCache::Start(MIPSState *mips, MIPSAnalyst::AnalysisResults &stats) { this->mips = mips; for (int i = 0; i < NUM_X_REGS; i++) { xregs[i].free = true; xregs[i].dirty = false; xregs[i].allocLocked = false; } for (int i = 0; i < NUM_MIPS_GPRS; i++) { regs[i].location = GetDefaultLocation(i); regs[i].away = false; regs[i].locked = false; } // todo: sort to find the most popular regs /* int maxPreload = 2; for (int i = 0; i < NUM_MIPS_GPRS; i++) { if (stats.numReads[i] > 2 || stats.numWrites[i] >= 2) { LoadToX64(i, true, false); //stats.firstRead[i] <= stats.firstWrite[i], false); maxPreload--; if (!maxPreload) break; } }*/ //Find top regs - preload them (load bursts ain't bad) //But only preload IF written OR reads >= 3 } // these are MIPS reg indices void GPRRegCache::Lock(int p1, int p2, int p3, int p4) { regs[p1].locked = true; if (p2 != 0xFF) regs[p2].locked = true; if (p3 != 0xFF) regs[p3].locked = true; if (p4 != 0xFF) regs[p4].locked = true; } // these are x64 reg indices void GPRRegCache::LockX(int x1, int x2, int x3, int x4) { if (xregs[x1].allocLocked) { PanicAlert("RegCache: x %i already locked!", x1); } xregs[x1].allocLocked = true; if (x2 != 0xFF) xregs[x2].allocLocked = true; if (x3 != 0xFF) xregs[x3].allocLocked = true; if (x4 != 0xFF) xregs[x4].allocLocked = true; } void GPRRegCache::UnlockAll() { for (int i = 0; i < NUM_MIPS_GPRS; i++) regs[i].locked = false; } void GPRRegCache::UnlockAllX() { for (int i = 0; i < NUM_X_REGS; i++) xregs[i].allocLocked = false; } X64Reg GPRRegCache::GetFreeXReg() { int aCount; const int *aOrder = GetAllocationOrder(aCount); for (int i = 0; i < aCount; i++) { X64Reg xr = (X64Reg)aOrder[i]; if (!xregs[xr].allocLocked && xregs[xr].free) { return (X64Reg)xr; } } //Okay, not found :( Force grab one //TODO - add a pass to grab xregs whose mipsreg is not used in the next 3 instructions for (int i = 0; i < aCount; i++) { X64Reg xr = (X64Reg)aOrder[i]; if (xregs[xr].allocLocked) continue; int preg = xregs[xr].mipsReg; if (!regs[preg].locked) { StoreFromRegister(preg); return xr; } } //Still no dice? Die! _assert_msg_(DYNA_REC, 0, "Regcache ran out of regs"); return (X64Reg) -1; } void GPRRegCache::FlushR(X64Reg reg) { if (reg >= NUM_X_REGS) PanicAlert("Flushing non existent reg"); if (!xregs[reg].free) StoreFromRegister(xregs[reg].mipsReg); } int GPRRegCache::SanityCheck() const { for (int i = 0; i < NUM_MIPS_GPRS; i++) { if (regs[i].away) { if (regs[i].location.IsSimpleReg()) { Gen::X64Reg simple = regs[i].location.GetSimpleReg(); if (xregs[simple].allocLocked) return 1; if (xregs[simple].mipsReg != i) return 2; } else if (regs[i].location.IsImm()) return 3; } } return 0; } void GPRRegCache::DiscardRegContentsIfCached(int preg) { if (regs[preg].away && regs[preg].location.IsSimpleReg()) { X64Reg xr = regs[preg].location.GetSimpleReg(); xregs[xr].free = true; xregs[xr].dirty = false; xregs[xr].mipsReg = -1; regs[preg].away = false; regs[preg].location = GetDefaultLocation(preg); } } void GPRRegCache::SetImmediate32(int preg, u32 immValue) { // ZERO is always zero. Let's just make sure. if (preg == 0) immValue = 0; DiscardRegContentsIfCached(preg); regs[preg].away = true; regs[preg].location = Imm32(immValue); } bool GPRRegCache::IsImmediate(int preg) const { // Always say yes for ZERO, even if it's in a temp reg. if (preg == 0) return true; return regs[preg].location.IsImm(); } u32 GPRRegCache::GetImmediate32(int preg) const { _dbg_assert_msg_(JIT, IsImmediate(preg), "Reg %d must be an immediate.", preg); // Always 0 for ZERO. if (preg == 0) return 0; return regs[preg].location.GetImmValue(); } const int *GPRRegCache::GetAllocationOrder(int &count) { count = sizeof(allocationOrder) / sizeof(const int); return allocationOrder; } OpArg GPRRegCache::GetDefaultLocation(int reg) const { return M(&mips->r[reg]); } void GPRRegCache::KillImmediate(int preg, bool doLoad, bool makeDirty) { if (regs[preg].away) { if (regs[preg].location.IsImm()) BindToRegister(preg, doLoad, makeDirty); else if (regs[preg].location.IsSimpleReg()) xregs[RX(preg)].dirty |= makeDirty; } } void GPRRegCache::BindToRegister(int i, bool doLoad, bool makeDirty) { if (!regs[i].away && regs[i].location.IsImm()) PanicAlert("Bad immediate"); if (!regs[i].away || (regs[i].away && regs[i].location.IsImm())) { X64Reg xr = GetFreeXReg(); if (xregs[xr].dirty) PanicAlert("Xreg already dirty"); if (xregs[xr].allocLocked) PanicAlert("GetFreeXReg returned locked register"); xregs[xr].free = false; xregs[xr].mipsReg = i; xregs[xr].dirty = makeDirty || regs[i].location.IsImm(); OpArg newloc = ::Gen::R(xr); if (doLoad) { // Force ZERO to be 0. if (i == 0) emit->MOV(32, newloc, Imm32(0)); else emit->MOV(32, newloc, regs[i].location); } for (int j = 0; j < 32; j++) { if (i != j && regs[j].location.IsSimpleReg() && regs[j].location.GetSimpleReg() == xr) { ERROR_LOG(JIT, "BindToRegister: Strange condition"); Crash(); } } regs[i].away = true; regs[i].location = newloc; } else { // reg location must be simplereg; memory locations // and immediates are taken care of above. xregs[RX(i)].dirty |= makeDirty; } if (xregs[RX(i)].allocLocked) { PanicAlert("Seriously WTF, this reg should have been flushed"); } } void GPRRegCache::StoreFromRegister(int i) { if (regs[i].away) { bool doStore; if (regs[i].location.IsSimpleReg()) { X64Reg xr = RX(i); xregs[xr].free = true; xregs[xr].mipsReg = -1; doStore = xregs[xr].dirty; xregs[xr].dirty = false; } else { //must be immediate - do nothing doStore = true; } OpArg newLoc = GetDefaultLocation(i); // But never store to ZERO. if (doStore && i != 0) emit->MOV(32, newLoc, regs[i].location); regs[i].location = newLoc; regs[i].away = false; } } void GPRRegCache::Flush() { for (int i = 0; i < NUM_X_REGS; i++) { if (xregs[i].allocLocked) PanicAlert("Someone forgot to unlock X64 reg %i.", i); } for (int i = 0; i < NUM_MIPS_GPRS; i++) { if (regs[i].locked) { PanicAlert("Somebody forgot to unlock MIPS reg %i.", i); } if (regs[i].away) { if (regs[i].location.IsSimpleReg()) { X64Reg xr = RX(i); StoreFromRegister(i); xregs[xr].dirty = false; } else if (regs[i].location.IsImm()) { StoreFromRegister(i); } else { _assert_msg_(DYNA_REC,0,"Jit64 - Flush unhandled case, reg %i PC: %08x", i, mips->pc); } } } }
glaubitz/ppsspp-debian
Core/MIPS/x86/RegCache.cpp
C++
gpl-2.0
8,092
[ 30522, 1013, 1013, 9385, 1006, 1039, 1007, 2262, 1011, 4903, 4757, 9397, 2622, 1012, 1013, 1013, 2023, 2565, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, 1013, 1013, 2009, 2104, 1996, 34...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
{% extends "kpi/base_kpi.html" %} {% block title %} Example of KPI report {% endblock %} {% block scripts %} <script type="text/javascript"> 'use strict'; $(document).ready(function () { var month_ago = Math.round(Date.now() / 1000) - 60 * 60 * 24 * 30; goal_position_in_top("kpi_container_position", {release: "icehouse", metric: "commits", module: "openstack"}, "companies", "Mirantis", 5, "Be in top 5 by commits"); goal_position_in_top("kpi_container_position", {release: "icehouse", metric: "marks", module: "openstack"}, "engineers", "boris-42", 5, "Be in top 5 by reviews"); goal_position_in_top("kpi_container_position", {release: "icehouse", metric: "marks", module: "glance"}, "engineers", "boris-42", 3, "Be in top 3 among reviewers"); goal_percentage_in_top_less_than("kpi_container_percentage", {release: "all", metric: "commits", project_type: "all", module: "stackalytics"}, "companies", "Mirantis", 0.8, "Mirantis contribution to Stackalytics is less than 80%"); goal_metric("kpi_container_position", {release: "icehouse", metric: "bpd", module: "glance"}, "modules", "glance", 50, "File at least 50 blueprints into Glance"); goal_metric("kpi_container_position", {release: "all", metric: "bpd", module: "glance", start_date: month_ago}, "modules", "glance", 20, "File at least 20 blueprints into Glance in last month"); goal_disagreement_ratio_less_than("kpi_container_percentage", {release: "all", metric: "marks", project_type: "all", module: "glance"}, "lzy-dev", 0.08, "Disagreement ratio should be less than 8%"); goal_core_engineer_in_project("kpi_core_status", "lzy-dev", "glance", "Become core engineer in Glance"); }); </script> {% endblock %} {% block content %} <h1>Example of KPI report</h1> <h2>Position in top</h2> <div id="kpi_container_position"></div> <h2>Percentage in top</h2> <div id="kpi_container_percentage"></div> <h2>Core status</h2> <div id="kpi_core_status"></div> {% endblock %}
ogazitt/stackalytics
dashboard/templates/kpi/example.html
HTML
apache-2.0
2,291
[ 30522, 1063, 1003, 8908, 1000, 1047, 8197, 1013, 2918, 1035, 1047, 8197, 1012, 16129, 1000, 1003, 1065, 1063, 1003, 3796, 2516, 1003, 1065, 2742, 1997, 1047, 8197, 3189, 1063, 1003, 2203, 23467, 1003, 1065, 1063, 1003, 3796, 14546, 1003, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Type definitions for sinon-chai 2.7.0 // Project: https://github.com/domenic/sinon-chai // Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/>, Jed Mao <https://github.com/jedmao/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="chai" /> /// <reference types="sinon" /> import * as Sinon from 'sinon'; declare global { export namespace Chai { interface LanguageChains { always: Assertion; } interface Assertion { /** * true if the spy was called at least once. */ called: Assertion; /** * @param count The number of recorded calls. */ callCount(count: number): Assertion; /** * true if the spy was called exactly once. */ calledOnce: Assertion; /** * true if the spy was called exactly twice. */ calledTwice: Assertion; /** * true if the spy was called exactly thrice. */ calledThrice: Assertion; /** * Returns true if the spy was called before anotherSpy. */ calledBefore(anotherSpy: Sinon.SinonSpy): Assertion; /** * Returns true if the spy was called after anotherSpy. */ calledAfter(anotherSpy: Sinon.SinonSpy): Assertion; /** * Returns true if spy/stub was called with the new operator. Beware that * this is inferred based on the value of the this object and the spy * function's prototype, so it may give false positives if you actively * return the right kind of object. */ calledWithNew: Assertion; /** * Returns true if context was this for this call. */ calledOn(context: any): Assertion; /** * Returns true if call received provided arguments (and possibly others). */ calledWith(...args: any[]): Assertion; /** * Returns true if call received provided arguments and no others. */ calledWithExactly(...args: any[]): Assertion; /** * Returns true if call received matching arguments (and possibly others). * This behaves the same as spyCall.calledWith(sinon.match(arg1), sinon.match(arg2), ...). */ calledWithMatch(...args: any[]): Assertion; /** * Returns true if spy returned the provided value at least once. Uses * deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) * for strict comparison (see matchers). */ returned(obj: any): Assertion; /** * Returns true if spy threw the provided exception object at least once. */ thrown(obj?: Error | typeof Error | string): Assertion; } } } declare function sinonChai(chai: any, utils: any): void; declare namespace sinonChai { } export = sinonChai;
GiedriusGrabauskas/DefinitelyTyped
types/sinon-chai/index.d.ts
TypeScript
mit
3,265
[ 30522, 1013, 1013, 2828, 15182, 2005, 19432, 2078, 1011, 15775, 2072, 1016, 1012, 1021, 1012, 1014, 1013, 1013, 2622, 1024, 16770, 1024, 1013, 1013, 21025, 2705, 12083, 1012, 4012, 1013, 8514, 8713, 1013, 19432, 2078, 1011, 15775, 2072, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 2.1.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>. 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. */ #ifndef NLOHMANN_JSON_HPP #define NLOHMANN_JSON_HPP #include <algorithm> // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform #include <array> // array #include <cassert> // assert #include <ciso646> // and, not, or #include <clocale> // lconv, localeconv #include <cmath> // isfinite, labs, ldexp, signbit #include <cstddef> // nullptr_t, ptrdiff_t, size_t #include <cstdint> // int64_t, uint64_t #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull #include <cstring> // memcpy, strlen #include <forward_list> // forward_list #include <functional> // function, hash, less #include <initializer_list> // initializer_list #include <iomanip> // hex #include <iosfwd> // istream, ostream #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator #include <limits> // numeric_limits #include <locale> // locale #include <map> // map #include <memory> // addressof, allocator, allocator_traits, unique_ptr #include <numeric> // accumulate #include <sstream> // stringstream #include <string> // getline, stoi, string, to_string #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type #include <utility> // declval, forward, make_pair, move, pair, swap #include <valarray> // valarray #include <vector> // vector // exclude unsupported compilers #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow for portable deprecation warnings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define JSON_DEPRECATED __declspec(deprecated) #else #define JSON_DEPRECATED #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #else #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #endif // manual branch prediction #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define JSON_LIKELY(x) x #define JSON_UNLIKELY(x) x #endif /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { template<typename = void, typename = void> struct adl_serializer; // forward declaration of basic_json (required to split the class) template<template<typename U, typename V, typename... Args> class ObjectType = std::map, template<typename U, typename... Args> class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template<typename U> class AllocatorType = std::allocator, template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer> class basic_json; // Ugly macros to avoid uglier copy-paste when specializing basic_json // This is only temporary and will be removed in 3.0 #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template<template<typename, typename, typename...> class ObjectType, \ template<typename, typename...> class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template<typename> class AllocatorType, \ template<typename, typename = void> class JSONSerializer> #define NLOHMANN_BASIC_JSON_TPL \ basic_json<ObjectType, ArrayType, StringType, BooleanType, \ NumberIntegerType, NumberUnsignedType, NumberFloatType, \ AllocatorType, JSONSerializer> /*! @brief unnamed namespace with internal helper functions This namespace collects some functions that could not be defined inside the @ref basic_json class. @since version 2.1.0 */ namespace detail { //////////////// // exceptions // //////////////// /*! @brief general exception of the @ref basic_json class This class is an extension of `std::exception` objects with a member @a id for exception ids. It is used as the base class for all exceptions thrown by the @ref basic_json class. This class can hence be used as "wildcard" to catch exceptions. Subclasses: - @ref parse_error for exceptions indicating a parse error - @ref invalid_iterator for exceptions indicating errors with iterators - @ref type_error for exceptions indicating executing a member function with a wrong type - @ref out_of_range for exceptions indicating access out of the defined range - @ref other_error for exceptions indicating other library errors @internal @note To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. @endinternal @liveexample{The following code shows how arbitrary library exceptions can be caught.,exception} @since version 3.0.0 */ class exception : public std::exception { public: /// returns the explanatory string const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; protected: exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} static std::string name(const std::string& ename, int id) { return "[json.exception." + ename + "." + std::to_string(id) + "] "; } private: /// an exception object as storage for error messages std::runtime_error m; }; /*! @brief exception indicating a parse error This excpetion is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Member @a byte holds the byte index of the last read character in the input file. Exceptions have ids 1xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number wihtout a leading `0`. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xf8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} @sa @ref exception for the base class of the library exceptions @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id the id of the exception @param[in] byte_ the byte index where the error occurred (or 0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ static parse_error create(int id, std::size_t byte_, const std::string& what_arg) { std::string w = exception::name("parse_error", id) + "parse error" + (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") + ": " + what_arg; return parse_error(id, byte_, w.c_str()); } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} }; /*! @brief exception indicating errors with iterators This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. name / id | example message | description ----------------------------------- | --------------- | ------------------------- json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class invalid_iterator : public exception { public: static invalid_iterator create(int id, const std::string& what_arg) { std::string w = exception::name("invalid_iterator", id) + what_arg; return invalid_iterator(id, w.c_str()); } private: invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating executing a member function with a wrong type This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. name / id | example message | description ----------------------------- | --------------- | ------------------------- json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class type_error : public exception { public: static type_error create(int id, const std::string& what_arg) { std::string w = exception::name("type_error", id) + what_arg; return type_error(id, w.c_str()); } private: type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating access out of the defined range This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. name / id | example message | description ------------------------------- | --------------- | ------------------------- json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class out_of_range : public exception { public: static out_of_range create(int id, const std::string& what_arg) { std::string w = exception::name("out_of_range", id) + what_arg; return out_of_range(id, w.c_str()); } private: out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating other library errors This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair) @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @liveexample{The following code shows how an `other_error` exception can be caught.,other_error} @since version 3.0.0 */ class other_error : public exception { public: static other_error create(int id, const std::string& what_arg) { std::string w = exception::name("other_error", id) + what_arg; return other_error(id, w.c_str()); } private: other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers or to approximate integers which do not fit in the limits of their respective type. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) discarded ///< discarded by the the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string - furthermore, each type is not smaller than itself @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array<uint8_t, 8> order = {{ 0, // null 3, // object 4, // array 5, // string 1, // boolean 2, // integer 2, // unsigned 2, // float } }; // discarded values are not comparable return lhs != value_t::discarded and rhs != value_t::discarded and order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)]; } ///////////// // helpers // ///////////// template<typename> struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {}; // alias templates to reduce boilerplate template<bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type; template<typename T> using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; // implementation of C++14 index_sequence and affiliates // source: https://stackoverflow.com/a/32223343 template<std::size_t... Ints> struct index_sequence { using type = index_sequence; using value_type = std::size_t; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; template<class Sequence1, class Sequence2> struct merge_and_renumber; template<std::size_t... I1, std::size_t... I2> struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>> : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template<std::size_t N> struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, typename make_index_sequence < N - N / 2 >::type > {}; template<> struct make_index_sequence<0> : index_sequence<> { }; template<> struct make_index_sequence<1> : index_sequence<0> { }; template<typename... Ts> using index_sequence_for = make_index_sequence<sizeof...(Ts)>; /* Implementation of two C++17 constructs: conjunction, negation. This is needed to avoid evaluating all the traits in a condition For example: not std::is_same<void, T>::value and has_value_type<T>::value will not compile when T = void (on MSVC at least). Whereas conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will stop evaluating if negation<...>::value == false Please note that those constructs must be used with caution, since symbols can become very long quickly (which can slow down compilation and cause MSVC internal compiler errors). Only use it when you have to (see example ahead). */ template<class...> struct conjunction : std::true_type {}; template<class B1> struct conjunction<B1> : B1 {}; template<class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; template<class B> struct negation : std::integral_constant < bool, !B::value > {}; // dispatch utility (taken from ranges-v3) template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; ////////////////// // constructors // ////////////////// template<value_t> struct external_constructor; template<> struct external_constructor<value_t::boolean> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor<value_t::string> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_type = value_t::string; j.m_value = std::move(s); j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_float> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_type = value_t::number_float; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_unsigned> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_integer> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::array> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_type = value_t::array; j.m_value = arr; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_type = value_t::array; j.m_value = std::move(arr); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_type = value_t::array; j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, const std::vector<bool>& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->reserve(arr.size()); for (bool x : arr) { j.m_value.array->push_back(x); } j.assert_invariant(); } template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray<T>& arr) { using std::begin; using std::end; j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); j.assert_invariant(); } }; template<> struct external_constructor<value_t::object> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_type = value_t::object; j.m_value = obj; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_type = value_t::object; j.m_value = std::move(obj); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_type = value_t::object; j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj)); j.assert_invariant(); } }; //////////////////////// // has_/is_ functions // //////////////////////// /*! @brief Helper to determine whether there's a key_type for T. This helper is used to tell associative containers apart from other containers such as sequence containers. For instance, `std::map` passes the test as it contains a `mapped_type`, whereas `std::vector` fails the test. @sa http://stackoverflow.com/a/7728728/266378 @since version 1.0.0, overworked in version 2.0.6 */ #define NLOHMANN_JSON_HAS_HELPER(type) \ template<typename T> struct has_##type { \ private: \ template<typename U, typename = typename U::type> \ static int detect(U &&); \ static void detect(...); \ public: \ static constexpr bool value = \ std::is_integral<decltype(detect(std::declval<T>()))>::value; \ } NLOHMANN_JSON_HAS_HELPER(mapped_type); NLOHMANN_JSON_HAS_HELPER(key_type); NLOHMANN_JSON_HAS_HELPER(value_type); NLOHMANN_JSON_HAS_HELPER(iterator); #undef NLOHMANN_JSON_HAS_HELPER template<bool B, class RealType, class CompatibleObjectType> struct is_compatible_object_type_impl : std::false_type {}; template<class RealType, class CompatibleObjectType> struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType> { static constexpr auto value = std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value; }; template<class BasicJsonType, class CompatibleObjectType> struct is_compatible_object_type { static auto constexpr value = is_compatible_object_type_impl < conjunction<negation<std::is_same<void, CompatibleObjectType>>, has_mapped_type<CompatibleObjectType>, has_key_type<CompatibleObjectType>>::value, typename BasicJsonType::object_t, CompatibleObjectType >::value; }; template<typename BasicJsonType, typename T> struct is_basic_json_nested_type { static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or std::is_same<T, typename BasicJsonType::const_iterator>::value or std::is_same<T, typename BasicJsonType::reverse_iterator>::value or std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value; }; template<class BasicJsonType, class CompatibleArrayType> struct is_compatible_array_type { static auto constexpr value = conjunction<negation<std::is_same<void, CompatibleArrayType>>, negation<is_compatible_object_type< BasicJsonType, CompatibleArrayType>>, negation<std::is_constructible<typename BasicJsonType::string_t, CompatibleArrayType>>, negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>, has_value_type<CompatibleArrayType>, has_iterator<CompatibleArrayType>>::value; }; template<bool, typename, typename> struct is_compatible_integer_type_impl : std::false_type {}; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits<RealIntegerType>; using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; static constexpr auto value = std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and CompatibleLimits::is_integer and RealLimits::is_signed == CompatibleLimits::is_signed; }; template<typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type { static constexpr auto value = is_compatible_integer_type_impl < std::is_integral<CompatibleNumberIntegerType>::value and not std::is_same<bool, CompatibleNumberIntegerType>::value, RealIntegerType, CompatibleNumberIntegerType > ::value; }; // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists template<typename BasicJsonType, typename T> struct has_from_json { private: // also check the return type of from_json template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json( std::declval<BasicJsonType>(), std::declval<T&>()))>::value>> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype( detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; // This trait checks if JSONSerializer<T>::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template<typename BasicJsonType, typename T> struct has_non_default_from_json { private: template < typename U, typename = enable_if_t<std::is_same< T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype(detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; // This trait checks if BasicJsonType::json_serializer<T>::to_json exists template<typename BasicJsonType, typename T> struct has_to_json { private: template<typename U, typename = decltype(uncvref_t<U>::to_json( std::declval<BasicJsonType&>(), std::declval<T>()))> static int detect(U&&); static void detect(...); public: static constexpr bool value = std::is_integral<decltype(detect( std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value; }; ///////////// // to_json // ///////////// template<typename BasicJsonType, typename T, enable_if_t< std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor<value_t::boolean>::construct(j, b); } template<typename BasicJsonType, typename CompatibleString, enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor<value_t::string>::construct(j, s); } template <typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor<value_t::string>::construct(j, std::move(s)); } template<typename BasicJsonType, typename FloatType, enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); } template < typename BasicJsonType, typename CompatibleNumberUnsignedType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0 > void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); } template < typename BasicJsonType, typename CompatibleNumberIntegerType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0 > void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type<EnumType>::type; external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e)); } template<typename BasicJsonType> void to_json(BasicJsonType& j, const std::vector<bool>& e) { external_constructor<value_t::array>::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor<value_t::array>::construct(j, arr); } template <typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> void to_json(BasicJsonType& j, std::valarray<T> arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template <typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0 > void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor<value_t::object>::construct(j, obj); } template <typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor<value_t::object>::construct(j, std::move(obj)); } template<typename BasicJsonType, typename T, std::size_t N, enable_if_t<not std::is_constructible< typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0> void to_json(BasicJsonType& j, T (&arr)[N]) { external_constructor<value_t::array>::construct(j, arr); } template<typename BasicJsonType, typename... Args> void to_json(BasicJsonType& j, const std::pair<Args...>& p) { j = {p.first, p.second}; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>) { j = {std::get<Idx>(t)...}; } template<typename BasicJsonType, typename... Args> void to_json(BasicJsonType& j, const std::tuple<Args...>& t) { to_json_tuple_impl(j, t, index_sequence_for<Args...> {}); } /////////////// // from_json // /////////////// // overloads for basic_json template parameters template<typename BasicJsonType, typename ArithmeticType, enable_if_t<std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_UNLIKELY(not j.is_boolean())) { JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); } b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_UNLIKELY(not j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type<EnumType>::type val; get_arithmetic_value(j, val); e = static_cast<EnumType>(val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); } // forward_list doesn't have an insert method template<typename BasicJsonType, typename T, typename Allocator, enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get<T>(); }); } // valarray doesn't have an insert method template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::valarray<T>& l) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } l.resize(j.size()); for (size_t i = 0; i < j.size(); ++i) { l[i] = j[i]; } } template<typename BasicJsonType, typename CompatibleArrayType> void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; std::transform(j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename CompatibleArrayType::value_type>(); }); } template<typename BasicJsonType, typename CompatibleArrayType> auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval<typename CompatibleArrayType::size_type>()), void()) { using std::end; arr.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename CompatibleArrayType::value_type>(); }); } template<typename BasicJsonType, typename T, std::size_t N> void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get<T>(); } } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0> void from_json(const BasicJsonType& j, CompatibleArrayType& arr) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } from_json_array_impl(j, arr, priority_tag<2> {}); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0> void from_json(const BasicJsonType& j, CompatibleObjectType& obj) { if (JSON_UNLIKELY(not j.is_object())) { JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); } auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); using value_type = typename CompatibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(obj, obj.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>()); }); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template<typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } case value_t::boolean: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template<typename BasicJsonType, typename A1, typename A2> void from_json(const BasicJsonType& j, std::pair<A1, A2>& p) { p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()}; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>) { t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...); } template<typename BasicJsonType, typename... Args> void from_json(const BasicJsonType& j, std::tuple<Args...>& t) { from_json_tuple_impl(j, t, index_sequence_for<Args...> {}); } struct to_json_fn { private: template<typename BasicJsonType, typename T> auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) -> decltype(to_json(j, std::forward<T>(val)), void()) { return to_json(j, std::forward<T>(val)); } template<typename BasicJsonType, typename T> void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept { static_assert(sizeof(BasicJsonType) == 0, "could not find to_json() method in T's namespace"); } public: template<typename BasicJsonType, typename T> void operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {}))) { return call(j, std::forward<T>(val), priority_tag<1> {}); } }; struct from_json_fn { private: template<typename BasicJsonType, typename T> auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const noexcept(noexcept(from_json(j, val))) -> decltype(from_json(j, val), void()) { return from_json(j, val); } template<typename BasicJsonType, typename T> void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept { static_assert(sizeof(BasicJsonType) == 0, "could not find from_json() method in T's namespace"); } public: template<typename BasicJsonType, typename T> void operator()(const BasicJsonType& j, T& val) const noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {}))) { return call(j, val, priority_tag<1> {}); } }; // taken from ranges-v3 template<typename T> struct static_const { static constexpr T value{}; }; template<typename T> constexpr T static_const<T>::value; //////////////////// // input adapters // //////////////////// /// abstract input adapter interface struct input_adapter_protocol { virtual int get_character() = 0; virtual std::string read(std::size_t offset, std::size_t length) = 0; virtual ~input_adapter_protocol() = default; }; /// a type to simplify interfaces using input_adapter_t = std::shared_ptr<input_adapter_protocol>; /// input adapter for cached stream input template<std::size_t BufferSize> class cached_input_stream_adapter : public input_adapter_protocol { public: explicit cached_input_stream_adapter(std::istream& i) : is(i), start_position(is.tellg()) { fill_buffer(); // skip byte order mark if (fill_size >= 3 and buffer[0] == '\xEF' and buffer[1] == '\xBB' and buffer[2] == '\xBF') { buffer_pos += 3; processed_chars += 3; } } ~cached_input_stream_adapter() override { // clear stream flags is.clear(); // We initially read a lot of characters into the buffer, and we may // not have processed all of them. Therefore, we need to "rewind" the // stream after the last processed char. is.seekg(start_position); is.ignore(static_cast<std::streamsize>(processed_chars)); // clear stream flags is.clear(); } int get_character() override { // check if refilling is necessary and possible if (buffer_pos == fill_size and not eof) { fill_buffer(); // check and remember that filling did not yield new input if (fill_size == 0) { eof = true; return std::char_traits<char>::eof(); } // the buffer is ready buffer_pos = 0; } ++processed_chars; assert(buffer_pos < buffer.size()); return buffer[buffer_pos++] & 0xFF; } std::string read(std::size_t offset, std::size_t length) override { // create buffer std::string result(length, '\0'); // save stream position const auto current_pos = is.tellg(); // save stream flags const auto flags = is.rdstate(); // clear stream flags is.clear(); // set stream position is.seekg(static_cast<std::streamoff>(offset)); // read bytes is.read(&result[0], static_cast<std::streamsize>(length)); // reset stream position is.seekg(current_pos); // reset stream flags is.setstate(flags); return result; } private: void fill_buffer() { // fill is.read(buffer.data(), static_cast<std::streamsize>(buffer.size())); // store number of bytes in the buffer fill_size = static_cast<size_t>(is.gcount()); } /// the associated input stream std::istream& is; /// chars returned via get_character() std::size_t processed_chars = 0; /// chars processed in the current buffer std::size_t buffer_pos = 0; /// whether stream reached eof bool eof = false; /// how many chars have been copied to the buffer by last (re)fill std::size_t fill_size = 0; /// position of the stream when we started const std::streampos start_position; /// internal buffer std::array<char, BufferSize> buffer{{}}; }; /// input adapter for buffer input class input_buffer_adapter : public input_adapter_protocol { public: input_buffer_adapter(const char* b, const std::size_t l) : cursor(b), limit(b + l), start(b) { // skip byte order mark if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF') { cursor += 3; } } // delete because of pointer members input_buffer_adapter(const input_buffer_adapter&) = delete; input_buffer_adapter& operator=(input_buffer_adapter&) = delete; int get_character() noexcept override { if (JSON_LIKELY(cursor < limit)) { return *(cursor++) & 0xFF; } return std::char_traits<char>::eof(); } std::string read(std::size_t offset, std::size_t length) override { // avoid reading too many characters const auto max_length = static_cast<size_t>(limit - start); return std::string(start + offset, (std::min)(length, max_length - offset)); } private: /// pointer to the current character const char* cursor; /// pointer past the last character const char* limit; /// pointer to the first character const char* start; }; class input_adapter { public: // native support /// input adapter for input stream input_adapter(std::istream& i) : ia(std::make_shared<cached_input_stream_adapter<16384>>(i)) {} /// input adapter for input stream input_adapter(std::istream&& i) : ia(std::make_shared<cached_input_stream_adapter<16384>>(i)) {} /// input adapter for buffer template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral< typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> input_adapter(CharT b, std::size_t l) : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {} // derived support /// input adapter for string literal template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral< typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> input_adapter(CharT b) : input_adapter(reinterpret_cast<const char*>(b), std::strlen(reinterpret_cast<const char*>(b))) {} /// input adapter for iterator range with contiguous storage template<class IteratorType, typename std::enable_if< std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> input_adapter(IteratorType first, IteratorType last) { // assertion to check that the iterator range is indeed contiguous, // see http://stackoverflow.com/a/35008842/266378 for more discussion assert(std::accumulate( first, last, std::pair<bool, int>(true, 0), [&first](std::pair<bool, int> res, decltype(*first) val) { res.first &= (val == *(std::next(std::addressof(*first), res.second++))); return res; }).first); // assertion to check that each element is 1 byte long static_assert( sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1, "each element in the iterator range must have the size of 1 byte"); const auto len = static_cast<size_t>(std::distance(first, last)); if (JSON_LIKELY(len > 0)) { // there is at least one element: use the address of first ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len); } else { // the address of first cannot be used: use nullptr ia = std::make_shared<input_buffer_adapter>(nullptr, len); } } /// input adapter for array template<class T, std::size_t N> input_adapter(T (&array)[N]) : input_adapter(std::begin(array), std::end(array)) {} /// input adapter for contiguous container template < class ContiguousContainer, typename std::enable_if < not std::is_pointer<ContiguousContainer>::value and std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value, int >::type = 0 > input_adapter(const ContiguousContainer& c) : input_adapter(std::begin(c), std::end(c)) {} operator input_adapter_t() { return ia; } private: /// the actual adapter input_adapter_t ia = nullptr; }; ////////////////////// // lexer and parser // ////////////////////// /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template<typename BasicJsonType> class lexer { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return "<uninitialized>"; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case lexer::token_type::value_unsigned: case lexer::token_type::value_integer: case lexer::token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return "<parse error>"; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; default: // catch non-enum values return "unknown token"; // LCOV_EXCL_LINE } } explicit lexer(detail::input_adapter_t adapter) : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {} // delete because of pointer members lexer(const lexer&) = delete; lexer& operator=(lexer&) = delete; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point static char get_decimal_point() noexcept { const auto loc = localeconv(); assert(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0]; } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` assert(current == 'u'); int codepoint = 0; const auto factors = { 12, 8, 4, 0 }; for (const auto factor : factors) { get(); if (current >= '0' and current <= '9') { codepoint += ((current - 0x30) << factor); } else if (current >= 'A' and current <= 'F') { codepoint += ((current - 0x37) << factor); } else if (current >= 'a' and current <= 'f') { codepoint += ((current - 0x57) << factor); } else { return -1; } } assert(0x0000 <= codepoint and codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list<int> ranges) { assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_LIKELY(*range <= current and current <= *(++range))) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 7159. While scanning, bytes are escaped and copied into buffer yytext. Then the function returns successfully, yytext is null-terminated and yylen contains the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset yytext (ignore opening quote) reset(); // we entered the function by reading an open quote assert(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case std::char_traits<char>::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { // terminate yytext add('\0'); --yylen; return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { int codepoint; const int codepoint1 = get_codepoint(); if (JSON_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_LIKELY(get() == '\\' and get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF)) { codepoint = // high surrogate occupies the most significant 22 bits (codepoint1 << 10) // low surrogate occupies the least significant 15 bits + codepoint2 // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00; } else { error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } // only work with first code point codepoint = codepoint1; } // result of the above calculation yields a proper codepoint assert(0x00 <= codepoint and codepoint <= 0x10FFFF); // translate code point to bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(codepoint); } else if (codepoint <= 0x7ff) { // 2-byte characters: 110xxxxx 10xxxxxx add(0xC0 | (codepoint >> 6)); add(0x80 | (codepoint & 0x3F)); } else if (codepoint <= 0xffff) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(0xE0 | (codepoint >> 12)); add(0x80 | ((codepoint >> 6) & 0x3F)); add(0x80 | (codepoint & 0x3F)); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(0xF0 | (codepoint >> 18)); add(0x80 | ((codepoint >> 12) & 0x3F)); add(0x80 | ((codepoint >> 6) & 0x3F)); add(0x80 | (codepoint & 0x3F)); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: { error_message = "invalid string: control character must be escaped"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5a: case 0x5b: case 0x5d: case 0x5e: case 0x5f: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xc2: case 0xc3: case 0xc4: case 0xc5: case 0xc6: case 0xc7: case 0xc8: case 0xc9: case 0xca: case 0xcb: case 0xcc: case 0xcd: case 0xce: case 0xcf: case 0xd0: case 0xd1: case 0xd2: case 0xd3: case 0xd4: case 0xd5: case 0xd6: case 0xd7: case 0xd8: case 0xd9: case 0xda: case 0xdb: case 0xdc: case 0xdd: case 0xde: case 0xdf: { if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xe0: { if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xe1: case 0xe2: case 0xe3: case 0xe4: case 0xe5: case 0xe6: case 0xe7: case 0xe8: case 0xe9: case 0xea: case 0xeb: case 0xec: case 0xee: case 0xef: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xed: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xf0: { if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xf1: case 0xf2: case 0xf3: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xf4: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 7159. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 7159. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in yytext. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() { // reset yytext to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { // all other characters are rejected outside scan_number() assert(false); // LCOV_EXCL_LINE } } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) --chars_read; next_unget = true; // terminate token add('\0'); --yylen; char* endptr = nullptr; errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(yytext.data(), &endptr, 10); // we checked the number format before assert(endptr == yytext.data() + yylen); if (errno == 0) { value_unsigned = static_cast<number_unsigned_t>(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(yytext.data(), &endptr, 10); // we checked the number format before assert(endptr == yytext.data() + yylen); if (errno == 0) { value_integer = static_cast<number_integer_t>(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, yytext.data(), &endptr); // we checked the number format before assert(endptr == yytext.data() + yylen); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ token_type scan_literal(const char* literal_text, const std::size_t length, token_type return_type) { assert(current == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_UNLIKELY(get() != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset yytext void reset() noexcept { yylen = 0; start_pos = chars_read - 1; } /// get a character from the input int get() { ++chars_read; return next_unget ? (next_unget = false, current) : (current = ia->get_character()); } /// add a character to yytext void add(int c) { // resize yytext if necessary; this condition is deemed unlikely, // because we start with a 1024-byte buffer if (JSON_UNLIKELY((yylen + 1 > yytext.capacity()))) { yytext.resize(2 * yytext.capacity(), '\0'); } assert(yylen < yytext.size()); yytext[yylen++] = static_cast<char>(c); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return string value const std::string get_string() { // yytext cannot be returned as char*, because it may contain a null // byte (parsed as "\u0000") return std::string(yytext.data(), yylen); } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr std::size_t get_position() const noexcept { return chars_read; } /// return the last read token (for errors only) std::string get_token_string() const { // get the raw byte sequence of the last token std::string s = ia->read(start_pos, chars_read - start_pos); // escape control characters std::string result; for (auto c : s) { if (c == '\0' or c == std::char_traits<char>::eof()) { // ignore EOF continue; } else if ('\x00' <= c and c <= '\x1f') { // escape control characters std::stringstream ss; ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(c) << ">"; result += ss.str(); } else { // add character as is result.push_back(c); } } return result; } /// return syntax error message constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// token_type scan() { // read next character and ignore whitespace do { get(); } while (current == ' ' or current == '\t' or current == '\n' or current == '\r'); switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': return scan_literal("true", 4, token_type::literal_true); case 'f': return scan_literal("false", 5, token_type::literal_false); case 'n': return scan_literal("null", 4, token_type::literal_null); // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case std::char_traits<char>::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter detail::input_adapter_t ia = nullptr; /// the current character int current = std::char_traits<char>::eof(); /// whether get() should return the last character again bool next_unget = false; /// the number of characters read std::size_t chars_read = 0; /// the start position of the current token std::size_t start_pos = 0; /// buffer for variable-length tokens (numbers, strings) std::vector<char> yytext = std::vector<char>(1024, '\0'); /// current index in yytext std::size_t yylen = 0; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char decimal_point_char = '.'; }; /*! @brief syntax analysis This class implements a recursive decent parser. */ template<typename BasicJsonType> class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using lexer_t = lexer<BasicJsonType>; using token_type = typename lexer_t::token_type; public: enum class parse_event_t : uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; using parser_callback_t = std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>; /// a parser reading from an input adapter explicit parser(detail::input_adapter_t adapter, const parser_callback_t cb = nullptr, const bool allow_exceptions_ = true) : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_) {} /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { // read first token get_token(); parse_internal(true, result); result.assert_invariant(); // in strict mode, input must be completely read if (strict) { get_token(); expect(token_type::end_of_input); } // in case of an error, return discarded value if (errored) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { // read first token get_token(); if (not accept_internal()) { return false; } // strict => last token must be EOF return not strict or (get_token() == token_type::end_of_input); } private: /*! @brief the actual parser @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse_internal(bool keep, BasicJsonType& result) { // never parse after a parse error was detected assert(not errored); // start with a discarded value if (not result.is_discarded()) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } switch (last_token) { case token_type::begin_object: { if (keep and (not callback or ((keep = callback(depth++, parse_event_t::object_start, result))))) { // explicitly set result to object to cope with {} result.m_type = value_t::object; result.m_value = value_t::object; } // read next token get_token(); // closing } -> we are done if (last_token == token_type::end_object) { if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } // parse values std::string key; BasicJsonType value; while (true) { // store key if (not expect(token_type::value_string)) { return; } key = m_lexer.get_string(); bool keep_tag = false; if (keep) { if (callback) { BasicJsonType k(key); keep_tag = callback(depth, parse_event_t::key, k); } else { keep_tag = true; } } // parse separator (:) get_token(); if (not expect(token_type::name_separator)) { return; } // parse and add value get_token(); value.m_value.destroy(value.m_type); value.m_type = value_t::discarded; parse_internal(keep, value); if (JSON_UNLIKELY(errored)) { return; } if (keep and keep_tag and not value.is_discarded()) { result.m_value.object->emplace(std::move(key), std::move(value)); } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing } if (not expect(token_type::end_object)) { return; } break; } if (keep and callback and not callback(--depth, parse_event_t::object_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } case token_type::begin_array: { if (keep and (not callback or ((keep = callback(depth++, parse_event_t::array_start, result))))) { // explicitly set result to object to cope with [] result.m_type = value_t::array; result.m_value = value_t::array; } // read next token get_token(); // closing ] -> we are done if (last_token == token_type::end_array) { if (callback and not callback(--depth, parse_event_t::array_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } // parse values BasicJsonType value; while (true) { // parse value value.m_value.destroy(value.m_type); value.m_type = value_t::discarded; parse_internal(keep, value); if (JSON_UNLIKELY(errored)) { return; } if (keep and not value.is_discarded()) { result.m_value.array->push_back(std::move(value)); } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing ] if (not expect(token_type::end_array)) { return; } break; } if (keep and callback and not callback(--depth, parse_event_t::array_end, result)) { result.m_value.destroy(result.m_type); result.m_type = value_t::discarded; } break; } case token_type::literal_null: { result.m_type = value_t::null; break; } case token_type::value_string: { result.m_type = value_t::string; result.m_value = m_lexer.get_string(); break; } case token_type::literal_true: { result.m_type = value_t::boolean; result.m_value = true; break; } case token_type::literal_false: { result.m_type = value_t::boolean; result.m_value = false; break; } case token_type::value_unsigned: { result.m_type = value_t::number_unsigned; result.m_value = m_lexer.get_number_unsigned(); break; } case token_type::value_integer: { result.m_type = value_t::number_integer; result.m_value = m_lexer.get_number_integer(); break; } case token_type::value_float: { result.m_type = value_t::number_float; result.m_value = m_lexer.get_number_float(); // throw in case of infinity or NAN if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float))) { if (allow_exceptions) { JSON_THROW(out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); } expect(token_type::uninitialized); } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message if (not expect(token_type::uninitialized)) { return; } break; // LCOV_EXCL_LINE } default: { // the last token was unexpected; we expected a value if (not expect(token_type::literal_or_value)) { return; } break; // LCOV_EXCL_LINE } } if (keep and callback and not callback(depth, parse_event_t::value, result)) { result.m_type = value_t::discarded; } } /*! @brief the acutal acceptor @invariant 1. The last token is not yet processed. Therefore, the caller of this function must make sure a token has been read. 2. When this function returns, the last token is processed. That is, the last read character was already considered. This invariant makes sure that no token needs to be "unput". */ bool accept_internal() { switch (last_token) { case token_type::begin_object: { // read next token get_token(); // closing } -> we are done if (last_token == token_type::end_object) { return true; } // parse values while (true) { // parse key if (last_token != token_type::value_string) { return false; } // parse separator (:) get_token(); if (last_token != token_type::name_separator) { return false; } // parse value get_token(); if (not accept_internal()) { return false; } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing } return (last_token == token_type::end_object); } } case token_type::begin_array: { // read next token get_token(); // closing ] -> we are done if (last_token == token_type::end_array) { return true; } // parse values while (true) { // parse value if (not accept_internal()) { return false; } // comma -> next value get_token(); if (last_token == token_type::value_separator) { get_token(); continue; } // closing ] return (last_token == token_type::end_array); } } case token_type::value_float: { // reject infinity or NAN return std::isfinite(m_lexer.get_number_float()); } case token_type::literal_false: case token_type::literal_null: case token_type::literal_true: case token_type::value_integer: case token_type::value_string: case token_type::value_unsigned: return true; default: // the last token was unexpected return false; } } /// get next token from lexer token_type get_token() { return (last_token = m_lexer.scan()); } /*! @throw parse_error.101 if expected token did not occur */ bool expect(token_type t) { if (JSON_UNLIKELY(t != last_token)) { errored = true; expected = t; if (allow_exceptions) { throw_exception(); } else { return false; } } return true; } [[noreturn]] void throw_exception() const { std::string error_msg = "syntax error - "; if (last_token == token_type::parse_error) { error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'"; } else { error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); } JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg)); } private: /// current level of recursion int depth = 0; /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether a syntax error occurred bool errored = false; /// possible reason for the syntax error token_type expected = token_type::uninitialized; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; /////////////// // iterators // /////////////// /*! @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { public: using difference_type = std::ptrdiff_t; constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type i) { auto result = *this; result += i; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it) { return os << it.m_it; } primitive_iterator_t& operator++() { ++m_it; return *this; } primitive_iterator_t operator++(int) { auto result = *this; m_it++; return result; } primitive_iterator_t& operator--() { --m_it; return *this; } primitive_iterator_t operator--(int) { auto result = *this; m_it--; return result; } primitive_iterator_t& operator+=(difference_type n) { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) { m_it -= n; return *this; } private: static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; /// iterator as signed integer type difference_type m_it = std::numeric_limits<std::ptrdiff_t>::min(); }; /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template<typename BasicJsonType> struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; template<typename IteratorType> class iteration_proxy; /*! @brief a template for a random access iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): The iterator that can be moved to point (forward and backward) to any element in constant time. @since version 1.0.0, simplified in version 2.0.9 */ template<typename BasicJsonType> class iter_impl : public std::iterator<std::random_access_iterator_tag, BasicJsonType> { /// allow basic_json to access private members friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>; friend BasicJsonType; friend iteration_proxy<iter_impl>; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value, "iter_impl only accepts (const) basic_json"); public: /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; /// the category of the iterator using iterator_category = std::bidirectional_iterator_tag; /// default constructor iter_impl() = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in,out] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept { m_object = other.m_object; m_it = other.m_it; return *this; } private: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } default: { if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator++(int) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator--(int) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator==(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator!=(const iter_impl& other) const { return not operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return not other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return not operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return not operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: { std::advance(m_it.array_iterator, i); break; } default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ typename object_t::key_type key() const { assert(m_object != nullptr); if (JSON_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } private: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {}; }; /// proxy class for the iterator_wrapper functions template<typename IteratorType> class iteration_proxy { private: /// helper class for iteration class iteration_proxy_internal { private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; public: explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {} /// dereference operator (needed for range-based for) iteration_proxy_internal& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_internal& operator++() { ++anchor; ++array_index; return *this; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_internal& o) const noexcept { return anchor != o.anchor; } /// return key of the iterator std::string key() const { assert(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: return std::to_string(array_index); // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types default: return ""; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_internal begin() noexcept { return iteration_proxy_internal(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_internal end() noexcept { return iteration_proxy_internal(container.end()); } }; /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator): The iterator that can be moved to point (forward and backward) to any element in constant time. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template<typename Base> class json_reverse_iterator : public std::reverse_iterator<Base> { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adaptor using base_iterator = std::reverse_iterator<Base>; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator operator++(int) { return static_cast<json_reverse_iterator>(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast<json_reverse_iterator&>(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator operator--(int) { return static_cast<json_reverse_iterator>(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast<json_reverse_iterator&>(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval<Base>().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; ///////////////////// // output adapters // ///////////////////// /// abstract output adapter interface template<typename CharType> struct output_adapter_protocol { virtual void write_character(CharType c) = 0; virtual void write_characters(const CharType* s, std::size_t length) = 0; virtual ~output_adapter_protocol() = default; }; /// a type to simplify interfaces template<typename CharType> using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>; /// output adapter for byte vectors template<typename CharType> class output_vector_adapter : public output_adapter_protocol<CharType> { public: explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {} void write_character(CharType c) override { v.push_back(c); } void write_characters(const CharType* s, std::size_t length) override { std::copy(s, s + length, std::back_inserter(v)); } private: std::vector<CharType>& v; }; /// output adapter for output streams template<typename CharType> class output_stream_adapter : public output_adapter_protocol<CharType> { public: explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {} void write_character(CharType c) override { stream.put(c); } void write_characters(const CharType* s, std::size_t length) override { stream.write(s, static_cast<std::streamsize>(length)); } private: std::basic_ostream<CharType>& stream; }; /// output adapter for basic_string template<typename CharType> class output_string_adapter : public output_adapter_protocol<CharType> { public: explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {} void write_character(CharType c) override { str.push_back(c); } void write_characters(const CharType* s, std::size_t length) override { str.append(s, length); } private: std::basic_string<CharType>& str; }; template<typename CharType> class output_adapter { public: output_adapter(std::vector<CharType>& vec) : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {} output_adapter(std::basic_ostream<CharType>& s) : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {} output_adapter(std::basic_string<CharType>& s) : oa(std::make_shared<output_string_adapter<CharType>>(s)) {} operator output_adapter_t<CharType>() { return oa; } private: output_adapter_t<CharType> oa = nullptr; }; ////////////////////////////// // binary reader and writer // ////////////////////////////// /*! @brief deserialization of CBOR and MessagePack values */ template<typename BasicJsonType> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter)) { assert(ia); } /*! @brief create a JSON value from CBOR input @param[in] strict whether to expect the input to be consumed completed @return JSON value created from CBOR input @throw parse_error.110 if input ended unexpectedly or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported byte was read */ BasicJsonType parse_cbor(const bool strict) { const auto res = parse_cbor_internal(); if (strict) { get(); check_eof(true); } return res; } /*! @brief create a JSON value from MessagePack input @param[in] strict whether to expect the input to be consumed completed @return JSON value created from MessagePack input @throw parse_error.110 if input ended unexpectedly or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported byte was read */ BasicJsonType parse_msgpack(const bool strict) { const auto res = parse_msgpack_internal(); if (strict) { get(); check_eof(true); } return res; } /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from http://stackoverflow.com/a/1001328/266378 */ static constexpr bool little_endianess(int num = 1) noexcept { return (*reinterpret_cast<char*>(&num) == 1); } private: /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead */ BasicJsonType parse_cbor_internal(const bool get_char = true) { switch (get_char ? get() : current) { // EOF case std::char_traits<char>::eof(): JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input")); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return static_cast<number_unsigned_t>(current); case 0x18: // Unsigned integer (one-byte uint8_t follows) return get_number<uint8_t>(); case 0x19: // Unsigned integer (two-byte uint16_t follows) return get_number<uint16_t>(); case 0x1a: // Unsigned integer (four-byte uint32_t follows) return get_number<uint32_t>(); case 0x1b: // Unsigned integer (eight-byte uint64_t follows) return get_number<uint64_t>(); // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return static_cast<int8_t>(0x20 - 1 - current); case 0x38: // Negative integer (one-byte uint8_t follows) { // must be uint8_t ! return static_cast<number_integer_t>(-1) - get_number<uint8_t>(); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { return static_cast<number_integer_t>(-1) - get_number<uint16_t>(); } case 0x3a: // Negative integer -1-n (four-byte uint32_t follows) { return static_cast<number_integer_t>(-1) - get_number<uint32_t>(); } case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows) { return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_number<uint64_t>()); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7f: // UTF-8 string (indefinite length) { return get_cbor_string(); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: { return get_cbor_array(current & 0x1f); } case 0x98: // array (one-byte uint8_t for n follows) { return get_cbor_array(get_number<uint8_t>()); } case 0x99: // array (two-byte uint16_t for n follow) { return get_cbor_array(get_number<uint16_t>()); } case 0x9a: // array (four-byte uint32_t for n follow) { return get_cbor_array(get_number<uint32_t>()); } case 0x9b: // array (eight-byte uint64_t for n follow) { return get_cbor_array(get_number<uint64_t>()); } case 0x9f: // array (indefinite length) { BasicJsonType result = value_t::array; while (get() != 0xff) { result.push_back(parse_cbor_internal(false)); } return result; } // map (0x00..0x17 pairs of data items follow) case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: { return get_cbor_object(current & 0x1f); } case 0xb8: // map (one-byte uint8_t for n follows) { return get_cbor_object(get_number<uint8_t>()); } case 0xb9: // map (two-byte uint16_t for n follow) { return get_cbor_object(get_number<uint16_t>()); } case 0xba: // map (four-byte uint32_t for n follow) { return get_cbor_object(get_number<uint32_t>()); } case 0xbb: // map (eight-byte uint64_t for n follow) { return get_cbor_object(get_number<uint64_t>()); } case 0xbf: // map (indefinite length) { BasicJsonType result = value_t::object; while (get() != 0xff) { auto key = get_cbor_string(); result[key] = parse_cbor_internal(); } return result; } case 0xf4: // false { return false; } case 0xf5: // true { return true; } case 0xf6: // null { return value_t::null; } case 0xf9: // Half-Precision Float (two-byte IEEE 754) { const int byte1 = get(); check_eof(); const int byte2 = get(); check_eof(); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const int half = (byte1 << 8) + byte2; const int exp = (half >> 10) & 0x1f; const int mant = half & 0x3ff; double val; if (exp == 0) { val = std::ldexp(mant, -24); } else if (exp != 31) { val = std::ldexp(mant + 1024, exp - 25); } else { val = (mant == 0) ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::quiet_NaN(); } return (half & 0x8000) != 0 ? -val : val; } case 0xfa: // Single-Precision Float (four-byte IEEE 754) { return get_number<float>(); } case 0xfb: // Double-Precision Float (eight-byte IEEE 754) { return get_number<double>(); } default: // anything else (0xFF is handled inside the other types) { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str())); } } } BasicJsonType parse_msgpack_internal() { switch (get()) { // EOF case std::char_traits<char>::eof(): JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input")); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5a: case 0x5b: case 0x5c: case 0x5d: case 0x5e: case 0x5f: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f: return static_cast<number_unsigned_t>(current); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f: { return get_msgpack_object(current & 0x0f); } // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9a: case 0x9b: case 0x9c: case 0x9d: case 0x9e: case 0x9f: { return get_msgpack_array(current & 0x0f); } // fixstr case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbc: case 0xbd: case 0xbe: case 0xbf: return get_msgpack_string(); case 0xc0: // nil return value_t::null; case 0xc2: // false return false; case 0xc3: // true return true; case 0xca: // float 32 return get_number<float>(); case 0xcb: // float 64 return get_number<double>(); case 0xcc: // uint 8 return get_number<uint8_t>(); case 0xcd: // uint 16 return get_number<uint16_t>(); case 0xce: // uint 32 return get_number<uint32_t>(); case 0xcf: // uint 64 return get_number<uint64_t>(); case 0xd0: // int 8 return get_number<int8_t>(); case 0xd1: // int 16 return get_number<int16_t>(); case 0xd2: // int 32 return get_number<int32_t>(); case 0xd3: // int 64 return get_number<int64_t>(); case 0xd9: // str 8 case 0xda: // str 16 case 0xdb: // str 32 return get_msgpack_string(); case 0xdc: // array 16 { return get_msgpack_array(get_number<uint16_t>()); } case 0xdd: // array 32 { return get_msgpack_array(get_number<uint32_t>()); } case 0xde: // map 16 { return get_msgpack_object(get_number<uint16_t>()); } case 0xdf: // map 32 { return get_msgpack_object(get_number<uint32_t>()); } // positive fixint case 0xe0: case 0xe1: case 0xe2: case 0xe3: case 0xe4: case 0xe5: case 0xe6: case 0xe7: case 0xe8: case 0xe9: case 0xea: case 0xeb: case 0xec: case 0xed: case 0xee: case 0xef: case 0xf0: case 0xf1: case 0xf2: case 0xf3: case 0xf4: case 0xf5: case 0xf6: case 0xf7: case 0xf8: case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff: return static_cast<int8_t>(current); default: // anything else { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(112, chars_read, "error reading MessagePack; last byte: 0x" + ss.str())); } } } /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns `std::char_traits<char>::eof()` in that case. @return character read from the input */ int get() { ++chars_read; return (current = ia->get_character()); } /* @brief read a number from the input @tparam NumberType the type of the number @return number of type @a NumberType @note This function needs to respect the system's endianess, because bytes in CBOR and MessagePack are stored in network order (big endian) and therefore need reordering on little endian systems. @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes */ template<typename NumberType> NumberType get_number() { // step 1: read input into array with system's byte order std::array<uint8_t, sizeof(NumberType)> vec; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); check_eof(); // reverse byte order prior to conversion if necessary if (is_little_endian) { vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current); } else { vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return NumberType result; std::memcpy(&result, vec.data(), sizeof(NumberType)); return result; } /*! @brief create a string by reading characters from the input @param[in] len number of bytes to read @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref check_eof() detects the end of the input before we run out of string memory. @return string created by reading @a len bytes @throw parse_error.110 if input has less than @a len bytes */ template<typename NumberType> std::string get_string(const NumberType len) { std::string result; std::generate_n(std::back_inserter(result), len, [this]() { get(); check_eof(); return current; }); return result; } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @return string @throw parse_error.110 if input ended @throw parse_error.113 if an unexpected byte is read */ std::string get_cbor_string() { check_eof(); switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(current & 0x1f); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { return get_string(get_number<uint8_t>()); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { return get_string(get_number<uint16_t>()); } case 0x7a: // UTF-8 string (four-byte uint32_t for n follow) { return get_string(get_number<uint32_t>()); } case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow) { return get_string(get_number<uint64_t>()); } case 0x7f: // UTF-8 string (indefinite length) { std::string result; while (get() != 0xff) { check_eof(); result.push_back(static_cast<char>(current)); } return result; } default: { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str())); } } } template<typename NumberType> BasicJsonType get_cbor_array(const NumberType len) { BasicJsonType result = value_t::array; std::generate_n(std::back_inserter(*result.m_value.array), len, [this]() { return parse_cbor_internal(); }); return result; } template<typename NumberType> BasicJsonType get_cbor_object(const NumberType len) { BasicJsonType result = value_t::object; std::generate_n(std::inserter(*result.m_value.object, result.m_value.object->end()), len, [this]() { get(); auto key = get_cbor_string(); auto val = parse_cbor_internal(); return std::make_pair(std::move(key), std::move(val)); }); return result; } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @return string @throw parse_error.110 if input ended @throw parse_error.113 if an unexpected byte is read */ std::string get_msgpack_string() { check_eof(); switch (current) { // fixstr case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7: case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf: case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7: case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbc: case 0xbd: case 0xbe: case 0xbf: { return get_string(current & 0x1f); } case 0xd9: // str 8 { return get_string(get_number<uint8_t>()); } case 0xda: // str 16 { return get_string(get_number<uint16_t>()); } case 0xdb: // str 32 { return get_string(get_number<uint32_t>()); } default: { std::stringstream ss; ss << std::setw(2) << std::setfill('0') << std::hex << current; JSON_THROW(parse_error::create(113, chars_read, "expected a MessagePack string; last byte: 0x" + ss.str())); } } } template<typename NumberType> BasicJsonType get_msgpack_array(const NumberType len) { BasicJsonType result = value_t::array; std::generate_n(std::back_inserter(*result.m_value.array), len, [this]() { return parse_msgpack_internal(); }); return result; } template<typename NumberType> BasicJsonType get_msgpack_object(const NumberType len) { BasicJsonType result = value_t::object; std::generate_n(std::inserter(*result.m_value.object, result.m_value.object->end()), len, [this]() { get(); auto key = get_msgpack_string(); auto val = parse_msgpack_internal(); return std::make_pair(std::move(key), std::move(val)); }); return result; } /*! @brief check if input ended @throw parse_error.110 if input ended */ void check_eof(const bool expect_eof = false) const { if (expect_eof) { if (JSON_UNLIKELY(current != std::char_traits<char>::eof())) { JSON_THROW(parse_error::create(110, chars_read, "expected end of input")); } } else { if (JSON_UNLIKELY(current == std::char_traits<char>::eof())) { JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input")); } } } private: /// input adapter input_adapter_t ia = nullptr; /// the current character int current = std::char_traits<char>::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianess const bool is_little_endian = little_endianess(); }; /*! @brief serialization to CBOR and MessagePack values */ template<typename BasicJsonType, typename CharType> class binary_writer { public: /*! @brief create a binary writer @param[in] adapter output adapter to write to */ explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter) { assert(oa); } /*! @brief[in] j JSON value to serialize */ void write_cbor(const BasicJsonType& j) { switch (j.type()) { case value_t::null: { oa->write_character(static_cast<CharType>(0xf6)); break; } case value_t::boolean: { oa->write_character(j.m_value.boolean ? static_cast<CharType>(0xf5) : static_cast<CharType>(0xf4)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(static_cast<CharType>(0x18)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(static_cast<CharType>(0x19)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(static_cast<CharType>(0x1a)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else { oa->write_character(static_cast<CharType>(0x1b)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { write_number(static_cast<uint8_t>(0x20 + positive_number)); } else if (positive_number <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(static_cast<CharType>(0x38)); write_number(static_cast<uint8_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(static_cast<CharType>(0x39)); write_number(static_cast<uint16_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(static_cast<CharType>(0x3a)); write_number(static_cast<uint32_t>(positive_number)); } else { oa->write_character(static_cast<CharType>(0x3b)); write_number(static_cast<uint64_t>(positive_number)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { write_number(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(static_cast<CharType>(0x18)); write_number(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(static_cast<CharType>(0x19)); write_number(static_cast<uint16_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(static_cast<CharType>(0x1a)); write_number(static_cast<uint32_t>(j.m_value.number_unsigned)); } else { oa->write_character(static_cast<CharType>(0x1b)); write_number(static_cast<uint64_t>(j.m_value.number_unsigned)); } break; } case value_t::number_float: // Double-Precision Float { oa->write_character(static_cast<CharType>(0xfb)); write_number(j.m_value.number_float); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0x60 + N)); } else if (N <= 0xff) { oa->write_character(static_cast<CharType>(0x78)); write_number(static_cast<uint8_t>(N)); } else if (N <= 0xffff) { oa->write_character(static_cast<CharType>(0x79)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { oa->write_character(static_cast<CharType>(0x7a)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { oa->write_character(static_cast<CharType>(0x7b)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0x80 + N)); } else if (N <= 0xff) { oa->write_character(static_cast<CharType>(0x98)); write_number(static_cast<uint8_t>(N)); } else if (N <= 0xffff) { oa->write_character(static_cast<CharType>(0x99)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { oa->write_character(static_cast<CharType>(0x9a)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { oa->write_character(static_cast<CharType>(0x9b)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.array) { write_cbor(el); } break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0xa0 + N)); } else if (N <= 0xff) { oa->write_character(static_cast<CharType>(0xb8)); write_number(static_cast<uint8_t>(N)); } else if (N <= 0xffff) { oa->write_character(static_cast<CharType>(0xb9)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { oa->write_character(static_cast<CharType>(0xba)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= 0xffffffffffffffff) { oa->write_character(static_cast<CharType>(0xbb)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.object) { write_cbor(el.first); write_cbor(el.second); } break; } default: break; } } /*! @brief[in] j JSON value to serialize */ void write_msgpack(const BasicJsonType& j) { switch (j.type()) { case value_t::null: // nil { oa->write_character(static_cast<CharType>(0xc0)); break; } case value_t::boolean: // true and false { oa->write_character(j.m_value.boolean ? static_cast<CharType>(0xc3) : static_cast<CharType>(0xc2)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we used // the code from the value_t::number_unsigned case here. if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { // uint 8 oa->write_character(static_cast<CharType>(0xcc)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { // uint 16 oa->write_character(static_cast<CharType>(0xcd)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { // uint 32 oa->write_character(static_cast<CharType>(0xce)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)()) { // uint 64 oa->write_character(static_cast<CharType>(0xcf)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum write_number(static_cast<int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)()) { // int 8 oa->write_character(static_cast<CharType>(0xd0)); write_number(static_cast<int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)()) { // int 16 oa->write_character(static_cast<CharType>(0xd1)); write_number(static_cast<int16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)()) { // int 32 oa->write_character(static_cast<CharType>(0xd2)); write_number(static_cast<int32_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)()) { // int 64 oa->write_character(static_cast<CharType>(0xd3)); write_number(static_cast<int64_t>(j.m_value.number_integer)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { // uint 8 oa->write_character(static_cast<CharType>(0xcc)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { // uint 16 oa->write_character(static_cast<CharType>(0xcd)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { // uint 32 oa->write_character(static_cast<CharType>(0xce)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)()) { // uint 64 oa->write_character(static_cast<CharType>(0xcf)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } break; } case value_t::number_float: // float 64 { oa->write_character(static_cast<CharType>(0xcb)); write_number(j.m_value.number_float); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr write_number(static_cast<uint8_t>(0xa0 | N)); } else if (N <= 255) { // str 8 oa->write_character(static_cast<CharType>(0xd9)); write_number(static_cast<uint8_t>(N)); } else if (N <= 65535) { // str 16 oa->write_character(static_cast<CharType>(0xda)); write_number(static_cast<uint16_t>(N)); } else if (N <= 4294967295) { // str 32 oa->write_character(static_cast<CharType>(0xdb)); write_number(static_cast<uint32_t>(N)); } // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray write_number(static_cast<uint8_t>(0x90 | N)); } else if (N <= 0xffff) { // array 16 oa->write_character(static_cast<CharType>(0xdc)); write_number(static_cast<uint16_t>(N)); } else if (N <= 0xffffffff) { // array 32 oa->write_character(static_cast<CharType>(0xdd)); write_number(static_cast<uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.array) { write_msgpack(el); } break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap write_number(static_cast<uint8_t>(0x80 | (N & 0xf))); } else if (N <= 65535) { // map 16 oa->write_character(static_cast<CharType>(0xde)); write_number(static_cast<uint16_t>(N)); } else if (N <= 4294967295) { // map 32 oa->write_character(static_cast<CharType>(0xdf)); write_number(static_cast<uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.object) { write_msgpack(el.first); write_msgpack(el.second); } break; } default: break; } } private: /* @brief write a number to output input @param[in] n number of type @a NumberType @tparam NumberType the type of the number @note This function needs to respect the system's endianess, because bytes in CBOR and MessagePack are stored in network order (big endian) and therefore need reordering on little endian systems. */ template<typename NumberType> void write_number(NumberType n) { // step 1: write number to array of length NumberType std::array<CharType, sizeof(NumberType)> vec; std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) if (is_little_endian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); } oa->write_characters(vec.data(), sizeof(NumberType)); } private: /// whether we can assume little endianess const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess(); /// the output output_adapter_t<CharType> oa = nullptr; }; /////////////////// // serialization // /////////////////// template<typename BasicJsonType> class serializer { using string_t = typename BasicJsonType::string_t; using number_float_t = typename BasicJsonType::number_float_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; public: /*! @param[in] s output stream to serialize to @param[in] ichar indentation character to use */ serializer(output_adapter_t<char> s, const char ichar) : o(std::move(s)), loc(std::localeconv()), thousands_sep(loc->thousands_sep == nullptr ? '\0' : loc->thousands_sep[0]), decimal_point(loc->decimal_point == nullptr ? '\0' : loc->decimal_point[0]), indent_char(ichar), indent_string(512, indent_char) {} // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format @param[in] val value to serialize @param[in] pretty_print whether the output shall be pretty-printed @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(const BasicJsonType& val, const bool pretty_print, const bool ensure_ascii, const unsigned int indent_step, const unsigned int current_indent = 0) { switch (val.m_type) { case value_t::object: { if (val.m_value.object->empty()) { o->write_characters("{}", 2); return; } if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element assert(i != val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend()); o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_character('{'); // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element assert(i != val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend()); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character('}'); } return; } case value_t::array: { if (val.m_value.array->empty()) { o->write_characters("[]", 2); return; } if (pretty_print) { o->write_characters("[\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { o->write_characters(indent_string.c_str(), new_indent); dump(*i, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element assert(not val.m_value.array->empty()); o->write_characters(indent_string.c_str(), new_indent); dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character(']'); } else { o->write_character('['); // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { dump(*i, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element assert(not val.m_value.array->empty()); dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); o->write_character(']'); } return; } case value_t::string: { o->write_character('\"'); dump_escaped(*val.m_value.string, ensure_ascii); o->write_character('\"'); return; } case value_t::boolean: { if (val.m_value.boolean) { o->write_characters("true", 4); } else { o->write_characters("false", 5); } return; } case value_t::number_integer: { dump_integer(val.m_value.number_integer); return; } case value_t::number_unsigned: { dump_integer(val.m_value.number_unsigned); return; } case value_t::number_float: { dump_float(val.m_value.number_float); return; } case value_t::discarded: { o->write_characters("<discarded>", 11); return; } case value_t::null: { o->write_characters("null", 4); return; } } } private: /*! @brief returns the number of expected bytes following in UTF-8 string @param[in] u the first byte of a UTF-8 string @return the number of expected bytes following */ static constexpr std::size_t bytes_following(const uint8_t u) { return ((0 <= u and u <= 127) ? 0 : ((192 <= u and u <= 223) ? 1 : ((224 <= u and u <= 239) ? 2 : ((240 <= u and u <= 247) ? 3 : std::string::npos)))); } /*! @brief calculates the extra space to escape a JSON string @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @return the number of characters required to escape string @a s @complexity Linear in the length of string @a s. */ static std::size_t extra_space(const string_t& s, const bool ensure_ascii) noexcept { std::size_t res = 0; for (std::size_t i = 0; i < s.size(); ++i) { switch (s[i]) { // control characters that can be escaped with a backslash case '"': case '\\': case '\b': case '\f': case '\n': case '\r': case '\t': { // from c (1 byte) to \x (2 bytes) res += 1; break; } // control characters that need \uxxxx escaping case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x0b: case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f: { // from c (1 byte) to \uxxxx (6 bytes) res += 5; break; } default: { if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)) { const auto bytes = bytes_following(static_cast<uint8_t>(s[i])); if (bytes == std::string::npos) { // invalid characters are treated as is, so no // additional space will be used break; } if (bytes == 3) { // codepoints that need 4 bytes (i.e., 3 additional // bytes) in UTF-8 need a surrogate pair when \u // escaping is used: from 4 bytes to \uxxxx\uxxxx // (12 bytes) res += (12 - bytes - 1); } else { // from x bytes to \uxxxx (6 bytes) res += (6 - bytes - 1); } // skip the additional bytes i += bytes; } break; } } } return res; } static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos) { // expecting a proper codepoint assert(0x00 <= codepoint and codepoint <= 0x10FFFF); // the last written character was the backslash before the 'u' assert(result[pos] == '\\'); // write the 'u' result[++pos] = 'u'; // convert a number 0..15 to its hex representation (0..f) static const std::array<char, 16> hexify = { { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' } }; if (codepoint < 0x10000) { // codepoints U+0000..U+FFFF can be represented as \uxxxx. result[++pos] = hexify[(codepoint >> 12) & 0x0F]; result[++pos] = hexify[(codepoint >> 8) & 0x0F]; result[++pos] = hexify[(codepoint >> 4) & 0x0F]; result[++pos] = hexify[codepoint & 0x0F]; } else { // codepoints U+10000..U+10FFFF need a surrogate pair to be // represented as \uxxxx\uxxxx. // http://www.unicode.org/faq/utf_bom.html#utf16-4 codepoint -= 0x10000; const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF); const int low_surrogate = 0xDC00 | (codepoint & 0x3FF); result[++pos] = hexify[(high_surrogate >> 12) & 0x0F]; result[++pos] = hexify[(high_surrogate >> 8) & 0x0F]; result[++pos] = hexify[(high_surrogate >> 4) & 0x0F]; result[++pos] = hexify[high_surrogate & 0x0F]; ++pos; // backslash is already in output result[++pos] = 'u'; result[++pos] = hexify[(low_surrogate >> 12) & 0x0F]; result[++pos] = hexify[(low_surrogate >> 8) & 0x0F]; result[++pos] = hexify[(low_surrogate >> 4) & 0x0F]; result[++pos] = hexify[low_surrogate & 0x0F]; } ++pos; } /*! @brief dump escaped string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. The escaped string is written to output stream @a o. @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @complexity Linear in the length of string @a s. */ void dump_escaped(const string_t& s, const bool ensure_ascii) const { const auto space = extra_space(s, ensure_ascii); if (space == 0) { o->write_characters(s.c_str(), s.size()); return; } // create a result string of necessary size string_t result(s.size() + space, '\\'); std::size_t pos = 0; for (std::size_t i = 0; i < s.size(); ++i) { switch (s[i]) { case '"': // quotation mark (0x22) { result[pos + 1] = '"'; pos += 2; break; } case '\\': // reverse solidus (0x5c) { // nothing to change pos += 2; break; } case '\b': // backspace (0x08) { result[pos + 1] = 'b'; pos += 2; break; } case '\f': // formfeed (0x0c) { result[pos + 1] = 'f'; pos += 2; break; } case '\n': // newline (0x0a) { result[pos + 1] = 'n'; pos += 2; break; } case '\r': // carriage return (0x0d) { result[pos + 1] = 'r'; pos += 2; break; } case '\t': // horizontal tab (0x09) { result[pos + 1] = 't'; pos += 2; break; } default: { // escape control characters (0x00..0x1F) or, if // ensure_ascii parameter is used, non-ASCII characters if ((0x00 <= s[i] and s[i] <= 0x1F) or (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))) { const auto bytes = bytes_following(static_cast<uint8_t>(s[i])); if (bytes == std::string::npos) { // copy invalid character as is result[pos++] = s[i]; break; } // check that the additional bytes are present assert(i + bytes < s.size()); // to use \uxxxx escaping, we first need to caluclate // the codepoint from the UTF-8 bytes int codepoint = 0; assert(0 <= bytes and bytes <= 3); switch (bytes) { case 0: { codepoint = s[i] & 0xFF; break; } case 1: { codepoint = ((s[i] & 0x3F) << 6) + (s[i + 1] & 0x7F); break; } case 2: { codepoint = ((s[i] & 0x1F) << 12) + ((s[i + 1] & 0x7F) << 6) + (s[i + 2] & 0x7F); break; } case 3: { codepoint = ((s[i] & 0xF) << 18) + ((s[i + 1] & 0x7F) << 12) + ((s[i + 2] & 0x7F) << 6) + (s[i + 3] & 0x7F); break; } default: break; // LCOV_EXCL_LINE } escape_codepoint(codepoint, result, pos); i += bytes; } else { // all other characters are added as-is result[pos++] = s[i]; } break; } } } assert(pos == result.size()); o->write_characters(result.c_str(), result.size()); } /*! @brief dump an integer Dump a given integer to output stream @a o. Works internally with @a number_buffer. @param[in] x integer number (signed or unsigned) to dump @tparam NumberType either @a number_integer_t or @a number_unsigned_t */ template < typename NumberType, detail::enable_if_t<std::is_same<NumberType, number_unsigned_t>::value or std::is_same<NumberType, number_integer_t>::value, int> = 0 > void dump_integer(NumberType x) { // special case for "0" if (x == 0) { o->write_character('0'); return; } const bool is_negative = x < 0; std::size_t i = 0; // spare 1 byte for '\0' while (x != 0 and i < number_buffer.size() - 1) { const auto digit = std::labs(static_cast<long>(x % 10)); number_buffer[i++] = static_cast<char>('0' + digit); x /= 10; } // make sure the number has been processed completely assert(x == 0); if (is_negative) { // make sure there is capacity for the '-' assert(i < number_buffer.size() - 2); number_buffer[i++] = '-'; } std::reverse(number_buffer.begin(), number_buffer.begin() + i); o->write_characters(number_buffer.data(), i); } /*! @brief dump a floating-point number Dump a given floating-point number to output stream @a o. Works internally with @a number_buffer. @param[in] x floating-point number to dump */ void dump_float(number_float_t x) { // NaN / inf if (not std::isfinite(x) or std::isnan(x)) { o->write_characters("null", 4); return; } // special case for 0.0 and -0.0 if (x == 0) { if (std::signbit(x)) { o->write_characters("-0.0", 4); } else { o->write_characters("0.0", 3); } return; } // get number of digits for a text -> float -> text round-trip static constexpr auto d = std::numeric_limits<number_float_t>::digits10; // the actual conversion std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x); // negative value indicates an error assert(len > 0); // check if buffer was large enough assert(static_cast<std::size_t>(len) < number_buffer.size()); // erase thousands separator if (thousands_sep != '\0') { const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); std::fill(end, number_buffer.end(), '\0'); assert((end - number_buffer.begin()) <= len); len = (end - number_buffer.begin()); } // convert decimal point to '.' if (decimal_point != '\0' and decimal_point != '.') { const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); if (dec_pos != number_buffer.end()) { *dec_pos = '.'; } } o->write_characters(number_buffer.data(), static_cast<std::size_t>(len)); // determine if need to append ".0" const bool value_is_int_like = std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return (c == '.' or c == 'e'); }); if (value_is_int_like) { o->write_characters(".0", 2); } } private: /// the output of the serializer output_adapter_t<char> o = nullptr; /// a (hopefully) large enough character buffer std::array<char, 64> number_buffer{{}}; /// the locale const std::lconv* loc = nullptr; /// the locale's thousand separator character const char thousands_sep = '\0'; /// the locale's decimal point character const char decimal_point = '\0'; /// the indentation character const char indent_char; /// the indentation string string_t indent_string; }; template<typename BasicJsonType> class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true) {} json_ref(const value_type& value) : value_ref(const_cast<value_type*>(&value)), is_rvalue(false) {} json_ref(std::initializer_list<json_ref> init) : owned_value(init), value_ref(&owned_value), is_rvalue(true) {} template <class... Args> json_ref(Args... args) : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true) {} // class should be movable only json_ref(json_ref&&) = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; value_type moved_or_copied() const { if (is_rvalue) { return std::move(*value_ref); } return *value_ref; } value_type const& operator*() const { return *static_cast<value_type const*>(value_ref); } value_type const* operator->() const { return static_cast<value_type const*>(value_ref); } private: mutable value_type owned_value = nullptr; value_type* value_ref = nullptr; const bool is_rvalue; }; } // namespace detail /// namespace to hold default `to_json` / `from_json` functions namespace { constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; } /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template<typename, typename> struct adl_serializer { /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @param[in] j JSON value to read from @param[in,out] val value to write to */ template<typename BasicJsonType, typename ValueType> static void from_json(BasicJsonType&& j, ValueType& val) noexcept( noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val))) { ::nlohmann::from_json(std::forward<BasicJsonType>(j), val); } /*! @brief convert any value type to a JSON value This function is usually called by the constructors of the @ref basic_json class. @param[in,out] j JSON value to write to @param[in] val value to read from */ template<typename BasicJsonType, typename ValueType> static void to_json(BasicJsonType& j, ValueType&& val) noexcept( noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val)))) { ::nlohmann::to_json(j, std::forward<ValueType>(val)); } }; /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ class json_pointer { /// allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; public: /*! @brief create JSON pointer Create a JSON pointer according to the syntax described in [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). @param[in] s string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value @throw parse_error.107 if the given JSON pointer @a s is nonempty and does not begin with a slash (`/`); see example below @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is not followed by `0` (representing `~`) or `1` (representing `/`); see example below @liveexample{The example shows the construction several valid JSON pointers as well as the exceptional behavior.,json_pointer} @since version 2.0.0 */ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /*! @brief return a string representation of the JSON pointer @invariant For each JSON pointer `ptr`, it holds: @code {.cpp} ptr == json_pointer(ptr.to_string()); @endcode @return a string representation of the JSON pointer @liveexample{The example shows the result of `to_string`., json_pointer__to_string} @since version 2.0.0 */ std::string to_string() const noexcept { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + escape(b); }); } /// @copydoc to_string() operator std::string() const { return to_string(); } private: /*! @brief remove and return last reference pointer @throw out_of_range.405 if JSON pointer has no parent */ std::string pop_back() { if (JSON_UNLIKELY(is_root())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } auto last = reference_tokens.back(); reference_tokens.pop_back(); return last; } /// return whether pointer points to the root document bool is_root() const { return reference_tokens.empty(); } json_pointer top() const { if (JSON_UNLIKELY(is_root())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const; /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const; /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector<std::string> split(const std::string& reference_string) { std::vector<std::string> result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'")); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == string::npos+1 = 0 start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { assert(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_UNLIKELY(pos == reference_token.size() - 1 or (reference_token[pos + 1] != '0' and reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); } } // finally, store the reference token unescape(reference_token); result.push_back(reference_token); } return result; } /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. **This precondition is enforced with an assertion.** @since version 2.0.0 */ static void replace_substring(std::string& s, const std::string& f, const std::string& t) { assert(not f.empty()); for (auto pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} } /// escape "~"" to "~0" and "/" to "~1" static std::string escape(std::string s) { replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /// unescape "~1" to tilde and "~0" to slash (order is important!) static void unescape(std::string& s) { replace_substring(s, "~1", "/"); replace_substring(s, "~0", "~"); } /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ NLOHMANN_BASIC_JSON_TPL_DECLARATION static void flatten(const std::string& reference_string, const NLOHMANN_BASIC_JSON_TPL& value, NLOHMANN_BASIC_JSON_TPL& result); /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ NLOHMANN_BASIC_JSON_TPL_DECLARATION static NLOHMANN_BASIC_JSON_TPL unflatten(const NLOHMANN_BASIC_JSON_TPL& value); friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept; friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept; /// the reference tokens std::vector<std::string> reference_tokens; }; /*! @brief a class to store JSON values @tparam ObjectType type for JSON objects (`std::map` by default; will be used in @ref object_t) @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used in @ref array_t) @tparam StringType type for JSON strings and object keys (`std::string` by default; will be used in @ref string_t) @tparam BooleanType type for JSON booleans (`bool` by default; will be used in @ref boolean_t) @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by default; will be used in @ref number_integer_t) @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c `uint64_t` by default; will be used in @ref number_unsigned_t) @tparam NumberFloatType type for JSON floating-point numbers (`double` by default; will be used in @ref number_float_t) @tparam AllocatorType type of the allocator to use (`std::allocator` by default) @tparam JSONSerializer the serializer to resolve internal calls to `to_json()` and `from_json()` (@ref adl_serializer by default) @requirement The class satisfies the following concept requirements: - Basic - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible): JSON values can be default constructed. The result will be a JSON null value. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible): A JSON value can be constructed from an rvalue argument. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible): A JSON value can be copy-constructed from an lvalue expression. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable): A JSON value van be assigned from an rvalue argument. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable): A JSON value can be copy-assigned from an lvalue expression. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible): JSON values can be destructed. - Layout - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType): JSON values have [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes. - Library-wide - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable): JSON values can be compared with `==`, see @ref operator==(const_reference,const_reference). - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable): JSON values can be compared with `<`, see @ref operator<(const_reference,const_reference). - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable): Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function call @ref swap(). - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer): JSON values can be compared against `std::nullptr_t` objects which are used to model the `null` value. - Container - [Container](http://en.cppreference.com/w/cpp/concept/Container): JSON values can be used like STL containers and provide iterator access. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer); JSON values can be used like STL containers and provide reverse iterator access. @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @internal @note ObjectType trick from http://stackoverflow.com/a/9860911 @endinternal @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://rfc7159.net/rfc7159) @since version 1.0.0 @nosubgrouping */ NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json { private: template<detail::value_t> friend struct detail::external_constructor; friend ::nlohmann::json_pointer; friend ::nlohmann::detail::parser<basic_json>; friend ::nlohmann::detail::serializer<basic_json>; template<typename BasicJsonType> friend class ::nlohmann::detail::iter_impl; template<typename BasicJsonType, typename CharType> friend class ::nlohmann::detail::binary_writer; template<typename BasicJsonType> friend class ::nlohmann::detail::binary_reader; /// workaround type for MSVC using basic_json_t = NLOHMANN_BASIC_JSON_TPL; // convenience aliases for types residing in namespace detail; using lexer = ::nlohmann::detail::lexer<basic_json>; using parser = ::nlohmann::detail::parser<basic_json>; using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; template<typename BasicJsonType> using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>; template<typename BasicJsonType> using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>; template<typename Iterator> using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>; template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>; template<typename CharType> using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>; using binary_reader = ::nlohmann::detail::binary_reader<basic_json>; template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>; using serializer = ::nlohmann::detail::serializer<basic_json>; public: using value_t = detail::value_t; // forward declarations using json_pointer = ::nlohmann::json_pointer; template<typename T, typename SFINAE> using json_serializer = JSONSerializer<T, SFINAE>; using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>; //////////////// // exceptions // //////////////// /// @name exceptions /// Classes to implement user-defined exceptions. /// @{ /// @copydoc detail::exception using exception = detail::exception; /// @copydoc detail::parse_error using parse_error = detail::parse_error; /// @copydoc detail::invalid_iterator using invalid_iterator = detail::invalid_iterator; /// @copydoc detail::type_error using type_error = detail::type_error; /// @copydoc detail::out_of_range using out_of_range = detail::out_of_range; /// @copydoc detail::other_error using other_error = detail::other_error; /// @} ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType<basic_json>; /// the type of an element pointer using pointer = typename std::allocator_traits<allocator_type>::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl<basic_json>; /// a const iterator for a basic_json container using const_iterator = iter_impl<const basic_json>; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>; /// @} /*! @brief returns the allocator associated with the container */ static allocator_type get_allocator() { return allocator_type(); } /*! @brief returns version information on the library This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. @return JSON object holding version information key | description ----------- | --------------- `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). `copyright` | The copyright line for the library as string. `name` | The name of the library as string. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. `url` | The URL of the project as string. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). @liveexample{The following code shows an example output of the `meta()` function.,meta} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @complexity Constant. @since 2.1.0 */ static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2017 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"] = { {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1} }; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ /*! @brief a type for an object [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, > where a name is a string and a value is a string, number, boolean, null, > object, or array. To store objects in C++, a type is defined by the template parameters described below. @tparam ObjectType the container to store objects (e.g., `std::map` or `std::unordered_map`) @tparam StringType the type of the keys or names (e.g., `std::string`). The comparison function `std::less<StringType>` is used to order elements inside the container. @tparam AllocatorType the allocator to use for objects (e.g., `std::allocator`) #### Default type With the default values for @a ObjectType (`std::map`), @a StringType (`std::string`), and @a AllocatorType (`std::allocator`), the default value for @a object_t is: @code {.cpp} std::map< std::string, // key_type basic_json, // value_type std::less<std::string>, // key_compare std::allocator<std::pair<const std::string, basic_json>> // allocator_type > @endcode #### Behavior The choice of @a object_t influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, later stored name/value pairs overwrite previously stored name/value pairs, leaving the used names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will be treated as equal and both stored as `{"key": 1}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see @ref dump) in this order. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and serialized as `{"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be treated as equal. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON object. #### Storage Objects are stored as pointers in a @ref basic_json type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. @sa @ref array_t -- type for an array value @since version 1.0.0 @note The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 7159](http://rfc7159.net/rfc7159), because any order implements the specified "unordered" nature of JSON objects. */ using object_t = ObjectType<StringType, basic_json, std::less<StringType>, AllocatorType<std::pair<const StringType, basic_json>>>; /*! @brief a type for an array [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. To store objects in C++, a type is defined by the template parameters explained below. @tparam ArrayType container type to store arrays (e.g., `std::vector` or `std::list`) @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) #### Default type With the default values for @a ArrayType (`std::vector`) and @a AllocatorType (`std::allocator`), the default value for @a array_t is: @code {.cpp} std::vector< basic_json, // value_type std::allocator<basic_json> // allocator_type > @endcode #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON array. #### Storage Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. @sa @ref object_t -- type for an object value @since version 1.0.0 */ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; /*! @brief a type for a string [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. @tparam StringType the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see @ref object_t. #### Default type With the default values for @a StringType (`std::string`), the default value for @a string_t is: @code {.cpp} std::string @endcode #### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of bytes in the string rather than the number of characters or glyphs. #### String comparison [RFC 7159](http://rfc7159.net/rfc7159) states: > Software implementations are typically required to test names of object > members for equality. Implementations that transform the textual > representation into sequences of Unicode code units and then perform the > comparison numerically, code unit by code unit, are interoperable in the > sense that implementations will agree in all cases on equality or > inequality of two strings. For example, implementations that compare > strings with escaped characters unconverted may incorrectly find that > `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. #### Storage String values are stored as pointers in a @ref basic_json type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. @since version 1.0.0 */ using string_t = StringType; /*! @brief a type for a boolean [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. To store objects in C++, a type is defined by the template parameter @a BooleanType which chooses the type to use. #### Default type With the default values for @a BooleanType (`bool`), the default value for @a boolean_t is: @code {.cpp} bool @endcode #### Storage Boolean values are stored directly inside a @ref basic_json type. @since version 1.0.0 */ using boolean_t = BooleanType; /*! @brief a type for a number (integer) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter @a NumberIntegerType which chooses the type to use. #### Default type With the default values for @a NumberIntegerType (`int64_t`), the default value for @a number_integer_t is: @code {.cpp} int64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `9223372036854775807` (INT64_MAX) and the minimal integer number that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_unsigned_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_integer_t = NumberIntegerType; /*! @brief a type for a number (unsigned) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter @a NumberUnsignedType which chooses the type to use. #### Default type With the default values for @a NumberUnsignedType (`uint64_t`), the default value for @a number_unsigned_t is: @code {.cpp} uint64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `18446744073709551615` (UINT64_MAX) and the minimal integer number that can be stored is `0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_integer_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_integer_t -- type for number values (integer) @since version 2.0.0 */ using number_unsigned_t = NumberUnsignedType; /*! @brief a type for a number (floating-point) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store floating-point numbers in C++, a type is defined by the template parameter @a NumberFloatType which chooses the type to use. #### Default type With the default values for @a NumberFloatType (`double`), the default value for @a number_float_t is: @code {.cpp} double @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) states: > This specification allows implementations to set limits on the range and > precision of numbers accepted. Since software that implements IEEE > 754-2008 binary64 (double precision) numbers is generally available and > widely used, good interoperability can be achieved by implementations > that expect no more precision or range than these provide, in the sense > that implementations will approximate JSON numbers within the expected > precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a @ref basic_json type. @sa @ref number_integer_t -- type for number values (integer) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_float_t = NumberFloatType; /// @} private: /// helper for exception-safe object creation template<typename T, typename... Args> static T* create(Args&& ... args) { AllocatorType<T> alloc; auto deleter = [&](T * object) { alloc.deallocate(object, 1); }; std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter); alloc.construct(object.get(), std::forward<Args>(args)...); assert(object != nullptr); return object.release(); } //////////////////////// // JSON value storage // //////////////////////// /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create<object_t>(); break; } case value_t::array: { array = create<array_t>(); break; } case value_t::string: { string = create<string_t>(""); break; } case value_t::boolean: { boolean = boolean_t(false); break; } case value_t::number_integer: { number_integer = number_integer_t(0); break; } case value_t::number_unsigned: { number_unsigned = number_unsigned_t(0); break; } case value_t::number_float: { number_float = number_float_t(0.0); break; } case value_t::null: { break; } default: { if (JSON_UNLIKELY(t == value_t::null)) { JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) { string = create<string_t>(value); } /// constructor for rvalue strings json_value(string_t&& value) { string = create<string_t>(std::move(value)); } /// constructor for objects json_value(const object_t& value) { object = create<object_t>(value); } /// constructor for rvalue objects json_value(object_t&& value) { object = create<object_t>(std::move(value)); } /// constructor for arrays json_value(const array_t& value) { array = create<array_t>(value); } /// constructor for rvalue arrays json_value(array_t&& value) { array = create<array_t>(std::move(value)); } void destroy(value_t t) { switch (t) { case value_t::object: { AllocatorType<object_t> alloc; alloc.destroy(object); alloc.deallocate(object, 1); break; } case value_t::array: { AllocatorType<array_t> alloc; alloc.destroy(array); alloc.deallocate(array, 1); break; } case value_t::string: { AllocatorType<string_t> alloc; alloc.destroy(string); alloc.deallocate(string, 1); break; } default: { break; } } } }; /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. */ void assert_invariant() const { assert(m_type != value_t::object or m_value.object != nullptr); assert(m_type != value_t::array or m_value.array != nullptr); assert(m_type != value_t::string or m_value.string != nullptr); } public: ////////////////////////// // JSON parser callback // ////////////////////////// using parse_event_t = typename parser::parse_event_t; /*! @brief per-element parser callback type With a parser callback function, the result of parsing a JSON text can be influenced. When passed to @ref parse(std::istream&, const parser_callback_t) or @ref parse(const CharT, const parser_callback_t), it is called on certain events (passed as @ref parse_event_t via parameter @a event) with a set recursion depth @a depth and context JSON value @a parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters @a depth, @a event, and @a parsed. parameter @a event | description | parameter @a depth | parameter @a parsed ------------------ | ----------- | ------------------ | ------------------- parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value @image html callback_events.png "Example when certain parse events are triggered" Discarding a value (i.e., returning `false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. @param[in] depth the depth of the recursion during parsing @param[in] event an event of type parse_event_t indicating the context in the callback function has been called @param[in,out] parsed the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events @return Whether the JSON value which called the function during parsing should be kept (`true`) or not (`false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. @sa @ref parse(std::istream&, parser_callback_t) or @ref parse(const CharT, const parser_callback_t) for examples @since version 1.0.0 */ using parser_callback_t = typename parser::parser_callback_t; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /*! @brief create an empty value with a given type Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @param[in] v the type of the value to create @complexity Constant. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor for different @ref value_t values,basic_json__value_t} @sa @ref clear() -- restores the postcondition of this constructor @since version 1.0.0 */ basic_json(const value_t v) : m_type(v), m_value(v) { assert_invariant(); } /*! @brief create a null object Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @liveexample{The following code shows the constructor with and without a null pointer parameter.,basic_json__nullptr_t} @since version 1.0.0 */ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /*! @brief create a JSON value This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exsits. The constructor forwards the parameter @a val to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact). Template type @a CompatibleType includes, but is not limited to, the following types: - **arrays**: @ref array_t and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a @ref basic_json value can be constructed. - **objects**: @ref object_t and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to @ref string_t and a `value_type` from which a @ref basic_json value can be constructed. - **strings**: @ref string_t, string literals, and all compatible string containers can be used. - **numbers**: @ref number_integer_t, @ref number_unsigned_t, @ref number_float_t, and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: @ref boolean_t / `bool` can be used. See the examples below. @tparam CompatibleType a type such that: - @a CompatibleType is not derived from `std::istream`, - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move constructors), - @a CompatibleType is not a @ref basic_json nested type (e.g., @ref json_pointer, @ref iterator, etc ...) - @ref @ref json_serializer<U> has a `to_json(basic_json_t&, CompatibleType&&)` method @tparam U = `uncvref_t<CompatibleType>` @param[in] val the value to be forwarded to the respective constructor @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor with several compatible types.,basic_json__CompatibleType} @since version 2.1.0 */ template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t<not std::is_base_of<std::istream, U>::value and not std::is_same<U, basic_json_t>::value and not detail::is_basic_json_nested_type< basic_json_t, U>::value and detail::has_to_json<basic_json, U>::value, int> = 0> basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json( std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) { JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); assert_invariant(); } /*! @brief create a container (array or object) from an initializer list Creates a JSON value of type array or object from the passed initializer list @a init. In case @a type_deduction is `true` (default), the type of the JSON value to be created is deducted from the initializer list @a init according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `{}` which is exactly an empty JSON object. 2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`[]`): use @ref array(initializer_list_t) with an empty initializer list in this case - arrays whose elements satisfy rule 2: use @ref array(initializer_list_t) with the same initializer list in this case @note When used without parentheses around an empty initializer list, @ref basic_json() is called instead of this function, yielding the JSON null value. @param[in] init initializer list with JSON values @param[in] type_deduction internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list @a init; when set to `false`, the type provided via @a manual_type is forced. This mode is used by the functions @ref array(initializer_list_t) and @ref object(initializer_list_t). @param[in] manual_type internal parameter; when @a type_deduction is set to `false`, the created JSON value will use the provided type (only @ref value_t::array and @ref value_t::object are valid); when @a type_deduction is set to `true`, this parameter has no effect @throw type_error.301 if @a type_deduction is `false`, @a manual_type is `value_t::object`, but @a init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If @a type_deduction would have be `true`, an array would have been created. See @ref object(initializer_list_t) for an example. @complexity Linear in the size of the initializer list @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows how JSON values are created from initializer lists.,basic_json__list_init_t} @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref<basic_json>& element_ref) { return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string()); }); // adjust type if type deduction is not wanted if (not type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list")); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref) { auto element = element_ref.moved_or_copied(); m_value.object->emplace( std::move(*((*element.m_value.array)[0].m_value.string)), std::move((*element.m_value.array)[1])); }); } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create<array_t>(init.begin(), init.end()); } assert_invariant(); } /*! @brief explicitly create an array from an initializer list Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created. @note This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (@ref basic_json(initializer_list_t, bool, value_t)). These cases are: 1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys 2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object @param[in] init initializer list with JSON values to create an array from (optional) @return JSON array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `array` function.,array} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ static basic_json array(initializer_list_t init = {}) { return basic_json(init, false, value_t::array); } /*! @brief explicitly create an object from an initializer list Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object `{}` is created. @note This function is only added for symmetry reasons. In contrast to the related function @ref array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list @a init can also be passed to the initializer list constructor @ref basic_json(initializer_list_t, bool, value_t). @param[in] init initializer list to create an object from (optional) @return JSON object value @throw type_error.301 if @a init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to @ref basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list @a init. See example below. @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `object` function.,object} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @since version 1.0.0 */ static basic_json object(initializer_list_t init = {}) { return basic_json(init, false, value_t::object); } /*! @brief construct an array with count copies of given value Constructs a JSON array value by creating @a cnt copies of a passed value. In case @a cnt is `0`, an empty array is created. @param[in] cnt the number of JSON copies of @a val to create @param[in] val the JSON value to copy @post `std::distance(begin(),end()) == cnt` holds. @complexity Linear in @a cnt. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows examples for the @ref basic_json(size_type\, const basic_json&) constructor.,basic_json__size_type_basic_json} @since version 1.0.0 */ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create<array_t>(cnt, val); assert_invariant(); } /*! @brief construct a JSON container given an iterator range Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of a null type, invalid_iterator.206 is thrown. - In case of other primitive types (number, boolean, or string), @a first must be `begin()` and @a last must be `end()`. In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range. @tparam InputIT an input iterator type (@ref iterator or @ref const_iterator) @param[in] first begin of the range to copy from (included) @param[in] last end of the range to copy from (excluded) @pre Iterators @a first and @a last must be initialized. **This precondition is enforced with an assertion (see warning).** If assertions are switched off, a violation of this precondition yields undefined behavior. @pre Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions below. A violation of this precondition yields undefined behavior. @warning A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See http://en.cppreference.com/w/cpp/error/assert for more information. @throw invalid_iterator.201 if iterators @a first and @a last are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined. @throw invalid_iterator.204 if iterators @a first and @a last belong to a primitive type (number, boolean, or string), but @a first does not point to the first element any more. In this case, the range `[first, last)` is undefined. See example code below. @throw invalid_iterator.206 if iterators @a first and @a last belong to a null value. In this case, the range `[first, last)` is undefined. @complexity Linear in distance between @a first and @a last. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows several ways to create JSON values by specifying a subrange with iterators.,basic_json__InputIt_InputIt} @since version 1.0.0 */ template<class InputIT, typename std::enable_if< std::is_same<InputIT, typename basic_json_t::iterator>::value or std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0> basic_json(InputIT first, InputIT last) { assert(first.m_object != nullptr); assert(last.m_object != nullptr); // make sure iterator fits the current value if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } break; } default: break; } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()))); } assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// /// @private basic_json(const detail::json_ref<basic_json>& ref) : basic_json(ref.moved_or_copied()) {} /*! @brief copy constructor Creates a copy of a given JSON value. @param[in] other the JSON value to copy @post `*this == other` @complexity Linear in the size of @a other. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. - As postcondition, it holds: `other == basic_json(other)`. @liveexample{The following code shows an example for the copy constructor.,basic_json__basic_json} @since version 1.0.0 */ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } default: break; } assert_invariant(); } /*! @brief move constructor Move constructor. Constructs a JSON value with the contents of the given value @a other using move semantics. It "steals" the resources from @a other and leaves it as JSON null value. @param[in,out] other value to move to this object @post `*this` has the same value as @a other before the call. @post @a other is a JSON null value. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @requirement This function helps `basic_json` satisfying the [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible) requirements. @liveexample{The code below shows the move constructor explicitly called via std::move.,basic_json__moveconstructor} @since version 1.0.0 */ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(); // invalidate payload other.m_type = value_t::null; other.m_value = {}; assert_invariant(); } /*! @brief copy assignment Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the `swap()` member function. @param[in] other value to copy from @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. @liveexample{The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally\, the copy of `a` (which is the null value after the swap) is destroyed.,basic_json__copyassignment} @since version 1.0.0 */ reference& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); assert_invariant(); return *this; } /*! @brief destructor Destroys the JSON value and frees all allocated memory. @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is linear. - All stored elements are destroyed and all memory is freed. @since version 1.0.0 */ ~basic_json() { assert_invariant(); m_value.destroy(m_type); } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /*! @brief serialization Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently supports its @a indent and @a ensure_ascii parameters. @param[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation. @param[in] indent_char The character to use for indentation if @a indent is greater than `0`. The default is ` ` (space). @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result consists of ASCII characters only. @return string containing the serialization of the JSON value @complexity Linear. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @liveexample{The following example shows the effect of different @a indent\, @a indent_char\, and @a ensure_ascii parameters to the result of the serialization.,dump} @see https://docs.python.org/2/library/json.html#json.dump @since version 1.0.0; indentation character @a indent_char and option @a ensure_ascii added in version 3.0.0 */ string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false) const { string_t result; serializer s(detail::output_adapter<char>(result), indent_char); if (indent >= 0) { s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent)); } else { s.dump(*this, false, ensure_ascii, 0); } return result; } /*! @brief return the type of the JSON value (explicit) Return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value Value type | return value ------------------------- | ------------------------- null | value_t::null boolean | value_t::boolean string | value_t::string number (integer) | value_t::number_integer number (unsigned integer) | value_t::number_unsigned number (foating-point) | value_t::number_float object | value_t::object array | value_t::array discarded | value_t::discarded @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `type()` for all JSON types.,type} @sa @ref operator value_t() -- return the type of the JSON value (implicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr value_t type() const noexcept { return m_type; } /*! @brief return whether type is primitive This function returns true if and only if the JSON type is primitive (string, number, boolean, or null). @return `true` if type is primitive (string, number, boolean, or null), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_primitive()` for all JSON types.,is_primitive} @sa @ref is_structured() -- returns whether JSON value is structured @sa @ref is_null() -- returns whether JSON value is `null` @sa @ref is_string() -- returns whether JSON value is a string @sa @ref is_boolean() -- returns whether JSON value is a boolean @sa @ref is_number() -- returns whether JSON value is a number @since version 1.0.0 */ constexpr bool is_primitive() const noexcept { return is_null() or is_string() or is_boolean() or is_number(); } /*! @brief return whether type is structured This function returns true if and only if the JSON type is structured (array or object). @return `true` if type is structured (array or object), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_structured()` for all JSON types.,is_structured} @sa @ref is_primitive() -- returns whether value is primitive @sa @ref is_array() -- returns whether value is an array @sa @ref is_object() -- returns whether value is an object @since version 1.0.0 */ constexpr bool is_structured() const noexcept { return is_array() or is_object(); } /*! @brief return whether value is null This function returns true if and only if the JSON value is null. @return `true` if type is null, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_null()` for all JSON types.,is_null} @since version 1.0.0 */ constexpr bool is_null() const noexcept { return (m_type == value_t::null); } /*! @brief return whether value is a boolean This function returns true if and only if the JSON value is a boolean. @return `true` if type is boolean, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_boolean()` for all JSON types.,is_boolean} @since version 1.0.0 */ constexpr bool is_boolean() const noexcept { return (m_type == value_t::boolean); } /*! @brief return whether value is a number This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. @return `true` if type is number (regardless whether integer, unsigned integer or floating-type), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number()` for all JSON types.,is_number} @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number() const noexcept { return is_number_integer() or is_number_float(); } /*! @brief return whether value is an integer number This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. @return `true` if type is an integer or unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_integer()` for all JSON types.,is_number_integer} @sa @ref is_number() -- check if value is a number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number_integer() const noexcept { return (m_type == value_t::number_integer or m_type == value_t::number_unsigned); } /*! @brief return whether value is an unsigned integer number This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. @return `true` if type is an unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_unsigned()` for all JSON types.,is_number_unsigned} @sa @ref is_number() -- check if value is a number @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 2.0.0 */ constexpr bool is_number_unsigned() const noexcept { return (m_type == value_t::number_unsigned); } /*! @brief return whether value is a floating-point number This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. @return `true` if type is a floating-point number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_float()` for all JSON types.,is_number_float} @sa @ref is_number() -- check if value is number @sa @ref is_number_integer() -- check if value is an integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @since version 1.0.0 */ constexpr bool is_number_float() const noexcept { return (m_type == value_t::number_float); } /*! @brief return whether value is an object This function returns true if and only if the JSON value is an object. @return `true` if type is object, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_object()` for all JSON types.,is_object} @since version 1.0.0 */ constexpr bool is_object() const noexcept { return (m_type == value_t::object); } /*! @brief return whether value is an array This function returns true if and only if the JSON value is an array. @return `true` if type is array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_array()` for all JSON types.,is_array} @since version 1.0.0 */ constexpr bool is_array() const noexcept { return (m_type == value_t::array); } /*! @brief return whether value is a string This function returns true if and only if the JSON value is a string. @return `true` if type is string, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_string()` for all JSON types.,is_string} @since version 1.0.0 */ constexpr bool is_string() const noexcept { return (m_type == value_t::string); } /*! @brief return whether value is discarded This function returns true if and only if the JSON value was discarded during parsing with a callback function (see @ref parser_callback_t). @note This function will always be `false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. @return `true` if type is discarded, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_discarded()` for all JSON types.,is_discarded} @since version 1.0.0 */ constexpr bool is_discarded() const noexcept { return (m_type == value_t::discarded); } /*! @brief return the type of the JSON value (implicit) Implicitly return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies the @ref value_t operator for all JSON types.,operator__value_t} @sa @ref type() -- return the type of the JSON value (explicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (JSON_LIKELY(is_boolean())) { return m_value.boolean; } JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /*! @brief helper function to implement get_ref() This function helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw type_error.303 if ReferenceType does not match underlying value type of the current JSON */ template<typename ReferenceType, typename ThisType> static ReferenceType get_ref_impl(ThisType& obj) { // delegate the call to get_ptr<>() auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>(); if (JSON_LIKELY(ptr != nullptr)) { return *ptr; } JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template < typename BasicJsonType, detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value, int> = 0 > basic_json get() const { return *this; } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and - @ref json_serializer<ValueType> does not have a `from_json()` method of the form `ValueType from_json(const basic_json&)` @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get__ValueType_const} @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t < not std::is_same<basic_json_t, ValueType>::value and detail::has_from_json<basic_json_t, ValueType>::value and not detail::has_non_default_from_json<basic_json_t, ValueType>::value, int > = 0 > ValueType get() const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get<const basic_json_t>(), which is why we // still need the uncvref static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); static_assert(std::is_default_constructible<ValueType>::value, "types must be DefaultConstructible when used with get()"); ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible) and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer<ValueTypeCV>::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer<ValueType> has a `from_json()` method of the form `ValueType from_json(const basic_json&)` @note If @ref json_serializer<ValueType> has both overloads of `from_json()`, this one is chosen. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and detail::has_non_default_from_json<basic_json_t, ValueType>::value, int> = 0 > ValueType get() const noexcept(noexcept( JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>()))) { static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); return JSONSerializer<ValueTypeCV>::from_json(*this); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> PointerType get() noexcept { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (explicit) @copydoc get() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> constexpr const PointerType get() const noexcept { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made. @warning Writing data to the pointee of the result yields an undefined state. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. Enforced by a static assertion. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get_ptr} @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> PointerType get_ptr() noexcept { // get the type of the PointerType (remove pointer and const) using pointee_t = typename std::remove_const<typename std::remove_pointer<typename std::remove_const<PointerType>::type>::type>::type; // make sure the type matches the allowed types static_assert( std::is_same<object_t, pointee_t>::value or std::is_same<array_t, pointee_t>::value or std::is_same<string_t, pointee_t>::value or std::is_same<boolean_t, pointee_t>::value or std::is_same<number_integer_t, pointee_t>::value or std::is_same<number_unsigned_t, pointee_t>::value or std::is_same<number_float_t, pointee_t>::value , "incompatible pointer type"); // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a pointer value (implicit) @copydoc get_ptr() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value and std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0> constexpr const PointerType get_ptr() const noexcept { // get the type of the PointerType (remove pointer and const) using pointee_t = typename std::remove_const<typename std::remove_pointer<typename std::remove_const<PointerType>::type>::type>::type; // make sure the type matches the allowed types static_assert( std::is_same<object_t, pointee_t>::value or std::is_same<array_t, pointee_t>::value or std::is_same<string_t, pointee_t>::value or std::is_same<boolean_t, pointee_t>::value or std::is_same<number_integer_t, pointee_t>::value or std::is_same<number_unsigned_t, pointee_t>::value or std::is_same<number_float_t, pointee_t>::value , "incompatible pointer type"); // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast<const PointerType>(nullptr)); } /*! @brief get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made. @warning Writing data to the referee of the result yields an undefined state. @tparam ReferenceType reference type; must be a reference to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref number_float_t. Enforced by static assertion. @return reference to the internally stored JSON value if the requested reference type @a ReferenceType fits to the JSON value; throws type_error.303 otherwise @throw type_error.303 in case passed type @a ReferenceType is incompatible with the stored JSON value; see example below @complexity Constant. @liveexample{The example shows several calls to `get_ref()`.,get_ref} @since version 1.1.0 */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a reference value (implicit) @copydoc get_ref() */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value and std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0> ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw type_error.302 in case passed type @a ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < not std::is_pointer<ValueType>::value and not std::is_same<ValueType, detail::json_ref<basic_json>>::value and not std::is_same<ValueType, typename string_t::value_type>::value #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value #endif #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSC_VER) && _MSC_VER >1900 && defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 and not std::is_same<ValueType, typename std::string_view>::value #endif , int >::type = 0 > operator ValueType() const { // delegate the call to get<>() const return get<ValueType>(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /*! @brief access specified array element with bounds checking Returns a reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__size_type} */ reference at(size_type idx) { // at only works for arrays if (JSON_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element with bounds checking Returns a const reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__size_type_const} */ const_reference at(size_type idx) const { // at only works for arrays if (JSON_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__object_t_key_type} */ reference at(const typename object_t::key_type& key) { // at only works for objects if (JSON_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a const reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return const reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__object_t_key_type_const} */ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (JSON_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element Returns a reference to the element at specified location @a idx. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), then the array is silently filled up with `null` values to make `idx` a valid reference to the last stored element. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array or null; in that cases, using the [] operator with an index makes no sense. @complexity Constant if @a idx is in the range of the array. Otherwise linear in `idx - size()`. @liveexample{The example below shows how array elements can be read and written using `[]` operator. Note the addition of `null` values.,operatorarray__size_type} @since version 1.0.0 */ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create<array_t>(); assert_invariant(); } // operator[] only works for arrays if (JSON_LIKELY(is_array())) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { m_value.array->insert(m_value.array->end(), idx - m_value.array->size() + 1, basic_json()); } return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified array element Returns a const reference to the element at specified location @a idx. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array; in that cases, using the [] operator with an index makes no sense. @complexity Constant. @liveexample{The example below shows how array elements can be read using the `[]` operator.,operatorarray__size_type_const} @since version 1.0.0 */ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (JSON_LIKELY(is_array())) { return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } // operator[] only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (JSON_LIKELY(is_object())) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> const_reference operator[](T* key) const { // at only works for objects if (JSON_LIKELY(is_object())) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name()))); } /*! @brief access specified object element with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(key); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const typename object_t::key_type&), this function does not throw if the given key @a key was not found. @note Unlike @ref operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by @a key. This function is furthermore also applicable to const objects. @param[in] key key of the element to access @param[in] default_value the value to return if @a key is not found @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.306 if the JSON value is not an objec; in that cases, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @since version 1.0.0 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const { // at only works for objects if (JSON_LIKELY(is_object())) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return *it; } return default_value; } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const */ string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /*! @brief access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(ptr); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const json_pointer&), this function does not throw if the given key @a key was not found. @param[in] ptr a JSON pointer to the element to access @param[in] default_value the value to return if @a ptr found no value @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.306 if the JSON value is not an objec; in that cases, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value_ptr} @sa @ref operator[](const json_pointer&) for unchecked access by reference @since version 2.0.2 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const json_pointer& ptr, const ValueType& default_value) const { // at only works for objects if (JSON_LIKELY(is_object())) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this); } JSON_CATCH (out_of_range&) { return default_value; } } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const json_pointer&, ValueType) const */ string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /*! @brief access the first element Returns a reference to the first element in the container. For a JSON container `c`, the expression `c.front()` is equivalent to `*c.begin()`. @return In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on `null` value @liveexample{The following code shows an example for `front()`.,front} @sa @ref back() -- access the last element @since version 1.0.0 */ reference front() { return *begin(); } /*! @copydoc basic_json::front() */ const_reference front() const { return *cbegin(); } /*! @brief access the last element Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to @code {.cpp} auto tmp = c.end(); --tmp; return *tmp; @endcode @return In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on a `null` value. See example below. @liveexample{The following code shows an example for `back()`.,back} @sa @ref front() -- access the first element @since version 1.0.0 */ reference back() { auto tmp = end(); --tmp; return *tmp; } /*! @copydoc basic_json::back() */ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /*! @brief remove element given an iterator Removes the element specified by iterator @a pos. The iterator @a pos must be valid and dereferenceable. Thus the `end()` iterator (which is valid, but is not dereferenceable) cannot be used as a value for @a pos. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] pos iterator to the element to remove @return Iterator following the last removed element. If the iterator @a pos refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"` @throw invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"` @complexity The complexity depends on the type: - objects: amortized constant - arrays: linear in distance between @a pos and the end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType} @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (JSON_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin())) { JSON_THROW(invalid_iterator::create(205, "iterator out of range")); } if (is_string()) { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove elements given an iterator range Removes the element specified by the range `[first; last)`. The iterator @a first does not need to be dereferenceable if `first == last`: erasing an empty range is a no-op. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] first iterator to the beginning of the range to remove @param[in] last iterator past the end of the range to remove @return Iterator following the last removed element. If the iterator @a second refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"` @throw invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"` @complexity The complexity depends on the type: - objects: `log(size()) + std::distance(first, last)` - arrays: linear in the distance between @a first and @a last, plus linear in the distance between @a last and end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType_IteratorType} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (JSON_UNLIKELY(this != first.m_object or this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } if (is_string()) { AllocatorType<string_t> alloc; alloc.destroy(m_value.string); alloc.deallocate(m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove element from a JSON object given a key Removes elements from a JSON object with the key value @a key. @param[in] key value of the elements to remove @return Number of elements removed. If @a ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @post References and iterators to the erased elements are invalidated. Other references and iterators are not affected. @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @complexity `log(size()) + count(key)` @liveexample{The example shows the effect of `erase()`.,erase__key_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->erase(key); } JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } /*! @brief remove element from a JSON array given an index Removes element from a JSON array at the index @a idx. @param[in] idx index of the element to remove @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 is out of range"` @complexity Linear in distance between @a idx and the end of the container. @liveexample{The example shows the effect of `erase()`.,erase__size_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @since version 1.0.0 */ void erase(const size_type idx) { // this erase only works for arrays if (JSON_LIKELY(is_array())) { if (JSON_UNLIKELY(idx >= size())) { JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); } else { JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /*! @brief find an element in a JSON object Finds an element in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, end() is returned. @note This method always returns @ref end() when executed on a JSON type that is not an object. @param[in] key key value of the element to search for @return Iterator to an element with key equivalent to @a key. If no such element is found or the JSON value is not an object, past-the-end (see @ref end()) iterator is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `find()` is used.,find__key_type} @since version 1.0.0 */ iterator find(typename object_t::key_type key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(key); } return result; } /*! @brief find an element in a JSON object @copydoc find(typename object_t::key_type) */ const_iterator find(typename object_t::key_type key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(key); } return result; } /*! @brief returns the number of occurrences of a key in a JSON object Returns the number of elements with key @a key. If ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @note This method always returns `0` when executed on a JSON type that is not an object. @param[in] key key value of the element to count @return Number of elements with key @a key. If the JSON value is not an object, the return value will be `0`. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `count()` is used.,count} @since version 1.0.0 */ size_type count(typename object_t::key_type key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(key) : 0; } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /*! @brief returns an iterator to the first element Returns an iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `begin()`.,begin} @sa @ref cbegin() -- returns a const iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /*! @copydoc basic_json::cbegin() */ const_iterator begin() const noexcept { return cbegin(); } /*! @brief returns a const iterator to the first element Returns a const iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`. @liveexample{The following code shows an example for `cbegin()`.,cbegin} @sa @ref begin() -- returns an iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /*! @brief returns an iterator to one past the last element Returns an iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `end()`.,end} @sa @ref cend() -- returns a const iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /*! @copydoc basic_json::cend() */ const_iterator end() const noexcept { return cend(); } /*! @brief returns a const iterator to one past the last element Returns a const iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).end()`. @liveexample{The following code shows an example for `cend()`.,cend} @sa @ref end() -- returns an iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /*! @brief returns an iterator to the reverse-beginning Returns an iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(end())`. @liveexample{The following code shows an example for `rbegin()`.,rbegin} @sa @ref crbegin() -- returns a const reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /*! @copydoc basic_json::crbegin() */ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /*! @brief returns an iterator to the reverse-end Returns an iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(begin())`. @liveexample{The following code shows an example for `rend()`.,rend} @sa @ref crend() -- returns a const reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /*! @copydoc basic_json::crend() */ const_reverse_iterator rend() const noexcept { return crend(); } /*! @brief returns a const reverse iterator to the last element Returns a const iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`. @liveexample{The following code shows an example for `crbegin()`.,crbegin} @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /*! @brief returns a const reverse iterator to one before the first Returns a const reverse iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`. @liveexample{The following code shows an example for `crend()`.,crend} @sa @ref rend() -- returns a reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } public: /*! @brief wrapper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. @liveexample{The following code shows how the wrapper is used,iterator_wrapper} @note The name of this function is not yet final and may change in the future. */ static iteration_proxy<iterator> iterator_wrapper(reference cont) { return iteration_proxy<iterator>(cont); } /*! @copydoc iterator_wrapper(reference) */ static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont) { return iteration_proxy<const_iterator>(cont); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /*! @brief checks whether the container is empty. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `true` boolean | `false` string | `false` number | `false` object | result of function `object_t::empty()` array | result of function `array_t::empty()` @liveexample{The following code uses `empty()` to check if a JSON object contains any elements.,empty} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `empty()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `begin() == end()`. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } default: { // all other types are nonempty return false; } } } /*! @brief returns the number of elements Returns the number of elements in a JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` boolean | `1` string | `1` number | `1` object | result of function object_t::size() array | result of function array_t::size() @liveexample{The following code calls `size()` on the different value types.,size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their size() functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of `std::distance(begin(), end())`. @sa @ref empty() -- checks whether the container is empty @sa @ref max_size() -- returns the maximal number of elements @since version 1.0.0 */ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } default: { // all other types have size 1 return 1; } } } /*! @brief returns the maximum possible number of elements Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. `std::distance(begin(), end())` for the JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` (same as `size()`) boolean | `1` (same as `size()`) string | `1` (same as `size()`) number | `1` (same as `size()`) object | result of function `object_t::max_size()` array | result of function `array_t::max_size()` @liveexample{The following code calls `max_size()` on the different value types. Note the output is implementation specific.,max_size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `max_size()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @requirement This function helps `basic_json` satisfying the [Container](http://en.cppreference.com/w/cpp/concept/Container) requirements: - The complexity is constant. - Has the semantics of returning `b.size()` where `b` is the largest possible JSON value. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /*! @brief clears the contents Clears the content of a JSON value and resets it to the default value as if @ref basic_json(value_t) would have been called with the current value type from @ref type(): Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @post Has the same effect as calling @code {.cpp} *this = basic_json(type()); @endcode @liveexample{The example below shows the effect of `clear()` to different JSON types.,clear} @complexity Linear in the size of the JSON value. @iterators All iterators, pointers and references related to this container are invalidated. @exceptionsafety No-throw guarantee: this function never throws exceptions. @sa @ref basic_json(value_t) -- constructor that creates an object with the same value than calling `clear()` @since version 1.0.0 */ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } default: break; } } /*! @brief add an object to an array Appends the given element @a val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending @a val. @param[in] val the value to add to the JSON array @throw type_error.308 when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,push_back} @since version 1.0.0 */ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) m_value.array->push_back(std::move(val)); // invalidate object val.m_type = value_t::null; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array m_value.array->push_back(val); } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(const basic_json& val) { push_back(val); return *this; } /*! @brief add an object to an object Inserts the given element @a val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting @a val. @param[in] val the value to add to the JSON object @throw type_error.308 when called on a type other than JSON object or null; example: `"cannot use push_back() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object.,push_back__object_t__value} @since version 1.0.0 */ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (JSON_UNLIKELY(not(is_null() or is_object()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array m_value.object->insert(val); } /*! @brief add an object to an object @copydoc push_back(const typename object_t::value_type&) */ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /*! @brief add an object to an object This function allows to use `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list @a init contains only two elements, and 3. the first element of @a init is a string, @a init is converted into an object element and added using @ref push_back(const typename object_t::value_type&). Otherwise, @a init is converted to a JSON value and added using @ref push_back(basic_json&&). @param[in] init an initializer list @complexity Linear in the size of the initializer list @a init. @note This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list<basic_json>`, see https://github.com/nlohmann/json/issues/235 for more information. @liveexample{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list} */ void push_back(initializer_list_t init) { if (is_object() and init.size() == 2 and (*init.begin())->is_string()) { basic_json&& key = init.begin()->moved_or_copied(); push_back(typename object_t::value_type( std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied())); } else { push_back(basic_json(init)); } } /*! @brief add an object to an object @copydoc push_back(initializer_list_t) */ reference operator+=(initializer_list_t init) { push_back(init); return *this; } /*! @brief add an object to an array Creates a JSON value from the passed parameters @a args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @throw type_error.311 when called on a type other than JSON array or null; example: `"cannot use emplace_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,emplace_back} @since version 2.0.8 */ template<class... Args> void emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) m_value.array->emplace_back(std::forward<Args>(args)...); } /*! @brief add an object to an object if key does not exist Inserts a new element into a JSON object constructed in-place with the given @a args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. @throw type_error.311 when called on a type other than JSON object or null; example: `"cannot use emplace() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace} @since version 2.0.8 */ template<class... Args> std::pair<iterator, bool> emplace(Args&& ... args) { // emplace only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_object()))) { JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward<Args>(args)...); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /*! @brief inserts element Inserts element @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] val element to insert @return iterator pointing to the inserted @a val. @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Constant plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert} @since version 1.0.0 */ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (JSON_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val); return result; } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts element @copydoc insert(const_iterator, const basic_json&) */ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /*! @brief inserts elements Inserts @a cnt copies of @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] cnt number of copies of @a val to insert @param[in] val element to insert @return iterator pointing to the first element inserted, or @a pos if `cnt==0` @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Linear in @a cnt plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__count} @since version 1.0.0 */ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (JSON_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); return result; } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts elements Inserts elements from range `[first, last)` before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @throw invalid_iterator.211 if @a first or @a last are iterators into container for which insert is called; example: `"passed iterators may not belong to container"` @return iterator pointing to the first element inserted, or @a pos if `first==last` @complexity Linear in `std::distance(first, last)` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__range} @since version 1.0.0 */ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } if (JSON_UNLIKELY(first.m_object == this or last.m_object == this)) { JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert( pos.m_it.array_iterator, first.m_it.array_iterator, last.m_it.array_iterator); return result; } /*! @brief inserts elements Inserts elements from initializer list @a ilist before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] ilist initializer list to insert the values from @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @return iterator pointing to the first element inserted, or @a pos if `ilist` is empty @complexity Linear in `ilist.size()` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__ilist} @since version 1.0.0 */ iterator insert(const_iterator pos, initializer_list_t ilist) { // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator iterator result(this); result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end()); return result; } /*! @brief inserts elements Inserts elements from range `[first, last)`. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than objects; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert. @liveexample{The example shows how `insert()` is used.,insert__range_object} @since version 3.0.0 */ void insert(const_iterator first, const_iterator last) { // insert only works for objects if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_UNLIKELY(not first.m_object->is_object() or not last.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from JSON object @a j and overwrites existing keys. @param[in] j JSON object to read values from @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_reference j) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } if (JSON_UNLIKELY(not j.is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); } for (auto it = j.begin(); it != j.end(); ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from from range `[first, last)` and overwrites existing keys. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used__range.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_iterator first, const_iterator last) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_UNLIKELY(not first.m_object->is_object() or not first.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } for (auto it = first; it != last; ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief exchanges the values Exchanges the contents of the JSON value with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ void swap(reference other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); assert_invariant(); } /*! @brief exchanges the values Exchanges the contents of a JSON array with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other array to exchange the contents with @throw type_error.310 when JSON value is not an array; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how arrays can be swapped with `swap()`.,swap__array_t} @since version 1.0.0 */ void swap(array_t& other) { // swap only works for arrays if (JSON_LIKELY(is_array())) { std::swap(*(m_value.array), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON object with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other object to exchange the contents with @throw type_error.310 when JSON value is not an object; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how objects can be swapped with `swap()`.,swap__object_t} @since version 1.0.0 */ void swap(object_t& other) { // swap only works for objects if (JSON_LIKELY(is_object())) { std::swap(*(m_value.object), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other string to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__string_t} @since version 1.0.0 */ void swap(string_t& other) { // swap only works for strings if (JSON_LIKELY(is_string())) { std::swap(*(m_value.string), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /*! @brief comparison: equal Compares two JSON values for equality according to the following rules: - Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective `operator==`. - Integer and floating-point numbers are automatically converted before comparison. Note than two NaN values are always treated as unequal. - Two JSON null values are equal. @note Floating-point inside JSON values numbers are compared with `json::number_float_t::operator==` which is `double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39) could be used, for instance @code {.cpp} template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept { return std::abs(a - b) <= epsilon; } @endcode @note NaN values never compare equal to themselves or to other NaN values. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are equal @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__equal} @since version 1.0.0 */ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return (*lhs.m_value.array == *rhs.m_value.array); case value_t::object: return (*lhs.m_value.object == *rhs.m_value.object); case value_t::null: return true; case value_t::string: return (*lhs.m_value.string == *rhs.m_value.string); case value_t::boolean: return (lhs.m_value.boolean == rhs.m_value.boolean); case value_t::number_integer: return (lhs.m_value.number_integer == rhs.m_value.number_integer); case value_t::number_unsigned: return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned); case value_t::number_float: return (lhs.m_value.number_float == rhs.m_value.number_float); default: return false; } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float); } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer)); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float); } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned)); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned)); } return false; } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept { return (lhs == basic_json(rhs)); } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) == rhs); } /*! @brief comparison: not equal Compares two JSON values for inequality by calculating `not (lhs == rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are not equal @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__notequal} @since version 1.0.0 */ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return not (lhs == rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs != basic_json(rhs)); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) != rhs); } /*! @brief comparison: less than Compares whether one JSON value @a lhs is less than another JSON value @a rhs according to the following rules: - If @a lhs and @a rhs have the same type, the values are compared using the default `<` operator. - Integer and floating-point numbers are automatically converted before comparison - In case @a lhs and @a rhs have different types, the values are ignored and the order of the types is considered, see @ref operator<(const value_t, const value_t). @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__less} @since version 1.0.0 */ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return (*lhs.m_value.array) < (*rhs.m_value.array); case value_t::object: return *lhs.m_value.object < *rhs.m_value.object; case value_t::null: return false; case value_t::string: return *lhs.m_value.string < *rhs.m_value.string; case value_t::boolean: return lhs.m_value.boolean < rhs.m_value.boolean; case value_t::number_integer: return lhs.m_value.number_integer < rhs.m_value.number_integer; case value_t::number_unsigned: return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; case value_t::number_float: return lhs.m_value.number_float < rhs.m_value.number_float; default: return false; } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept { return (lhs < basic_json(rhs)); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) < rhs); } /*! @brief comparison: less than or equal Compares whether one JSON value @a lhs is less than or equal to another JSON value by calculating `not (rhs < lhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greater} @since version 1.0.0 */ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return not (rhs < lhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs <= basic_json(rhs)); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) <= rhs); } /*! @brief comparison: greater than Compares whether one JSON value @a lhs is greater than another JSON value by calculating `not (lhs <= rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__lessequal} @since version 1.0.0 */ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return not (lhs <= rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept { return (lhs > basic_json(rhs)); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) > rhs); } /*! @brief comparison: greater than or equal Compares whether one JSON value @a lhs is greater than or equal to another JSON value by calculating `not (lhs < rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greaterequal} @since version 1.0.0 */ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return not (lhs < rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs >= basic_json(rhs)); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) >= rhs); } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ /*! @brief serialize to stream Serialize the given JSON value @a j to the output stream @a o. The JSON value will be serialized using the @ref dump member function. - The indentation of the output can be controlled with the member variable `width` of the output stream @a o. For instance, using the manipulator `std::setw(4)` on @a o sets the indentation level to `4` and the serialization result is the same as calling `dump(4)`. - The indentation characrer can be controlled with the member variable `fill` of the output stream @a o. For instance, the manipulator `std::setfill('\\t')` sets indentation to use a tab character rather than the default space character. @param[in,out] o stream to serialize to @param[in] j JSON value to serialize @return the stream @a o @complexity Linear. @liveexample{The example below shows the serialization with different parameters to `width` to adjust the indentation level.,operator_serialize} @since version 1.0.0; indentaction character added in version 3.0.0 */ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = (o.width() > 0); const auto indentation = (pretty_print ? o.width() : 0); // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization serializer s(detail::output_adapter<char>(o), o.fill()); s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation)); return o; } /*! @brief serialize to stream @deprecated This stream operator is deprecated and will be removed in a future version of the library. Please use @ref operator<<(std::ostream&, const basic_json&) instead; that is, replace calls like `j >> o;` with `o << j;`. */ JSON_DEPRECATED friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /*! @brief deserialize from a compatible input This function reads from a compatible input. Examples are: - an array of 1-byte values - strings with character/literal type with size of 1 byte - input streams - container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @pre The container storage is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with a noncompliant container and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @param[in] i input to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an array.,parse__array__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__string__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__istream__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function reading from a contiguous container.,parse__contiguouscontainer__parser_callback_t} @since version 2.0.3 (contiguous containers) */ static basic_json parse(detail::input_adapter i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(i, cb, allow_exceptions).parse(true, result); return result; } /*! @copydoc basic_json parse(detail::input_adapter, const parser_callback_t) */ static basic_json parse(detail::input_adapter& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(i, cb, allow_exceptions).parse(true, result); return result; } static bool accept(detail::input_adapter i) { return parser(i).accept(true); } static bool accept(detail::input_adapter& i) { return parser(i).accept(true); } /*! @brief deserialize from an iterator range with contiguous storage This function reads from an iterator range of a container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre The iterator range is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element in the range has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with noncompliant iterators and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @tparam IteratorType iterator of container with contiguous storage @param[in] first begin of the range to parse (included) @param[in] last end of the range to parse (excluded) @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @return result of the deserialization @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an iterator range.,parse__iteratortype__parser_callback_t} @since version 2.0.3 */ template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result); return result; } template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static bool accept(IteratorType first, IteratorType last) { return parser(detail::input_adapter(first, last)).accept(true); } /*! @brief deserialize from stream @deprecated This stream operator is deprecated and will be removed in a future version of the library. Please use @ref operator>>(std::istream&, basic_json&) instead; that is, replace calls like `j << i;` with `i >> j;`. */ JSON_DEPRECATED friend std::istream& operator<<(basic_json& j, std::istream& i) { return operator>>(i, j); } /*! @brief deserialize from stream Deserializes an input stream to a JSON value. @param[in,out] i input stream to read a serialized JSON value from @param[in,out] j JSON value to write the deserialized input to @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize} @sa parse(std::istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing @since version 1.0.0 */ friend std::istream& operator>>(std::istream& i, basic_json& j) { parser(detail::input_adapter(i)).parse(false, j); return i; } /// @} /////////////////////////// // convenience functions // /////////////////////////// /*! @brief return the type as string Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type. @return a string representation of a the @a m_type member: Value type | return value ----------- | ------------- null | `"null"` boolean | `"boolean"` string | `"string"` number | `"number"` (for all number types) object | `"object"` array | `"array"` discarded | `"discarded"` @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Constant. @liveexample{The following code exemplifies `type_name()` for all JSON types.,type_name} @sa @ref type() -- return the type of the JSON value @sa @ref operator value_t() -- return the type of the JSON value (implicit) @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` since 3.0.0 */ const char* type_name() const noexcept { { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::discarded: return "discarded"; default: return "number"; } } } private: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ public: /*! @brief create a CBOR serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049): JSON value type | value/range | CBOR type | first byte --------------- | ------------------------------------------ | ---------------------------------- | --------------- null | `null` | Null | 0xf6 boolean | `true` | True | 0xf5 boolean | `false` | False | 0xf4 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3b number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3a number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 number_integer | -24..-1 | Negative integer | 0x20..0x37 number_integer | 0..23 | Integer | 0x00..0x17 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b number_unsigned | 0..23 | Integer | 0x00..0x17 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b number_float | *any value* | Double-Precision Float | 0xfb string | *length*: 0..23 | UTF-8 string | 0x60..0x77 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7a string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7b array | *size*: 0..23 | array | 0x80..0x97 array | *size*: 23..255 | array (1 byte follow) | 0x98 array | *size*: 256..65535 | array (2 bytes follow) | 0x99 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9a array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9b object | *size*: 0..23 | map | 0xa0..0xb7 object | *size*: 23..255 | map (1 byte follow) | 0xb8 object | *size*: 256..65535 | map (2 bytes follow) | 0xb9 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xba object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xbb @note The mapping is **complete** in the sense that any JSON value type can be converted to a CBOR value. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The following CBOR types are not used in the conversion: - byte strings (0x40..0x5f) - UTF-8 strings terminated by "break" (0x7f) - arrays terminated by "break" (0x9f) - maps terminated by "break" (0xbf) - date/time (0xc0..0xc1) - bignum (0xc2..0xc3) - decimal fraction (0xc4) - bigfloat (0xc5) - tagged items (0xc6..0xd4, 0xd8..0xdb) - expected conversions (0xd5..0xd7) - simple values (0xe0..0xf3, 0xf8) - undefined (0xf7) - half and single-precision floats (0xf9-0xfa) - break (0xff) @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor} @sa http://cbor.io @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the analogous deserialization @sa @ref to_msgpack(const basic_json&) for the related MessagePack format @since version 2.0.9 */ static std::vector<uint8_t> to_cbor(const basic_json& j) { std::vector<uint8_t> result; to_cbor(j, result); return result; } static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_cbor(j); } static void to_cbor(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_cbor(j); } /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type | value/range | MessagePack type | first byte --------------- | --------------------------------- | ---------------- | ---------- null | `null` | nil | 0xc0 boolean | `true` | true | 0xc3 boolean | `false` | false | 0xc2 number_integer | -9223372036854775808..-2147483649 | int64 | 0xd3 number_integer | -2147483648..-32769 | int32 | 0xd2 number_integer | -32768..-129 | int16 | 0xd1 number_integer | -128..-33 | int8 | 0xd0 number_integer | -32..-1 | negative fixint | 0xe0..0xff number_integer | 0..127 | positive fixint | 0x00..0x7f number_integer | 128..255 | uint 8 | 0xcc number_integer | 256..65535 | uint 16 | 0xcd number_integer | 65536..4294967295 | uint 32 | 0xce number_integer | 4294967296..18446744073709551615 | uint 64 | 0xcf number_unsigned | 0..127 | positive fixint | 0x00..0x7f number_unsigned | 128..255 | uint 8 | 0xcc number_unsigned | 256..65535 | uint 16 | 0xcd number_unsigned | 65536..4294967295 | uint 32 | 0xce number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xcf number_float | *any value* | float 64 | 0xcb string | *length*: 0..31 | fixstr | 0xa0..0xbf string | *length*: 32..255 | str 8 | 0xd9 string | *length*: 256..65535 | str 16 | 0xda string | *length*: 65536..4294967295 | str 32 | 0xdb array | *size*: 0..15 | fixarray | 0x90..0x9f array | *size*: 16..65535 | array 16 | 0xdc array | *size*: 65536..4294967295 | array 32 | 0xdd object | *size*: 0..15 | fix map | 0x80..0x8f object | *size*: 16..65535 | map 16 | 0xde object | *size*: 65536..4294967295 | map 32 | 0xdf @note The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value. @note The following values can **not** be converted to a MessagePack value: - strings with more than 4294967295 bytes - arrays with more than 4294967295 elements - objects with more than 4294967295 elements @note The following MessagePack types are not used in the conversion: - bin 8 - bin 32 (0xc4..0xc6) - ext 8 - ext 32 (0xc7..0xc9) - float 32 (0xca) - fixext 1 - fixext 16 (0xd4..0xd8) @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack} @sa http://msgpack.org @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @since version 2.0.9 */ static std::vector<uint8_t> to_msgpack(const basic_json& j) { std::vector<uint8_t> result; to_msgpack(j, result); return result; } static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_msgpack(j); } static void to_msgpack(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_msgpack(j); } /*! @brief create a JSON value from an input in CBOR format Deserializes a given input @a i to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. The library maps CBOR types to JSON value types as follows: CBOR type | JSON value type | first byte ---------------------- | --------------- | ---------- Integer | number_unsigned | 0x00..0x17 Unsigned integer | number_unsigned | 0x18 Unsigned integer | number_unsigned | 0x19 Unsigned integer | number_unsigned | 0x1a Unsigned integer | number_unsigned | 0x1b Negative integer | number_integer | 0x20..0x37 Negative integer | number_integer | 0x38 Negative integer | number_integer | 0x39 Negative integer | number_integer | 0x3a Negative integer | number_integer | 0x3b Negative integer | number_integer | 0x40..0x57 UTF-8 string | string | 0x60..0x77 UTF-8 string | string | 0x78 UTF-8 string | string | 0x79 UTF-8 string | string | 0x7a UTF-8 string | string | 0x7b UTF-8 string | string | 0x7f array | array | 0x80..0x97 array | array | 0x98 array | array | 0x99 array | array | 0x9a array | array | 0x9b array | array | 0x9f map | object | 0xa0..0xb7 map | object | 0xb8 map | object | 0xb9 map | object | 0xba map | object | 0xbb map | object | 0xbf False | `false` | 0xf4 True | `true` | 0xf5 Nill | `null` | 0xf6 Half-Precision Float | number_float | 0xf9 Single-Precision Float | number_float | 0xfa Double-Precision Float | number_float | 0xfb @warning The mapping is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112): - byte strings (0x40..0x5f) - date/time (0xc0..0xc1) - bignum (0xc2..0xc3) - decimal fraction (0xc4) - bigfloat (0xc5) - tagged items (0xc6..0xd4, 0xd8..0xdb) - expected conversions (0xd5..0xd7) - simple values (0xe0..0xf3, 0xf8) - undefined (0xf7) @warning CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113). @note Any CBOR output created @ref to_cbor can be successfully parsed by @ref from_cbor. @param[in] i an input in CBOR format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @return deserialized JSON value @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from CBOR were used in the given input @a v or if the input is not valid CBOR @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor} @sa http://cbor.io @sa @ref to_cbor(const basic_json&) for the analogous serialization @sa @ref from_msgpack(detail::input_adapter, const bool) for the related MessagePack format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0 */ static basic_json from_cbor(detail::input_adapter i, const bool strict = true) { return binary_reader(i).parse_cbor(strict); } /*! @copydoc from_cbor(detail::input_adapter, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true) { return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict); } /*! @brief create a JSON value from an input in MessagePack format Deserializes a given input @a i to a JSON value using the MessagePack serialization format. The library maps MessagePack types to JSON value types as follows: MessagePack type | JSON value type | first byte ---------------- | --------------- | ---------- positive fixint | number_unsigned | 0x00..0x7f fixmap | object | 0x80..0x8f fixarray | array | 0x90..0x9f fixstr | string | 0xa0..0xbf nil | `null` | 0xc0 false | `false` | 0xc2 true | `true` | 0xc3 float 32 | number_float | 0xca float 64 | number_float | 0xcb uint 8 | number_unsigned | 0xcc uint 16 | number_unsigned | 0xcd uint 32 | number_unsigned | 0xce uint 64 | number_unsigned | 0xcf int 8 | number_integer | 0xd0 int 16 | number_integer | 0xd1 int 32 | number_integer | 0xd2 int 64 | number_integer | 0xd3 str 8 | string | 0xd9 str 16 | string | 0xda str 32 | string | 0xdb array 16 | array | 0xdc array 32 | array | 0xdd map 16 | object | 0xde map 32 | object | 0xdf negative fixint | number_integer | 0xe0-0xff @warning The mapping is **incomplete** in the sense that not all MessagePack types can be converted to a JSON value. The following MessagePack types are not supported and will yield parse errors: - bin 8 - bin 32 (0xc4..0xc6) - ext 8 - ext 32 (0xc7..0xc9) - fixext 1 - fixext 16 (0xd4..0xd8) @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @param[in] i an input in MessagePack format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from MessagePack were used in the given input @a i or if the input is not valid MessagePack @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack} @sa http://msgpack.org @sa @ref to_msgpack(const basic_json&) for the analogous serialization @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0 */ static basic_json from_msgpack(detail::input_adapter i, const bool strict = true) { return binary_reader(i).parse_msgpack(strict); } /*! @copydoc from_msgpack(detail::input_adapter, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true) { return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict); } /// @} ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to @ref operator[](const typename object_t::key_type&), `null` values are created in arrays and objects if necessary. In particular: - If the JSON pointer points to an object key that does not exist, it is created an filled with a `null` value before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created an filled with a `null` value before a reference to it is returned. All indices between the current maximum and the given index are also filled with `null`. - The special value `-` is treated as a synonym for the index past the end. @param[in] ptr a JSON pointer @return reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer} @since version 2.0.0 */ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no `null` values are created. In particular, the the special value `-` yields an exception. @param[in] ptr JSON pointer to the desired element @return const reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} @since version 2.0.0 */ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Returns a reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer} */ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /*! @brief access specified element via JSON Pointer Returns a const reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer_const} */ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /*! @brief return flattened JSON value The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive. The original JSON value can be restored using the @ref unflatten() function. @return an object that maps JSON pointers to primitive values @note Empty objects and arrays are flattened to `null` and will not be reconstructed correctly by the @ref unflatten() function. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten} @sa @ref unflatten() for the reverse function @since version 2.0.0 */ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /*! @brief unflatten a previously flattened JSON value The function restores the arbitrary nesting of a JSON value that has been flattened before using the @ref flatten() function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. @return the original JSON from a flattened version @note Empty objects and arrays are flattened by @ref flatten() to `null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `j == j.flatten().unflatten()`. @complexity Linear in the size the JSON value. @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @liveexample{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten} @sa @ref flatten() for the reverse function @since version 2.0.0 */ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /*! @brief applies a JSON patch [JSON Patch](http://jsonpatch.com) defines a JSON document structure for expressing a sequence of operations to apply to a JSON) document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. @param[in] json_patch JSON patch document @return patched document @note The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value. @throw parse_error.104 if the JSON patch does not consist of an array of objects @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: `"operation add must have member path"` @throw out_of_range.401 if an array index is out of range. @throw out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: `"key baz not found"` @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", "move") @throw other_error.501 if "test" operation was unsuccessful @complexity Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected. @liveexample{The following code shows how a JSON patch is applied to a value.,patch} @sa @ref diff -- create a JSON patch by comparing two JSON values @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string & op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.is_root()) { result = val; } else { // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = std::stoi(last_path); if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size())) { // avoid undefined behavior JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } else { // default case: insert add offset parent.insert(parent.begin() + static_cast<difference_type>(idx), val); } } break; } default: { // if there exists a parent it cannot be primitive assert(false); // LCOV_EXCL_LINE } } } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [&result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (JSON_LIKELY(it != parent.end())) { parent.erase(it); } else { JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); } } else if (parent.is_array()) { // note erase performs range check parent.erase(static_cast<size_type>(std::stoi(last_path))); } }; // type check: top level value must be an array if (JSON_UNLIKELY(not json_patch.is_array())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json& { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (JSON_UNLIKELY(it == val.m_value.object->end())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); } // check if result is of type string if (JSON_UNLIKELY(string_type and not it->second.is_string())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); } // no error: return value return it->second; }; // type check: every element of the array must be an object if (JSON_UNLIKELY(not val.is_object())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // collect mandatory members const std::string op = get_value("op", "op", true); const std::string path = get_value(op, "path", true); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const std::string from_path = get_value("move", "from", true); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const std::string from_path = get_value("copy", "from", true); const json_pointer from_ptr(from_path); // the "from" location must exist - use at() result[ptr] = result.at(from_ptr); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_CATCH (out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (JSON_UNLIKELY(not success)) { JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); } break; } case patch_operations::invalid: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); } } } return result; } /*! @brief creates a diff as a JSON patch Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can be changed into the value @a target by calling @ref patch function. @invariant For two JSON values @a source and @a target, the following code yields always `true`: @code {.cpp} source.patch(diff(source, target)) == target; @endcode @note Currently, only `remove`, `add`, and `replace` operations are generated. @param[in] source JSON value to compare from @param[in] target JSON value to compare against @param[in] path helper value to create JSON pointers @return a JSON patch to convert the @a source to @a target @complexity Linear in the lengths of @a source and @a target. @liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff} @sa @ref patch -- apply a JSON patch @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @since version 2.0.0 */ static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); } else { switch (source.type()) { case value_t::array: { // first pass: traverse common elements std::size_t i = 0; while (i < source.size() and i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // i now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast<difference_type>(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/" + std::to_string(i)}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.begin(); it != source.end(); ++it) { // escape the key name to be used in a JSON patch const auto key = json_pointer::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path + "/" + key} })); } } // second pass: traverse other object's elements for (auto it = target.begin(); it != target.end(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto key = json_pointer::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path + "/" + key}, {"value", it.value()} }); } } break; } default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } } return result; } /// @} }; ///////////// // presets // ///////////// /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; ////////////////// // json_pointer // ////////////////// NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; auto result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->m_type) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array JSON_TRY { result = &result->operator[](static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); } } return *result; } NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->m_type == detail::value_t::null) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const char x) { return (x >= '0' and x <= '9'); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums or reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->m_type) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access JSON_TRY { ptr = &ptr->operator[]( static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL& json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // note: at performs range check JSON_TRY { ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // use unchecked array access JSON_TRY { ptr = &ptr->operator[]( static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION const NLOHMANN_BASIC_JSON_TPL& json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const { using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // note: at performs range check JSON_TRY { ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } NLOHMANN_BASIC_JSON_TPL_DECLARATION void json_pointer::flatten(const std::string& reference_string, const NLOHMANN_BASIC_JSON_TPL& value, NLOHMANN_BASIC_JSON_TPL& result) { switch (value.m_type) { case detail::value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + escape(element.first), element.second, result); } } break; } default: { // add primitive value with its reference string result[reference_string] = value; break; } } } NLOHMANN_BASIC_JSON_TPL_DECLARATION NLOHMANN_BASIC_JSON_TPL json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value) { if (JSON_UNLIKELY(not value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); } NLOHMANN_BASIC_JSON_TPL result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (JSON_UNLIKELY(not element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return (lhs.reference_tokens == rhs.reference_tokens); } inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return not (lhs == rhs); } } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// // specialization of std::swap, and std::hash namespace std { /*! @brief exchanges the values of two JSON objects @since version 1.0.0 */ template<> inline void swap(nlohmann::json& j1, nlohmann::json& j2) noexcept( is_nothrow_move_constructible<nlohmann::json>::value and is_nothrow_move_assignable<nlohmann::json>::value ) { j1.swap(j2); } /// hash value for JSON objects template<> struct hash<nlohmann::json> { /*! @brief return a hash value for a JSON object @since version 1.0.0 */ std::size_t operator()(const nlohmann::json& j) const { // a naive hashing via the string representation const auto& h = hash<nlohmann::json::string_t>(); return h(j.dump()); } }; /// specialization for std::less<value_t> /// @note: do not remove the space after '<', /// see https://github.com/nlohmann/json/pull/679 template<> struct less< ::nlohmann::detail::value_t> { /*! @brief compare two value_t enum values @since version 3.0.0 */ bool operator()(nlohmann::detail::value_t lhs, nlohmann::detail::value_t rhs) const noexcept { return nlohmann::detail::operator<(lhs, rhs); } }; } // namespace std /*! @brief user-defined string literal for JSON values This operator implements a user-defined string literal for JSON objects. It can be used by adding `"_json"` to a string literal and returns a JSON object if no parse error occurred. @param[in] s a string representation of a JSON object @param[in] n the length of string @a s @return a JSON object @since version 1.0.0 */ inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /*! @brief user-defined string literal for JSON pointer This operator implements a user-defined string literal for JSON Pointers. It can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer object if no parse error occurred. @param[in] s a string representation of a JSON Pointer @param[in] n the length of string @a s @return a JSON pointer object @since version 2.0.0 */ inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // restore GCC/clang diagnostic settings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_LIKELY #undef JSON_UNLIKELY #undef JSON_DEPRECATED #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #endif
Emmatipate/ava
src/json.hpp
C++
bsd-3-clause
504,573
[ 30522, 1013, 1008, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1035, 1064, 1064, 1035, 1035, 1064, 1064, 1064, 1064, 1046, 3385, 2005, 2715, 1039, 1009, 1009, 1064, 1064, 106...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
from ..models import Album from ..resource import SingleResource, ListResource from ..schemas import AlbumSchema class SingleAlbum(SingleResource): schema = AlbumSchema() routes = ('/album/<int:id>/',) model = Album class ListAlbums(ListResource): schema = AlbumSchema(many=True) routes = ('/album/', '/tracklist/') model = Album
justanr/owa
owa/api/album.py
Python
gpl-3.0
358
[ 30522, 2013, 1012, 1012, 4275, 12324, 2201, 2013, 1012, 1012, 7692, 12324, 2309, 6072, 8162, 3401, 1010, 2862, 6072, 8162, 3401, 2013, 1012, 1012, 8040, 28433, 2015, 12324, 4042, 5403, 2863, 2465, 2309, 2389, 8569, 2213, 1006, 2309, 6072, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * * @author Axel Kirch <axel@globeglotter.com> * @author MaWi <drmaxxis@gmail.com> * @author lp <spam@lukpopp.ch> * @author Martin <martin@andev.de> * @author F. Mueller-Donath <j.felix@mueller-donath.de> * @author Andreas Gohr <andi@splitbrain.org> * @author Christof <gagi@fin.de> * @author Anika Henke <anika@selfthinker.org> * @author Esther Brunner <esther@kaffeehaus.ch> * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net> * @author Michael Klier <chi@chimeric.de> * @author Leo Moll <leo@yeasoft.com> * @author Florian Anderiasch <fa@art-core.org> * @author Robin Kluth <commi1993@gmail.com> * @author Arne Pelka <mail@arnepelka.de> * @author Alexander Fischer <tbanus@os-forge.net> * @author Juergen Schwarzer <jschwarzer@freenet.de> * @author Marcel Metz <marcel_metz@gmx.de> * @author Matthias Schulte <dokuwiki@lupo49.de> * @author Christian Wichmann <nospam@zone0.de> * @author Pierre Corell <info@joomla-praxis.de> * @author Frank Loizzi <contact@software.bacal.de> * @author Volker Bödker <volker@boedker.de> * @author Janosch <janosch@moinzen.de> * @author rnck <dokuwiki@rnck.de> */ $lang['encoding'] = 'utf-8'; $lang['direction'] = 'ltr'; $lang['doublequoteopening'] = '„'; $lang['doublequoteclosing'] = '“'; $lang['singlequoteopening'] = '‚'; $lang['singlequoteclosing'] = '‘'; $lang['apostrophe'] = '’'; $lang['btn_edit'] = 'Diese Seite bearbeiten'; $lang['btn_source'] = 'Quelltext anzeigen'; $lang['btn_show'] = 'Seite anzeigen'; $lang['btn_create'] = 'Seite anlegen'; $lang['btn_search'] = 'Suchen'; $lang['btn_save'] = 'Speichern'; $lang['btn_preview'] = 'Vorschau'; $lang['btn_top'] = 'Nach oben'; $lang['btn_newer'] = '<< jüngere Änderungen'; $lang['btn_older'] = 'ältere Änderungen >>'; $lang['btn_revs'] = 'Ältere Versionen'; $lang['btn_recent'] = 'Letzte Änderungen'; $lang['btn_upload'] = 'Hochladen'; $lang['btn_cancel'] = 'Abbrechen'; $lang['btn_index'] = 'Übersicht'; $lang['btn_secedit'] = 'Bearbeiten'; $lang['btn_login'] = 'Anmelden'; $lang['btn_logout'] = 'Abmelden'; $lang['btn_admin'] = 'Admin'; $lang['btn_update'] = 'Aktualisieren'; $lang['btn_delete'] = 'Löschen'; $lang['btn_back'] = 'Zurück'; $lang['btn_backlink'] = 'Links hierher'; $lang['btn_subscribe'] = 'Aboverwaltung'; $lang['btn_profile'] = 'Benutzerprofil'; $lang['btn_reset'] = 'Zurücksetzen'; $lang['btn_resendpwd'] = 'Neues Passwort festlegen'; $lang['btn_draft'] = 'Entwurf bearbeiten'; $lang['btn_recover'] = 'Entwurf wiederherstellen'; $lang['btn_draftdel'] = 'Entwurf löschen'; $lang['btn_revert'] = 'Wiederherstellen'; $lang['btn_register'] = 'Registrieren'; $lang['btn_apply'] = 'Übernehmen'; $lang['btn_media'] = 'Medien-Manager'; $lang['btn_deleteuser'] = 'Benutzerprofil löschen'; $lang['btn_img_backto'] = 'Zurück zu %s'; $lang['btn_mediaManager'] = 'Im Medien-Manager anzeigen'; $lang['loggedinas'] = 'Angemeldet als:'; $lang['user'] = 'Benutzername'; $lang['pass'] = 'Passwort'; $lang['newpass'] = 'Neues Passwort'; $lang['oldpass'] = 'Bestätigen (Altes Passwort)'; $lang['passchk'] = 'Passwort erneut eingeben'; $lang['remember'] = 'Angemeldet bleiben'; $lang['fullname'] = 'Voller Name'; $lang['email'] = 'E-Mail'; $lang['profile'] = 'Benutzerprofil'; $lang['badlogin'] = 'Benutzername oder Passwort sind falsch.'; $lang['badpassconfirm'] = 'Das Passwort war falsch.'; $lang['minoredit'] = 'Kleine Änderung'; $lang['draftdate'] = 'Entwurf automatisch gesichert am'; $lang['nosecedit'] = 'Diese Seite wurde inzwischen geändert. Weil deshalb ein oder mehrere Abschnitte veraltet sind, wurde die Seite komplett neu geladen.'; $lang['searchcreatepage'] = 'Falls der gesuchte Begriff nicht gefunden wurde, kannst du die nach deiner Anfrage benannte Seite %s umgehend neu anlegen.'; $lang['search_fullresults'] = 'Volltextergebnisse'; $lang['js']['search_toggle_tools'] = 'Suchwerkzeuge umschalten'; $lang['js']['willexpire'] = 'Die Sperre zur Bearbeitung dieser Seite läuft in einer Minute ab.\nUm Bearbeitungskonflikte zu vermeiden, solltest du sie durch einen Klick auf den Vorschau-Knopf verlängern.'; $lang['js']['notsavedyet'] = 'Nicht gespeicherte Änderungen gehen verloren!'; $lang['js']['searchmedia'] = 'Suche nach Dateien'; $lang['js']['keepopen'] = 'Fenster nach Auswahl nicht schließen'; $lang['js']['hidedetails'] = 'Details ausblenden'; $lang['js']['mediatitle'] = 'Link-Eigenschaften'; $lang['js']['mediadisplay'] = 'Linktyp'; $lang['js']['mediaalign'] = 'Ausrichtung'; $lang['js']['mediasize'] = 'Bildgröße'; $lang['js']['mediatarget'] = 'Linkziel'; $lang['js']['mediaclose'] = 'Schließen'; $lang['js']['mediainsert'] = 'Einfügen'; $lang['js']['mediadisplayimg'] = 'Bild anzeigen'; $lang['js']['mediadisplaylnk'] = 'Nur den Link anzeigen'; $lang['js']['mediasmall'] = 'Bild in kleiner Auflösung'; $lang['js']['mediamedium'] = 'Bild in mittlerer Auflösung'; $lang['js']['medialarge'] = 'Bild in hoher Auflösung'; $lang['js']['mediaoriginal'] = 'Originalauflösung'; $lang['js']['medialnk'] = 'Link zur Detailseite'; $lang['js']['mediadirect'] = 'Direkter Link zum Original'; $lang['js']['medianolnk'] = 'Kein Link'; $lang['js']['medianolink'] = 'Bild nicht verlinken'; $lang['js']['medialeft'] = 'Bild linksbündig ausrichten.'; $lang['js']['mediaright'] = 'Bild rechtsbündig ausrichten.'; $lang['js']['mediacenter'] = 'Bild horizontal zentriert ausrichten'; $lang['js']['medianoalign'] = 'Bild ohne bestimmte Ausrichtung lassen'; $lang['js']['nosmblinks'] = 'Das Verlinken von Windows-Freigaben funktioniert nur im Microsoft Internet-Explorer.\nDer Link kann jedoch zum Einfügen kopiert werden.'; $lang['js']['linkwiz'] = 'Link-Assistent'; $lang['js']['linkto'] = 'Link zu:'; $lang['js']['del_confirm'] = 'Die ausgewählten Dateien wirklich löschen?'; $lang['js']['restore_confirm'] = 'Wirklich diese Version wiederherstellen?'; $lang['js']['media_diff'] = 'Unterschiede anzeigen:'; $lang['js']['media_diff_both'] = 'Nebeneinander'; $lang['js']['media_diff_opacity'] = 'Überblenden'; $lang['js']['media_diff_portions'] = 'Übergang'; $lang['js']['media_select'] = 'Dateien auswählen…'; $lang['js']['media_upload_btn'] = 'Hochladen'; $lang['js']['media_done_btn'] = 'Fertig'; $lang['js']['media_drop'] = 'Dateien hier hinziehen um sie hochzuladen'; $lang['js']['media_cancel'] = 'Entfernen'; $lang['js']['media_overwrt'] = 'Existierende Dateien überschreiben'; $lang['search_exact_match'] = 'Genaue Treffer'; $lang['search_starts_with'] = 'Beginnt mit'; $lang['search_ends_with'] = 'Endet mit'; $lang['search_contains'] = 'Enthält'; $lang['search_custom_match'] = 'Angepasst '; $lang['search_any_ns'] = 'Alle Namensräume'; $lang['search_any_time'] = 'Jederzeit'; $lang['search_past_7_days'] = 'Letzte Woche'; $lang['search_past_month'] = 'Letzter Monat'; $lang['search_past_year'] = 'Letztes Jahr'; $lang['search_sort_by_hits'] = 'Sortiere nach Treffer'; $lang['search_sort_by_mtime'] = 'Sortiere nach letzter Änderung'; $lang['regmissing'] = 'Alle Felder müssen ausgefüllt werden'; $lang['reguexists'] = 'Der Benutzername existiert leider schon.'; $lang['regsuccess'] = 'Der neue Benutzer wurde angelegt und das Passwort per E-Mail versandt.'; $lang['regsuccess2'] = 'Der neue Benutzer wurde angelegt.'; $lang['regfail'] = 'Der Benutzer konnte nicht erstellt werden.'; $lang['regmailfail'] = 'Offenbar ist ein Fehler beim Versenden der Passwortmail aufgetreten. Bitte wende dich an den Wiki-Admin.'; $lang['regbadmail'] = 'Die angegebene Mail-Adresse scheint ungültig zu sein. Falls dies ein Fehler ist, wende dich bitte an den Wiki-Admin.'; $lang['regbadpass'] = 'Die beiden eingegeben Passwörter stimmen nicht überein. Bitte versuche es noch einmal.'; $lang['regpwmail'] = 'Ihr DokuWiki-Passwort'; $lang['reghere'] = 'Du hast noch keinen Zugang? Hier registrieren'; $lang['profna'] = 'Änderung des Benutzerprofils in diesem Wiki nicht möglich.'; $lang['profnochange'] = 'Keine Änderungen, nichts zu tun.'; $lang['profnoempty'] = 'Es muss ein Name oder eine E-Mail Adresse angegeben werden.'; $lang['profchanged'] = 'Benutzerprofil erfolgreich geändert.'; $lang['profnodelete'] = 'Dieses Wiki unterstützt nicht das Löschen von Benutzern.'; $lang['profdeleteuser'] = 'Benutzerprofil löschen'; $lang['profdeleted'] = 'Dein Benutzerprofil wurde im Wiki gelöscht.'; $lang['profconfdelete'] = 'Ich möchte mein Benutzerprofil löschen.<br/> Diese Aktion ist nicht umkehrbar.'; $lang['profconfdeletemissing'] = 'Bestätigungs-Checkbox wurde nicht angehakt.'; $lang['proffail'] = 'Das Benutzerprofil wurde nicht aktualisiert.'; $lang['pwdforget'] = 'Passwort vergessen? Fordere ein neues an'; $lang['resendna'] = 'Passwörter versenden ist in diesem Wiki nicht möglich.'; $lang['resendpwd'] = 'Neues Passwort setzen für'; $lang['resendpwdmissing'] = 'Es tut mir leid, aber du musst alle Felder ausfüllen.'; $lang['resendpwdnouser'] = 'Es tut mir leid, aber der Benutzer existiert nicht in unserer Datenbank.'; $lang['resendpwdbadauth'] = 'Es tut mir leid, aber dieser Authentifizierungscode ist ungültig. Stelle sicher, dass du den kompletten Bestätigungslink verwendet haben.'; $lang['resendpwdconfirm'] = 'Ein Bestätigungslink wurde per E-Mail versandt.'; $lang['resendpwdsuccess'] = 'Dein neues Passwort wurde per E-Mail versandt.'; $lang['license'] = 'Falls nicht anders bezeichnet, ist der Inhalt dieses Wikis unter der folgenden Lizenz veröffentlicht:'; $lang['licenseok'] = 'Hinweis: Durch das Bearbeiten dieser Seite gibst du dein Einverständnis, dass dein Inhalt unter der folgenden Lizenz veröffentlicht wird:'; $lang['searchmedia'] = 'Suche nach Datei:'; $lang['searchmedia_in'] = 'Suche in %s'; $lang['txt_upload'] = 'Datei zum Hochladen auswählen:'; $lang['txt_filename'] = 'Hochladen als (optional):'; $lang['txt_overwrt'] = 'Bestehende Datei überschreiben'; $lang['maxuploadsize'] = 'Max. %s pro Datei-Upload.'; $lang['allowedmime'] = 'Liste der erlaubten Dateiendungen'; $lang['lockedby'] = 'Momentan gesperrt von:'; $lang['lockexpire'] = 'Sperre läuft ab am:'; $lang['rssfailed'] = 'Es ist ein Fehler beim Laden des Feeds aufgetreten: '; $lang['nothingfound'] = 'Nichts gefunden.'; $lang['mediaselect'] = 'Dateiauswahl'; $lang['uploadsucc'] = 'Datei wurde erfolgreich hochgeladen'; $lang['uploadfail'] = 'Hochladen fehlgeschlagen. Keine Berechtigung?'; $lang['uploadwrong'] = 'Hochladen verweigert. Diese Dateiendung ist nicht erlaubt.'; $lang['uploadexist'] = 'Datei existiert bereits. Keine Änderungen vorgenommen.'; $lang['uploadbadcontent'] = 'Die hochgeladenen Daten stimmen nicht mit der Dateiendung %s überein.'; $lang['uploadspam'] = 'Hochladen verweigert: Treffer auf der Spamliste.'; $lang['uploadxss'] = 'Hochladen verweigert: Daten scheinen Schadcode zu enthalten.'; $lang['uploadsize'] = 'Die hochgeladene Datei war zu groß. (max. %s)'; $lang['deletesucc'] = 'Die Datei "%s" wurde gelöscht.'; $lang['deletefail'] = '"%s" konnte nicht gelöscht werden. Keine Berechtigung?.'; $lang['mediainuse'] = 'Die Datei "%s" wurde nicht gelöscht. Sie wird noch verwendet.'; $lang['namespaces'] = 'Namensräume'; $lang['mediafiles'] = 'Vorhandene Dateien in'; $lang['accessdenied'] = 'Du hast keinen Zugriff auf diese Seite'; $lang['mediausage'] = 'Syntax zum Verwenden dieser Datei:'; $lang['mediaview'] = 'Originaldatei öffnen'; $lang['mediaroot'] = 'Wurzel'; $lang['mediaupload'] = 'Lade hier eine Datei in den momentanen Namensraum hoch. Um Unterordner zu erstellen, stelle diese dem Dateinamen durch Doppelpunkt getrennt voran, nachdem Du die Datei ausgewählt hast.'; $lang['mediaextchange'] = 'Dateiendung vom .%s nach .%s geändert!'; $lang['reference'] = 'Verwendung von'; $lang['ref_inuse'] = 'Diese Datei kann nicht gelöscht werden, da sie noch von folgenden Seiten benutzt wird:'; $lang['ref_hidden'] = 'Einige Verweise sind auf Seiten, für die du keine Leseberechtigung hast.'; $lang['hits'] = 'Treffer'; $lang['quickhits'] = 'Passende Seitennamen'; $lang['toc'] = 'Inhaltsverzeichnis'; $lang['current'] = 'aktuell'; $lang['yours'] = 'Deine Version'; $lang['diff'] = 'Zeige Unterschiede zu aktueller Version'; $lang['diff2'] = 'Zeige Unterschiede der ausgewählten Versionen'; $lang['difflink'] = 'Link zu der Vergleichsansicht'; $lang['diff_type'] = 'Unterschiede anzeigen:'; $lang['diff_inline'] = 'Inline'; $lang['diff_side'] = 'Nebeneinander'; $lang['diffprevrev'] = 'Vorherige Überarbeitung'; $lang['diffnextrev'] = 'Nächste Überarbeitung'; $lang['difflastrev'] = 'Letzte Überarbeitung'; $lang['diffbothprevrev'] = 'Beide Seiten, vorherige Überarbeitung'; $lang['diffbothnextrev'] = 'Beide Seiten, nächste Überarbeitung'; $lang['line'] = 'Zeile'; $lang['breadcrumb'] = 'Zuletzt angesehen:'; $lang['youarehere'] = 'Du befindest dich hier:'; $lang['lastmod'] = 'Zuletzt geändert:'; $lang['by'] = 'von'; $lang['deleted'] = 'gelöscht'; $lang['created'] = 'angelegt'; $lang['restored'] = 'alte Version wiederhergestellt (%s)'; $lang['external_edit'] = 'Externe Bearbeitung'; $lang['summary'] = 'Zusammenfassung'; $lang['noflash'] = 'Das <a href="http://www.adobe.com/products/flashplayer/">Adobe Flash Plugin</a> wird benötigt, um diesen Inhalt anzuzeigen.'; $lang['download'] = 'Schnipsel herunterladen'; $lang['tools'] = 'Werkzeuge'; $lang['user_tools'] = 'Benutzer-Werkzeuge'; $lang['site_tools'] = 'Webseiten-Werkzeuge'; $lang['page_tools'] = 'Seiten-Werkzeuge'; $lang['skip_to_content'] = 'zum Inhalt springen'; $lang['sidebar'] = 'Seitenleiste'; $lang['mail_newpage'] = 'Neue Seite:'; $lang['mail_changed'] = 'Seite geändert:'; $lang['mail_subscribe_list'] = 'Geänderte Seiten im Namensraum:'; $lang['mail_new_user'] = 'Neuer Benutzer:'; $lang['mail_upload'] = 'Datei hochgeladen:'; $lang['changes_type'] = 'Änderungen anzeigen von'; $lang['pages_changes'] = 'Seiten'; $lang['media_changes'] = 'Mediendateien'; $lang['both_changes'] = 'Beides, Seiten- und Mediendateien'; $lang['qb_bold'] = 'Fetter Text'; $lang['qb_italic'] = 'Kursiver Text'; $lang['qb_underl'] = 'Unterstrichener Text'; $lang['qb_code'] = 'Code Text'; $lang['qb_strike'] = 'Durchgestrichener Text'; $lang['qb_h1'] = 'Level 1 Überschrift'; $lang['qb_h2'] = 'Level 2 Überschrift'; $lang['qb_h3'] = 'Level 3 Überschrift'; $lang['qb_h4'] = 'Level 4 Überschrift'; $lang['qb_h5'] = 'Level 5 Überschrift'; $lang['qb_h'] = 'Überschrift'; $lang['qb_hs'] = 'Wähle eine Überschrift'; $lang['qb_hplus'] = 'Überschrift eine Ebene höher'; $lang['qb_hminus'] = 'Überschrift eine Ebene runter'; $lang['qb_hequal'] = 'Überschrift auf selber Ebene'; $lang['qb_link'] = 'Interner Link'; $lang['qb_extlink'] = 'Externer Link'; $lang['qb_hr'] = 'Horizontale Linie'; $lang['qb_ol'] = 'Nummerierter Listenpunkt'; $lang['qb_ul'] = 'Listenpunkt'; $lang['qb_media'] = 'Bilder und andere Dateien hinzufügen'; $lang['qb_sig'] = 'Unterschrift einfügen'; $lang['qb_smileys'] = 'Smileys'; $lang['qb_chars'] = 'Sonderzeichen'; $lang['upperns'] = 'Gehe zum übergeordneten Namensraum'; $lang['metaedit'] = 'Metadaten bearbeiten'; $lang['metasaveerr'] = 'Die Metadaten konnten nicht gesichert werden'; $lang['metasaveok'] = 'Metadaten gesichert'; $lang['img_title'] = 'Titel:'; $lang['img_caption'] = 'Bildunterschrift:'; $lang['img_date'] = 'Datum:'; $lang['img_fname'] = 'Dateiname:'; $lang['img_fsize'] = 'Größe:'; $lang['img_artist'] = 'Fotograf:'; $lang['img_copyr'] = 'Copyright:'; $lang['img_format'] = 'Format:'; $lang['img_camera'] = 'Kamera:'; $lang['img_keywords'] = 'Schlagwörter:'; $lang['img_width'] = 'Breite:'; $lang['img_height'] = 'Höhe:'; $lang['subscr_subscribe_success'] = 'Die Seite %s wurde zur Abonnementliste von %s hinzugefügt'; $lang['subscr_subscribe_error'] = 'Fehler beim Hinzufügen von %s zur Abonnementliste von %s'; $lang['subscr_subscribe_noaddress'] = 'In deinem Account ist keine E-Mail-Adresse hinterlegt. Dadurch kann die Seite nicht abonniert werden'; $lang['subscr_unsubscribe_success'] = 'Die Seite %s wurde von der Abonnementliste von %s entfernt'; $lang['subscr_unsubscribe_error'] = 'Fehler beim Entfernen von %s von der Abonnementliste von %s'; $lang['subscr_already_subscribed'] = '%s ist bereits auf der Abonnementliste von %s'; $lang['subscr_not_subscribed'] = '%s ist nicht auf der Abonnementliste von %s'; $lang['subscr_m_not_subscribed'] = 'Du hast kein Abonnement von dieser Seite oder dem Namensraum.'; $lang['subscr_m_new_header'] = 'Abonnementen hinzufügen'; $lang['subscr_m_current_header'] = 'Aktive Abonnements'; $lang['subscr_m_unsubscribe'] = 'Abbestellen'; $lang['subscr_m_subscribe'] = 'Abonnieren'; $lang['subscr_m_receive'] = 'Erhalten'; $lang['subscr_style_every'] = 'E-Mail bei jeder Änderung'; $lang['subscr_style_digest'] = 'E-Mail mit zusammengefasster Übersicht der Seitenänderungen (alle %.2f Tage)'; $lang['subscr_style_list'] = 'Auflistung aller geänderten Seiten seit der letzten E-Mail (alle %.2f Tage)'; $lang['authtempfail'] = 'Benutzerüberprüfung momentan nicht möglich. Falls das Problem andauert, wende dich an den Admin.'; $lang['i_chooselang'] = 'Wähle deine Sprache'; $lang['i_installer'] = 'DokuWiki-Installation'; $lang['i_wikiname'] = 'Wiki-Name'; $lang['i_enableacl'] = 'Zugriffskontrolle (ACL) aktivieren (empfohlen)'; $lang['i_superuser'] = 'Benutzername des Administrators'; $lang['i_problems'] = 'Das Installationsprogramm hat unten aufgeführte Probleme festgestellt, die zunächst behoben werden müssen, bevor du mit der Installation fortfahren kannst.'; $lang['i_modified'] = 'Aus Sicherheitsgründen arbeitet dieses Skript nur mit einer neuen bzw. nicht modifizierten DokuWiki-Installation. Du solltest entweder alle Dateien noch einmal frisch installieren oder die <a href="http://dokuwiki.org/install">Dokuwiki-Installationsanleitung</a> konsultieren.'; $lang['i_funcna'] = 'Die PHP-Funktion <code>%s</code> ist nicht verfügbar. Unter Umständen wurde sie von deinem Hoster deaktiviert?'; $lang['i_disabled'] = 'Es wurde von deinem Provider deaktiviert.'; $lang['i_funcnmail'] = '<b>Hinweis:</b> Die PHP-Funktion "mail()" ist nicht verfügbar. %s Alternativ kansnt du das <a href="https://www.dokuwiki.org/plugin:smtp">SMTP-Plugin</a> installieren.'; $lang['i_phpver'] = 'Deine PHP-Version <code>%s</code> ist niedriger als die benötigte Version <code>%s</code>. Bitte aktualisiere deine PHP-Installation.'; $lang['i_mbfuncoverload'] = 'mbstring.func_overload muss in php.in deaktiviert werden um DokuWiki auszuführen.'; $lang['i_urandom'] = 'DokuWiki kann keine kryptografisch sicheren Werte für Cookies generieren. Möglicherweise möchtest du die "open_basedir"-Einstellungen in der zutreffenden php.ini auf korrekten Zugriff auf <code>/ dev/urandom</ code> überprüfen.'; $lang['i_permfail'] = '<code>%s</code> ist nicht durch DokuWiki beschreibbar. Du musst die Berechtigungen dieses Ordners ändern!'; $lang['i_confexists'] = '<code>%s</code> existiert bereits'; $lang['i_writeerr'] = '<code>%s</code> konnte nicht erzeugt werden. Du solltest die Verzeichnis-/Datei-Rechte überprüfen und die Datei manuell anlegen.'; $lang['i_badhash'] = 'Unbekannte oder modifizierte dokuwiki.php (Hash=<code>%s</code>)'; $lang['i_badval'] = '<code>%s</code> - unerlaubter oder leerer Wert'; $lang['i_success'] = 'Die Konfiguration wurde erfolgreich abgeschlossen. Du kannst jetzt die install.php löschen. Dein <a href="doku.php?id=wiki:welcome">neues DokuWiki</a> ist jetzt für dich bereit.'; $lang['i_failure'] = 'Es sind Fehler beim Schreiben der Konfigurationsdateien aufgetreten. Du musst diese von Hand beheben, bevor du dein <a href="doku.php?id=wiki:welcome">neues DokuWiki</a> nutzen kannst.'; $lang['i_policy'] = 'Anfangseinstellungen der Zugriffskontrolle (ACL)'; $lang['i_pol0'] = 'Offenes Wiki (lesen, schreiben und hochladen für alle Benutzer)'; $lang['i_pol1'] = 'Öffentliches Wiki (Lesen für alle, Schreiben und Hochladen nur für registrierte Benutzer)'; $lang['i_pol2'] = 'Geschlossenes Wiki (Lesen, Schreiben und Hochladen nur für registrierte Benutzer)'; $lang['i_allowreg'] = 'Benutzer können sich selbst registrieren'; $lang['i_retry'] = 'Wiederholen'; $lang['i_license'] = 'Bitte wähle die Lizenz aus unter der die Wiki-Inhalte veröffentlicht werden sollen:'; $lang['i_license_none'] = 'Keine Lizenzinformationen anzeigen'; $lang['i_pop_field'] = 'Bitte helfe uns, die DokuWiki-Erfahrung zu verbessern'; $lang['i_pop_label'] = 'Sende einmal im Monat anonyme Nutzungsdaten an die DokuWiki Entwickler'; $lang['recent_global'] = 'Im Moment siehst du die Änderungen im Namensraum <b>%s</b>. Du kannst auch <a href="%s">die Änderungen im gesamten Wiki sehen</a>.'; $lang['years'] = 'vor %d Jahren'; $lang['months'] = 'vor %d Monaten'; $lang['weeks'] = 'vor %d Wochen'; $lang['days'] = 'vor %d Tagen'; $lang['hours'] = 'vor %d Stunden'; $lang['minutes'] = 'vor %d Minuten'; $lang['seconds'] = 'vor %d Sekunden'; $lang['wordblock'] = 'Deine Bearbeitung wurde nicht gespeichert, da sie gesperrten Text enthielt (Spam).'; $lang['media_uploadtab'] = 'Hochladen'; $lang['media_searchtab'] = 'Suchen'; $lang['media_file'] = 'Datei'; $lang['media_viewtab'] = 'Anzeigen'; $lang['media_edittab'] = 'Bearbeiten'; $lang['media_historytab'] = 'Verlauf'; $lang['media_list_thumbs'] = 'Medien anzeigen als Miniaturansicht'; $lang['media_list_rows'] = 'Medien anzeigen als Listenansicht'; $lang['media_sort_name'] = 'Sortieren nach Name'; $lang['media_sort_date'] = 'Sortieren nach Datum'; $lang['media_namespaces'] = 'Namensraum wählen'; $lang['media_files'] = 'Medien im Namensraum <strong>%s</strong>.'; $lang['media_upload'] = 'In den <strong>%s</strong> Namensraum hochladen.'; $lang['media_search'] = 'Im Namensraum <strong>%s</strong> suchen.'; $lang['media_view'] = '%s'; $lang['media_viewold'] = '%s in %s'; $lang['media_edit'] = '%s bearbeiten'; $lang['media_history'] = 'Versionen von %s'; $lang['media_meta_edited'] = 'Meta-Informationen bearbeitet'; $lang['media_perm_read'] = 'Du besitzt nicht die notwendigen Berechtigungen um die Datei anzuzeigen.'; $lang['media_perm_upload'] = 'Du besitzt nicht die notwendigen Berechtigungen um Dateien hochzuladen.'; $lang['media_update'] = 'Neue Version hochladen'; $lang['media_restore'] = 'Diese Version wiederherstellen'; $lang['media_acl_warning'] = 'Diese Liste ist möglicherweise nicht vollständig. Versteckte und durch ACL gesperrte Seiten werden nicht angezeigt.'; $lang['email_fail'] = 'PHP-Funktion "mail ()" fehlt oder ist deaktiviert. Die folgende E-Mail wurde nicht gesendet:'; $lang['currentns'] = 'Aktueller Namensraum'; $lang['searchresult'] = 'Suchergebnis'; $lang['plainhtml'] = 'Reines HTML'; $lang['wikimarkup'] = 'Wiki Markup'; $lang['page_nonexist_rev'] = 'Seite existierte nicht an der Stelle %s. Sie wurde an folgende Stelle erstellt: <a href="%s">%s</a>.'; $lang['unable_to_parse_date'] = 'Parameter "%s" kann nicht geparsed werden.'; $lang['email_signature_text'] = 'Diese E-Mail wurde erzeugt vom DokuWiki unter @DOKUWIKIURL@';
mprins/dokuwiki
inc/lang/de-informal/lang.php
PHP
gpl-2.0
26,205
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 1030, 6105, 14246, 2140, 1016, 1006, 8299, 1024, 1013, 1013, 7479, 1012, 27004, 1012, 8917, 1013, 15943, 1013, 14246, 2140, 1012, 16129, 1007, 1008, 1008, 1030, 3166, 18586, 11382, 11140, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #include "registryaccess.h" #include <QApplication> #include <QDir> #include <QTextStream> namespace RegistryAccess { static QString winErrorMessage(unsigned long error) { QString rc = QString::fromLatin1("#%1: ").arg(error); ushort *lpMsgBuf; const int len = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (LPTSTR)&lpMsgBuf, 0, NULL); if (len) { rc = QString::fromUtf16(lpMsgBuf, len); LocalFree(lpMsgBuf); } else { rc += QString::fromLatin1("<unknown error>"); } return rc; } QString msgFunctionFailed(const char *f, unsigned long error) { return QString::fromLatin1("\"%1\" failed: %2").arg(QLatin1String(f), winErrorMessage(error)); } static bool registryReadBinaryKey(HKEY handle, // HKEY_LOCAL_MACHINE, etc. const WCHAR *valueName, QByteArray *data, QString *errorMessage) { data->clear(); DWORD type; DWORD size; // get size and retrieve LONG rc = RegQueryValueEx(handle, valueName, 0, &type, 0, &size); if (rc != ERROR_SUCCESS) { *errorMessage = msgRegistryOperationFailed("read", valueName, msgFunctionFailed("RegQueryValueEx1", rc)); return false; } BYTE *dataC = new BYTE[size + 1]; // Will be Utf16 in case of a string rc = RegQueryValueEx(handle, valueName, 0, &type, dataC, &size); if (rc != ERROR_SUCCESS) { *errorMessage = msgRegistryOperationFailed("read", valueName, msgFunctionFailed("RegQueryValueEx2", rc)); return false; } *data = QByteArray(reinterpret_cast<const char*>(dataC), size); delete [] dataC; return true; } bool registryReadStringKey(HKEY handle, // HKEY_LOCAL_MACHINE, etc. const WCHAR *valueName, QString *s, QString *errorMessage) { QByteArray data; if (!registryReadBinaryKey(handle, valueName, &data, errorMessage)) return false; data += '\0'; data += '\0'; *s = QString::fromUtf16(reinterpret_cast<const unsigned short*>(data.data())); return true; } bool openRegistryKey(HKEY category, // HKEY_LOCAL_MACHINE, etc. const WCHAR *key, bool readWrite, HKEY *keyHandle, AccessMode mode, QString *errorMessage) { Q_UNUSED(debuggerRegistryKeyC); // avoid warning from MinGW REGSAM accessRights = KEY_READ; if (readWrite) accessRights |= KEY_SET_VALUE; switch (mode) { case RegistryAccess::DefaultAccessMode: break; case RegistryAccess::Registry32Mode: accessRights |= KEY_WOW64_32KEY; break; case RegistryAccess::Registry64Mode: accessRights |= KEY_WOW64_64KEY; break; } const LONG rc = RegOpenKeyEx(category, key, 0, accessRights, keyHandle); if (rc != ERROR_SUCCESS) { *errorMessage = msgFunctionFailed("RegOpenKeyEx", rc); if (readWrite) *errorMessage += QLatin1String("You need administrator privileges to edit the registry."); return false; } return true; } // Installation helpers: Format the debugger call with placeholders for PID and event // '"[path]\qtcdebugger" [-wow] %ld %ld'. QString debuggerCall(const QString &additionalOption) { QString rc; QTextStream str(&rc); str << '"' << QDir::toNativeSeparators(QApplication::applicationDirPath() + QLatin1Char('/') + QLatin1String(debuggerApplicationFileC) + QLatin1String(".exe")) << '"'; if (!additionalOption.isEmpty()) str << ' ' << additionalOption; str << " %ld %ld"; return rc; } bool isRegistered(HKEY handle, const QString &call, QString *errorMessage, QString *oldDebugger) { QString registeredDebugger; registryReadStringKey(handle, debuggerRegistryValueNameC, &registeredDebugger, errorMessage); if (oldDebugger) *oldDebugger = registeredDebugger; return !registeredDebugger.compare(call, Qt::CaseInsensitive); } } // namespace RegistryAccess
Philips14171/qt-creator-opensource-src-4.2.1
src/shared/registryaccess/registryaccess.cpp
C++
gpl-3.0
5,457
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 30524, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * SYSTEM/FS/FAT.H * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef FAT_H_INCLUDED #define FAT_H_INCLUDED #include <FORMATTING.H> typedef struct _FAT121632_BPB { uint8_t OEMName[8]; uint16_t BytesPerSector; uint8_t SectorsPerCluster; uint16_t ReservedSectors; uint8_t NumberOfFats; uint16_t NumDirEntries; uint16_t NumSectors; uint8_t Media; uint16_t SectorsPerFat; uint16_t SectorsPerTrack; uint16_t HeadsPerCyl; uint32_t HiddenSectors; uint32_t LongSectors; }__attribute__((packed)) FATBPB, *PFATBPB; typedef struct _FAT1216_BPB_EXT { uint8_t DriveNumber; uint8_t Flags; uint8_t Signiture; uint32_t Serial; char VolumeLable[11]; char SysIDString[8]; }__attribute__((packed)) FAT1216BPBEXT, *PFAT1216BPBEXT; typedef struct _FAT32_BPB_EXT { uint32_t SectorsPerFat32; uint16_t Flags; uint16_t Version; uint32_t RootCluster; uint16_t InfoCluster; uint16_t BackupBoot; uint16_t Reserved[6]; uint8_t DriveNumber; uint8_t flag; uint8_t Signiture; uint32_t Serial; char VolumeLable[11]; char SysIDString[8]; }__attribute__((packed)) FAT32BPBEXT, *PFAT32BPBEXT; typedef struct _FAT1216_BS { uint8_t Ignore[3]; //first 3 bytes are ignored FATBPB Bpb; FAT1216BPBEXT BpbExt; uint8_t Filler[448]; //needed to make struct 512 bytes uint16_t BootSig; }__attribute__((packed)) FAT1216BS, *PFAT1216BS; typedef struct _FAT32_BS { uint8_t Ignore[3]; //first 3 bytes are ignored FATBPB Bpb; FAT32BPBEXT BpbExt; uint8_t Filler[420]; //needed to make struct 512 bytes uint16_t BootSig; }__attribute__((packed)) FAT32BS, *PFAT32BS; typedef struct _FAT_DIRECTORY { uint8_t Filename[11]; uint8_t Attrib; uint8_t Reserved; uint8_t TimeCreatedMs; uint16_t TimeCreated; uint16_t DateCreated; uint16_t DateLastAccessed; uint16_t FirstClusterHiBytes; uint16_t LastModTime; uint16_t LastModDate; uint16_t FirstCluster; uint32_t FileSize; }__attribute__((packed)) FATDIR, *PFATDIR; typedef struct _FAT_DIR_SECTOR { FATDIR DIRENT[16]; } DIRSEC, *PDIRSEC; typedef struct _TEMP_DIR { DIRSEC Sector[4096]; } TDIR, *PTDIR; void _FAT_init(void); #endif
basicfreak/BOS
0.0.1/SRC/SYSTEM/FS/FAT.H
C++
unlicense
2,287
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 2291, 1013, 1042, 2015, 1013, 6638, 1012, 1044, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <title>MorTeam</title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:700,300,400' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Exo+2:400,300,200' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Titillium+Web' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="css/index.css" type="text/css"> </head> <body> <div id="login_area"> <form id="form"> <input class="login_item" type="text" placeholder="Username/Email" id="username_box"></input> <input class="login_item" type="password" placeholder="Password" id="password_box"></input> <div id="remember"><input type="checkbox" id="remember_box" checked></input><label for="remember_box" id="remember_text">Remember me?</label></div> <input class="login_item" type="submit" value="Log In" id="login_button"></input> </form> <input class="login_item" type="submit" value="Sign Up" id="signup_buttonL"></input> </div> <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ document.getElementById("form").onsubmit = function() { var userOrEmail = document.getElementById("username_box").value.trim(); var pass = document.getElementById("password_box").value.trim(); var xhr = new XMLHttpRequest(); xhr.open("POST", "/f/loginUser", true); xhr.onreadystatechange = function() { if(xhr.readyState == 4&&xhr.status == 200) { if (xhr.responseText != "invalid login"){ var resData = JSON.parse(xhr.responseText); var token = resData.token; var user = resData.user; var firstName = resData.first; var lastName = resData.last; var phone = resData.phone; var email = resData.email; //var teamName = resData.teamName; //var teamCode = resData.teamCode; //var teamNumber = resData.teamNumber; localStorage.setItem("username", user); console.log(user); localStorage.setItem("userToken", token); localStorage.firstName = firstName; localStorage.lastName = lastName; localStorage.phone = phone; localStorage.email = email; localStorage.teamName = ""; localStorage.teamCode = ""; localStorage.teamNumber = ""; location="index"; } else { //Failed login console.log("ransad") alert("Incorrect user/email or password"); } } }; xhr.send(JSON.stringify({"user":userOrEmail, "pass":pass})); return false; }; $('#signup_buttonL').click(function(){ location = "signup"; }); }); window.onunload = function(){}; </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-66914799-1', 'auto'); ga('send', 'pageview'); </script> </html>
mortorqrobotics/Morganizer-website
login.html
HTML
mit
4,126
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1013, 1028, 1026, 18804, 8299, 1011, 1041, 15549, 2615, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** Copyright (C) 2014 by Krishna C Tripathi, Johns Creek, GA All rights reserved. This file is part of DHCPv6 Library. DHCPv6 Library 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, version 3 of the License. DHCPv6 Library 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 DHCPv6 Library. If not, see <http://www.gnu.org/licenses/>. */ package org.himalay.dhcpv6; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.himalay.msgs.runtime.ByteArray; import org.himalay.msgs.runtime.Created; import org.himalay.msgs.runtime.DumpContext; import org.himalay.msgs.runtime.NullStream; @Created(date = "Fri Nov 07 11:29:35 EST 2014") public class Authentication extends DhcpOptionFactory.DhcpOption { // Concrete // type is // Authentication // members variables // header public DhcpOptionHeader header; // protocol public short protocol; // algorithm public short algorithm; // rdm public short rdm; // replayDetection public ReplayDetection replayDetection; // authInfo public ByteArray authInfo; public Authentication() // throws Exception { init(); } private void init() { // Initialize header header = new DhcpOptionHeader(); // Initialize protocol // Initialize algorithm // Initialize rdm // Initialize replayDetection replayDetection = new ReplayDetection(); // Initialize authInfo authInfo = new ByteArray(); authInfo.setSizeType("EXTERNAL"); } public int readNoHeader(DataInputStream istream) throws IOException { preRead(); int retVal = 0; // read protocol { protocol = (short) (istream.readUnsignedByte()); retVal += 1; } // read algorithm { algorithm = (short) (istream.readUnsignedByte()); retVal += 1; } // read rdm { rdm = (short) (istream.readUnsignedByte()); retVal += 1; } // read replayDetection retVal += replayDetection.read(istream); // read authInfo { authInfo.setSizeType("EXTERNAL"); int iRead = getHeader().length + (-11); authInfo.setSize(iRead); retVal += authInfo.read(istream); } postRead(); return retVal; } public int read(DataInputStream istream) throws IOException { preRead(); int retVal = 0; // read header retVal += header.read(istream); // read protocol { protocol = (short) (istream.readUnsignedByte()); retVal += 1; } // read algorithm { algorithm = (short) (istream.readUnsignedByte()); retVal += 1; } // read rdm { rdm = (short) (istream.readUnsignedByte()); retVal += 1; } // read replayDetection retVal += replayDetection.read(istream); // read authInfo { authInfo.setSizeType("EXTERNAL"); int iRead = getHeader().length + (-11); authInfo.setSize(iRead); retVal += authInfo.read(istream); } postRead(); return retVal; } public int write(DataOutputStream ostream) throws IOException { preWrite(); int retVal = 0; { /** fix dependent sizes for header **/ } { /** fix dependent sizes for replayDetection **/ } { /** fix dependent sizes for authInfo **/ header.length = ((short) authInfo.getSize() - (-11)); } // write header if (header != null) retVal += header.write(ostream); // write protocol ostream.writeByte(protocol); retVal += 1; // write algorithm ostream.writeByte(algorithm); retVal += 1; // write rdm ostream.writeByte(rdm); retVal += 1; // write replayDetection if (replayDetection != null) retVal += replayDetection.write(ostream); // write authInfo { retVal += authInfo.write(ostream); } postWrite(); return retVal; } public int dump(DumpContext dc) throws IOException { dc.indent(); dc.getPs().print("Authentication\n"); dc.increaseIndent(); int retVal = 0; // write header if (header != null) { dc.indent(); dc.getPs().println("header"); retVal += header.dump(dc); } // write protocol dc.indent(); dc.getPs().println( "protocol=" + protocol + "(0x" + Integer.toHexString(protocol) + ")"); // write algorithm dc.indent(); dc.getPs().println( "algorithm=" + algorithm + "(0x" + Integer.toHexString(algorithm) + ")"); // write rdm dc.indent(); dc.getPs().println( "rdm=" + rdm + "(0x" + Integer.toHexString(rdm) + ")"); // write replayDetection if (replayDetection != null) { dc.indent(); dc.getPs().println("replayDetection"); retVal += replayDetection.dump(dc); } // write authInfo dc.indent(); dc.getPs().print( "authInfo: " + authInfo.getSize() + "(0x" + Integer.toHexString(authInfo.getSize()) + ")\n"); this.authInfo.dump(dc); dc.decreaseIndent(); return retVal; } // Getter for header // public DhcpOptionHeader getHeader() // { // return header ; // } // Setter for header // public void setHeader(DhcpOptionHeader val) // { // this.header= val; // } // Getter for protocol // public short getProtocol() // { // return protocol ; // } // Setter for protocol // public void setProtocol(short val) // { // this.protocol= val; // } // Getter for algorithm // public short getAlgorithm() // { // return algorithm ; // } // Setter for algorithm // public void setAlgorithm(short val) // { // this.algorithm= val; // } // Getter for rdm // public short getRdm() // { // return rdm ; // } // Setter for rdm // public void setRdm(short val) // { // this.rdm= val; // } // Getter for replayDetection // public ReplayDetection getReplayDetection() // { // return replayDetection ; // } // Setter for replayDetection // public void setReplayDetection(ReplayDetection val) // { // this.replayDetection= val; // } // Getter for authInfo // public ByteArray getAuthInfo() // { // return authInfo ; // } // Setter for authInfo // public void setAuthInfo(ByteArray val) // { // this.authInfo= val; // } public void setAuthInfo(byte[] val) { this.authInfo.setData(val); } public int getSize() throws IOException { DataOutputStream dos = new DataOutputStream(new NullStream()); return this.write(dos); } public void setHeader(DhcpOptionHeader header) { this.header = header; } public DhcpOptionHeader getHeader() { return this.header; } } // End of code
krishnact/dhcpv6lib
src/java/other/org/himalay/dhcpv6/Authentication.java
Java
gpl-3.0
6,957
[ 30522, 1013, 30524, 1010, 11545, 3636, 1010, 11721, 2035, 2916, 9235, 1012, 2023, 5371, 2003, 2112, 1997, 28144, 21906, 2615, 2575, 3075, 1012, 28144, 21906, 2615, 2575, 3075, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Node.js - Aula 03 - Exercício **User:** ronal2do **Author:** Ronaldo Lima **Date:** 1468022470175 ##### [Exercício-01](#por-que-quando-requisitamos-ao-nosso-servidor-de-query-string-com-o-chrome-ele-executa-2-requisi%C3%A7%C3%B5es-sendo-a-%C3%BAltima-vazia) ##### [Exercício-02](#qual-a-diferen%C3%A7a-entre-o-get-e-o-post) ##### [Exercício-03](#crie-um-pokemon-na-nossa-api-com-seu-nome-depois-modifique-seu-nome-pelo-seu-user-do-github-colocando-aqui-a-resposta-de-cada-passo) ##### [Exercício-04](#depois-fa%C3%A7a-o-delete-criando-o-script-para-tal-colocando-aqui-a-resposta) ##### [Exercício-05](#escolha-uma-api-externa-e-crie-um-script-para-fazer-um-get-nela-mostrando-o-resultado-em-html) # Por que quando requisitamos ao nosso servidor de Query String, com o Chrome, ele executa 2 requisições, sendo a última "vazia"? Pois em cada requisição, o Chrome também faz a solicitação de um `favicon`. # Qual a diferença entre o GET e o POST? O `GET` é utilizado para quando queremos acessar alguma informação no servidor, outra coisa, o mesmo é visualizado através da url(a querystring após o endereço do servidor), e só pode enviar texto. O `POST` é utilizado para quando queremos gravar alguma informação no servidor, pode enviar diversos tipos de dados(texto, arquivos, etc...). # Crie um Pokemon na nossa API com seu nome, depois modifique seu nome pelo seu User do Github, colocando aqui a resposta de cada passo. ### Cadastrando com o meu nome ```js 'use strict'; const http = require('http'); const querystring = require('querystring'); const postData = querystring.stringify({ name: '2D Lima' , type: 'Lokoooo!' }); const options = { host: 'webschool-io.herokuapp.com' , path: '/api/pokemons' , method: 'POST' , headers: { 'Content-Type': 'application/x-www-form-urlencoded' , 'Content-Length': postData.length } }; function callback(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Dados finalizados: ', data) }) } const req = http.request(options, callback); req.on('error', (e) => { console.log('ERROOOO: ' + e.message); }); req.write(postData); req.end(); ``` ### Saída no terminal ```js STATUS: 201 HEADERS: {"server":"Cowboy","x-powered-by":"Express","access-control-allow-origin":"*","content-type":"application/json; charset=utf-8","content-length":"77","etag":"W/\"4d-K1XAJt0nixO1Ke2TlcK+0g\"","date":"Sat, 09 Jul 2016 02:39:50 GMT","via":"1.1 vegur"} Dados finalizados: {"__v":0,"name":"2D Lima","type":"Lokoooo!","_id":"578063f62d78cb11006de9c4"} ``` ### Modificando com o meu user do github ```js 'use strict'; const http = require('http'); const querystring = require('querystring'); const postData = querystring.stringify({ name: 'ronal2do' , type: 'Lokoo!' }); const options = { host: 'webschool-io.herokuapp.com' , path: '/api/pokemons/578063f62d78cb11006de9c4' , method: 'PUT' , headers: { 'Content-Type': 'application/x-www-form-urlencoded' , 'Content-Length': postData.length } }; function callback(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Dados finalizados: ', data) }) } const req = http.request(options, callback); req.on('error', (e) => { console.log('ERROOOO: ' + e.message); }); req.write(postData); req.end(); ``` ### Saída no terminal ```js STATUS: 202 HEADERS: {"server":"Cowboy","x-powered-by":"Express","access-control-allow-origin":"*","content-type":"application/json; charset=utf-8","content-length":"108","etag":"W/\"6c-KUssZB1YDVSRLM9IZUNAAA\"","date":"Sat, 09 Jul 2016 02:53:02 GMT","via":"1.1 vegur"} Dados finalizados: {"data":{"ok":1,"nModified":1,"n":1,"lastOp":"6305152788145897473","electionId":"576451dfece94f32689e021d"}} ``` # Depois faça o delete, criando o script para tal, colocando aqui a resposta. ```js 'use strict'; const http = require('http'); const querystring = require('querystring'); const postData = querystring.stringify({ name: 'ronal2do' , type: 'Lokoo!' }); const options = { host: 'webschool-io.herokuapp.com' , path: '/api/pokemons/578063f62d78cb11006de9c4' , method: 'DELETE' , headers: { 'Content-Type': 'application/x-www-form-urlencoded' , 'Content-Length': postData.length } }; function callback(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Dados finalizados: ', data) }) } const req = http.request(options, callback); req.on('error', (e) => { console.log('ERROOOO: ' + e.message); }); req.write(postData); req.end(); ``` ### Saída no terminal ```js STATUS: 204 HEADERS: {"server":"Cowboy","content-length":"0","x-powered-by":"Express","access-control-allow-origin":"*","date":"Sat, 09 Jul 2016 02:57:29 GMT","via":"1.1 vegur"} Dados finalizados: ``` # Escolha uma API externa e crie um script para fazer um GET nela mostrando o resultado em HTML. ### Código ```js // API do Magic TCG 'use strict'; const http = require('http'); const options = { host: 'api.deckbrew.com' , path: '/mtg/cards/about-face' }; function callback(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Dados finalizados: ', data) }) } const req = http.request(options, callback); req.on('error', (e) => { console.log('ERROOOO: ' + e.message); }); req.end(); ``` ### Resultado Terminal com JSON ```js STATUS: 200 HEADERS: {"date":"Sat, 09 Jul 2016 03:04:03 GMT","content-type":"application/json; charset=utf-8","content-length":"1186","set-cookie":["__cfduid=d62533328f17b2bacebe1331b35537e781468033443; expires=Sun, 09-Jul-17 03:04:03 GMT; path=/; domain=.deckbrew.com; HttpOnly"],"access-control-allow-origin":"*","access-control-expose-headers":"link,content-length","cache-control":"public,max-age=3600","disclaimer":"This API is not produced, endorsed, supported, or affiliated with Wizards of the Coast.","license":"The textual information presented through this API about Magic: The Gathering is copyrighted by Wizards of the Coast.","pricing":"store.tcgplayer.com allows you to buy cards from any of our vendors, all at the same time, in a simple checkout experience. Shop, Compare & Save with TCGplayer.com!","strict-transport-security":"max-age=86400","via":"1.1 vegur","server":"cloudflare-nginx","cf-ray":"2bf88be07bef07bb-MIA"} Dados finalizados: { "name": "About Face", "id": "about-face", "url": "https://api.deckbrew.com/mtg/cards/about-face", "store_url": "http://store.tcgplayer.com/magic/urzas-legacy/about-face?partner=DECKBREW", "types": [ "instant" ], "colors": [ "red" ], "cmc": 1, "cost": "{R}", "text": "Switch target creature's power and toughness until end of turn.", "formats": { "commander": "legal", "legacy": "legal", "vintage": "legal" }, "editions": [ { "set": "Urza's Legacy", "set_id": "ULG", "rarity": "common", "artist": "Melissa A. Benson", "multiverse_id": 12414, "flavor": "The overconfident are the most vulnerable.", "number": "73", "layout": "normal", "price": { "low": 0, "median": 0, "high": 0 }, "url": "https://api.deckbrew.com/mtg/cards?multiverseid=12414", "image_url": "https://image.deckbrew.com/mtg/multiverseid/12414.jpg", "set_url": "https://api.deckbrew.com/mtg/sets/ULG", "store_url": "http://store.tcgplayer.com/magic/urzas-legacy/about-face?partner=DECKBREW", "html_url": "https://deckbrew.com/mtg/cards/12414" } ] } ``` ### Resultado HTML ```js // API do Magic TCG 'use strict'; const http = require('http'); const json2Html = require('node-json2html'); const options = { host: 'api.deckbrew.com' , path: '/mtg/cards/about-face' }; function callback(res){ console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); let dados = ''; res.on('data', (chunk) => { dados += chunk; }); res.on('end', () => { let js = JSON.parse(dados); console.log('<ul>'); console.log('<li> Nome: ' + js.name + '</li>'); console.log('<li> id: ' + js.id + '</li>'); console.log('<li> url: ' + js.url + '</li>'); console.log('<li> text: ' + js.text + '</li>'); console.log('<li> power: ' + js.power + '</li>'); console.log('<ul>'); }) } const req = http.request(options, callback); req.on('erros', (e) => { console.log('ERRO: ' + e.message); }); req.end(); ``` ```js STATUS: 200 HEADERS: {"date":"Sat, 09 Jul 2016 03:31:51 GMT","content-type":"application/json; charset=utf-8","content-length":"1186","set-cookie":["__cfduid=ddf6689c13114b06f1204dd2355c37aac1468035111; expires=Sun, 09-Jul-17 03:31:51 GMT; path=/; domain=.deckbrew.com; HttpOnly"],"access-control-allow-origin":"*","access-control-expose-headers":"link,content-length","cache-control":"public,max-age=3600","disclaimer":"This API is not produced, endorsed, supported, or affiliated with Wizards of the Coast.","license":"The textual information presented through this API about Magic: The Gathering is copyrighted by Wizards of the Coast.","pricing":"store.tcgplayer.com allows you to buy cards from any of our vendors, all at the same time, in a simple checkout experience. Shop, Compare & Save with TCGplayer.com!","strict-transport-security":"max-age=86400","via":"1.1 vegur","server":"cloudflare-nginx","cf-ray":"2bf8b49549172e7b-MIA"} <ul> <li> Nome: About Face</li> <li> id: about-face</li> <li> url: https://api.deckbrew.com/mtg/cards/about-face</li> <li> text: Switch target creature's power and toughness until end of turn.</li> <li> power: undefined</li> <ul> sh-3.2# ```
Webschool-io/be-mean-instagram-nodejs-exercises
class-03/class-03-resolved-ronal2do-ronaldo-lima.md
Markdown
cc0-1.0
10,627
[ 30522, 1001, 13045, 1012, 1046, 2015, 1011, 8740, 2721, 6021, 1011, 4654, 2121, 19053, 3695, 1008, 1008, 5310, 1024, 1008, 1008, 6902, 2389, 2475, 3527, 1008, 1008, 3166, 1024, 1008, 1008, 8923, 2080, 12967, 1008, 1008, 3058, 1024, 1008, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: page title: Introduction permalink: /voynich-manuscript/introduction --- Voynich Manuscript is an unique illustrated codex hand-written in early 15th century in an unknown language and writing system, no one has yet been able in deciphering the text of **240 pages**, not a single confirmed word has been decoded. ![_config.yml]({{ site.baseurl }}/voynich/images/f50v-part.jpg) In this section of the website I'll be posting my on-going research, the goal is to create tools and generate reliable results that can be tested and used by others, hopefully to solve the mystery. I will curate previous research done by other people, keep in mind there are many pseudo-scientific blogs and YouTube videos that claimed to have deciphered it, with unconvincing hypothesis. [Go Back](/voynich-manuscript) ### Further Reading * [Wikipedia - Voynich Manuscript](https://en.wikipedia.org/wiki/Voynich_manuscript) * [voynich.nu](http://www.voynich.nu/) * [ic.unicamp.br/~stolfi/voynich/](http://www.ic.unicamp.br/~stolfi/voynich/)
AndreiRegiani/andreiregiani.github.io
voynich/introduction.md
Markdown
mit
1,038
[ 30522, 1011, 1011, 1011, 9621, 1024, 3931, 2516, 1024, 4955, 2566, 9067, 19839, 1024, 1013, 29536, 6038, 7033, 1011, 8356, 1013, 4955, 1011, 1011, 1011, 29536, 6038, 7033, 8356, 2003, 2019, 4310, 7203, 15763, 2192, 1011, 2517, 1999, 2220, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; namespace LiteDB { /// <summary> /// A class that represent all index options used on a index creation /// </summary> public class IndexOptions : IEquatable<IndexOptions> { public IndexOptions() { Unique = false; IgnoreCase = true; TrimWhitespace = true; EmptyStringToNull = true; RemoveAccents = true; } /// <summary> /// Unique keys? /// </summary> public bool Unique { get; set; } /// <summary> /// Ignore case? (convert all strings to lowercase) /// </summary> public bool IgnoreCase { get; set; } /// <summary> /// Remove all whitespace on start/end string? /// </summary> public bool TrimWhitespace { get; set; } /// <summary> /// Convert all empty string to null? /// </summary> public bool EmptyStringToNull { get; set; } /// <summary> /// Removing accents on string? /// </summary> public bool RemoveAccents { get; set; } public bool Equals(IndexOptions other) { return Unique == other.Unique && IgnoreCase == other.IgnoreCase && TrimWhitespace == other.TrimWhitespace && EmptyStringToNull == other.EmptyStringToNull && RemoveAccents == other.RemoveAccents; } public IndexOptions Clone() { return new IndexOptions { Unique = Unique, IgnoreCase = IgnoreCase, TrimWhitespace = TrimWhitespace, EmptyStringToNull = EmptyStringToNull, RemoveAccents = RemoveAccents }; } } }
Xicy/SilkroadScript
Shared/Core/LiteDB/DbEngine/Structures/IndexOptions.cs
C#
gpl-3.0
1,846
[ 30522, 2478, 2291, 1025, 3415, 15327, 5507, 2098, 2497, 1063, 1013, 1013, 1013, 1026, 12654, 1028, 1013, 1013, 1013, 1037, 2465, 2008, 5050, 2035, 5950, 7047, 2109, 2006, 1037, 5950, 4325, 1013, 1013, 1013, 1026, 1013, 12654, 1028, 2270, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
//! Abstracts out the APIs necessary to `Runtime` for integrating the blocking //! pool. When the `blocking` feature flag is **not** enabled, these APIs are //! shells. This isolates the complexity of dealing with conditional //! compilation. mod pool; pub(crate) use pool::{spawn_blocking, BlockingPool, Mandatory, Spawner, Task}; cfg_fs! { pub(crate) use pool::spawn_mandatory_blocking; } mod schedule; mod shutdown; mod task; pub(crate) use schedule::NoopSchedule; pub(crate) use task::BlockingTask; use crate::runtime::Builder; pub(crate) fn create_blocking_pool(builder: &Builder, thread_cap: usize) -> BlockingPool { BlockingPool::new(builder, thread_cap) } /* cfg_not_blocking_impl! { use crate::runtime::Builder; use std::time::Duration; #[derive(Debug, Clone)] pub(crate) struct BlockingPool {} pub(crate) use BlockingPool as Spawner; pub(crate) fn create_blocking_pool(_builder: &Builder, _thread_cap: usize) -> BlockingPool { BlockingPool {} } impl BlockingPool { pub(crate) fn spawner(&self) -> &BlockingPool { self } pub(crate) fn shutdown(&mut self, _duration: Option<Duration>) { } } } */
tokio-rs/tokio
tokio/src/runtime/blocking/mod.rs
Rust
mit
1,211
[ 30522, 1013, 1013, 999, 29474, 2041, 1996, 17928, 2015, 4072, 2000, 1036, 2448, 7292, 1036, 2005, 22380, 1996, 10851, 1013, 1013, 999, 4770, 1012, 2043, 1996, 1036, 10851, 1036, 3444, 5210, 2003, 1008, 1008, 2025, 1008, 1008, 9124, 1010, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php namespace PpgwBundle\Controller; use PpgwBundle\Helpers\CodeHighlighter; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class TechController extends Controller { public function ch1Action(){ return $this->render('PpgwBundle:Tech:ch1.html.twig', array( )); } public function ch2Action(){ return $this->render('PpgwBundle:Tech:ch2.html.twig', array( )); } public function ch3Action(){ return $this->render('PpgwBundle:Tech:ch3.html.twig', array( )); } public function ch4Action(){ return $this->render('PpgwBundle:Tech:ch4.html.twig', array( )); } public function ch5Action(){ $em = $this->getDoctrine() ->getManager(); $plant = $em->getRepository('PpgwBundle:Plant')->find(1); $ar = array(); $ar[] = 'BloggerBlogBundle::layout.html.twig'; $ar[] = 'bundles/bloggerblog/css/plant.css'; $ar[] = 'BloggerBlogBundle_plant_show'; $ar[] = 'PpgwBundle::layout.html.twig'; $ar[] = 'bundles/ppgw/css/forms.css'; $ar[] = 'bundles/ppgw/js/forms.js'; $ar[] = 'widget_container_attributes'; $ar[] = 'widget_attributes'; $ar[] = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'; $ar[] = 'PpgwBundle_plant_index'; $ar[] = 'PpgwBundle_plant_new'; $ar[] = 'http://www.catalogueoflife.org/annual-checklist/2015/browse/'; $ar[] = 'bundles/ppgw/css/plant.css'; $ar[] = 'PpgwBundle_plant_edit'; $ar[] = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNDcrG80wqzVn2wZRARTJEuZ3mUVSXxMiXfE6cGOvm6TOEiI_F'; $helper = $this->get('twig.highlighter'); $twig_1 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/ch5_snippet_1.html.twig', $ar); $twig_2 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/new.html.twig', $ar); $php_1 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/Entity/Plant.php'); $php_2 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/Form/PlantForm.php'); $twig_3 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/show.html.twig', $ar); $php_3 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/ch5_snippet_3.php'); $twig_4 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/edit.html.twig', $ar); $php_4 = $helper->highlightPhpFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/ch5_snippet_4.php'); return $this->render('PpgwBundle:Tech:ch5.html.twig', array( 'plant' => $plant, 'twig_1' => $twig_1, 'twig_2' => $twig_2, 'twig_3'=> $twig_3, 'php_1' => $php_1, 'php_2' => $php_2, 'php_3' => $php_3, 'twig_4' => $twig_4, 'php_4' => $php_4, )); } public function ch6Action(){ return $this->render('PpgwBundle:Tech:ch6.html.twig', array( )); } public function ch7Action(){ $ar = array(); $ar[1] = 'PpgwBundle::layout.html.twig'; $ar[2] = 'bundles/ppgw/css/plant.css'; $ar[3] = 'PpgwBundle_sort'; $ar[4] = 'PpgwBundle_plant_new'; $ar[5] = 'PpgwBundle_plant_show'; $helper = $this->get('twig.highlighter'); $twig_1 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/Resources/views/Plant/index.html.twig', $ar); $twig_2 = $helper->highlightTwigFile('C:/WAMP/www/website/src/PpgwBundle/code_snippets/pagination_snippet_1.html.twig', $ar); return $this->render('PpgwBundle:Tech:ch7.html.twig', array( 'twig_1' => $twig_1, 'twig_2' => $twig_2 )); } public function ch8Action(){ return $this->render('PpgwBundle:Tech:ch8.html.twig', array( )); } public function ch9Action(){ return $this->render('PpgwBundle:Tech:ch9.html.twig', array( )); } public function part1Action(){ return $this->render('PpgwBundle:Tech:pt1.html.twig', array( )); } public function part2Action(){ return $this->render('PpgwBundle:Tech:pt2.html.twig', array( )); } public function part3Action(){ return $this->render('PpgwBundle:Tech:pt3.html.twig', array( )); } public function part4Action(){ return $this->render('PpgwBundle:Tech:pt4.html.twig', array( )); } public function part5Action(){ return $this->render('PpgwBundle:Tech:pt5.html.twig', array( )); } public function part6Action(){ return $this->render('PpgwBundle:Tech:pt6.html.twig', array( )); } public function introAction(){ return $this->render('PpgwBundle:Tech:intro.html.twig', array( )); } public function indexAction(Request $request){ return $this->render('PpgwBundle:Tech:index.html.twig', array( )); } public function tableOfContentsAction(){ //slugs: $pt1 = "part-1-symfony2-configuration-and-templating"; $pt2 = "part-2-contact-page-validators-forms-and-emailing"; $pt3 = "part-3-the-blog-model-using-doctrine2-and-data-fixtures"; $pt4 = "part-4-the-comments-model-adding-comments-doctrine-repositories-and-migrations"; $pt5 = "part-5-customizing-the-view-twig-extensions-the-sidebar-and-assetic"; $pt6 = "part-6-testing-unit-and-functional-with-PHPUnit"; $ch1 = "chapter-1-symfony2-configuration-windows-wamp-netbeans-symfony2"; $ch2 = "chapter-2-symfony2-coding-standards"; $ch3 = "chapter-3-symfony2-github-working-in-teams-and-backup"; $ch4 = "chapter-4-symfony2-doctrine2"; $ch5 = "chapter-5-symfony2-index-new-edit-show-delete-actions"; $ch6 = "chapter-6-symfony2-embedded-forms"; $ch7 = "chapter-7-symfony2-pagination"; $ch8 = "chapter-8-symfony2-search"; $ch9 = "services-symfony2-answer-for-global-functions"; return $this->render('PpgwBundle:Tech:toc.html.twig', array( 'pt1' => $pt1, 'pt2' => $pt2, 'ch1' => $ch1, 'ch4' => $ch4, 'pt3' => $pt3, 'pt4' => $pt4, 'ch2' => $ch2, 'ch5' => $ch5, 'pt5' => $pt5, 'pt6' => $pt6, 'ch3' => $ch3, 'ch6' => $ch6, 'ch7' => $ch7, 'ch8' => $ch8, 'ch9' => $ch9 )); } }
phillharmonic/propagators_world
src/PpgwBundle/Controller/TechController.php
PHP
gpl-2.0
6,910
[ 30522, 1026, 1029, 25718, 3415, 15327, 4903, 2290, 2860, 27265, 2571, 1032, 11486, 1025, 2224, 4903, 2290, 2860, 27265, 2571, 1032, 2393, 2545, 1032, 3642, 4048, 5603, 7138, 2121, 1025, 2224, 25353, 2213, 14876, 4890, 1032, 6922, 1032, 8299...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* a10 513 * Copyright (c) 2001-2012 Nicolas Léveillé <knos.free.fr> * * You should have received this file ('src/lib/cokus.c') with a license * agreement. ('LICENSE' file) * * Copying, using, modifying and distributing this file are rights * covered under this licensing agreement and are conditioned by its * full acceptance and understanding. * e 513 */ // This is the ``Mersenne Twister'' random number generator MT19937, which // generates pseudorandom integers uniformly distributed in 0..(2^32 - 1) // starting from any odd seed in 0..(2^32 - 1). This version is a recode // by Shawn Cokus (Cokus@math.washington.edu) on March 8, 1998 of a version by // Takuji Nishimura (who had suggestions from Topher Cooper and Marc Rieffel in // July-August 1997). // // Effectiveness of the recoding (on Goedel2.math.washington.edu, a DEC Alpha // running OSF/1) using GCC -O3 as a compiler: before recoding: 51.6 sec. to // generate 300 million random numbers; after recoding: 24.0 sec. for the same // (i.e., 46.5% of original time), so speed is now about 12.5 million random // number generations per second on this machine. // // According to the URL <http://www.math.keio.ac.jp/~matumoto/emt.html> // (and paraphrasing a bit in places), the Mersenne Twister is ``designed // with consideration of the flaws of various existing generators,'' has // a period of 2^19937 - 1, gives a sequence that is 623-dimensionally // equidistributed, and ``has passed many stringent tests, including the // die-hard test of G. Marsaglia and the load test of P. Hellekalek and // S. Wegenkittl.'' It is efficient in memory usage (typically using 2506 // to 5012 bytes of static data, depending on data type sizes, and the code // is quite short as well). It generates random numbers in batches of 624 // at a time, so the caching and pipelining of modern systems is exploited. // It is also divide- and mod-free. // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published by // the Free Software Foundation (either version 2 of the License or, at your // option, any later version). This library 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 Library General Public License for more details. You should have // received a copy of the GNU Library General Public License along with this // library; if not, write to the Free Software Foundation, Inc., 59 Temple // Place, Suite 330, Boston, MA 02111-1307, USA. // // The code as Shawn received it included the following notice: // // Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. When // you use this, send an e-mail to <matumoto@math.keio.ac.jp> with // an appropriate reference to your work. // // It would be nice to CC: <Cokus@math.washington.edu> when you write. // #include <libc/stdio.h> #include <libc/stdlib.h> #include <libc/stdint.h> // // uint32_t must be an unsigned integer type capable of holding at least 32 // bits; exactly 32 should be fastest, but 64 is better on an Alpha with // GCC at -O3 optimization so try your options and see what's best for you // #define N (624) // length of state vector #define M (397) // a period parameter #define K (0x9908B0DFU) // a magic constant #define hiBit(u) ((u)&0x80000000U) // mask all but highest bit of u #define loBit(u) ((u)&0x00000001U) // mask all but lowest bit of u #define loBits(u) ((u)&0x7FFFFFFFU) // mask the highest bit of u #define mixBits(u, v) (hiBit(u) | loBits(v)) // move hi bit of u to hi bit of v static uint32_t state[N + 1]; // state vector + 1 extra to not violate ANSI C static uint32_t *next; // next random value is computed from here static int left = -1; // can *next++ this many times before reloading extern void seedMT(uint32_t seed) { // // We initialize state[0..(N-1)] via the generator // // x_new = (69069 * x_old) mod 2^32 // // from Line 15 of Table 1, p. 106, Sec. 3.3.4 of Knuth's // _The Art of Computer Programming_, Volume 2, 3rd ed. // // Notes (SJC): I do not know what the initial state requirements // of the Mersenne Twister are, but it seems this seeding generator // could be better. It achieves the maximum period for its modulus // (2^30) iff x_initial is odd (p. 20-21, Sec. 3.2.1.2, Knuth); if // x_initial can be even, you have sequences like 0, 0, 0, ...; // 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, // 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. // // Even if x_initial is odd, if x_initial is 1 mod 4 then // // the lowest bit of x is always 1, // the next-to-lowest bit of x is always 0, // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , // the 3rd-from-lowest bit of x 4-cycles ... 0 1 1 0 0 1 1 0 ... , // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 0 1 1 1 1 0 ... , // ... // // and if x_initial is 3 mod 4 then // // the lowest bit of x is always 1, // the next-to-lowest bit of x is always 1, // the 2nd-from-lowest bit of x alternates ... 0 1 0 1 0 1 0 1 ... , // the 3rd-from-lowest bit of x 4-cycles ... 0 0 1 1 0 0 1 1 ... , // the 4th-from-lowest bit of x has the 8-cycle ... 0 0 1 1 1 1 0 0 ... , // ... // // The generator's potency (min. s>=0 with (69069-1)^s = 0 mod 2^32) is // 16, which seems to be alright by p. 25, Sec. 3.2.1.3 of Knuth. It // also does well in the dimension 2..5 spectral tests, but it could be // better in dimension 6 (Line 15, Table 1, p. 106, Sec. 3.3.4, Knuth). // // Note that the random number user does not see the values generated // here directly since reloadMT() will always munge them first, so maybe // none of all of this matters. In fact, the seed values made here could // even be extra-special desirable if the Mersenne Twister theory says // so-- that's why the only change I made is to restrict to odd seeds. // register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state; register int j; for (left = 0, *s++ = x, j = N; --j; *s++ = (x *= 69069U) & 0xFFFFFFFFU) ; } extern uint32_t reloadMT(void) { register uint32_t *p0 = state, *p2 = state + 2, *pM = state + M, s0, s1; register int j; if (left < -1) seedMT(4357U); left = N - 1, next = state + 1; for (s0 = state[0], s1 = state[1], j = N - M + 1; --j; s0 = s1, s1 = *p2++) *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); for (pM = state, j = M; --j; s0 = s1, s1 = *p2++) *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); s1 = state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U); s1 ^= (s1 >> 11); s1 ^= (s1 << 7) & 0x9D2C5680U; s1 ^= (s1 << 15) & 0xEFC60000U; return (s1 ^ (s1 >> 18)); } extern uint32_t randomMT(void) { uint32_t y; if (--left < 0) return (reloadMT()); y = *next++; y ^= (y >> 11); y ^= (y << 7) & 0x9D2C5680U; y ^= (y << 15) & 0xEFC60000U; return (y ^ (y >> 18)); } #if 0 int main(void) { int j; // you can seed with any uint32_t, but the best are odds in 0..(2^32 - 1) seedMT(4357U); // print the first 2,002 random numbers seven to a line as an example for(j=0; j<2002; j++) printf(" %10lu%s", (unsigned long) randomMT(), (j%7)==6 ? "\n" : ""); return(EXIT_SUCCESS); } #endif
uucidl/plus-one-minus-one
src/lib/cokus.c
C
gpl-2.0
7,813
[ 30522, 1013, 1008, 17350, 2692, 4868, 2509, 1008, 9385, 1006, 1039, 1007, 2541, 1011, 2262, 9473, 23310, 24359, 2571, 1026, 14161, 2891, 1012, 2489, 1012, 10424, 1028, 1008, 1008, 2017, 2323, 2031, 2363, 2023, 5371, 1006, 1005, 5034, 2278, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * @file lab.c * @synopsis * @author a1an1in@sina.com * @version * @date 2016-10-11 */ /* Copyright (c) 2015-2020 alan lin <a1an1in@sina.com> * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <libobject/core/utils/dbg/debug.h> #include <libobject/core/utils/registry/registry.h> int ex(int a, int b) { int d = 1; int i; for (i = 0; i < b ; i++) { d = d * a; } return d; } int hexstr_to_int(char *str) { int len, i, d, t = 0, count = 0; char c; len = strlen(str); for (i = len - 1; i >= 0; i--) { printf("%d\n", i); c = str[i]; if (c >= 'a' && c <= 'f') { d = c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { d = c - 'A' + 10; } else { d = c - '0'; } if (c == 'x' || c == 'X') break; t += ex(16, count++) * d; printf("len = %d count=%d e=%d d=%d\n",len, count, ex(16, count), d); } return t; } int test_hex_to_int() { char buf[1024]; int d; while(gets(buf)) { d = hexstr_to_int(buf); printf("%d\n", d); } } REGISTER_TEST_CMD(test_hex_to_int); char* strchr_n(char *s, char c, int n) { int count = 0; while(*s != '\0') { if (*s == c) { count++; } if (count == n) break; ++s; } if (count == n) { return s; } else return NULL; } int test_strchr(TEST_ENTRY *entry) { char *str = "lbrnsepcfjzcpfgzqdiujo"; char *p; int len, i; len = strlen(str); for (i = 0; i < len; i++) { p = strchr_n(str, str[i], 2); if (p == NULL) { printf("found %c", str[i]); break; } } } REGISTER_TEST_CMD(test_strchr);
a1an1in/libobject
src/cmds/mockery/lab/string.c
C
lgpl-2.1
3,226
[ 30522, 1013, 1008, 1008, 1008, 1030, 5371, 6845, 1012, 1039, 1008, 1030, 19962, 22599, 1008, 1030, 3166, 17350, 2319, 2487, 2378, 1030, 8254, 2050, 1012, 4012, 1008, 1030, 2544, 1008, 1030, 3058, 2355, 1011, 2184, 1011, 2340, 1008, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
require 'web_blocks/thor/inspect' module WebBlocks module Thor class Inspect order_desc = "File order based on topological sort of dependency list" desc "dependency_order", order_desc long_desc order_desc method_option :type, :desc => "Any of: \"#{types.keys.join('", "')}\"; default \"all\"." def dependency_order prepare_blocks! type = self.class.type_get_class_from_string options.type root.get_file_load_order(type).each do |file| say "#{file.resolved_path.to_s}" end end end end end
WebBlocks/WebBlocks
lib/web_blocks/thor/inspect/dependency_order.rb
Ruby
bsd-3-clause
585
[ 30522, 5478, 1005, 4773, 1035, 5991, 1013, 15321, 1013, 22459, 1005, 11336, 10923, 7878, 2015, 11336, 15321, 2465, 22459, 2344, 1035, 4078, 2278, 1027, 1000, 5371, 2344, 2241, 2006, 24309, 4066, 1997, 24394, 2862, 1000, 4078, 2278, 1000, 24...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- categories: - 思考感悟 date: '2014-09-07' description: '' tags: [] title: 创业感悟 url: /2014/09/07/startup/ --- 时光飞逝,转眼间距离上一篇博客已经快三年时间。这三年里,人们逐渐从博客转移到了微博,看的人少了,写的人也少了。以前,写博客是一种潮流,现在,写博客已经是一种坚持了。连Google都放弃了RSS,我不知道那些曾经订阅过我博客的朋友,你们还在坚持用RSS看文章吗?我写的这篇文章,你们在用Google Reader的替代品看到我的文章吗?如果有看到,并且我的文章对你有帮助,请留言告诉我。这会是我更新博客很好的动力。 <!--more--> ### 编程,游戏 也许是缘分,和游戏结下了不解之缘。从小,我就是个爱玩游戏的小孩。小学时因考三好学生,家人奖励了我一台小霸王游戏机,从此爱不释手。家人怕影响我学习,只有寒暑假才能拿出来玩,所以每次玩有格外珍惜。后来,电脑开始慢慢普及,网络开始盛行。人们开始成群的挤在网吧,玩大富翁4,红警,仙剑,FIFA99。我这时正读初中,参加了QB编程竞赛小组。 那时候的学习资源很有限,走遍整个小县城的书店也找不到几本关于编程的书。竞赛的结果并不理想,但是通过编程小组,让我在很早的时候就接触到了计算机,并且被编程所吸引。不知小叔从哪里找来的一台比386还旧的电脑,于是我就在这台电脑上折腾DOS、QB、WPS。当时编了一个小游戏,随机生成几个字母从左到右移动然后消失,然后需要玩家通过记忆输入刚才出现过的字母,玩的不亦乐乎。 高中时去租电脑光碟,偶然听老板说了一句:现在不用QB了,都流行用VB了。于是开始学VB。高二时还给英语老师做了一套英语听力教学系统,老师讲解一道题,然后出现四个选项,勾选后会出现对错的结果。当时的自豪感还杠杠的。 然而,高考的压力,我并未选择喜欢的计算机专业,而是保守的选择了招生最多的土木工程专业,中南大学的土木系在全国还能排在前几名,但是我不喜欢。于是我开始玩游戏,肆无忌惮的玩游戏,通宵达旦的玩剑一,每天晚上宋金战场抢夺BOSS人头总有我的身影,游戏里拉帮结派,抢地盘,打群架,做买卖。记得有一个帮会的人和我们打了一天架后,居然成了好朋友。至今还记得他们的帮会名字叫洪兴十三妹什么的。也有人被我们欺负后说要来长沙找我人肉PK,当时还真有那么一点害怕。 游戏中有太多有意思的回忆,在此就略过了。从那时起,我才真正意识到一个虚拟的网络世界真的会让人沉迷,忘记了吃饭睡觉,不去上课,考试挂科,对现实世界麻木不仁。当时我也很讨厌自己,为什么会这么没出息?我这学业还能不能完成,我是不是一直在辜负家人的期望。我想改变,但是发现很难。游戏里,我是快乐的,自豪的,精力无限充沛的,而现实中是麻木的,自责的,没精打采的。这种游戏的状态和感受,多年后也不曾再出现过。 游戏之余,同样有个东西吸引着我,那就是编程。并且很幸运加入了学校的学子天空网(中国大学生创业网)。在那里我遇到了很多优秀的同学,学习到太多的东西。它给了我信心,告诉我,也许,土木工程不一定是我的唯一出路。也许,我毕业后可以做自己喜欢的事情,那就是编程。 大学临近毕业了,我们专业的就业机会是很多的,而且各大铁路局都抢着要人。同学们纷纷签订了中铁XX局,XX设计院。而我一直在等待,等待着一个机会。有一天,偶然的机会,我看到金山软件在校本部举行校园招聘的消息。室友陪我一起逃课去参加了招聘会。我选择了WPS的自动化测试工程师,因为只有这个职位需要我熟悉的C#语言。我同学当时选了游戏策划,笔试完后,他异常兴奋,他说这是他从小到大答过的最爽的一次考试,里面问的全是游戏怎么好玩的问题。然而兴奋之余,他竟然在联系电话一栏忘记了填。 后来,我来到了金山软件。他在外面干了几年建筑设计后来回到老家进了个不错的设计院。我来到金山,成为金山训练营第一批成员,从此开始了我的编程生涯。之后从金山WPS,到金山毒霸,后来到西山居,有太多优秀的同事,给予了我巨大的帮助。在金山的这几年,是我学习积累非常重要的几年。测试开发的工作,没有太多项目的压力,不需要加班,可以尽情的利用业余时间去研究各种新奇好玩的技术。我的大部分技术博客,也是在那段时间完成的。 测试开发的工作,主要是编写一些测试代码去对产品代码进行测试,保证其功能的正确性,稳定性,安全性等。其实在我心里,一直都很羡慕直接参与产品开发的程序员。虽然我知道就编程来说,他们的工作其实和我的并没有多大的区别。但是,看着用户在使用着你的产品,关注着你的产品,作为一个产品直接的开发人员,自豪感是更强的。我告诉自己,我不想再测试别人的代码了,我想自己来写! 我一直在寻找和等待着这样一个机会,并且也做了不少的尝试。某天,当我听到我原来的技术老大鱼头要出来创业做游戏时,我已经按捺不住兴奋的心情了。于是我放弃了金山安逸的生活,来到了广州,开始了我的游戏开发的生涯,开始了我的创业生涯。 ### 创业 公司初创人员有10几个, 大都来自金山内部。我经历了公司从无到有的整个过程,从申请营业执照,到选取办公地点、办公设备,申请域名,搭建Git,RTX,Wiki,项目管理平台Redmine,持续构建CCNet…… 这些都是一个公司必要的支持。而对于我来说,还是蛮新鲜的,能接触到一些平时不容易接触到的东西,初创人员也是激情四溢,各擅所长,感觉平时听他们聊天都能学习到不少的知识。 即使我平时游戏玩的够多,自认为也算是个中高端游戏玩家。但做为一个刚刚涉入游戏开发领域的新人,心中还是有一些胆怯的,所以我更多的是去听他们的想法,然后在心里理解分析。 关于游戏定位的讨论一开始就进行了。我们认真去玩并且分析了当时市面上刚出的几款端游。比如《征途2》、《凡人修仙传》等。最终,我们给出了我们游戏的定位:面向低端玩家的电脑配置要求低、易上手操作简单的道具收费玄幻题材的3DMMORPG。好吧,前面这句话是我自己总结的,大致是符合当时的想法的。我对于游戏定位的思考,一直贯穿着整个创业过程。但是在当时,身边都是比我有游戏经验的同事,我其实是没有太多的想法的。我的想法就是,信任他们。 为了实现游戏的配置低的目标,我们想出一个办法。就是给所有人的电脑配置都比较低,价格控制在3000块左右。一旦一个不合理的算法出现,或者不合理的美术资源添加,将直接影响到我们自己的游戏体验,从而督促着我们去修改。当时的我配置甚至是一台联想笔记本,在上面开发着3D游戏。 关于这种做法,当时我是纠结的。它的好处是明显的,开发环境和玩家环境一致,可以时刻督促我们的游戏在配置上不至于跑偏。当然,也有另外一个好处就是帮老板省钱。它的坏处也是明显的,严重影响了我们的开发效率。实际上,这条规则并没有一直贯穿执行下去,老同事用着慢如蜗牛的机器,用幻灯片的方式艰难的玩着LOL。新来的同事的配置调到最高却依然满帧。就在前几天,我们给所有程序的电脑升级到8G的内存,并且配置240G的SSD(固态硬盘),我使用了3年的老旧电脑也被替换了下来。用这种极端的方式控制游戏的性能,我也不能完全说是对是错,至少这是我们走过的路。 开始阶段,我负责整个游戏的UI脚本和表现逻辑部分。这在西山居可是两个组干的活,而且我还是个新手,需要不断的在摸索中学习。很快,我就已经上手。UI需要直接和游戏逻辑交互,表现逻辑需要直接和3D引擎交互,很快,我又担当起了游戏逻辑组的重担,并且在3D引擎组打了一手酱油。如今,我已经成为了程序组内的Full Stack,对整体开发环节最了解的一个。 写这篇文章,并不是从程序角度对写过的代码和模块进行总结。而是通过回忆一路走过的创业历程,让自己重新去思考,公司和人员是如何变化的,游戏产品是如何演变的,当然最重要的,是自己的心态和思维方式是如何改变的。 (未完待续……)
wowdudu/funbsd
content/post/2014/2014-09-07-startup.md
Markdown
mit
9,265
[ 30522, 1011, 1011, 1011, 7236, 1024, 1011, 100, 100, 100, 100, 3058, 1024, 1005, 2297, 1011, 5641, 1011, 5718, 1005, 6412, 1024, 1005, 1005, 22073, 1024, 1031, 1033, 2516, 1024, 100, 100, 100, 100, 24471, 2140, 1024, 1013, 2297, 1013, 5...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# - Try to find the GLIB2 libraries # Once done this will define # # GLIB2_FOUND - system has glib2 # GLIB2_INCLUDE_DIR - the glib2 include directory # GLIB2_LIBRARIES - glib2 library # Copyright (c) 2008 Laurent Montel, <montel@kde.org> # # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. if(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) # Already in cache, be silent set(GLIB2_FIND_QUIETLY TRUE) endif(GLIB2_INCLUDE_DIR AND GLIB2_LIBRARIES) if (NOT WIN32) find_package(PkgConfig REQUIRED) pkg_check_modules(PKG_GLIB REQUIRED glib-2.0) endif(NOT WIN32) find_path(GLIB2_MAIN_INCLUDE_DIR glib.h PATH_SUFFIXES glib-2.0 PATHS ${PKG_GLIB_INCLUDE_DIRS} ) # search the glibconfig.h include dir under the same root where the library is found find_library(GLIB2_LIBRARIES NAMES glib-2.0 PATHS ${PKG_GLIB_LIBRARY_DIRS} ) find_path(GLIB2_INTERNAL_INCLUDE_DIR glibconfig.h PATH_SUFFIXES glib-2.0/include ../lib/glib-2.0/include PATHS ${PKG_GLIB_INCLUDE_DIRS} ${PKG_GLIB_LIBRARIES} ${CMAKE_SYSTEM_LIBRARY_PATH}) set(GLIB2_INCLUDE_DIR ${GLIB2_MAIN_INCLUDE_DIR}) # not sure if this include dir is optional or required # for now it is optional if(GLIB2_INTERNAL_INCLUDE_DIR) set(GLIB2_INCLUDE_DIR ${GLIB2_INCLUDE_DIR} ${GLIB2_INTERNAL_INCLUDE_DIR}) endif(GLIB2_INTERNAL_INCLUDE_DIR) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(GLIB2 DEFAULT_MSG GLIB2_LIBRARIES GLIB2_MAIN_INCLUDE_DIR) mark_as_advanced(GLIB2_INCLUDE_DIR GLIB2_LIBRARIES)
detrout/kamoso
cmake/FindGLIB2.cmake
CMake
gpl-2.0
1,634
[ 30522, 1001, 1011, 3046, 2000, 2424, 1996, 1043, 29521, 2475, 8860, 1001, 2320, 2589, 2023, 2097, 9375, 1001, 1001, 1043, 29521, 2475, 1035, 2179, 1011, 2291, 2038, 1043, 29521, 2475, 1001, 1043, 29521, 2475, 1035, 2421, 1035, 16101, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Tests for Keras core layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.eager import context from tensorflow.python.framework import ops from tensorflow.python.keras import keras_parameterized from tensorflow.python.keras import testing_utils from tensorflow.python.keras.mixed_precision.experimental import policy from tensorflow.python.ops import math_ops from tensorflow.python.platform import test @keras_parameterized.run_all_keras_modes class DropoutLayersTest(keras_parameterized.TestCase): def test_dropout(self): testing_utils.layer_test( keras.layers.Dropout, kwargs={'rate': 0.5}, input_shape=(3, 2)) testing_utils.layer_test( keras.layers.Dropout, kwargs={'rate': 0.5, 'noise_shape': [3, 1]}, input_shape=(3, 2)) def test_dropout_supports_masking(self): dropout = keras.layers.Dropout(0.5) self.assertEqual(True, dropout.supports_masking) def test_spatial_dropout_1d(self): testing_utils.layer_test( keras.layers.SpatialDropout1D, kwargs={'rate': 0.5}, input_shape=(2, 3, 4)) def test_spatial_dropout_2d(self): testing_utils.layer_test( keras.layers.SpatialDropout2D, kwargs={'rate': 0.5}, input_shape=(2, 3, 4, 5)) testing_utils.layer_test( keras.layers.SpatialDropout2D, kwargs={'rate': 0.5, 'data_format': 'channels_first'}, input_shape=(2, 3, 4, 5)) def test_spatial_dropout_3d(self): testing_utils.layer_test( keras.layers.SpatialDropout3D, kwargs={'rate': 0.5}, input_shape=(2, 3, 4, 4, 5)) testing_utils.layer_test( keras.layers.SpatialDropout3D, kwargs={'rate': 0.5, 'data_format': 'channels_first'}, input_shape=(2, 3, 4, 4, 5)) @keras_parameterized.run_all_keras_modes class LambdaLayerTest(keras_parameterized.TestCase): def test_lambda(self): testing_utils.layer_test( keras.layers.Lambda, kwargs={'function': lambda x: x + 1}, input_shape=(3, 2)) testing_utils.layer_test( keras.layers.Lambda, kwargs={ 'function': lambda x, a, b: x * a + b, 'arguments': { 'a': 0.6, 'b': 0.4 } }, input_shape=(3, 2)) # test serialization with function def f(x): return x + 1 ld = keras.layers.Lambda(f) config = ld.get_config() ld = keras.layers.deserialize({ 'class_name': 'Lambda', 'config': config }) # test with lambda ld = keras.layers.Lambda( lambda x: keras.backend.concatenate([math_ops.square(x), x])) config = ld.get_config() ld = keras.layers.Lambda.from_config(config) def test_lambda_multiple_inputs(self): ld = keras.layers.Lambda(lambda x: x[0], output_shape=lambda x: x[0]) x1 = np.ones([3, 2], np.float32) x2 = np.ones([3, 5], np.float32) out = ld([x1, x2]) self.assertAllEqual(out.shape, [3, 2]) def test_lambda_output_shape(self): l = keras.layers.Lambda(lambda x: x + 1, output_shape=(1, 1)) l(keras.backend.variable(np.ones((1, 1)))) self.assertEqual((1, 1), l.get_config()['output_shape']) def test_lambda_output_shape_function(self): def get_output_shape(input_shape): return 1 * input_shape l = keras.layers.Lambda(lambda x: x + 1, output_shape=get_output_shape) l(keras.backend.variable(np.ones((1, 1)))) self.assertEqual('lambda', l.get_config()['output_shape_type']) def test_lambda_output_shape_autocalculate_multiple_inputs(self): def lambda_fn(x): return math_ops.matmul(x[0], x[1]) l = keras.layers.Lambda(lambda_fn) output_shape = l.compute_output_shape([(10, 10), (10, 20)]) self.assertAllEqual((10, 20), output_shape) def test_lambda_output_shape_list_multiple_outputs(self): def lambda_fn(x): return x l = keras.layers.Lambda(lambda_fn, output_shape=[(10,), (20,)]) output_shape = l.compute_output_shape([(10, 10), (10, 20)]) self.assertAllEqual([(10, 10), (10, 20)], output_shape) def test_lambda_output_shape_tuple_with_none(self): def lambda_fn(x): return x l = keras.layers.Lambda(lambda_fn, output_shape=(None, 10)) output_shape = l.compute_output_shape((5, 10, 20)) self.assertAllEqual([5, None, 10], output_shape.as_list()) def test_lambda_output_shape_function_multiple_outputs(self): def lambda_fn(x): return x def output_shape_fn(input_shape): return input_shape l = keras.layers.Lambda(lambda_fn, output_shape=output_shape_fn) output_shape = l.compute_output_shape([(10, 10), (10, 20)]) self.assertAllEqual([(10, 10), (10, 20)], output_shape) def test_lambda_config_serialization(self): # Test serialization with output_shape and output_shape_type layer = keras.layers.Lambda(lambda x: x + 1, output_shape=(1, 1)) layer(keras.backend.variable(np.ones((1, 1)))) config = layer.get_config() layer = keras.layers.deserialize({ 'class_name': 'Lambda', 'config': config }) layer = keras.layers.Lambda.from_config(config) @keras_parameterized.run_all_keras_modes class CoreLayersTest(keras_parameterized.TestCase): def test_masking(self): testing_utils.layer_test( keras.layers.Masking, kwargs={}, input_shape=(3, 2, 3)) def test_keras_mask(self): x = np.ones((10, 10)) y = keras.layers.Masking(1.)(x) self.assertTrue(hasattr(y, '_keras_mask')) self.assertTrue(y._keras_mask is not None) self.assertAllClose(self.evaluate(y._keras_mask), np.zeros((10,))) def test_activation(self): # with string argument testing_utils.layer_test( keras.layers.Activation, kwargs={'activation': 'relu'}, input_shape=(3, 2)) # with function argument testing_utils.layer_test( keras.layers.Activation, kwargs={'activation': keras.backend.relu}, input_shape=(3, 2)) def test_reshape(self): testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (8, 1)}, input_shape=(3, 2, 4)) testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (-1, 1)}, input_shape=(3, 2, 4)) testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (1, -1)}, input_shape=(3, 2, 4)) testing_utils.layer_test( keras.layers.Reshape, kwargs={'target_shape': (-1, 1)}, input_shape=(None, None, 2)) def test_permute(self): testing_utils.layer_test( keras.layers.Permute, kwargs={'dims': (2, 1)}, input_shape=(3, 2, 4)) def test_permute_errors_on_invalid_starting_dims_index(self): with self.assertRaisesRegexp(ValueError, r'Invalid permutation .*dims.*'): testing_utils.layer_test( keras.layers.Permute, kwargs={'dims': (0, 1, 2)}, input_shape=(3, 2, 4)) def test_permute_errors_on_invalid_set_of_dims_indices(self): with self.assertRaisesRegexp(ValueError, r'Invalid permutation .*dims.*'): testing_utils.layer_test( keras.layers.Permute, kwargs={'dims': (1, 4, 2)}, input_shape=(3, 2, 4)) def test_flatten(self): testing_utils.layer_test( keras.layers.Flatten, kwargs={}, input_shape=(3, 2, 4)) # Test channels_first inputs = np.random.random((10, 3, 5, 5)).astype('float32') outputs = testing_utils.layer_test( keras.layers.Flatten, kwargs={'data_format': 'channels_first'}, input_data=inputs) target_outputs = np.reshape( np.transpose(inputs, (0, 2, 3, 1)), (-1, 5 * 5 * 3)) self.assertAllClose(outputs, target_outputs) def test_flatten_scalar_channels(self): testing_utils.layer_test( keras.layers.Flatten, kwargs={}, input_shape=(3,)) # Test channels_first inputs = np.random.random((10,)).astype('float32') outputs = testing_utils.layer_test( keras.layers.Flatten, kwargs={'data_format': 'channels_first'}, input_data=inputs) target_outputs = np.expand_dims(inputs, -1) self.assertAllClose(outputs, target_outputs) def test_repeat_vector(self): testing_utils.layer_test( keras.layers.RepeatVector, kwargs={'n': 3}, input_shape=(3, 2)) def test_dense(self): testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(3, 2)) testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(3, 4, 2)) testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(None, None, 2)) testing_utils.layer_test( keras.layers.Dense, kwargs={'units': 3}, input_shape=(3, 4, 5, 2)) def test_dense_dtype(self): inputs = ops.convert_to_tensor( np.random.randint(low=0, high=7, size=(2, 2))) layer = keras.layers.Dense(5, dtype='float32') outputs = layer(inputs) self.assertEqual(outputs.dtype, 'float32') def test_dense_with_policy(self): inputs = ops.convert_to_tensor( np.random.randint(low=0, high=7, size=(2, 2)), dtype='float16') layer = keras.layers.Dense(5, dtype=policy.Policy('infer_float32_vars')) outputs = layer(inputs) self.assertEqual(outputs.dtype, 'float16') self.assertEqual(layer.kernel.dtype, 'float32') def test_dense_regularization(self): layer = keras.layers.Dense( 3, kernel_regularizer=keras.regularizers.l1(0.01), bias_regularizer='l1', activity_regularizer='l2', name='dense_reg') layer(keras.backend.variable(np.ones((2, 4)))) self.assertEqual(3, len(layer.losses)) def test_dense_constraints(self): k_constraint = keras.constraints.max_norm(0.01) b_constraint = keras.constraints.max_norm(0.01) layer = keras.layers.Dense( 3, kernel_constraint=k_constraint, bias_constraint=b_constraint) layer(keras.backend.variable(np.ones((2, 4)))) self.assertEqual(layer.kernel.constraint, k_constraint) self.assertEqual(layer.bias.constraint, b_constraint) def test_activity_regularization(self): layer = keras.layers.ActivityRegularization(l1=0.1) layer(keras.backend.variable(np.ones((2, 4)))) self.assertEqual(1, len(layer.losses)) config = layer.get_config() self.assertEqual(config.pop('l1'), 0.1) def test_numpy_inputs(self): if context.executing_eagerly(): layer = keras.layers.RepeatVector(2) x = np.ones((10, 10)) self.assertAllEqual(np.ones((10, 2, 10)), layer(x)) layer = keras.layers.Concatenate() x, y = np.ones((10, 10)), np.ones((10, 10)) self.assertAllEqual(np.ones((10, 20)), layer([x, y])) if __name__ == '__main__': test.main()
ageron/tensorflow
tensorflow/python/keras/layers/core_test.py
Python
apache-2.0
11,584
[ 30522, 1001, 9385, 2355, 1996, 23435, 12314, 6048, 1012, 2035, 2916, 9235, 1012, 1001, 1001, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 30524, 1024, 1013, 1013, 7479, 1012, 15895, 1012, 8917, 1013, 15943, 1013, 6105, 1011, 1016, 1012,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package buildconfig import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/http" "net/http/httptest" "reflect" "strings" "testing" corev1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" apirequest "k8s.io/apiserver/pkg/endpoints/request" clientesting "k8s.io/client-go/testing" "k8s.io/kubernetes/pkg/api/legacyscheme" kapi "k8s.io/kubernetes/pkg/apis/core" buildv1 "github.com/openshift/api/build/v1" buildfake "github.com/openshift/client-go/build/clientset/versioned/fake" buildclientv1 "github.com/openshift/client-go/build/clientset/versioned/typed/build/v1" "github.com/openshift/openshift-apiserver/pkg/build/apiserver/apiserverbuildutil" "github.com/openshift/openshift-apiserver/pkg/build/apiserver/webhook" "github.com/openshift/openshift-apiserver/pkg/build/apiserver/webhook/bitbucket" "github.com/openshift/openshift-apiserver/pkg/build/apiserver/webhook/github" "github.com/openshift/openshift-apiserver/pkg/build/apiserver/webhook/gitlab" // _ "github.com/openshift/openshift-apiserver/pkg/api/install" ) type fakeInstantiator interface { Instantiate(buildConfigName string, buildRequest *buildv1.BuildRequest) (*buildv1.Build, error) } type fakeBuildConfigInterface struct { inst fakeInstantiator client buildclientv1.BuildConfigInterface namespace string } func (f *fakeBuildConfigInterface) Create(build *buildv1.BuildConfig) (*buildv1.BuildConfig, error) { return f.client.Create(build) } func (f *fakeBuildConfigInterface) Update(build *buildv1.BuildConfig) (*buildv1.BuildConfig, error) { return f.client.Update(build) } func (f *fakeBuildConfigInterface) UpdateStatus(build *buildv1.BuildConfig) (*buildv1.BuildConfig, error) { return f.client.UpdateStatus(build) } func (f *fakeBuildConfigInterface) Delete(name string, options *metav1.DeleteOptions) error { return f.client.Delete(name, options) } func (f *fakeBuildConfigInterface) DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error { panic("implement me") } func (f *fakeBuildConfigInterface) Get(name string, options metav1.GetOptions) (*buildv1.BuildConfig, error) { return f.client.Get(name, options) } func (f *fakeBuildConfigInterface) List(opts metav1.ListOptions) (*buildv1.BuildConfigList, error) { return f.client.List(opts) } func (f *fakeBuildConfigInterface) Watch(opts metav1.ListOptions) (watch.Interface, error) { return f.client.Watch(opts) } func (f *fakeBuildConfigInterface) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *buildv1.BuildConfig, err error) { return f.client.Patch(name, pt, data, subresources...) } func (f *fakeBuildConfigInterface) Instantiate(buildConfigName string, buildRequest *buildv1.BuildRequest) (*buildv1.Build, error) { return f.inst.Instantiate(f.namespace, buildRequest) } type fakeBuildConfigClient struct { inst fakeInstantiator client buildclientv1.BuildConfigsGetter fakeclient *buildfake.Clientset } func (i *fakeBuildConfigClient) BuildConfigs(namespace string) buildclientv1.BuildConfigInterface { return &fakeBuildConfigInterface{inst: i.inst, client: i.client.BuildConfigs(namespace)} } func newBuildConfigClient(inst fakeInstantiator, objs ...runtime.Object) buildclientv1.BuildConfigsGetter { client := buildfake.NewSimpleClientset(objs...) return &fakeBuildConfigClient{ inst: inst, fakeclient: client, client: client.BuildV1(), } } type buildConfigInstantiator struct { Build *buildv1.Build Err error Request *buildv1.BuildRequest } func (i *buildConfigInstantiator) Instantiate(namespace string, request *buildv1.BuildRequest) (*buildv1.Build, error) { i.Request = request if i.Build != nil { return i.Build, i.Err } return &buildv1.Build{ ObjectMeta: metav1.ObjectMeta{ Name: request.Name, Namespace: namespace, }, }, i.Err } type plugin struct { Triggers []*buildv1.WebHookTrigger Err error Env []corev1.EnvVar DockerStrategyOptions *buildv1.DockerStrategyOptions Proceed bool } func (p *plugin) Extract(buildCfg *buildv1.BuildConfig, trigger *buildv1.WebHookTrigger, req *http.Request) (*buildv1.SourceRevision, []corev1.EnvVar, *buildv1.DockerStrategyOptions, bool, error) { p.Triggers = []*buildv1.WebHookTrigger{trigger} return nil, p.Env, p.DockerStrategyOptions, p.Proceed, p.Err } func (p *plugin) GetTriggers(buildConfig *buildv1.BuildConfig) ([]*buildv1.WebHookTrigger, error) { trigger := &buildv1.WebHookTrigger{ Secret: "secret", } return []*buildv1.WebHookTrigger{trigger}, nil } func newStorage() (*WebHook, *buildConfigInstantiator, *buildfake.Clientset) { bci := &buildConfigInstantiator{} fakeBuildClient := newBuildConfigClient(bci) plugins := map[string]webhook.Plugin{ "ok": &plugin{Proceed: true}, "okenv": &plugin{ Env: []corev1.EnvVar{ { Name: "foo", Value: "bar", }, }, Proceed: true, }, "errsecret": &plugin{Err: webhook.ErrSecretMismatch}, "errhook": &plugin{Err: webhook.ErrHookNotEnabled}, "err": &plugin{Err: fmt.Errorf("test error")}, } hook := newWebHookREST(fakeBuildClient, nil, buildv1.SchemeGroupVersion, plugins) return hook, bci, fakeBuildClient.(*fakeBuildConfigClient).fakeclient } type fakeResponder struct { called bool statusCode int object runtime.Object err error } func (r *fakeResponder) Object(statusCode int, obj runtime.Object) { if r.called { panic("called twice") } r.called = true r.statusCode = statusCode r.object = obj } func (r *fakeResponder) Error(err error) { if r.called { panic("called twice") } r.called = true r.err = err } func TestConnectWebHook(t *testing.T) { testCases := map[string]struct { Name string Path string Obj *buildv1.BuildConfig RegErr error ErrFn func(error) bool WFn func(*httptest.ResponseRecorder) bool EnvLen int Instantiate bool }{ "hook returns generic error": { Name: "test", Path: "secret/err", Obj: &buildv1.BuildConfig{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"}}, ErrFn: func(err error) bool { return strings.Contains(err.Error(), "Internal error occurred: hook failed: test error") }, Instantiate: false, }, "hook returns unauthorized for bad secret": { Name: "test", Path: "secret/errsecret", Obj: &buildv1.BuildConfig{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"}}, ErrFn: kerrors.IsUnauthorized, Instantiate: false, }, "hook returns unauthorized for bad hook": { Name: "test", Path: "secret/errhook", Obj: &buildv1.BuildConfig{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"}}, ErrFn: kerrors.IsUnauthorized, Instantiate: false, }, "hook returns unauthorized for missing build config": { Name: "test", Path: "secret/errhook", Obj: &buildv1.BuildConfig{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"}}, RegErr: fmt.Errorf("any old error"), ErrFn: kerrors.IsUnauthorized, Instantiate: false, }, "hook returns 200 for ok hook": { Name: "test", Path: "secret/ok", Obj: &buildv1.BuildConfig{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"}}, ErrFn: func(err error) bool { return err == nil }, WFn: func(w *httptest.ResponseRecorder) bool { body, _ := ioutil.ReadAll(w.Body) // We want to make sure that we return the created build in the body. if w.Code == http.StatusOK && len(body) > 0 { // The returned json needs to be a buildclientv1 Build specifically newBuild := &buildv1.Build{} err := json.Unmarshal(body, newBuild) if err == nil { return true } return false } return false }, Instantiate: true, }, "hook returns 200 for okenv hook": { Name: "test", Path: "secret/okenv", Obj: &buildv1.BuildConfig{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"}}, ErrFn: func(err error) bool { return err == nil }, WFn: func(w *httptest.ResponseRecorder) bool { return w.Code == http.StatusOK }, EnvLen: 1, Instantiate: true, }, } for k, testCase := range testCases { hook, bci, fakeBuildClient := newStorage() if testCase.Obj != nil { fakeBuildClient.PrependReactor("get", "buildconfigs", func(action clientesting.Action) (handled bool, ret runtime.Object, err error) { return true, testCase.Obj, nil }) } if testCase.RegErr != nil { fakeBuildClient.PrependReactor("get", "buildconfigs", func(action clientesting.Action) (handled bool, ret runtime.Object, err error) { return true, nil, testCase.RegErr }) } responder := &fakeResponder{} handler, err := hook.Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), testCase.Name, &kapi.PodProxyOptions{Path: testCase.Path}, responder) if err != nil { t.Errorf("%s: %v", k, err) continue } w := httptest.NewRecorder() handler.ServeHTTP(w, &http.Request{}) if err := responder.err; !testCase.ErrFn(err) { t.Errorf("%s: unexpected error: %v", k, err) continue } if testCase.WFn != nil && !testCase.WFn(w) { t.Errorf("%s: unexpected response: %#v", k, w) continue } if testCase.Instantiate { if bci.Request == nil { t.Errorf("%s: instantiator not invoked", k) continue } if bci.Request.Name != testCase.Obj.Name { t.Errorf("%s: instantiator incorrect: %#v", k, bci) continue } } else { if bci.Request != nil { t.Errorf("%s: instantiator should not be invoked: %#v", k, bci) continue } } if bci.Request != nil && testCase.EnvLen != len(bci.Request.Env) { t.Errorf("%s: build request does not have correct env vars: %+v \n", k, bci.Request) } } } type okBuildConfigInstantiator struct{} func (*okBuildConfigInstantiator) Instantiate(namespace string, request *buildv1.BuildRequest) (*buildv1.Build, error) { return &buildv1.Build{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, Name: request.Name, }, }, nil } type errorBuildConfigInstantiator struct{} func (*errorBuildConfigInstantiator) Instantiate(namespace string, request *buildv1.BuildRequest) (*buildv1.Build, error) { return nil, errors.New("Build error!") } type errorBuildConfigGetter struct{} func (*errorBuildConfigGetter) Get(namespace, name string) (*buildv1.BuildConfig, error) { return &buildv1.BuildConfig{}, errors.New("BuildConfig error!") } type errorBuildConfigUpdater struct{} func (*errorBuildConfigUpdater) Update(buildConfig *buildv1.BuildConfig) error { return errors.New("BuildConfig error!") } type pathPlugin struct { } func (p *pathPlugin) Extract(buildCfg *buildv1.BuildConfig, trigger *buildv1.WebHookTrigger, req *http.Request) (*buildv1.SourceRevision, []corev1.EnvVar, *buildv1.DockerStrategyOptions, bool, error) { return nil, []corev1.EnvVar{}, nil, true, nil } func (p *pathPlugin) GetTriggers(buildConfig *buildv1.BuildConfig) ([]*buildv1.WebHookTrigger, error) { trigger := &buildv1.WebHookTrigger{ Secret: "secret101", } return []*buildv1.WebHookTrigger{trigger}, nil } type errPlugin struct { } func (*errPlugin) Extract(buildCfg *buildv1.BuildConfig, trigger *buildv1.WebHookTrigger, req *http.Request) (*buildv1.SourceRevision, []corev1.EnvVar, *buildv1.DockerStrategyOptions, bool, error) { return nil, []corev1.EnvVar{}, nil, false, errors.New("Plugin error!") } func (p *errPlugin) GetTriggers(buildConfig *buildv1.BuildConfig) ([]*buildv1.WebHookTrigger, error) { trigger := &buildv1.WebHookTrigger{ Secret: "secret101", } return []*buildv1.WebHookTrigger{trigger}, nil } var testBuildConfig = &buildv1.BuildConfig{ ObjectMeta: metav1.ObjectMeta{Namespace: "foo", Name: "build100"}, Spec: buildv1.BuildConfigSpec{ Triggers: []buildv1.BuildTriggerPolicy{ { Type: buildv1.GitHubWebHookBuildTriggerType, GitHubWebHook: &buildv1.WebHookTrigger{ Secret: "secret101", }, }, { Type: buildv1.GitLabWebHookBuildTriggerType, GitLabWebHook: &buildv1.WebHookTrigger{ Secret: "secret201", }, }, { Type: buildv1.BitbucketWebHookBuildTriggerType, BitbucketWebHook: &buildv1.WebHookTrigger{ Secret: "secret301", }, }, }, CommonSpec: buildv1.CommonSpec{ Source: buildv1.BuildSource{ Git: &buildv1.GitBuildSource{ URI: "git://github.com/my/repo.git", }, }, Strategy: mockBuildStrategy, }, }, } var mockBuildStrategy = buildv1.BuildStrategy{ SourceStrategy: &buildv1.SourceBuildStrategy{ From: corev1.ObjectReference{ Kind: "DockerImage", Name: "repository/image", }, }, } func TestParseUrlError(t *testing.T) { responder := &fakeResponder{} client := newBuildConfigClient(&okBuildConfigInstantiator{}) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"github": github.New(), "gitlab": gitlab.New(), "bitbucket": bitbucket.New()}). Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "build100", &kapi.PodProxyOptions{Path: ""}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !responder.called || !strings.Contains(responder.err.Error(), "unexpected hook subpath") { t.Errorf("Expected BadRequest, got %s, expected error %s!", responder.err.Error(), "unexpected hook subpath") } } func TestParseUrlOK(t *testing.T) { responder := &fakeResponder{} client := newBuildConfigClient(&okBuildConfigInstantiator{}, testBuildConfig) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"pathplugin": &pathPlugin{}}). Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "build100", &kapi.PodProxyOptions{Path: "secret101/pathplugin"}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if responder.err != nil { t.Errorf("Expected no error, got %v", responder.err) } } func TestParseUrlLong(t *testing.T) { plugin := &pathPlugin{} responder := &fakeResponder{} client := newBuildConfigClient(&okBuildConfigInstantiator{}, testBuildConfig) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"pathplugin": plugin}). Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "build100", &kapi.PodProxyOptions{Path: "secret101/pathplugin/some/more/args"}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !responder.called || !strings.Contains(responder.err.Error(), "unexpected hook subpath") { t.Errorf("Expected BadRequest, got %s, expected error %s!", responder.err.Error(), "unexpected hook subpath") } } func TestInvokeWebhookMissingPlugin(t *testing.T) { responder := &fakeResponder{} client := newBuildConfigClient(&okBuildConfigInstantiator{}, testBuildConfig) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"pathplugin": &pathPlugin{}}).Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "build100", &kapi.PodProxyOptions{Path: "secret101/missingplugin"}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Errorf("Unexpected error: %v", err) } if !responder.called || !strings.Contains(responder.err.Error(), `buildconfighook.build.openshift.io "missingplugin" not found`) { t.Errorf("Expected BadRequest, got %s, expected error %s!", responder.err.Error(), `buildconfighook.build.openshift.io "missingplugin" not found`) } } func TestInvokeWebhookErrorBuildConfigInstantiate(t *testing.T) { responder := &fakeResponder{} client := newBuildConfigClient(&errorBuildConfigInstantiator{}, testBuildConfig) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"pathplugin": &pathPlugin{}}). Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "build100", &kapi.PodProxyOptions{Path: "secret101/pathplugin"}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !responder.called || !strings.Contains(responder.err.Error(), "could not generate a build") { t.Errorf("Expected BadRequest, got %s, expected error %s!", responder.err.Error(), "could not generate a build") } } func TestInvokeWebhookErrorGetConfig(t *testing.T) { responder := &fakeResponder{} client := newBuildConfigClient(&okBuildConfigInstantiator{}, testBuildConfig) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"pathplugin": &pathPlugin{}}). Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "badbuild100", &kapi.PodProxyOptions{Path: "secret101/pathplugin"}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !responder.called { t.Fatalf("Should have received an error") } if !strings.Contains(responder.err.Error(), "did not accept your secret") { t.Errorf("Expected BadRequest, got %s, expected error %s!", responder.err.Error(), "did not accept your secret") } } func TestInvokeWebhookErrorCreateBuild(t *testing.T) { responder := &fakeResponder{} client := newBuildConfigClient(&okBuildConfigInstantiator{}, testBuildConfig) handler, _ := newWebHookREST(client, nil, buildv1.SchemeGroupVersion, map[string]webhook.Plugin{"errPlugin": &errPlugin{}}). Connect(apirequest.WithNamespace(apirequest.NewDefaultContext(), testBuildConfig.Namespace), "build100", &kapi.PodProxyOptions{Path: "secret101/errPlugin"}, responder) server := httptest.NewServer(handler) defer server.Close() _, err := http.Post(server.URL, "application/json", nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if !responder.called || !strings.Contains(responder.err.Error(), "Internal error occurred: hook failed: Plugin error!") { t.Errorf("Expected BadRequest, got %s, expected error %s!", responder.err.Error(), "Internal error occurred: hook failed: Plugin error!") } } func TestGeneratedBuildTriggerInfoGenericWebHook(t *testing.T) { revision := &buildv1.SourceRevision{ Git: &buildv1.GitSourceRevision{ Author: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Committer: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Message: "A random act of kindness", }, } externalRevision := &buildv1.SourceRevision{} if err := legacyscheme.Scheme.Convert(revision, externalRevision, nil); err != nil { panic(err) } buildtriggerCause := webhook.GenerateBuildTriggerInfo(externalRevision, "generic") hiddenSecret := "<secret>" for _, cause := range buildtriggerCause { if !reflect.DeepEqual(externalRevision, cause.GenericWebHook.Revision) { t.Errorf("Expected returned revision to equal: %v", revision) } if cause.GenericWebHook.Secret != hiddenSecret { t.Errorf("Expected obfuscated secret to be: %s", hiddenSecret) } if cause.Message != apiserverbuildutil.BuildTriggerCauseGenericMsg { t.Errorf("Expected build reason to be 'Generic WebHook, go %s'", cause.Message) } } } func TestGeneratedBuildTriggerInfoGitHubWebHook(t *testing.T) { revision := &buildv1.SourceRevision{ Git: &buildv1.GitSourceRevision{ Author: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Committer: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Message: "A random act of kindness", }, } externalRevision := &buildv1.SourceRevision{} if err := legacyscheme.Scheme.Convert(revision, externalRevision, nil); err != nil { panic(err) } buildtriggerCause := webhook.GenerateBuildTriggerInfo(externalRevision, "github") hiddenSecret := "<secret>" for _, cause := range buildtriggerCause { if !reflect.DeepEqual(externalRevision, cause.GitHubWebHook.Revision) { t.Errorf("Expected returned revision to equal: %v", revision) } if cause.GitHubWebHook.Secret != hiddenSecret { t.Errorf("Expected obfuscated secret to be: %s", hiddenSecret) } if cause.Message != apiserverbuildutil.BuildTriggerCauseGithubMsg { t.Errorf("Expected build reason to be 'GitHub WebHook, go %s'", cause.Message) } } } func TestGeneratedBuildTriggerInfoGitLabWebHook(t *testing.T) { revision := &buildv1.SourceRevision{ Git: &buildv1.GitSourceRevision{ Author: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Committer: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Message: "A random act of kindness", }, } externalRevision := &buildv1.SourceRevision{} if err := legacyscheme.Scheme.Convert(revision, externalRevision, nil); err != nil { panic(err) } buildtriggerCause := webhook.GenerateBuildTriggerInfo(externalRevision, "gitlab") hiddenSecret := "<secret>" for _, cause := range buildtriggerCause { if !reflect.DeepEqual(externalRevision, cause.GitLabWebHook.Revision) { t.Errorf("Expected returned revision to equal: %v", revision) } if cause.GitLabWebHook.Secret != hiddenSecret { t.Errorf("Expected obfuscated secret to be: %s", hiddenSecret) } if cause.Message != apiserverbuildutil.BuildTriggerCauseGitLabMsg { t.Errorf("Expected build reason to be 'GitLab WebHook, go %s'", cause.Message) } } } func TestGeneratedBuildTriggerInfoBitbucketWebHook(t *testing.T) { revision := &buildv1.SourceRevision{ Git: &buildv1.GitSourceRevision{ Author: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Committer: buildv1.SourceControlUser{ Name: "John Doe", Email: "john.doe@test.com", }, Message: "A random act of kindness", }, } externalRevision := &buildv1.SourceRevision{} if err := legacyscheme.Scheme.Convert(revision, externalRevision, nil); err != nil { panic(err) } buildtriggerCause := webhook.GenerateBuildTriggerInfo(externalRevision, "bitbucket") hiddenSecret := "<secret>" for _, cause := range buildtriggerCause { if !reflect.DeepEqual(externalRevision, cause.BitbucketWebHook.Revision) { t.Errorf("Expected returned revision to equal: %v", revision) } if cause.BitbucketWebHook.Secret != hiddenSecret { t.Errorf("Expected obfuscated secret to be: %s", hiddenSecret) } if cause.Message != apiserverbuildutil.BuildTriggerCauseBitbucketMsg { t.Errorf("Expected build reason to be 'Bitbucket WebHook, go %s'", cause.Message) } } }
anpingli/origin
staging/src/github.com/openshift/openshift-apiserver/pkg/build/apiserver/registry/buildconfig/webhook_test.go
GO
apache-2.0
23,538
[ 30522, 7427, 3857, 8663, 8873, 2290, 12324, 1006, 1000, 17181, 1013, 1046, 3385, 1000, 1000, 10697, 1000, 1000, 4718, 2102, 1000, 1000, 22834, 1013, 22834, 21823, 2140, 1000, 1000, 5658, 1013, 8299, 1000, 1000, 5658, 1013, 8299, 1013, 8299,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include <cstdio> template<typename T> auto kitten(T x) __attribute__((noinline)); template<class T> auto kitten(T t) { static T x = 0; return (x += 1) + t; } int main() { printf("%d\n", kitten(1)); printf("%g\n", kitten(3.14)); }
Lester-Dowling/studies
C++/CppCon/2015/Arthur-ODwyer-Lambdas-from-First-Principles/kitten-static-T.cpp
C++
gpl-3.0
238
[ 30522, 1001, 2421, 1026, 20116, 2102, 20617, 1028, 23561, 1026, 2828, 18442, 1056, 1028, 8285, 18401, 1006, 1056, 1060, 1007, 1035, 1035, 17961, 1035, 1035, 1006, 1006, 2053, 2378, 4179, 1007, 1007, 1025, 23561, 1026, 2465, 1056, 1028, 8285...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
version https://git-lfs.github.com/spec/v1 oid sha256:4f8b1998d2048d6a6cabacdfb3689eba7c9cb669d6f81dbbd18156bdb0dbe18f size 1880
yogeshsaroya/new-cdnjs
ajax/libs/uikit/2.5.0/js/addons/form-password.js
JavaScript
mit
129
[ 30522, 2544, 16770, 1024, 1013, 1013, 21025, 2102, 1011, 1048, 10343, 1012, 21025, 2705, 12083, 1012, 4012, 1013, 28699, 1013, 1058, 2487, 1051, 3593, 21146, 17788, 2575, 1024, 1018, 2546, 2620, 2497, 16147, 2683, 2620, 2094, 11387, 18139, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#------------------------------------------------------------------------------------------ # # Copyright 2017 Robert Pengelly. # # This file is part of ppa-helper. # # 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 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # #------------------------------------------------------------------------------------------ # coding: utf-8 from __future__ import unicode_literals import collections import os import shutil import sys if sys.version_info >= (3, 0): compat_getenv = os.getenv compat_expanduser = os.path.expanduser def compat_setenv(key, value, env=os.environ): env[key] = value else: # Environment variables should be decoded with filesystem encoding. # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918) def compat_getenv(key, default=None): from .utils import get_filesystem_encoding env = os.getenv(key, default) if env: env = env.decode(get_filesystem_encoding()) return env # Python < 2.6.5 require kwargs to be bytes try: def _testfunc(x): pass _testfunc(**{'x': 0}) except TypeError: def compat_kwargs(kwargs): return dict((bytes(k), v) for k, v in kwargs.items()) else: compat_kwargs = lambda kwargs: kwargs if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3 compat_get_terminal_size = shutil.get_terminal_size else: _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines']) def compat_get_terminal_size(fallback=(80, 24)): columns = compat_getenv('COLUMNS') if columns: columns = int(columns) else: columns = None lines = compat_getenv('LINES') if lines: lines = int(lines) else: lines = None if columns is None or lines is None or columns <= 0 or lines <= 0: try: sp = subprocess.Popen( ['stty', 'size'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = sp.communicate() _lines, _columns = map(int, out.split()) except Exception: _columns, _lines = _terminal_size(*fallback) if columns is None or columns <= 0: columns = _columns if lines is None or lines <= 0: lines = _lines return _terminal_size(columns, lines)
robertapengelly/ppa-helper
ppa_helper/compat.py
Python
gpl-3.0
3,031
[ 30522, 1001, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- layout: page title: Eternal Zone International Party date: 2016-05-24 author: Benjamin Andrews tags: weekly links, java status: published summary: Suspendisse potenti. Praesent sollicitudin nisi ante, non ultricies purus. banner: images/banner/people.jpg booking: startDate: 07/15/2019 endDate: 07/16/2019 ctyhocn: COUUMHX groupCode: EZIP published: true --- Vestibulum consectetur egestas consequat. Nullam eu aliquet magna. Ut ac tortor elit. Proin aliquam tellus sed ante convallis, porttitor dapibus metus tempus. Donec orci odio, condimentum nec mi sit amet, pharetra condimentum augue. Suspendisse libero erat, placerat a eros eget, facilisis pretium justo. Etiam feugiat tellus erat, facilisis pretium ipsum tincidunt aliquet. Nullam vel posuere ligula. Ut mollis ligula ut lacus sodales rutrum. Etiam sit amet bibendum velit. Nunc tristique sed lacus et convallis. Maecenas felis sapien, rhoncus vel pulvinar eget, facilisis vel lectus. Nunc tincidunt ut quam eu facilisis. * Sed vitae eros porttitor, venenatis mi nec, pretium libero * Mauris vitae dolor eget urna vestibulum mollis * Quisque porttitor est egestas arcu lobortis, vel varius sem rhoncus * Curabitur nec enim tincidunt, ultrices nunc quis, placerat diam * Aenean egestas lectus gravida, lacinia orci id, vulputate lectus. Sed at tempus nisl. Phasellus arcu arcu, ornare eu dapibus nec, lacinia et purus. Maecenas magna eros, volutpat posuere imperdiet nec, ultrices vitae mi. Nulla euismod velit et mi interdum, quis interdum nisi tristique. Aliquam finibus odio et augue ultrices, id suscipit quam convallis. Vivamus ac placerat purus, ultricies pulvinar mi. Mauris quam nunc, vulputate et felis nec, ullamcorper tincidunt felis. Aenean luctus sem dolor, sit amet feugiat mauris lacinia sed. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur tincidunt congue varius. Interdum et malesuada fames ac ante ipsum primis in faucibus. In ut scelerisque mauris. Suspendisse orci mi, aliquet sit amet lorem id, sagittis malesuada nisl. Nulla eget dapibus sem. Pellentesque tincidunt, justo sit amet feugiat efficitur, tortor quam porttitor enim, quis dictum diam lorem sit amet metus. Phasellus vulputate elit ac venenatis gravida. Phasellus ac lobortis nulla. Nullam a vulputate libero, sit amet scelerisque felis. Praesent nec arcu gravida, rutrum ipsum et, tincidunt dolor. Fusce tristique vitae eros non viverra. Morbi tincidunt lacus vestibulum libero molestie volutpat.
KlishGroup/prose-pogs
pogs/C/COUUMHX/EZIP/index.md
Markdown
mit
2,479
[ 30522, 1011, 1011, 1011, 9621, 1024, 3931, 2516, 1024, 10721, 4224, 2248, 2283, 3058, 1024, 2355, 1011, 5709, 1011, 2484, 3166, 1024, 6425, 9261, 22073, 1024, 4882, 6971, 1010, 9262, 3570, 1024, 2405, 12654, 1024, 28324, 23491, 16834, 2072,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @namespace */ namespace Zend\Tool\Project\Provider; /** * @uses \Zend\Tool\Framework\Provider\Pretendable * @uses \Zend\Tool\Project\Exception * @uses \Zend\Tool\Project\Provider\AbstractProvider * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Application extends AbstractProvider implements \Zend\Tool\Framework\Provider\Pretendable { protected $_specialties = array('ClassNamePrefix'); /** * * @param $classNamePrefix Prefix of classes * @param $force */ public function changeClassNamePrefix($classNamePrefix /* , $force = false */) { $profile = $this->_loadProfile(self::NO_PROFILE_THROW_EXCEPTION); $originalClassNamePrefix = $classNamePrefix; if (substr($classNamePrefix, -1) != '\\') { $classNamePrefix .= '\\'; } $configFileResource = $profile->search('ApplicationConfigFile'); $zc = $configFileResource->getAsZendConfig('production'); if ($zc->appnamespace == $classNamePrefix) { throw new \Zend\Tool\Project\Exception('The requested name ' . $classNamePrefix . ' is already the prefix.'); } // remove the old $configFileResource->removeStringItem('appnamespace', 'production'); $configFileResource->create(); // add the new $configFileResource->addStringItem('appnamespace', $classNamePrefix, 'production', true); $configFileResource->create(); // update the project profile $applicationDirectory = $profile->search('ApplicationDirectory'); $applicationDirectory->setClassNamePrefix($classNamePrefix); $response = $this->_registry->getResponse(); if ($originalClassNamePrefix !== $classNamePrefix) { $response->appendContent( 'Note: the name provided "' . $originalClassNamePrefix . '" was' . ' altered to "' . $classNamePrefix . '" for correctness.', array('color' => 'yellow') ); } // note to the user $response->appendContent('Note: All existing models will need to be altered to this new namespace by hand', array('color' => 'yellow')); $response->appendContent('application.ini updated with new appnamespace ' . $classNamePrefix); // store profile $this->_storeProfile(); } }
magicobject/zf2
library/Zend/Tool/Project/Provider/Application.php
PHP
bsd-3-clause
3,334
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 16729, 2094, 7705, 1008, 1008, 6105, 1008, 1008, 2023, 3120, 5371, 2003, 3395, 2000, 1996, 2047, 18667, 2094, 6105, 2008, 2003, 24378, 1008, 2007, 2023, 7427, 1999, 1996, 5371, 6105, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<div class="col-md-6 col-md-offset-3"> <h2>Register</h2> <form name="form" (ngSubmit)="f.form.valid && register()" #f="ngForm" novalidate> <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !firstName.valid }"> <label for="firstName">First Name</label> <input type="text" class="form-control" name="firstName" [(ngModel)]="model.firstName" #firstName="ngModel" required /> <div *ngIf="f.submitted && !firstName.valid" class="help-block">First Name is required</div> </div> <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !lastName.valid }"> <label for="lastName">Last Name</label> <input type="text" class="form-control" name="lastName" [(ngModel)]="model.lastName" #lastName="ngModel" required /> <div *ngIf="f.submitted && !lastName.valid" class="help-block">Last Name is required</div> </div> <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }"> <label for="username">Username</label> <input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required /> <div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div> </div> <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }"> <label for="password">Password</label> <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required /> <div *ngIf="f.submitted && !password.valid" class="help-block">Password is required</div> </div> <div class="form-group"> <button [disabled]="loading" class="btn btn-primary">Register</button> <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" /> <a [routerLink]="['/login']" class="btn btn-link">Cancel</a> </div> </form> </div>
ravite/Duplicate-mean
client/src/app/register/register.component.html
HTML
mit
2,914
[ 30522, 1026, 4487, 2615, 2465, 1027, 1000, 8902, 1011, 9108, 1011, 1020, 8902, 1011, 9108, 1011, 16396, 1011, 1017, 1000, 1028, 1026, 1044, 2475, 1028, 4236, 1026, 1013, 1044, 2475, 1028, 1026, 2433, 2171, 1027, 1000, 2433, 1000, 1006, 12...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# frozen_string_literal: true def expire_token HubSpot::OAuth::TokenStore.expire end
danrabinowitz/hub_spot
spec/support/oauth_helper.rb
Ruby
mit
88
[ 30522, 1001, 7708, 1035, 5164, 1035, 18204, 1024, 2995, 13366, 4654, 20781, 1035, 19204, 9594, 13102, 4140, 1024, 1024, 1051, 4887, 2705, 1024, 1024, 19204, 23809, 2063, 1012, 4654, 20781, 2203, 102, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Hygieia SCM Collectors / Bitbucket (Community Contribution) Collect source code details from Bitbucket based on URL and branch. Provides implementations for both Bitbucket Cloud (formerly known as Bitbucket) and Bitbucket Server (formerly known as Stash). This project uses Spring Boot to package the collector as an executable JAR with dependencies. ## Building and Deploying To package the collector into an executable JAR file, run: ```bash mvn install ``` Copy this file to your server and launch it using: ```bash java -jar bitbucket-collector.jar ``` ## application.properties You will need to provide an **application.properties** file that contains information about how to connect to the Dashboard MongoDB database instance, as well as properties the Bitbucket collector requires. See the Spring Boot [documentation](http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-application-property-files) for information about sourcing this properties file. ### Sample application.properties file ```properties # Database Name spring.data.mongodb.dbname=dashboarddb # Database HostName - default is localhost spring.data.mongodb.host= # Database Port - default is 27017 spring.data.mongodb.port= # Database Username - default is blank spring.data.mongodb.username= # Database Password - default is blank spring.data.mongodb.password= # Collector schedule (required) git.cron=0 0/5 * * * * # mandatory: git.host=mybitbucketrepo.com/ git.api=/rest/api/1.0/ # Maximum number of days to go back in time when fetching commits git.commitThresholdDays=15 # Page size for rest calls. # Only applicable to Bitbucket Server. # Only applicable to Bitbucket Cloud. git.pageSize=25 # Bitbucket product # Set to "cloud" to use Bitbucket Cloud (formerly known as Bitbucket) # Set to "server" to use Bitbucket Server (formerly known as Stash) # More information can be found here: # https://github.com/capitalone/Hygieia/issues/609 git.product=server ```
harish961/Hygieia-WFN
collectors/scm/bitbucket/README.md
Markdown
apache-2.0
2,030
[ 30522, 1001, 1044, 2100, 11239, 2401, 8040, 2213, 14256, 1013, 2978, 24204, 3388, 1006, 2451, 6691, 1007, 8145, 3120, 3642, 4751, 2013, 2978, 24204, 3388, 2241, 2006, 24471, 2140, 1998, 3589, 1012, 3640, 24977, 2005, 2119, 2978, 24204, 3388...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * copyright (C) 2013 Christian P Rasmussen * * 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 cprasmu.rascam.camera.model; public enum MeteringMode { AVERAGE (0,"average","Average"), SPOT (1,"spot","Spot"), BACKLIT (2,"backlit","Backlit"), MATRIX (3,"matrix","Matrix"); public int mode; public String name; public String displayName; private MeteringMode(int mode, String name,String displayName) { this.mode = mode; this.name = name; this.displayName=displayName; } public static MeteringMode fromInt(int code) { switch(code) { case 0: return AVERAGE; case 1: return SPOT; case 2: return BACKLIT; case 3: return MATRIX; } return null; } public MeteringMode next(){ if(this.equals(AVERAGE)){ return SPOT; } else if(this.equals(SPOT)){ return BACKLIT; } else if(this.equals(BACKLIT)){ return MATRIX; } else if(this.equals(MATRIX)){ return AVERAGE; } else { return null; } } public MeteringMode previous(){ if(this.equals(MATRIX)){ return BACKLIT; } else if(this.equals(BACKLIT)){ return SPOT; } else if(this.equals(SPOT)){ return AVERAGE; } else if(this.equals(AVERAGE)){ return MATRIX; } else { return null; } } }
cprasmu/RasCam-Server
src/cprasmu/rascam/camera/model/MeteringMode.java
Java
gpl-2.0
1,840
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2286, 3017, 1052, 20710, 29134, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, 5371, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Solanum apiculatibaccatum Bitter SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Solanaceae/Solanum/Solanum mite/ Syn. Solanum apiculatibaccatum/README.md
Markdown
apache-2.0
189
[ 30522, 1001, 14017, 27975, 17928, 19879, 3775, 3676, 16665, 11667, 8618, 2427, 1001, 1001, 1001, 1001, 3570, 10675, 1001, 1001, 1001, 1001, 2429, 2000, 1996, 10161, 1997, 2166, 1010, 3822, 2254, 2249, 1001, 1001, 1001, 1001, 2405, 1999, 197...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=no-self-use, pointless-statement, missing-docstring, invalid-name,len-as-condition from functools import partial from rebulk.pattern import StringPattern from ..validators import chars_before, chars_after, chars_surround, validators chars = ' _.' left = partial(chars_before, chars) right = partial(chars_after, chars) surrounding = partial(chars_surround, chars) def test_left_chars(): matches = list(StringPattern("word", validator=left).matches("xxxwordxxx")) assert len(matches) == 0 matches = list(StringPattern("word", validator=left).matches("xxx_wordxxx")) assert len(matches) == 1 matches = list(StringPattern("word", validator=left).matches("wordxxx")) assert len(matches) == 1 def test_right_chars(): matches = list(StringPattern("word", validator=right).matches("xxxwordxxx")) assert len(matches) == 0 matches = list(StringPattern("word", validator=right).matches("xxxword.xxx")) assert len(matches) == 1 matches = list(StringPattern("word", validator=right).matches("xxxword")) assert len(matches) == 1 def test_surrounding_chars(): matches = list(StringPattern("word", validator=surrounding).matches("xxxword xxx")) assert len(matches) == 0 matches = list(StringPattern("word", validator=surrounding).matches("xxx.wordxxx")) assert len(matches) == 0 matches = list(StringPattern("word", validator=surrounding).matches("xxx word_xxx")) assert len(matches) == 1 matches = list(StringPattern("word", validator=surrounding).matches("word")) assert len(matches) == 1 def test_chain(): matches = list(StringPattern("word", validator=validators(left, right)).matches("xxxword xxx")) assert len(matches) == 0 matches = list(StringPattern("word", validator=validators(left, right)).matches("xxx.wordxxx")) assert len(matches) == 0 matches = list(StringPattern("word", validator=validators(left, right)).matches("xxx word_xxx")) assert len(matches) == 1 matches = list(StringPattern("word", validator=validators(left, right)).matches("word")) assert len(matches) == 1
Toilal/rebulk
rebulk/test/test_validators.py
Python
mit
2,170
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 1001, 1011, 1008, 1011, 16861, 1024, 21183, 2546, 1011, 1022, 1011, 1008, 1011, 1001, 1052, 8516, 18447, 1024, 4487, 19150, 1027, 2053, 1011, 2969, 1011, 2224, 1010, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qelapsedtimer.h" #include <windows.h> #include <private/qsystemlibrary_p.h> typedef ULONGLONG (WINAPI *PtrGetTickCount64)(void); static PtrGetTickCount64 ptrGetTickCount64 = 0; QT_BEGIN_NAMESPACE // Result of QueryPerformanceFrequency, 0 indicates that the high resolution timer is unavailable static quint64 counterFrequency = 0; static void resolveLibs() { static volatile bool done = false; if (done) return; // try to get GetTickCount64 from the system QSystemLibrary kernel32(QLatin1String("kernel32")); if (!kernel32.load()) return; // does this function exist on WinCE, or will ever exist? ptrGetTickCount64 = (PtrGetTickCount64)kernel32.resolve("GetTickCount64"); // Retrieve the number of high-resolution performance counter ticks per second LARGE_INTEGER frequency; if (!QueryPerformanceFrequency(&frequency)) { counterFrequency = 0; } else { counterFrequency = frequency.QuadPart; } done = true; } static inline qint64 ticksToNanoseconds(qint64 ticks) { if (counterFrequency > 0) { // QueryPerformanceCounter uses an arbitrary frequency qint64 seconds = ticks / counterFrequency; qint64 nanoSeconds = (ticks - seconds * counterFrequency) * 1000000000 / counterFrequency; return seconds * 1000000000 + nanoSeconds; } else { // GetTickCount(64) return milliseconds return ticks * 1000000; } } static quint64 getTickCount() { resolveLibs(); // This avoids a division by zero and disables the high performance counter if it's not available if (counterFrequency > 0) { LARGE_INTEGER counter; if (QueryPerformanceCounter(&counter)) { return counter.QuadPart; } else { qWarning("QueryPerformanceCounter failed, although QueryPerformanceFrequency succeeded."); return 0; } } if (ptrGetTickCount64) return ptrGetTickCount64(); static quint32 highdword = 0; static quint32 lastval = 0; quint32 val = GetTickCount(); if (val < lastval) ++highdword; lastval = val; return val | (quint64(highdword) << 32); } QElapsedTimer::ClockType QElapsedTimer::clockType() { resolveLibs(); if (counterFrequency > 0) return PerformanceCounter; else return TickCounter; } bool QElapsedTimer::isMonotonic() { return true; } void QElapsedTimer::start() { t1 = getTickCount(); t2 = 0; } qint64 QElapsedTimer::restart() { qint64 oldt1 = t1; t1 = getTickCount(); t2 = 0; return ticksToNanoseconds(t1 - oldt1) / 1000000; } qint64 QElapsedTimer::nsecsElapsed() const { qint64 elapsed = getTickCount() - t1; return ticksToNanoseconds(elapsed); } qint64 QElapsedTimer::elapsed() const { qint64 elapsed = getTickCount() - t1; return ticksToNanoseconds(elapsed) / 1000000; } qint64 QElapsedTimer::msecsSinceReference() const { return ticksToNanoseconds(t1) / 1000000; } qint64 QElapsedTimer::msecsTo(const QElapsedTimer &other) const { qint64 difference = other.t1 - t1; return ticksToNanoseconds(difference) / 1000000; } qint64 QElapsedTimer::secsTo(const QElapsedTimer &other) const { return msecsTo(other) / 1000; } bool operator<(const QElapsedTimer &v1, const QElapsedTimer &v2) { return (v1.t1 - v2.t1) < 0; } QT_END_NAMESPACE
dulton/vlc-2.1.4.32.subproject-2013-update2
win32/include/qt4/src/corelib/tools/qelapsedtimer_win.cpp
C++
gpl-2.0
5,376
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * PI */ return $builder ->_pi('php', 'echo "HelloWorld"') ->root_ ;
hirak/php-XML_Builder
tests/test011.php
PHP
mit
82
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 14255, 1008, 1013, 2709, 1002, 12508, 1011, 1028, 1035, 14255, 1006, 1005, 25718, 1005, 1010, 1005, 9052, 1000, 7592, 11108, 1000, 1005, 1007, 1011, 1028, 7117, 1035, 1025, 102, 0, 0, 0, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Type definitions for jasmine-ajax 3.1 // Project: https://github.com/jasmine/jasmine-ajax // Definitions by: Louis Grignon <https://github.com/lgrignon> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 interface JasmineAjaxResponse { status?: number; statusText?: string; responseText?: string; response?: string; contentType?: string; responseHeaders?: { [key: string]: string }; } interface JasmineAjaxRequest extends XMLHttpRequest { url: string; method: string; params: any; username: string; password: string; requestHeaders: { [key: string]: string }; overriddenMimeType: string; data(): string; respondWith(response: JasmineAjaxResponse): void; responseTimeout(): void; responseError(): void; } interface JasmineAjaxRequestTracker { track(request: JasmineAjaxRequest): void; first(): JasmineAjaxRequest; count(): number; reset(): void; mostRecent(): JasmineAjaxRequest; at(index: number): JasmineAjaxRequest; filter(urlToMatch: RegExp): JasmineAjaxRequest[]; filter(urlToMatch: Function): JasmineAjaxRequest[]; filter(urlToMatch: string): JasmineAjaxRequest[]; } interface JasmineAjaxRequestStubReturnOptions { status?: number; contentType?: string; response?: string; responseText?: string; responseHeaders?: { [key: string]: string }; } interface JasmineAjaxRequestStub { data?: string; method?: string; andReturn(options: JasmineAjaxRequestStubReturnOptions): void; matches(fullUrl: string, data: string, method: string): boolean; } interface JasmineAjaxStubTracker { addStub(stub: JasmineAjaxRequestStub): void; reset(): void; findStub(url: string, data?: string, method?: string): JasmineAjaxRequestStub; } interface JasmineAjaxParamParser { test(xhr: XMLHttpRequest): boolean; parse(paramString: string): any; } declare class MockAjax { constructor(globals: any); install(): void; uninstall(): void; withMock(closure: () => void): void; addCustomParamParser(parser: JasmineAjaxParamParser): void; stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: string, method?: string): JasmineAjaxRequestStub; stubRequest(url: RegExp, data?: RegExp, method?: string): JasmineAjaxRequestStub; stubRequest(url: string, data?: RegExp, method?: string): JasmineAjaxRequestStub; requests: JasmineAjaxRequestTracker; stubs: JasmineAjaxStubTracker; } declare namespace jasmine { const Ajax: MockAjax; }
AgentME/DefinitelyTyped
types/jasmine-ajax/index.d.ts
TypeScript
mit
2,475
[ 30522, 1013, 1013, 2828, 15182, 2005, 14032, 1011, 30524, 1024, 16770, 1024, 1013, 1013, 21025, 2705, 12083, 1012, 4012, 1013, 14032, 1013, 14032, 1011, 18176, 1013, 1013, 15182, 2011, 1024, 3434, 24665, 24796, 1026, 16770, 1024, 1013, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { UserListComponent } from "../user-list/user-list.component"; import { UserDetailComponent } from "../user-detail/user-detail.component"; const routes: Routes = [ { path: '', children: [ { path: '', component: UserListComponent, data: { title: 'Users' } }, { path: 'add', component: UserDetailComponent, data: { title: 'Add User' } } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class UsersRoutingModule { }
gcasanova90/tp-support
client/app/users/_shared/users-routing.module.ts
TypeScript
mit
599
[ 30522, 12324, 1063, 12835, 5302, 8566, 2571, 1065, 2013, 1005, 1030, 16108, 1013, 4563, 1005, 1025, 12324, 1063, 5847, 1010, 2799, 10867, 7716, 9307, 1065, 2013, 1005, 1030, 16108, 1013, 2799, 2099, 1005, 1025, 12324, 1063, 5310, 9863, 9006...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Hieracium piloselloides subsp. cylindriceps (Nägeli & Peter) Zahn SUBSPECIES #### Status HETEROTYPIC_SYNONYM #### According to Euro+Med Plantbase #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/incertae sedis/Pilosella piloselloides/ Syn. Hieracium piloselloides cylindriceps/README.md
Markdown
apache-2.0
217
[ 30522, 1001, 7632, 6906, 6895, 2819, 14255, 10483, 15350, 8621, 24807, 1012, 22330, 27164, 17599, 4523, 1006, 6583, 12439, 2072, 1004, 2848, 1007, 23564, 7295, 11056, 1001, 1001, 1001, 1001, 3570, 21770, 10624, 23186, 1035, 10675, 1001, 1001,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# # Autogenerated by Thrift Compiler (0.8.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # require 5.6.0; use strict; use warnings; use Thrift; use EDAMUserStore::Types; # HELPER FUNCTIONS AND STRUCTURES package EDAMUserStore::UserStore_checkVersion_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_checkVersion_args->mk_accessors( qw( clientName edamVersionMajor edamVersionMinor ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{clientName} = undef; $self->{edamVersionMajor} = 1; $self->{edamVersionMinor} = 21; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{clientName}) { $self->{clientName} = $vals->{clientName}; } if (defined $vals->{edamVersionMajor}) { $self->{edamVersionMajor} = $vals->{edamVersionMajor}; } if (defined $vals->{edamVersionMinor}) { $self->{edamVersionMinor} = $vals->{edamVersionMinor}; } } return bless ($self, $classname); } sub getName { return 'UserStore_checkVersion_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{clientName}); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::I16) { $xfer += $input->readI16(\$self->{edamVersionMajor}); } else { $xfer += $input->skip($ftype); } last; }; /^3$/ && do{ if ($ftype == TType::I16) { $xfer += $input->readI16(\$self->{edamVersionMinor}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_checkVersion_args'); if (defined $self->{clientName}) { $xfer += $output->writeFieldBegin('clientName', TType::STRING, 1); $xfer += $output->writeString($self->{clientName}); $xfer += $output->writeFieldEnd(); } if (defined $self->{edamVersionMajor}) { $xfer += $output->writeFieldBegin('edamVersionMajor', TType::I16, 2); $xfer += $output->writeI16($self->{edamVersionMajor}); $xfer += $output->writeFieldEnd(); } if (defined $self->{edamVersionMinor}) { $xfer += $output->writeFieldBegin('edamVersionMinor', TType::I16, 3); $xfer += $output->writeI16($self->{edamVersionMinor}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_checkVersion_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_checkVersion_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } } return bless ($self, $classname); } sub getName { return 'UserStore_checkVersion_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::BOOL) { $xfer += $input->readBool(\$self->{success}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_checkVersion_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::BOOL, 0); $xfer += $output->writeBool($self->{success}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getBootstrapInfo_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getBootstrapInfo_args->mk_accessors( qw( locale ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{locale} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{locale}) { $self->{locale} = $vals->{locale}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getBootstrapInfo_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{locale}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getBootstrapInfo_args'); if (defined $self->{locale}) { $xfer += $output->writeFieldBegin('locale', TType::STRING, 1); $xfer += $output->writeString($self->{locale}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getBootstrapInfo_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getBootstrapInfo_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getBootstrapInfo_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::BootstrapInfo(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getBootstrapInfo_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_authenticate_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_authenticate_args->mk_accessors( qw( username password consumerKey consumerSecret ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{username} = undef; $self->{password} = undef; $self->{consumerKey} = undef; $self->{consumerSecret} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{username}) { $self->{username} = $vals->{username}; } if (defined $vals->{password}) { $self->{password} = $vals->{password}; } if (defined $vals->{consumerKey}) { $self->{consumerKey} = $vals->{consumerKey}; } if (defined $vals->{consumerSecret}) { $self->{consumerSecret} = $vals->{consumerSecret}; } } return bless ($self, $classname); } sub getName { return 'UserStore_authenticate_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{username}); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{password}); } else { $xfer += $input->skip($ftype); } last; }; /^3$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{consumerKey}); } else { $xfer += $input->skip($ftype); } last; }; /^4$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{consumerSecret}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_authenticate_args'); if (defined $self->{username}) { $xfer += $output->writeFieldBegin('username', TType::STRING, 1); $xfer += $output->writeString($self->{username}); $xfer += $output->writeFieldEnd(); } if (defined $self->{password}) { $xfer += $output->writeFieldBegin('password', TType::STRING, 2); $xfer += $output->writeString($self->{password}); $xfer += $output->writeFieldEnd(); } if (defined $self->{consumerKey}) { $xfer += $output->writeFieldBegin('consumerKey', TType::STRING, 3); $xfer += $output->writeString($self->{consumerKey}); $xfer += $output->writeFieldEnd(); } if (defined $self->{consumerSecret}) { $xfer += $output->writeFieldBegin('consumerSecret', TType::STRING, 4); $xfer += $output->writeString($self->{consumerSecret}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_authenticate_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_authenticate_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_authenticate_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::AuthenticationResult(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_authenticate_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_refreshAuthentication_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_refreshAuthentication_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_refreshAuthentication_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_refreshAuthentication_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_refreshAuthentication_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_refreshAuthentication_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_refreshAuthentication_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::AuthenticationResult(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_refreshAuthentication_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getUser_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getUser_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getUser_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getUser_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getUser_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getUser_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getUser_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMTypes::User(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getUser_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPublicUserInfo_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPublicUserInfo_args->mk_accessors( qw( username ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{username} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{username}) { $self->{username} = $vals->{username}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPublicUserInfo_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{username}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPublicUserInfo_args'); if (defined $self->{username}) { $xfer += $output->writeFieldBegin('username', TType::STRING, 1); $xfer += $output->writeString($self->{username}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPublicUserInfo_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPublicUserInfo_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{notFoundException} = undef; $self->{systemException} = undef; $self->{userException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{notFoundException}) { $self->{notFoundException} = $vals->{notFoundException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPublicUserInfo_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::PublicUserInfo(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{notFoundException} = new EDAMErrors::EDAMNotFoundException(); $xfer += $self->{notFoundException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^3$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPublicUserInfo_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{notFoundException}) { $xfer += $output->writeFieldBegin('notFoundException', TType::STRUCT, 1); $xfer += $self->{notFoundException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 3); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPremiumInfo_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPremiumInfo_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPremiumInfo_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPremiumInfo_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getPremiumInfo_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getPremiumInfo_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getPremiumInfo_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRUCT) { $self->{success} = new EDAMUserStore::PremiumInfo(); $xfer += $self->{success}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getPremiumInfo_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRUCT, 0); $xfer += $self->{success}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getNoteStoreUrl_args; use base qw(Class::Accessor); EDAMUserStore::UserStore_getNoteStoreUrl_args->mk_accessors( qw( authenticationToken ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{authenticationToken} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{authenticationToken}) { $self->{authenticationToken} = $vals->{authenticationToken}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getNoteStoreUrl_args'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^1$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{authenticationToken}); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getNoteStoreUrl_args'); if (defined $self->{authenticationToken}) { $xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1); $xfer += $output->writeString($self->{authenticationToken}); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStore_getNoteStoreUrl_result; use base qw(Class::Accessor); EDAMUserStore::UserStore_getNoteStoreUrl_result->mk_accessors( qw( success ) ); sub new { my $classname = shift; my $self = {}; my $vals = shift || {}; $self->{success} = undef; $self->{userException} = undef; $self->{systemException} = undef; if (UNIVERSAL::isa($vals,'HASH')) { if (defined $vals->{success}) { $self->{success} = $vals->{success}; } if (defined $vals->{userException}) { $self->{userException} = $vals->{userException}; } if (defined $vals->{systemException}) { $self->{systemException} = $vals->{systemException}; } } return bless ($self, $classname); } sub getName { return 'UserStore_getNoteStoreUrl_result'; } sub read { my ($self, $input) = @_; my $xfer = 0; my $fname; my $ftype = 0; my $fid = 0; $xfer += $input->readStructBegin(\$fname); while (1) { $xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid); if ($ftype == TType::STOP) { last; } SWITCH: for($fid) { /^0$/ && do{ if ($ftype == TType::STRING) { $xfer += $input->readString(\$self->{success}); } else { $xfer += $input->skip($ftype); } last; }; /^1$/ && do{ if ($ftype == TType::STRUCT) { $self->{userException} = new EDAMErrors::EDAMUserException(); $xfer += $self->{userException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; /^2$/ && do{ if ($ftype == TType::STRUCT) { $self->{systemException} = new EDAMErrors::EDAMSystemException(); $xfer += $self->{systemException}->read($input); } else { $xfer += $input->skip($ftype); } last; }; $xfer += $input->skip($ftype); } $xfer += $input->readFieldEnd(); } $xfer += $input->readStructEnd(); return $xfer; } sub write { my ($self, $output) = @_; my $xfer = 0; $xfer += $output->writeStructBegin('UserStore_getNoteStoreUrl_result'); if (defined $self->{success}) { $xfer += $output->writeFieldBegin('success', TType::STRING, 0); $xfer += $output->writeString($self->{success}); $xfer += $output->writeFieldEnd(); } if (defined $self->{userException}) { $xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1); $xfer += $self->{userException}->write($output); $xfer += $output->writeFieldEnd(); } if (defined $self->{systemException}) { $xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2); $xfer += $self->{systemException}->write($output); $xfer += $output->writeFieldEnd(); } $xfer += $output->writeFieldStop(); $xfer += $output->writeStructEnd(); return $xfer; } package EDAMUserStore::UserStoreIf; use strict; sub checkVersion{ my $self = shift; my $clientName = shift; my $edamVersionMajor = shift; my $edamVersionMinor = shift; die 'implement interface'; } sub getBootstrapInfo{ my $self = shift; my $locale = shift; die 'implement interface'; } sub authenticate{ my $self = shift; my $username = shift; my $password = shift; my $consumerKey = shift; my $consumerSecret = shift; die 'implement interface'; } sub refreshAuthentication{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } sub getUser{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } sub getPublicUserInfo{ my $self = shift; my $username = shift; die 'implement interface'; } sub getPremiumInfo{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } sub getNoteStoreUrl{ my $self = shift; my $authenticationToken = shift; die 'implement interface'; } package EDAMUserStore::UserStoreRest; use strict; sub new { my ($classname, $impl) = @_; my $self ={ impl => $impl }; return bless($self,$classname); } sub checkVersion{ my ($self, $request) = @_; my $clientName = ($request->{'clientName'}) ? $request->{'clientName'} : undef; my $edamVersionMajor = ($request->{'edamVersionMajor'}) ? $request->{'edamVersionMajor'} : undef; my $edamVersionMinor = ($request->{'edamVersionMinor'}) ? $request->{'edamVersionMinor'} : undef; return $self->{impl}->checkVersion($clientName, $edamVersionMajor, $edamVersionMinor); } sub getBootstrapInfo{ my ($self, $request) = @_; my $locale = ($request->{'locale'}) ? $request->{'locale'} : undef; return $self->{impl}->getBootstrapInfo($locale); } sub authenticate{ my ($self, $request) = @_; my $username = ($request->{'username'}) ? $request->{'username'} : undef; my $password = ($request->{'password'}) ? $request->{'password'} : undef; my $consumerKey = ($request->{'consumerKey'}) ? $request->{'consumerKey'} : undef; my $consumerSecret = ($request->{'consumerSecret'}) ? $request->{'consumerSecret'} : undef; return $self->{impl}->authenticate($username, $password, $consumerKey, $consumerSecret); } sub refreshAuthentication{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->refreshAuthentication($authenticationToken); } sub getUser{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->getUser($authenticationToken); } sub getPublicUserInfo{ my ($self, $request) = @_; my $username = ($request->{'username'}) ? $request->{'username'} : undef; return $self->{impl}->getPublicUserInfo($username); } sub getPremiumInfo{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->getPremiumInfo($authenticationToken); } sub getNoteStoreUrl{ my ($self, $request) = @_; my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef; return $self->{impl}->getNoteStoreUrl($authenticationToken); } package EDAMUserStore::UserStoreClient; use base qw(EDAMUserStore::UserStoreIf); sub new { my ($classname, $input, $output) = @_; my $self = {}; $self->{input} = $input; $self->{output} = defined $output ? $output : $input; $self->{seqid} = 0; return bless($self,$classname); } sub checkVersion{ my $self = shift; my $clientName = shift; my $edamVersionMajor = shift; my $edamVersionMinor = shift; $self->send_checkVersion($clientName, $edamVersionMajor, $edamVersionMinor); return $self->recv_checkVersion(); } sub send_checkVersion{ my $self = shift; my $clientName = shift; my $edamVersionMajor = shift; my $edamVersionMinor = shift; $self->{output}->writeMessageBegin('checkVersion', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_checkVersion_args(); $args->{clientName} = $clientName; $args->{edamVersionMajor} = $edamVersionMajor; $args->{edamVersionMinor} = $edamVersionMinor; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_checkVersion{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_checkVersion_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } die "checkVersion failed: unknown result"; } sub getBootstrapInfo{ my $self = shift; my $locale = shift; $self->send_getBootstrapInfo($locale); return $self->recv_getBootstrapInfo(); } sub send_getBootstrapInfo{ my $self = shift; my $locale = shift; $self->{output}->writeMessageBegin('getBootstrapInfo', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getBootstrapInfo_args(); $args->{locale} = $locale; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getBootstrapInfo{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getBootstrapInfo_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } die "getBootstrapInfo failed: unknown result"; } sub authenticate{ my $self = shift; my $username = shift; my $password = shift; my $consumerKey = shift; my $consumerSecret = shift; $self->send_authenticate($username, $password, $consumerKey, $consumerSecret); return $self->recv_authenticate(); } sub send_authenticate{ my $self = shift; my $username = shift; my $password = shift; my $consumerKey = shift; my $consumerSecret = shift; $self->{output}->writeMessageBegin('authenticate', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_authenticate_args(); $args->{username} = $username; $args->{password} = $password; $args->{consumerKey} = $consumerKey; $args->{consumerSecret} = $consumerSecret; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_authenticate{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_authenticate_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "authenticate failed: unknown result"; } sub refreshAuthentication{ my $self = shift; my $authenticationToken = shift; $self->send_refreshAuthentication($authenticationToken); return $self->recv_refreshAuthentication(); } sub send_refreshAuthentication{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('refreshAuthentication', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_refreshAuthentication_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_refreshAuthentication{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_refreshAuthentication_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "refreshAuthentication failed: unknown result"; } sub getUser{ my $self = shift; my $authenticationToken = shift; $self->send_getUser($authenticationToken); return $self->recv_getUser(); } sub send_getUser{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('getUser', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getUser_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getUser{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getUser_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "getUser failed: unknown result"; } sub getPublicUserInfo{ my $self = shift; my $username = shift; $self->send_getPublicUserInfo($username); return $self->recv_getPublicUserInfo(); } sub send_getPublicUserInfo{ my $self = shift; my $username = shift; $self->{output}->writeMessageBegin('getPublicUserInfo', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getPublicUserInfo_args(); $args->{username} = $username; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getPublicUserInfo{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getPublicUserInfo_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{notFoundException}) { die $result->{notFoundException}; } if (defined $result->{systemException}) { die $result->{systemException}; } if (defined $result->{userException}) { die $result->{userException}; } die "getPublicUserInfo failed: unknown result"; } sub getPremiumInfo{ my $self = shift; my $authenticationToken = shift; $self->send_getPremiumInfo($authenticationToken); return $self->recv_getPremiumInfo(); } sub send_getPremiumInfo{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('getPremiumInfo', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getPremiumInfo_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getPremiumInfo{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getPremiumInfo_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "getPremiumInfo failed: unknown result"; } sub getNoteStoreUrl{ my $self = shift; my $authenticationToken = shift; $self->send_getNoteStoreUrl($authenticationToken); return $self->recv_getNoteStoreUrl(); } sub send_getNoteStoreUrl{ my $self = shift; my $authenticationToken = shift; $self->{output}->writeMessageBegin('getNoteStoreUrl', TMessageType::CALL, $self->{seqid}); my $args = new EDAMUserStore::UserStore_getNoteStoreUrl_args(); $args->{authenticationToken} = $authenticationToken; $args->write($self->{output}); $self->{output}->writeMessageEnd(); $self->{output}->getTransport()->flush(); } sub recv_getNoteStoreUrl{ my $self = shift; my $rseqid = 0; my $fname; my $mtype = 0; $self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid); if ($mtype == TMessageType::EXCEPTION) { my $x = new TApplicationException(); $x->read($self->{input}); $self->{input}->readMessageEnd(); die $x; } my $result = new EDAMUserStore::UserStore_getNoteStoreUrl_result(); $result->read($self->{input}); $self->{input}->readMessageEnd(); if (defined $result->{success} ) { return $result->{success}; } if (defined $result->{userException}) { die $result->{userException}; } if (defined $result->{systemException}) { die $result->{systemException}; } die "getNoteStoreUrl failed: unknown result"; } package EDAMUserStore::UserStoreProcessor; use strict; sub new { my ($classname, $handler) = @_; my $self = {}; $self->{handler} = $handler; return bless ($self, $classname); } sub process { my ($self, $input, $output) = @_; my $rseqid = 0; my $fname = undef; my $mtype = 0; $input->readMessageBegin(\$fname, \$mtype, \$rseqid); my $methodname = 'process_'.$fname; if (!$self->can($methodname)) { $input->skip(TType::STRUCT); $input->readMessageEnd(); my $x = new TApplicationException('Function '.$fname.' not implemented.', TApplicationException::UNKNOWN_METHOD); $output->writeMessageBegin($fname, TMessageType::EXCEPTION, $rseqid); $x->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); return; } $self->$methodname($rseqid, $input, $output); return 1; } sub process_checkVersion { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_checkVersion_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_checkVersion_result(); $result->{success} = $self->{handler}->checkVersion($args->clientName, $args->edamVersionMajor, $args->edamVersionMinor); $output->writeMessageBegin('checkVersion', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getBootstrapInfo { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getBootstrapInfo_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getBootstrapInfo_result(); $result->{success} = $self->{handler}->getBootstrapInfo($args->locale); $output->writeMessageBegin('getBootstrapInfo', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_authenticate { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_authenticate_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_authenticate_result(); eval { $result->{success} = $self->{handler}->authenticate($args->username, $args->password, $args->consumerKey, $args->consumerSecret); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('authenticate', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_refreshAuthentication { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_refreshAuthentication_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_refreshAuthentication_result(); eval { $result->{success} = $self->{handler}->refreshAuthentication($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('refreshAuthentication', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getUser { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getUser_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getUser_result(); eval { $result->{success} = $self->{handler}->getUser($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('getUser', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getPublicUserInfo { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getPublicUserInfo_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getPublicUserInfo_result(); eval { $result->{success} = $self->{handler}->getPublicUserInfo($args->username); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMNotFoundException') ){ $result->{notFoundException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; } $output->writeMessageBegin('getPublicUserInfo', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getPremiumInfo { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getPremiumInfo_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getPremiumInfo_result(); eval { $result->{success} = $self->{handler}->getPremiumInfo($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('getPremiumInfo', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } sub process_getNoteStoreUrl { my ($self, $seqid, $input, $output) = @_; my $args = new EDAMUserStore::UserStore_getNoteStoreUrl_args(); $args->read($input); $input->readMessageEnd(); my $result = new EDAMUserStore::UserStore_getNoteStoreUrl_result(); eval { $result->{success} = $self->{handler}->getNoteStoreUrl($args->authenticationToken); }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){ $result->{userException} = $@; }; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){ $result->{systemException} = $@; } $output->writeMessageBegin('getNoteStoreUrl', TMessageType::REPLY, $seqid); $result->write($output); $output->writeMessageEnd(); $output->getTransport()->flush(); } 1;
nobuoka/evernote-sdk-perl
lib/EDAMUserStore/UserStore.pm
Perl
bsd-2-clause
58,040
[ 30522, 1001, 1001, 8285, 6914, 16848, 2011, 16215, 16338, 21624, 1006, 1014, 1012, 1022, 1012, 1014, 1007, 1001, 1001, 2079, 2025, 10086, 4983, 2017, 2024, 2469, 2008, 2017, 2113, 2054, 2017, 2024, 2725, 1001, 5478, 1019, 1012, 1020, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# `res.location()` Sets the "Location" response header to the specified URL expression (`url`). ### Usage ```usage res.location(url); ``` ### Example ```javascript res.location('/foo/bar'); res.location('foo/bar'); res.location('http://example.com'); res.location('../login'); res.location('back'); ``` ### Notes >+ You can use the same kind of URL expressions as in `res.redirect()`. <docmeta name="displayName" value="res.location()"> <docmeta name="pageType" value="method">
balderdashy/sails
docs/reference/res/res.location.md
Markdown
mit
493
[ 30522, 1001, 1036, 24501, 1012, 3295, 1006, 1007, 1036, 4520, 1996, 1000, 3295, 1000, 3433, 20346, 2000, 1996, 9675, 24471, 2140, 3670, 1006, 1036, 24471, 2140, 1036, 1007, 1012, 1001, 1001, 1001, 8192, 1036, 1036, 1036, 8192, 24501, 1012, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /// Please, do not edit this file manually! It's auto generated from /// contents stored in your standard lang pack files: /// (langconfig.php, install.php, moodle.php, admin.php and error.php) /// /// If you find some missing string in Moodle installation, please, /// keep us informed using http://moodle.org/bugs Thanks! /// /// File generated by cvs://contrib/lang2installer/installer_builder /// using strings defined in stringnames.txt (same dir) $string['admindirerror'] = 'O diretório admin indicado não é correto'; $string['admindirname'] = 'Diretório Admin'; $string['admindirsettinghead'] = 'Criando o diretório admin ...'; $string['admindirsettingsub'] = 'Alguns serviços de hospedagem de sites web usam /admin como URL especial para acessar o painel de controle. Isto cria conflitos com os diretórios das páginas de administração de Moodle. para resolver este problema é necessário mudar o nome do diretório admin da sua instalação, e indicar este nome aqui. Por exemplo: <br /> <br /><b>moodleadmin</b><br /> <br /> Isto resolve os eventuais problemas com links do painel de administração de Moodle.'; $string['bypassed'] = 'Ignorado'; $string['cannotcreatelangdir'] = 'Impossível criar diretório lang'; $string['cannotcreatetempdir'] = 'Impossível criar diretório temp'; $string['cannotdownloadcomponents'] = 'Impossível baixar componentes'; $string['cannotdownloadzipfile'] = 'Impossível baixar arquivo ZIP'; $string['cannotfindcomponent'] = 'Impossível achar componente'; $string['cannotsavemd5file'] = 'Impossível salvar arquivo md5'; $string['cannotsavezipfile'] = 'Impossível salvar arquivo ZIP'; $string['cannotunzipfile'] = 'Impossível descompactar arquivo ZIP'; $string['caution'] = 'Atenção'; $string['check'] = 'Selecionar'; $string['chooselanguagehead'] = 'Escolha um idioma'; $string['chooselanguagesub'] = 'Escolha um idioma a ser usado durante a instalação. Após a instalação você pode definir o idioma principal do site e outros idiomas a serem utilizados pelos usuários.'; $string['closewindow'] = 'Fechar esta janela'; $string['compatibilitysettingshead'] = 'Controlando configurações do PHP ...'; $string['compatibilitysettingssub'] = 'O seu servidor deve ser compatível com este teste para que o Moodle funcione apropriadamente'; $string['componentisuptodate'] = 'Componente atualizado'; $string['configfilenotwritten'] = 'O script do instalador não conseguiu criar o arquivo config.php com as configurações que você definiu, provavelmente o diretório não está protegido e não aceita modificações. Você pode copiar o seguinte código manualmente em um arquivo de texto com o nome config.php e carregar este arquivo no diretório principal do Moodle.'; $string['configfilewritten'] = 'config.php foi criado com sucesso'; $string['configurationcompletehead'] = 'Configuração completada'; $string['configurationcompletesub'] = 'Moodle tentou salvar a sua configuração em um arquivo na área principal (root) da sua instalação do Moodle'; $string['continue'] = 'Continuar'; $string['ctyperecommended'] = 'Instalar a extensão ctype opcional do PHP para melhorar a performance do site, especialmente se são utilizados idiomas não latinos'; $string['ctyperequired'] = 'A extensão ctype do PHP ´necessária para melhorar a performance e a compatibilidade com funcionalidades multi-lingua.'; $string['curlrecommended'] = 'Instalar a biblioteca opcional cURL é altamente recomendável para permitir a ativação de Redes Moodle'; $string['customcheck'] = 'Outros controles'; $string['database'] = 'Base de dados'; $string['databasecreationsettingshead'] = 'Agora você precisa configurar a base de dados que será criada automaticamente pelo instalador com os valores especificados abaixo.'; $string['databasecreationsettingssub'] = '<b>Tipo:</b> definido como \"mysql\" pelo instalador<br /> <b>Host:</b> definido como \"localhost\" pelo instalador<br /> <b>Nome:</b> nome da base de dados, por exemplo moodle<br /> <b>Usuário:</b> definido como \"root\" pelo instalador<br /> <b>Senha:</b> a senha de acesso à base de dados<br /> <b>Prefixo das Tabelas:</b> prefixo opcional usaado no nome das tabelas'; $string['databasesettingshead'] = 'Agora você precisa configurar a base de dados. Esta base de dados deve ter sido criada e configurada com uma senha e um nome de usuário.'; $string['databasesettingssub'] = '<b>Tipo:</b> mysql ou postgres7<br /> <b>Host:</b> ex. localhost ou db.isp.com<br /> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo opcional a ser utilizado no nome das tabelas'; $string['databasesettingssub_mssql'] = '<b>Tipo:</b> Servidor SQL (não UTF-8) <b><font color=\"red\">Experimental! (não deve ser usado em produção)</font></b><br /> <b>Host:</b> ex. localhost ou db.isp.com<br /> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (obrigatório)'; $string['databasesettingssub_mssql_n'] = '<b>Tipo:</b> Servidor SQL (UTF-8 habilitado)<br /> <b>Host:</b> ex. localhost ou db.isp.com<br /> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (obrigatório)'; $string['databasesettingssub_mysql'] = '<b>Tipo:</b> MySQL <br /> <b>Host:</b> ex. localhost ou db.isp.com<br /> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (opcional)'; $string['databasesettingssub_mysqli'] = '<b>Tipo:</b> MySQL aperfeiçoado <br /> <b>Host:</b> ex. localhost ou db.isp.com<br /> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (opcional)'; $string['databasesettingssub_oci8po'] = '<b>Tipo:</b> Oracle<br /> <b>Host:</b> não é utilizado, deve ser deixado em branco<br /> <b>Nome:</b> nome da conexão tnsnames.ora<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (opcional)'; $string['databasesettingssub_odbc_mssql'] = '<b>Tipo:</b> Servidor SQL (em ODBC) <b><font color=\"red\">Experimental! (não use em produção)</font></b><br/> <b>Host:</b> nome do DSN no painel de controle do ODBC<br/> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (obrigatório)'; $string['databasesettingssub_postgres7'] = '<b>Tipo:</b> PostgreSQL <br /> <b>Host:</b> ex. localhost ou db.isp.com<br /> <b>Nome:</b> nome da base de dados, ex. moodle<br /> <b>Usuário:</b> nome de usuário da base de dados<br /> <b>Senha:</b> senha da base de dados<br /> <b>Prefixo das tabelas:</b> prefixo a ser utilizado no nome das tabelas (obrigatório)'; $string['databasesettingswillbecreated'] = '<b>Nota:</b> O instalador tentará criar o banco de dados automaticamente se não existir.'; $string['dataroot'] = 'Diretório Data'; $string['datarooterror'] = 'O \'Diretório Data\' indicado não foi encontrado e não foi possível criar um novo diretório. Corrija a indicação do percurso ou crie o diretório manualmente.'; $string['datarootpublicerror'] = 'O diretório de dados que você indicou é acessível no web, è melhor escolher um outro diretório.'; $string['dbconnectionerror'] = 'Não foi possível fazer a conexão com a base de dados indicada. Controle as configurações da base de dados.'; $string['dbcreationerror'] = 'Erro de ciação de base de dados. Não foi possível criar o nome da base de dados indicado com os parâmetros fornecidos.'; $string['dbhost'] = 'Servidor hospedeiro'; $string['dbprefix'] = 'Prefixo das tabelas'; $string['dbtype'] = 'Tipo'; $string['dbwrongencoding'] = 'A base de dados selecionada usa uma codificação que não é recomendável($a). É melhor usar uma codificação Unicode (UTF-8). Você pode saltar este teste clicando \"Saltar teste de codificação da base de dados\", mas é possível que se apresentem problemas no futuro.'; $string['dbwronghostserver'] = 'Você deve seguir regras de host como explicado acima.'; $string['dbwrongnlslang'] = 'A variável de ambiente NLS_LANG em seu servidor web deve usar o conjunto de caracteres AL32UTF8. Veja a documentação do PHP sobre como configurar OCI8.'; $string['dbwrongprefix'] = 'Você deve seguir regras de prefixos de tabela como explicado acima.'; $string['directorysettingshead'] = 'Confirme os percursos de acesso desta instalação de Moodle'; $string['directorysettingssub'] = '<b>Endereço Web:</b> Especifique o endereço web completo em que Moodle pode ser acessado. Se o acesso é múltiplo, escolha o endereço mais fácil para os alunos. Não inclua uma barra final no endereço. br /> <br /> <b>Diretório Moodle:</b> Especifique o percurso completo de acesso ao diretório de instalação. Atenção ao uso de maiúsculas e minúsculas. <br /> <br /> <b>Diretório de dados:</b> Especifique um diretório para que o Moodle possa salvar arquivos carregados no servidor. Este diretório deve ter permissões de leitura e escrita pelo usuário do servidor web (normalmente \'nobody\' ou \'apache\'), mas não deve ter acesso livre via web.'; $string['dirroot'] = 'Diretório Moodle'; $string['dirrooterror'] = 'A configuração do percurso de acesso ao Diretório Moodle parece errada - não foi possível encontrar uma instalação de Moodle neste endereço. O valor abaixo foi reconfigurado.'; $string['download'] = 'Download'; $string['downloadedfilecheckfailed'] = 'Impossível fazer o controle do arquivo baixado'; $string['downloadlanguagebutton'] = 'Baixar o Pacote de Idioma \"$a\"'; $string['downloadlanguagehead'] = 'Baixar Pacote de Idioma'; $string['downloadlanguagenotneeded'] = 'Você pode continuar a instalação usando o idioma padrão \"$a\".'; $string['downloadlanguagesub'] = 'Você pode indicar um idioma a ser instalado para que o processo continue com o uso deste idioma.<br /><br /> Se não for possível baixar o pacote do idioma, a instalação vai continuar em Inglês. (Depois da instalação é possível acrescentar outros pacotes de idioma)'; $string['environmenterrortodo'] = 'Você deve resolver os problemas indicados acima antes de instalar esta versão de Moodle.'; $string['environmenthead'] = 'Verificando o ambiente ...'; $string['environmentrecommendcustomcheck'] = 'Se esse teste falhar, será indício de um possível problema'; $string['environmentrecommendinstall'] = 'recomendado como instalado/habilitado'; $string['environmentrecommendversion'] = 'a versão $a->needed é recomendada e você está usando a versão $a->current'; $string['environmentrequirecustomcheck'] = 'Este teste deve funcionar'; $string['environmentrequireinstall'] = 'deve ser instalado/habilitado'; $string['environmentrequireversion'] = 'a versão $a->needed é necessária e você está usando a versão $a->current'; $string['environmentsub'] = 'Verificando se componentes do seu sistema são compatíveis com os requisitos de sistema'; $string['environmentxmlerror'] = 'Erro de leitura dos dados do ambiente ($a->error_code)'; $string['error'] = 'Erro'; $string['fail'] = 'Erro'; $string['fileuploads'] = 'Carregamento de arquivos'; $string['fileuploadserror'] = 'Isto deve estar ativado'; $string['fileuploadshelp'] = '<p>Parece que o envio de documentos a este servidor não está habilitado.</p> <p>Moodle pode ser instalado, mas não será possível carregar arquivos ou imagens nos cursos.</p> <p>para habilitar o envio de arquivos é necessário editar o arquivo php.ini do sistema e mudar a configuração de <b>file_uploads</b> para \'1\'.</p>'; $string['gdversion'] = 'Versão do gd'; $string['gdversionerror'] = 'A library GD'; $string['gdversionhelp'] = '<p>Parece que o seu servidor não tem o GD instalado.</p> <p>GD é uma biblioteca de PHP necessária à elaboração de imagens como as fotos do perfil do usuário e os gráficos de estatísticas. O Moodle funciona sem o GD mas a elaboração de imagens não será possível.</p> <p>Para adicionar o GD ao PHP em Unix, compile o PHP usando o parâmetro --with-gd .</p> <p>Em Windows edite php.ini and cancele o comentário à linha que se refere a php_gd2.dll.</p>'; $string['globalsquotes'] = 'Tratamento de Globais sem Segurança'; $string['globalsquoteserror'] = 'Corrija a configuração do seu PHP: desabilitar register_globals e/ou habilitar magic_quotes_gpc'; $string['globalsquoteshelp'] = '<p>Não é aconselhável habilitar Register Globals e desabilitar Magic Quotes GPC ao mesmo tempo.</p> <p>A configuração aconselhada é <b>magic_quotes_gpc = On</b> e <b>register_globals = Off</b> no seu php.ini</p> <p>Se você não tem acesso ao seu php.ini, adicione a seguinte linha de código no arquivo .htaccess do diretório principal do seu Moodle: <blockquote>php_value magic_quotes_gpc On</blockquote> <blockquote>php_value register_globals Off</blockquote> </p>'; $string['globalswarning'] = '<p><strong>Aviso de segurança</strong>: para operar propriamente, Moodle requer <br /> que você faça certas mudanças nas configurações atuais do seu PHP.<p/><p>Você <em>deve</em> ajustar<code>register_globals=off</code>.<p>Essa configuração é controlada editando a configuração de <code>php.ini</code>, Apache/IIS <br /> ou <code>.htaccess</code> file.</p>'; $string['help'] = 'Ajuda'; $string['iconvrecommended'] = 'Instalar ICONV library é altamente recomendável para aumentar a performance do site, especialmente quando o site suporta o uso de idiomas não-latinos'; $string['info'] = 'Informação'; $string['installation'] = 'Instalação'; $string['invalidmd5'] = 'md5 inválido'; $string['langdownloaderror'] = 'Infelizmente o idioma \"$a\" não foi instalado. A instalação vai continuar em Inglês.'; $string['langdownloadok'] = 'Idioma \"$a\" instalado com sucesso. O processo de instalação vai continuar neste idioma.'; $string['language'] = 'Idioma'; $string['magicquotesruntime'] = 'Magic Quotes Run Time'; $string['magicquotesruntimeerror'] = 'Isto deveria estar desativado'; $string['magicquotesruntimehelp'] = '<p> A runtime Magic Quotes deve ser desativada para que Moodle funcione corretamente.</p> <p>Normalmente esta runtime já é desativada... controle o parâmetro <b>magic_quotes_runtime</b> no seu arquivo php.ini .</p> <p>Se você não tem acesso ao arquivo php.ini , adicione a seguinte linha no código de um arquivo chamado .htaccess no diretório Moodle: <blockquote>php_value magic_quotes_runtime Off</blockquote> </p>'; $string['mbstringrecommended'] = 'A instalação da MBSTRING library é altamente recomendável para melhorar a performanse do site, especialmente se o seu site suporta idiomas não-latinos.'; $string['memorylimit'] = 'Limite de Memória'; $string['memorylimiterror'] = 'A configuração do limite da memória do PHP está muito baixa ... isto pode causar problemas no futuro.'; $string['memorylimithelp'] = '<p>O limite de memória do PHP configurado atualmente no seu servidor é de $a.</p> <p>Este limite pode causar problemas no futuro, especialmente quando muitos módulos estiverem ativados ou em caso de um número elevado de usuários.</p> <p>É aconselhável a configuração do limite de memória com o valor mais alto possível, como 40M. Você pode tentar um dos seguintes caminhos:</p> <ol> <li>Se você puder, recompile o PHP com <i>--enable-memory-limit</i>. Com esta operação Moodle será capaz de configurar o limite de memória sózinho.</li> <li>Se você tiver acesso ao arquivo php.ini, você pode mudar o parâmetro <b>memory_limit</b> para um valor próximo a 40M. Se você não tiver acesso direto, peça ao administrador do sistema para fazer esta operação.</li> <li>Em alguns servidores é possível fazer esta mudança criando um arquivo .htaccess no diretório Moodle. O arquivo deve conter a seguinte expressão: <p><blockquote>php_value memory_limit 40M</blockquote></p> <p>Alguns servidores não aceitam este procedimento e <b>todas</b> as páginas PHP do servidor ficam bloqueadas ou imprimem mensagens de erro. Neste caso será necessário cancelar o arquivo .htaccess .</p> </li></ol>'; $string['missingrequiredfield'] = 'Faltam informações obrigatórias'; $string['moodledocslink'] = 'Documentação de Moodle relativa a esta página'; $string['mssql'] = 'Servidor SQL (mssql)'; $string['mssqlextensionisnotpresentinphp'] = 'O PHP não foi configurado corretamente com a extensão MSSQL para que possa se comunicar com o servidor SQL. Por favor, verifique o seu arquivo php.ini ou faça a recompilação do PHP.'; $string['mssql_n'] = 'Servidor SQL com suporte a UTF-8 (mssql_n)'; $string['mysql'] = 'MySQL (mysql)'; $string['mysql416bypassed'] = 'Entretanto, se o seu site usa apenas idiomas iso-8859-1 (latin), você pode continuar a usar a sua base de dados atual MySQL 4.1.12 (ou superior).'; $string['mysql416required'] = 'MySQL 4.1.16 é a versão mínima necessária para ainstalação de Moodle 1.6 em modo que os dados possam ser convertidos para UTF-8.'; $string['mysqlextensionisnotpresentinphp'] = 'O PHP não foi configurado corretamente com a extensão MySQL para que possa se comunicar com MySQL. Por favor, verifique o seu arquivo php.ini ou faça a recompilação do PHP.'; $string['mysqli'] = 'MySQL aperfeiçoado (mysqli)'; $string['mysqliextensionisnotpresentinphp'] = 'O PHP não foi configurado corretamente com a extensão MySQLi para que possa se comunicar com MySQL. Por favor, verifique o seu arquivo php.ini ou faça a recompilação do PHP. A extensão MySQL não está disponível para PHP 4.'; $string['name'] = 'Nome'; $string['next'] = 'Próximo'; $string['oci8po'] = 'Oracle (oci8po)'; $string['ociextensionisnotpresentinphp'] = 'O PHP não foi configurado corretamente com a extensão OCI8 para que possa se comunicar com Oracle. Por favor, verifique o seu arquivo php.ini ou faça a recompilação do PHP.'; $string['odbcextensionisnotpresentinphp'] = 'O PHP não foi configurado corretamente com a extensão ODBC para que possa se comunicar com o servidor SQL. Por favor, verifique o seu arquivo php.ini ou faça a recompilação do PHP.'; $string['odbc_mssql'] = 'Servidor SQL em ODBC (odbc_mssql)'; $string['ok'] = 'OK'; $string['opensslrecommended'] = 'É altamente recomendável a instalação da biblioteca OpenSSL, que é opcional, isto permite a funcionalidade Moodle em Rede.'; $string['pass'] = 'OK'; $string['password'] = 'Senha'; $string['pgsqlextensionisnotpresentinphp'] = 'O PHP não foi configurado corretamente com a extensão PGSQL para que possa se comunicar com PstgreSQL. Por favor, verifique o seu arquivo php.ini ou faça a recompilação do PHP.'; $string['php50restricted'] = 'O PHP 5.0.x apresenta muitos problemas conhecidos, faça o upgrade para a versão 5.1.x ou faça o downgrade para a versão 4.3.x ou 4.4.x'; $string['phpversion'] = 'Versão do PHP'; $string['phpversionerror'] = 'A versão do PHP não deve ser inferior a 4.1.0'; $string['phpversionhelp'] = '<p>Moodle requer a versão 4.1.0 de PHP ou posterior.</p> <p>A sua versão é $a</p> <p>Atualize a versão do PHP!</p>'; $string['postgres7'] = '<p>Moodle requer a versão 4.1.0 de PHP ou posterior.</p> <p>A sua versão é $a</p> <p>Atualize a versão do PHP!</p> PostgreSQL (postgres7)'; $string['postgresqlwarning'] = '<strong>Nota:</strong> Em caso de problemas de conexão, tente configurar o campo Host Server assim: Servidor hospedeiro=\'postgresql_host\' porta=\'5432\' nome do db=\'postgresql_database_name\' usuário=\'postgresql_user\' senha=\'postgresql_user_password\' e deixe vazios os campos Database, Usuário e Senha. Leia também <a href=\"http://docs.moodle.org/en/Installing_Postgres_for_PHP\">Moodle Docs</a>'; $string['previous'] = 'Anterior'; $string['qtyperqpwillberemoved'] = 'Durante a migração, o tipo de questão RQP será removido. Como você não estava usando este tipo de questão então não terá problemas.'; $string['qtyperqpwillberemovedanyway'] = 'Durante a migração, as questões do tipo RQP serão removidas. Você tem algumas questões RQP no seu banco de dados e elas não funcionarão a menos que você reinstale o código de http://moodle.org/mod/data/view.php?d=13&amp;rid=797 antes de continuar a migração.'; $string['remotedownloaderror'] = 'O download do componente falhou, por favor verifique as configurações do proxy. A extensão cURL do PHP é altamente recomendada.<br /><br />Você precisar baixar o <a href=\"$a->url\">arquivo</a> manualmente, copiar para \"$a->dest\" e descompactar lá.'; $string['remotedownloadnotallowed'] = 'Não é permitido baixar componentes no seu servidor (allow_url_fopen está desabilitado).).<br /><br />Você deve baixar o arquivo <a href=\"$a->url\">$a->url</a> manualmente, copiar em \"$a->dest\" no seu servidor e descomprimir o arquivo nesta posição.'; $string['report'] = 'Relatório'; $string['restricted'] = 'Restringido'; $string['safemode'] = 'Modalidade segura'; $string['safemodeerror'] = 'Moodle pode ter problemas se a modalidade segura estiver ativa'; $string['safemodehelp'] = '<p>Moodle pode ter alguns problemas quando o safe mode está ativado. Provavelmente não será possível criar novos arquivos.</p> <p>O safe mode normalmente é ativado apenas por serviços de web hosting públicos paranóicos por segurança, é possível que você tenha que escolher um outro serviço de webhosting para o seu site.</p> <p>Você pode continuar a instalação mas provavelmente outros problemas surgirão.</p>'; $string['serverchecks'] = 'Verificações do servidor'; $string['sessionautostart'] = 'Início da sessão automático'; $string['sessionautostarterror'] = 'Isto deve estar ativado'; $string['sessionautostarthelp'] = '<p>Moodle requer o suporte a sessões e não funciona sem isto.</p> <p>As sessões podem se habilitadas no arquivo php.ini ... controle o parâmetro session.auto_start .</p>'; $string['skipdbencodingtest'] = 'Saltar Teste de Codificação da Base de Dados'; $string['status'] = 'Status'; $string['thischarset'] = 'UTF-8'; $string['thisdirection'] = 'ltr'; $string['thislanguage'] = 'Português - Brasil'; $string['unicoderecommended'] = 'É recomendado que todos os dados sejam armazenados em Unicode (UTF-8). Instalações novas devem ser construídas em banco de dados que tenham o seu conjunto de caracteres padrão em Unicode. Se você está migrando, você deverá executar o processo de migração para o UTF-8. (veja a página do Admin)'; $string['unicoderequired'] = 'É obrigatório que você guarde todos os seus dados no formato Unicode (UTF-8). Instalações novas devem ser construidas em banco de dados que tenham o seu conjunto de caracteres padrão em Unicode. Se você está migrando, você deverá executar o processo de migração para o UTF-8. (veja a página do Admin)'; $string['user'] = 'Usuário'; $string['welcomep10'] = '$a->installername ($a->installerversion)'; $string['welcomep20'] = 'Se você chegou nesta página, o pacote <strong>$a->packname $a->packversion</strong> foi instalado. Parabéns!'; $string['welcomep30'] = 'Esta versão do <strong>$a->installername</strong> inclui as aplicações para a criação de um ambiente em que <strong>Moodle</strong> possa operar:'; $string['welcomep40'] = 'O pacote inclui também o <strong>Moodle $a->moodlerelease ($a->moodleversion)</strong>.'; $string['welcomep50'] = 'O uso das aplicações incluídas neste pacote é regulamentado pelas respectivas licenças. O instalador completo <strong>$a->installername</strong> é <a href=\"http://www.opensource.org/docs/definition_plain.html\">open source</a> e é distribuído com uma licença <a href=\"http://www.gnu.org/copyleft/gpl.html\">GPL</a>.'; $string['welcomep60'] = 'As seguinte páginas guiam passo a passo a configuração de <strong>Moodle</strong> no seu computador. Você pode usar a configuração padrão ou alterá-las de acordo com as suas necessidades.'; $string['welcomep70'] = 'Clicar o botão \"Próxima\" abaixo para continuar a configuração de <strong>Moodle</strong>.'; $string['wrongdestpath'] = 'Percurso do destino errado'; $string['wrongsourcebase'] = 'URL do recurso errado'; $string['wrongzipfilename'] = 'Nome do arquivo ZIP errado'; $string['wwwroot'] = 'Endereço web'; $string['wwwrooterror'] = 'Este endereço web não está correto - a instalação do Moodle não foi encontrada.'; $string['xmlrpcrecommended'] = 'Instalar a extensão opcional xmlrpc é útil para a funcionalidade Moodle Networking.'; $string['ziprequired'] = 'A extensão Zip do PHP é necessária. Binários infoZIP ou PclZip não são mais utilizados.'; ?>
henriquecrang/e-UNI
install/lang/pt_br_utf8/installer.php
PHP
gpl-2.0
25,327
[ 30522, 1026, 1029, 25718, 1013, 1013, 1013, 3531, 1010, 2079, 2025, 10086, 2023, 5371, 21118, 999, 2009, 1005, 1055, 8285, 7013, 2013, 1013, 1013, 1013, 8417, 8250, 1999, 2115, 3115, 11374, 5308, 6764, 1024, 1013, 1013, 1013, 1006, 11374, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# frozen_string_literal: true require 'fieldhand/metadata_format' module Fieldhand # A parser for ListMetadataFormats responses. # # See https://www.openarchives.org/OAI/openarchivesprotocol.html#ListMetadataFormats class ListMetadataFormatsParser attr_reader :response_parser # Return a parser for the given response parser. def initialize(response_parser) @response_parser = response_parser end # Return an array of `MetadataFormat`s found in the response. def items response_parser. root. locate('ListMetadataFormats/metadataFormat'). map { |item| MetadataFormat.new(item, response_parser.response_date) } end end end
altmetric/fieldhand
lib/fieldhand/list_metadata_formats_parser.rb
Ruby
mit
699
[ 30522, 1001, 7708, 1035, 5164, 1035, 18204, 1024, 2995, 5478, 1005, 2492, 11774, 1013, 27425, 1035, 4289, 1005, 11336, 2492, 11774, 1001, 1037, 11968, 8043, 2005, 2862, 11368, 8447, 2696, 14192, 11149, 10960, 1012, 1001, 1001, 2156, 16770, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org> * 1999-2001 Lars Knoll <knoll@kde.org> * 1999-2001 Antti Koivisto <koivisto@kde.org> * 2000-2001 Simon Hausmann <hausmann@kde.org> * 2000-2001 Dirk Mueller <mueller@kde.org> * 2000 Stefan Schimanski <1Stein@gmx.de> * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2008 Eric Seidel <eric@webkit.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef Frame_h #define Frame_h #include "AdjustViewSizeOrNot.h" #include "DragImage.h" #include "FrameLoader.h" #include "FrameTree.h" #include "IntRect.h" #include "NavigationScheduler.h" #include "ScrollTypes.h" #include "UserScriptTypes.h" #include <wtf/RefCounted.h> #if PLATFORM(WIN) #include "FrameWin.h" #endif #if USE(TILED_BACKING_STORE) #include "TiledBackingStoreClient.h" #endif #if PLATFORM(WIN) typedef struct HBITMAP__* HBITMAP; #endif namespace WebCore { class AnimationController; class Color; class Document; class Editor; class Element; class EventHandler; class FrameDestructionObserver; class FrameSelection; class FrameView; class HTMLTableCellElement; class IntRect; class Node; class RegularExpression; class RenderPart; class RenderView; class ScriptController; class Settings; class TiledBackingStore; class TreeScope; class VisiblePosition; #if !USE(TILED_BACKING_STORE) class TiledBackingStoreClient { }; #endif enum { LayerTreeFlagsIncludeDebugInfo = 1 << 0, LayerTreeFlagsIncludeVisibleRects = 1 << 1, LayerTreeFlagsIncludeTileCaches = 1 << 2, LayerTreeFlagsIncludeRepaintRects = 1 << 3, LayerTreeFlagsIncludePaintingPhases = 1 << 4 }; typedef unsigned LayerTreeFlags; class Frame : public RefCounted<Frame>, public TiledBackingStoreClient { public: static PassRefPtr<Frame> create(Page*, HTMLFrameOwnerElement*, FrameLoaderClient*); void init(); void setView(PassRefPtr<FrameView>); void createView(const IntSize&, const Color&, bool, const IntSize& fixedLayoutSize = IntSize(), const IntRect& fixedVisibleContentRect = IntRect(), bool useFixedLayout = false, ScrollbarMode = ScrollbarAuto, bool horizontalLock = false, ScrollbarMode = ScrollbarAuto, bool verticalLock = false); ~Frame(); void addDestructionObserver(FrameDestructionObserver*); void removeDestructionObserver(FrameDestructionObserver*); void willDetachPage(); void detachFromPage(); void disconnectOwnerElement(); Page* page() const; HTMLFrameOwnerElement* ownerElement() const; Document* document() const; FrameView* view() const; Editor& editor() const; EventHandler* eventHandler() const; FrameLoader* loader() const; NavigationScheduler* navigationScheduler() const; FrameSelection* selection() const; FrameTree* tree() const; AnimationController* animation() const; ScriptController* script(); RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame. RenderPart* ownerRenderer() const; // Renderer for the element that contains this frame. #if ENABLE(PAGE_VISIBILITY_API) void dispatchVisibilityStateChangeEvent(); #endif // ======== All public functions below this point are candidates to move out of Frame into another class. ======== bool inScope(TreeScope*) const; void injectUserScripts(UserScriptInjectionTime); String layerTreeAsText(LayerTreeFlags = 0) const; String trackedRepaintRectsAsText() const; static Frame* frameForWidget(const Widget*); Settings* settings() const; // can be NULL void setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot); void addResetPage(int page); void getPagination(int page, int pages, int &logicalPage, int &logicalPages) const; bool shouldUsePrintingLayout() const; FloatSize resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize); bool inViewSourceMode() const; void setInViewSourceMode(bool = true); void setDocument(PassRefPtr<Document>); void setPageZoomFactor(float factor); float pageZoomFactor() const { return m_pageZoomFactor; } void setTextZoomFactor(float factor); float textZoomFactor() const { return m_textZoomFactor; } void setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor); // Scale factor of this frame with respect to the container. float frameScaleFactor() const; #if USE(ACCELERATED_COMPOSITING) void deviceOrPageScaleFactorChanged(); #endif #if ENABLE(ORIENTATION_EVENTS) // Orientation is the interface orientation in degrees. Some examples are: // 0 is straight up; -90 is when the device is rotated 90 clockwise; // 90 is when rotated counter clockwise. void sendOrientationChangeEvent(int orientation); int orientation() const { return m_orientation; } #endif void clearTimers(); static void clearTimers(FrameView*, Document*); String documentTypeString() const; String displayStringModifiedByEncoding(const String&) const; DragImageRef nodeImage(Node*); DragImageRef dragImageForSelection(); VisiblePosition visiblePositionForPoint(const IntPoint& framePoint); Document* documentAtPoint(const IntPoint& windowPoint); PassRefPtr<Range> rangeForPoint(const IntPoint& framePoint); String searchForLabelsAboveCell(RegularExpression*, HTMLTableCellElement*, size_t* resultDistanceFromStartOfCell); String searchForLabelsBeforeElement(const Vector<String>& labels, Element*, size_t* resultDistance, bool* resultIsInCellAbove); String matchLabelsAgainstElement(const Vector<String>& labels, Element*); void suspendActiveDOMObjectsAndAnimations(); void resumeActiveDOMObjectsAndAnimations(); bool activeDOMObjectsAndAnimationsSuspended() const { return m_activeDOMObjectsAndAnimationsSuspendedCount > 0; } // Should only be called on the main frame of a page. void notifyChromeClientWheelEventHandlerCountChanged() const; bool isURLAllowed(const KURL&) const; // ======== private: Frame(Page*, HTMLFrameOwnerElement*, FrameLoaderClient*); void injectUserScriptsForWorld(DOMWrapperWorld*, const UserScriptVector&, UserScriptInjectionTime); HashSet<FrameDestructionObserver*> m_destructionObservers; Page* m_page; mutable FrameTree m_treeNode; mutable FrameLoader m_loader; mutable NavigationScheduler m_navigationScheduler; HTMLFrameOwnerElement* m_ownerElement; RefPtr<FrameView> m_view; RefPtr<Document> m_doc; OwnPtr<ScriptController> m_script; const OwnPtr<Editor> m_editor; OwnPtr<FrameSelection> m_selection; OwnPtr<EventHandler> m_eventHandler; OwnPtr<AnimationController> m_animationController; float m_pageZoomFactor; float m_textZoomFactor; #if ENABLE(ORIENTATION_EVENTS) int m_orientation; #endif bool m_inViewSourceMode; Vector<int> m_pageResets; #if USE(TILED_BACKING_STORE) // FIXME: The tiled backing store belongs in FrameView, not Frame. public: TiledBackingStore* tiledBackingStore() const { return m_tiledBackingStore.get(); } void setTiledBackingStoreEnabled(bool); private: // TiledBackingStoreClient interface virtual void tiledBackingStorePaintBegin(); virtual void tiledBackingStorePaint(GraphicsContext*, const IntRect&); virtual void tiledBackingStorePaintEnd(const Vector<IntRect>& paintedArea); virtual IntRect tiledBackingStoreContentsRect(); virtual IntRect tiledBackingStoreVisibleRect(); virtual Color tiledBackingStoreBackgroundColor() const; OwnPtr<TiledBackingStore> m_tiledBackingStore; #endif int m_activeDOMObjectsAndAnimationsSuspendedCount; }; inline void Frame::init() { m_loader.init(); } inline FrameLoader* Frame::loader() const { return &m_loader; } inline NavigationScheduler* Frame::navigationScheduler() const { return &m_navigationScheduler; } inline FrameView* Frame::view() const { return m_view.get(); } inline ScriptController* Frame::script() { return m_script.get(); } inline Document* Frame::document() const { return m_doc.get(); } inline FrameSelection* Frame::selection() const { return m_selection.get(); } inline Editor& Frame::editor() const { return *m_editor; } inline AnimationController* Frame::animation() const { return m_animationController.get(); } inline HTMLFrameOwnerElement* Frame::ownerElement() const { return m_ownerElement; } inline bool Frame::inViewSourceMode() const { return m_inViewSourceMode; } inline void Frame::setInViewSourceMode(bool mode) { m_inViewSourceMode = mode; } inline FrameTree* Frame::tree() const { return &m_treeNode; } inline Page* Frame::page() const { return m_page; } inline void Frame::detachFromPage() { m_page = 0; } inline EventHandler* Frame::eventHandler() const { return m_eventHandler.get(); } } // namespace WebCore #endif // Frame_h
pataquets/phantomjs
src/qt/qtwebkit/Source/WebCore/page/Frame.h
C
bsd-3-clause
10,796
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2687, 1010, 2639, 17153, 10609, 11417, 2015, 1026, 11417, 2015, 1030, 1047, 3207, 1012, 8917, 1028, 1008, 2639, 1011, 2541, 16357, 14161, 14511, 1026, 14161, 14511, 1030, 1047, 3207, 1012, 89...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
cask 'dsp-radio' do version '1.4.1' sha256 'b04ff63d41a47923455499340e32706df83a184c54c590d70191072b8fdbbbc9' url "https://dl2sdr.homepage.t-online.de/files/DSP_Radio_#{version.delete('.')}.zip" name 'DSP Radio' homepage 'https://dl2sdr.homepage.t-online.de/' license :gratis app "DSP Radio #{version}.app" end
JosephViolago/homebrew-cask
Casks/dsp-radio.rb
Ruby
bsd-2-clause
327
[ 30522, 25222, 2243, 1005, 16233, 2361, 1011, 2557, 1005, 2079, 2544, 1005, 1015, 1012, 1018, 1012, 1015, 1005, 21146, 17788, 2575, 1005, 1038, 2692, 2549, 4246, 2575, 29097, 23632, 2050, 22610, 2683, 21926, 19961, 27009, 2683, 2683, 22022, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
///******************************************************************************* // * Copyright (c) 2015, 2016 EfficiOS Inc., Alexandre Montplaisir // * // * All rights reserved. This program and the accompanying materials are // * made available under the terms of the Eclipse Public License v1.0 which // * accompanies this distribution, and is available at // * http://www.eclipse.org/legal/epl-v10.html // *******************************************************************************/ // //package org.lttng.scope.lami.ui.viewers; // //import org.eclipse.jface.viewers.TableViewer; //import org.eclipse.swt.SWT; //import org.eclipse.swt.widgets.Composite; //import org.lttng.scope.lami.core.module.LamiChartModel; //import org.lttng.scope.lami.ui.views.LamiReportViewTabPage; // ///** // * Common interface for all Lami viewers. // * // * @author Alexandre Montplaisir // */ //public interface ILamiViewer { // // /** // * Dispose the viewer widget. // */ // void dispose(); // // /** // * Factory method to create a new Table viewer. // * // * @param parent // * The parent composite // * @param page // * The {@link LamiReportViewTabPage} parent page // * @return The new viewer // */ // static ILamiViewer createLamiTable(Composite parent, LamiReportViewTabPage page) { // TableViewer tableViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL); // return new LamiTableViewer(tableViewer, page); // } // // /** // * Factory method to create a new chart viewer. The chart type is specified // * by the 'chartModel' parameter. // * // * @param parent // * The parent composite // * @param page // * The {@link LamiReportViewTabPage} parent page // * @param chartModel // * The information about the chart to display // * @return The new viewer // */ // static ILamiViewer createLamiChart(Composite parent, LamiReportViewTabPage page, LamiChartModel chartModel) { // switch (chartModel.getChartType()) { // case BAR_CHART: // return new LamiBarChartViewer(parent, page, chartModel); // case XY_SCATTER: // return new LamiScatterViewer(parent, page, chartModel); // case PIE_CHART: // default: // throw new UnsupportedOperationException("Unsupported chart type: " + chartModel.toString()); //$NON-NLS-1$ // } // } //}
alexmonthy/lttng-scope
lttng-scope/src/main/java/org/lttng/scope/lami/viewers/ILamiViewer.java
Java
epl-1.0
2,501
[ 30522, 1013, 1013, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>metacoq: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1 / metacoq - 1.0~beta2+8.13</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> metacoq <small> 1.0~beta2+8.13 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-05 19:37:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-05 19:37:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.7.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;matthieu.sozeau@inria.fr&quot; homepage: &quot;https://metacoq.github.io/metacoq&quot; dev-repo: &quot;git+https://github.com/MetaCoq/metacoq.git#coq-8.11&quot; bug-reports: &quot;https://github.com/MetaCoq/metacoq/issues&quot; authors: [&quot;Abhishek Anand &lt;aa755@cs.cornell.edu&gt;&quot; &quot;Simon Boulier &lt;simon.boulier@inria.fr&gt;&quot; &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; &quot;Yannick Forster &lt;forster@ps.uni-saarland.de&gt;&quot; &quot;Fabian Kunze &lt;fkunze@fakusb.de&gt;&quot; &quot;Gregory Malecha &lt;gmalecha@gmail.com&gt;&quot; &quot;Matthieu Sozeau &lt;matthieu.sozeau@inria.fr&gt;&quot; &quot;Nicolas Tabareau &lt;nicolas.tabareau@inria.fr&gt;&quot; &quot;Théo Winterhalter &lt;theo.winterhalter@inria.fr&gt;&quot; ] license: &quot;MIT&quot; depends: [ &quot;coq-metacoq-template&quot; {= version} &quot;coq-metacoq-pcuic&quot; {= version} &quot;coq-metacoq-safechecker&quot; {= version} &quot;coq-metacoq-erasure&quot; {= version} &quot;coq-metacoq-translations&quot; {= version} ] synopsis: &quot;A meta-programming framework for Coq&quot; description: &quot;&quot;&quot; MetaCoq is a meta-programming framework for Coq. The meta-package includes the template-coq library, unverified checker for Coq, PCUIC development including a verified translation from Coq to PCUIC, safe checker and erasure for PCUIC and example translations. See individual packages for more detailed descriptions. &quot;&quot;&quot; url { src: &quot;https://github.com/MetaCoq/metacoq/archive/v1.0-beta2-8.13.tar.gz&quot; checksum: &quot;sha256=15e1cfde70e6c4dbf33bff1a77266ac5c0c3e280586ef059e0cdec07bee814f2&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-metacoq.1.0~beta2+8.13 coq.8.7.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1). The following dependencies couldn&#39;t be met: - coq-metacoq -&gt; coq-metacoq-template &gt;= 1.0~beta2+8.13 -&gt; ocaml &gt;= 4.07.1 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq.1.0~beta2+8.13</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.03.0-2.0.5/released/8.7.1/metacoq/1.0~beta2+8.13.html
HTML
mit
7,602
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 418...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
''' This module corresponds to ARDroneLib/Soft/Common/navdata_common.h ''' import ctypes import functools from pyardrone.utils.structure import Structure uint8_t = ctypes.c_uint8 uint16_t = ctypes.c_uint16 uint32_t = ctypes.c_uint32 int16_t = ctypes.c_int16 int32_t = ctypes.c_int32 bool_t = ctypes.c_uint32 # ARDroneTool's bool is 4 bytes char = ctypes.c_char float32_t = ctypes.c_float NB_GYROS = 3 NB_ACCS = 3 NB_NAVDATA_DETECTION_RESULTS = 4 NB_CORNER_TRACKERS_WIDTH = 5 NB_CORNER_TRACKERS_HEIGHT = 4 DEFAULT_NB_TRACKERS_WIDTH = NB_CORNER_TRACKERS_WIDTH + 1 DEFAULT_NB_TRACKERS_HEIGHT = NB_CORNER_TRACKERS_HEIGHT + 1 NAVDATA_MAX_CUSTOM_TIME_SAVE = 20 _vector31_t = float32_t * 3 _velocities_t = _vector31_t _vector21_t = float32_t * 2 _screen_point_t = int32_t * 2 _matrix33_t = float32_t * 3 * 3 class OptionHeader(dict): def register(self, tag): return functools.partial(self._register, tag) def _register(self, tag, function): if tag in self: raise KeyError('Key {!r} conflict with existing item {}'.format( tag, self[tag])) self[tag] = function return function index = OptionHeader() class Metadata(Structure): ''' Header of :py:class:`~pyardrone.navdata.NavData`. Available via :py:class:`~pyardrone.navdata.NavData`.metadata Corresponds to C struct ``navdata_t``. ''' _pack_ = 1 _attrname = 'metadata' header = uint32_t #: Should be 0x55667788 #: raw drone state, #: see also: :py:class:`~pyardrone.navdata.states.DroneState` state = uint32_t sequence_number = uint32_t #: vision_flag = uint32_t #: class OptionHeader(Structure): _pack_ = 1 tag = uint16_t size = uint16_t @index.register(0) class Demo(OptionHeader): ''' Minimal navigation data for all flights. Corresponds to C struct ``navdata_demo_t``. ''' _attrname = 'demo' #: Flying state (landed, flying, hovering, etc.) #: defined in CTRL_STATES enum. ctrl_state = uint32_t vbat_flying_percentage = uint32_t #: battery voltage filtered (mV) theta = float32_t #: UAV's pitch in milli-degrees phi = float32_t #: UAV's roll in milli-degrees psi = float32_t #: UAV's yaw in milli-degrees altitude = int32_t #: UAV's altitude in centimeters vx = float32_t #: UAV's estimated linear velocity vy = float32_t #: UAV's estimated linear velocity vz = float32_t #: UAV's estimated linear velocity #: streamed frame index Not used -> To integrate in video stage. num_frames = uint32_t # Camera parameters compute by detection detection_camera_rot = _matrix33_t #: Deprecated ! Don't use ! detection_camera_trans = _vector31_t #: Deprecated ! Don't use ! detection_tag_index = uint32_t #: Deprecated ! Don't use ! detection_camera_type = uint32_t #: Type of tag searched in detection # Camera parameters compute by drone drone_camera_rot = _matrix33_t #: Deprecated ! Don't use ! drone_camera_trans = _vector31_t #: Deprecated ! Don't use ! @index.register(1) class Time(OptionHeader): ''' Timestamp Corresponds to C struct ``navdata_time_t``. ''' _attrname = 'time' #: 32 bit value where the 11 most significant bits represents the seconds, #: and the 21 least significant bits are the microseconds. time = uint32_t @index.register(2) class RawMeasures(OptionHeader): ''' Raw sensors measurements Corresponds to C struct ``navdata_raw_measures_t``. ''' _attrname = 'raw_measures' # +12 bytes raw_accs = uint16_t * NB_ACCS #: filtered accelerometers raw_gyros = int16_t * NB_GYROS #: filtered gyrometers raw_gyros_110 = int16_t * 2 #: gyrometers x/y 110 deg/s vbat_raw = uint32_t #: battery voltage raw (mV) us_debut_echo = uint16_t us_fin_echo = uint16_t us_association_echo = uint16_t us_distance_echo = uint16_t us_courbe_temps = uint16_t us_courbe_valeur = uint16_t us_courbe_ref = uint16_t flag_echo_ini = uint16_t # TODO: uint16_t frame_number from ARDrone_Magneto nb_echo = uint16_t sum_echo = uint32_t alt_temp_raw = int32_t gradient = int16_t @index.register(21) class PressureRaw(OptionHeader): 'Corresponds to C struct ``navdata_pressure_raw_t``.' _attrname = 'pressure_raw' up = int32_t ut = int16_t Temperature_meas = int32_t Pression_meas = int32_t @index.register(22) class Magneto(OptionHeader): 'Corresponds to C struct ``navdata_magneto_t``.' _attrname = 'magneto' mx = int16_t my = int16_t mz = int16_t magneto_raw = _vector31_t #: magneto in the body frame, in mG magneto_rectified = _vector31_t magneto_offset = _vector31_t heading_unwrapped = float32_t heading_gyro_unwrapped = float32_t heading_fusion_unwrapped = float32_t magneto_calibration_ok = char magneto_state = uint32_t magneto_radius = float32_t error_mean = float32_t error_var = float32_t @index.register(23) class WindSpeed(OptionHeader): 'Corresponds to C struct ``navdata_wind_speed_t``.' _attrname = 'wind_speed' wind_speed = float32_t #: estimated wind speed [m/s] #: estimated wind direction in North-East frame [rad] e.g. #: if wind_angle is pi/4, wind is from South-West to North-East wind_angle = float32_t wind_compensation_theta = float32_t wind_compensation_phi = float32_t state_x1 = float32_t state_x2 = float32_t state_x3 = float32_t state_x4 = float32_t state_x5 = float32_t state_x6 = float32_t magneto_debug1 = float32_t magneto_debug2 = float32_t magneto_debug3 = float32_t @index.register(24) class KalmanPressure(OptionHeader): 'Corresponds to C struct ``navdata_kalman_pressure_t``.' _attrname = 'kalman_pressure' offset_pressure = float32_t est_z = float32_t est_zdot = float32_t est_bias_PWM = float32_t est_biais_pression = float32_t offset_US = float32_t prediction_US = float32_t cov_alt = float32_t cov_PWM = float32_t cov_vitesse = float32_t bool_effet_sol = bool_t somme_inno = float32_t flag_rejet_US = bool_t u_multisinus = float32_t gaz_altitude = float32_t Flag_multisinus = bool_t Flag_multisinus_debut = bool_t @index.register(27) class Zimmu3000(OptionHeader): 'Corresponds to C struct ``navdata_zimmu_3000_t``.' _attrname = 'zimmu_3000' vzimmuLSB = int32_t vzfind = float32_t @index.register(3) class PhysMeasures(OptionHeader): 'Corresponds to C struct ``navdata_phys_measures_t``.' _attrname = 'phys_measures' accs_temp = float32_t gyro_temp = uint16_t phys_accs = float32_t * NB_ACCS phys_gyros = float32_t * NB_GYROS alim3V3 = uint32_t #: 3.3volt alim [LSB] vrefEpson = uint32_t #: ref volt Epson gyro [LSB] vrefIDG = uint32_t #: ref volt IDG gyro [LSB] @index.register(4) class GyrosOffsets(OptionHeader): 'Corresponds to C struct ``navdata_gyros_offsets_t``.' _attrname = 'gyros_offsets' offset_g = float32_t * NB_GYROS @index.register(5) class EulerAngles(OptionHeader): 'Corresponds to C struct ``navdata_euler_angles_t``.' _attrname = 'eular_angles' theta_a = float32_t phi_a = float32_t @index.register(6) class References(OptionHeader): 'Corresponds to C struct ``navdata_references_t``.' _attrname = 'references' ref_theta = int32_t ref_phi = int32_t ref_theta_I = int32_t ref_phi_I = int32_t ref_pitch = int32_t ref_roll = int32_t ref_yaw = int32_t ref_psi = int32_t vx_ref = float32_t vy_ref = float32_t theta_mod = float32_t phi_mod = float32_t k_v_x = float32_t k_v_y = float32_t k_mode = uint32_t ui_time = float32_t ui_theta = float32_t ui_phi = float32_t ui_psi = float32_t ui_psi_accuracy = float32_t ui_seq = int32_t @index.register(7) class Trims(OptionHeader): 'Corresponds to C struct ``navdata_trims_t``.' _attrname = 'trims' angular_rates_trim_r = float32_t euler_angles_trim_theta = float32_t euler_angles_trim_phi = float32_t @index.register(8) class RcReferences(OptionHeader): 'Corresponds to C struct ``navdata_rc_references_t``.' _attrname = 'rc_references' rc_ref_pitch = int32_t rc_ref_roll = int32_t rc_ref_yaw = int32_t rc_ref_gaz = int32_t rc_ref_ag = int32_t @index.register(9) class Pwm(OptionHeader): 'Corresponds to C struct ``navdata_pwm_t``.' _attrname = 'pwm' motor1 = uint8_t motor2 = uint8_t motor3 = uint8_t motor4 = uint8_t sat_motor1 = uint8_t sat_motor2 = uint8_t sat_motor3 = uint8_t sat_motor4 = uint8_t gaz_feed_forward = float32_t gaz_altitude = float32_t altitude_integral = float32_t vz_ref = float32_t u_pitch = int32_t u_roll = int32_t u_yaw = int32_t yaw_u_I = float32_t u_pitch_planif = int32_t u_roll_planif = int32_t u_yaw_planif = int32_t u_gaz_planif = float32_t current_motor1 = uint16_t current_motor2 = uint16_t current_motor3 = uint16_t current_motor4 = uint16_t # WARNING: new navdata (FC 26/07/2011) altitude_prop = float32_t altitude_der = float32_t @index.register(10) class Altitude(OptionHeader): 'Corresponds to C struct ``navdata_altitude_t``.' _attrname = 'altitude' altitude_vision = int32_t altitude_vz = float32_t altitude_ref = int32_t altitude_raw = int32_t obs_accZ = float32_t obs_alt = float32_t obs_x = _vector31_t obs_state = uint32_t est_vb = _vector21_t est_state = uint32_t @index.register(11) class VisionRaw(OptionHeader): 'Corresponds to C struct ``navdata_vision_raw_t``.' _attrname = 'vision_raw' vision_tx_raw = float32_t vision_ty_raw = float32_t vision_tz_raw = float32_t @index.register(13) class Vision(OptionHeader): 'Corresponds to C struct ``navdata_vision_t``.' _attrname = 'vision' vision_state = uint32_t vision_misc = int32_t vision_phi_trim = float32_t vision_phi_ref_prop = float32_t vision_theta_trim = float32_t vision_theta_ref_prop = float32_t new_raw_picture = int32_t theta_capture = float32_t phi_capture = float32_t psi_capture = float32_t altitude_capture = int32_t time_capture = uint32_t #: time in TSECDEC format (see config.h) body_v = _velocities_t delta_phi = float32_t delta_theta = float32_t delta_psi = float32_t gold_defined = uint32_t gold_reset = uint32_t gold_x = float32_t gold_y = float32_t @index.register(14) class VisionPerf(OptionHeader): 'Corresponds to C struct ``navdata_vision_perf_t``.' _attrname = 'vision_perf' time_szo = float32_t time_corners = float32_t time_compute = float32_t time_tracking = float32_t time_trans = float32_t time_update = float32_t time_custom = float32_t * NAVDATA_MAX_CUSTOM_TIME_SAVE @index.register(15) class TrackersSend(OptionHeader): 'Corresponds to C struct ``navdata_trackers_send_t``.' _attrname = 'trackers_send' locked = int32_t * (DEFAULT_NB_TRACKERS_WIDTH * DEFAULT_NB_TRACKERS_HEIGHT) point = _screen_point_t * ( DEFAULT_NB_TRACKERS_WIDTH * DEFAULT_NB_TRACKERS_HEIGHT ) @index.register(16) class VisionDetect(OptionHeader): 'Corresponds to C struct ``navdata_vision_detect_t``.' # Change the function 'navdata_server_reset_vision_detect()' # if this structure is modified _attrname = 'vision_detect' nb_detected = uint32_t type = uint32_t * NB_NAVDATA_DETECTION_RESULTS xc = uint32_t * NB_NAVDATA_DETECTION_RESULTS yc = uint32_t * NB_NAVDATA_DETECTION_RESULTS width = uint32_t * NB_NAVDATA_DETECTION_RESULTS height = uint32_t * NB_NAVDATA_DETECTION_RESULTS dist = uint32_t * NB_NAVDATA_DETECTION_RESULTS orientation_angle = float32_t * NB_NAVDATA_DETECTION_RESULTS rotation = _matrix33_t * NB_NAVDATA_DETECTION_RESULTS translation = _vector31_t * NB_NAVDATA_DETECTION_RESULTS camera_source = uint32_t * NB_NAVDATA_DETECTION_RESULTS @index.register(12) class VisionOf(OptionHeader): 'Corresponds to C struct ``navdata_vision_of_t``.' _attrname = 'vision_of' of_dx = float32_t * 5 of_dy = float32_t * 5 @index.register(17) class Watchdog(OptionHeader): 'Corresponds to C struct ``navdata_watchdog_t``.' _attrname = 'watchdog' # +4 bytes watchdog = int32_t @index.register(18) class AdcDataFrame(OptionHeader): 'Corresponds to C struct ``navdata_adc_data_frame_t``.' _attrname = 'adc_data_frame' version = uint32_t data_frame = uint8_t * 32 @index.register(19) class VideoStream(OptionHeader): 'Corresponds to C struct ``navdata_video_stream_t``.' _attrname = 'video_stream' quant = uint8_t #: quantizer reference used to encode frame [1:31] frame_size = uint32_t #: frame size (bytes) frame_number = uint32_t #: frame index atcmd_ref_seq = uint32_t #: atmcd ref sequence number #: mean time between two consecutive atcmd_ref (ms) atcmd_mean_ref_gap = uint32_t atcmd_var_ref_gap = float32_t atcmd_ref_quality = uint32_t #: estimator of atcmd link quality # drone2 #: measured out throughput from the video tcp socket out_bitrate = uint32_t #: last frame size generated by the video encoder desired_bitrate = uint32_t # misc temporary data data1 = int32_t data2 = int32_t data3 = int32_t data4 = int32_t data5 = int32_t # queue usage tcp_queue_level = uint32_t fifo_queue_level = uint32_t @index.register(25) class HdvideoStream(OptionHeader): 'Corresponds to C struct ``navdata_hdvideo_stream_t``.' _attrname = 'hdvideo_stream' hdvideo_state = uint32_t storage_fifo_nb_packets = uint32_t storage_fifo_size = uint32_t usbkey_size = uint32_t #: USB key in kbytes - 0 if no key present #: USB key free space in kbytes - 0 if no key present usbkey_freespace = uint32_t #: 'frame_number' PaVE field of the frame starting to be encoded for the #: HD stream frame_number = uint32_t usbkey_remaining_time = uint32_t #: time in seconds @index.register(20) class Games(OptionHeader): 'Corresponds to C struct ``navdata_games_t``.' _attrname = 'games' double_tap_counter = uint32_t finish_line_counter = uint32_t @index.register(26) class Wifi(OptionHeader): 'Corresponds to C struct ``navdata_wifi_t``.' _attrname = 'wifi' link_quality = uint32_t @index.register(0xFFFF) class Cks(OptionHeader): 'Corresponds to C struct ``navdata_cks_t``.' _attrname = 'cks' value = uint32_t #: Value of the checksum
afg984/pyardrone
pyardrone/navdata/options.py
Python
mit
14,941
[ 30522, 1005, 1005, 1005, 2023, 11336, 14788, 2000, 12098, 19440, 20806, 2497, 1013, 3730, 1013, 2691, 1013, 6583, 16872, 6790, 1035, 2691, 1012, 1044, 1005, 1005, 1005, 12324, 14931, 18863, 2015, 12324, 4569, 6593, 13669, 2015, 2013, 1052, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.develnext.jphp.android.ext.classes.app; import android.os.Bundle; import org.develnext.jphp.android.AndroidStandaloneLoader; import org.develnext.jphp.android.ext.AndroidExtension; import php.runtime.annotation.Reflection; @Reflection.Name(AndroidExtension.NAMESPACE + "app\\BootstrapActivity") public class WrapBootstrapActivity extends WrapActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreateClearly(savedInstanceState); AndroidStandaloneLoader.INSTANCE.run(this); getEnvironment().invokeMethodNoThrow(this, "onCreate"); } }
livingvirus/jphp
jphp-android/src/main/java/org/develnext/jphp/android/ext/classes/app/WrapBootstrapActivity.java
Java
apache-2.0
616
[ 30522, 7427, 8917, 1012, 16475, 2884, 2638, 18413, 1012, 16545, 22269, 1012, 11924, 1012, 4654, 2102, 1012, 4280, 1012, 10439, 1025, 12324, 11924, 1012, 9808, 1012, 14012, 1025, 12324, 8917, 1012, 16475, 2884, 2638, 18413, 1012, 16545, 22269,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
const models = require('../../models'); const {i18n} = require('../../lib/common'); const errors = require('@tryghost/errors'); const urlUtils = require('../../../shared/url-utils'); const ALLOWED_INCLUDES = ['tags', 'authors', 'authors.roles']; const UNSAFE_ATTRS = ['status', 'authors', 'visibility']; module.exports = { docName: 'pages', browse: { options: [ 'include', 'filter', 'fields', 'formats', 'limit', 'order', 'page', 'debug', 'absolute_urls' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, formats: { values: models.Post.allowedFormats } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.findPage(frame.options); } }, read: { options: [ 'include', 'fields', 'formats', 'debug', 'absolute_urls', // NOTE: only for internal context 'forUpdate', 'transacting' ], data: [ 'id', 'slug', 'uuid' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, formats: { values: models.Post.allowedFormats } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.findOne(frame.data, frame.options) .then((model) => { if (!model) { throw new errors.NotFoundError({ message: i18n.t('errors.api.pages.pageNotFound') }); } return model; }); } }, add: { statusCode: 201, headers: {}, options: [ 'include', 'source' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, source: { values: ['html'] } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.add(frame.data.pages[0], frame.options) .then((model) => { if (model.get('status') !== 'published') { this.headers.cacheInvalidate = false; } else { this.headers.cacheInvalidate = true; } return model; }); } }, edit: { headers: {}, options: [ 'include', 'id', 'source', // NOTE: only for internal context 'forUpdate', 'transacting' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, id: { required: true }, source: { values: ['html'] } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { return models.Post.edit(frame.data.pages[0], frame.options) .then((model) => { if ( model.get('status') === 'published' && model.wasChanged() || model.get('status') === 'draft' && model.previous('status') === 'published' ) { this.headers.cacheInvalidate = true; } else if ( model.get('status') === 'draft' && model.previous('status') !== 'published' || model.get('status') === 'scheduled' && model.wasChanged() ) { this.headers.cacheInvalidate = { value: urlUtils.urlFor({ relativeUrl: urlUtils.urlJoin('/p', model.get('uuid'), '/') }) }; } else { this.headers.cacheInvalidate = false; } return model; }); } }, destroy: { statusCode: 204, headers: { cacheInvalidate: true }, options: [ 'include', 'id' ], validation: { options: { include: { values: ALLOWED_INCLUDES }, id: { required: true } } }, permissions: { docName: 'posts', unsafeAttrs: UNSAFE_ATTRS }, query(frame) { frame.options.require = true; return models.Post.destroy(frame.options) .then(() => null) .catch(models.Post.NotFoundError, () => { return Promise.reject(new errors.NotFoundError({ message: i18n.t('errors.api.pages.pageNotFound') })); }); } } };
e10/Ghost
core/server/api/v2/pages.js
JavaScript
mit
5,771
[ 30522, 9530, 3367, 4275, 1027, 5478, 1006, 1005, 1012, 1012, 1013, 1012, 1012, 1013, 4275, 1005, 1007, 1025, 9530, 3367, 1063, 1045, 15136, 2078, 1065, 1027, 5478, 1006, 1005, 1012, 1012, 1013, 1012, 1012, 1013, 5622, 2497, 1013, 2691, 10...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.cruise.utils; import java.util.*; /** * @author cruisechang * @description * Check utils. */ public class CheckUtil { public static final String DATA_TYPE_INT="int"; public static final String DATA_TYPE_STRING="string"; public static final String DATA_TYPE_BOOLEAN="bool"; public static final String DATA_TYPE_DOUBLE="dou"; public static final String DATA_TYPE_LONG="lon"; private static boolean dataType(Object data,String type) { if(type.equals(DATA_TYPE_INT)){ if(data instanceof Integer){ return true; } }else if(type.equals(DATA_TYPE_STRING)){ if(data instanceof String){ return true; } }else if(type.equals(DATA_TYPE_BOOLEAN)){ if(data instanceof Boolean){ return true; } }else if(type.equals(DATA_TYPE_DOUBLE)){ if(data instanceof Double){ return true; } }else if(type.equals(DATA_TYPE_LONG)){ if(data instanceof Long){ return true; } } return false; } public static boolean checkLong(long lon,int min) { if(dataType(lon,DATA_TYPE_LONG)){ if(lon>=min) return true; } return false; } public static boolean checkString(String str) { if(dataType(str,DATA_TYPE_STRING)){ return true; } return false; } public static boolean checkString(String str,int lenMin) { if(dataType(str,DATA_TYPE_STRING)){ if(str.length()>=lenMin) return true; } return false; } public static boolean checkBool(Object data) { return dataType(data,DATA_TYPE_BOOLEAN); } public static boolean checkInt(int num) { if(dataType(num,DATA_TYPE_INT)){ return true; } return false; } /** * check if param is int and if >=min && < =max * @param num * @param min * @param max * @return */ public static boolean checkInt(int num,int min,int max) { if(dataType(num,DATA_TYPE_INT)){ if(num>=min && num<=max){ return true; } } return false; } /** * @param num * @param min * @return */ public static boolean checkInt(int num,int min) { if(dataType(num,DATA_TYPE_INT)){ if(num>=min){ return true; } } return false; } public static boolean checkId(int id) { if(dataType(id,DATA_TYPE_INT)){ if(id>=0){ return true; } } return false; } public static boolean checkPlayerNum(int playerNum) { if(dataType(playerNum,DATA_TYPE_INT)){ if(playerNum>0 && playerNum<7){ return true; } } return false; } public static boolean checkLatLng(double lat,double lng) { if(dataType(lat,DATA_TYPE_DOUBLE)){ if(lat>=0 && lat<=90 ){ return true; } } return false; } public static String getRandomKey(int length) { String s=""; List <String> aList=getStringArrayList(); int size=aList.size(); //����摨衣��葡 for(int i=0;i<length;i++){ String r=aList.get(MathUtil.random(0, size-1)); s+=r; } return s; } private static List<String> getStringArrayList() { List<String> list = new ArrayList<String>(); list.add("~"); list.add("!"); list.add("@"); list.add("$"); list.add("^"); list.add("&"); list.add("*"); list.add("("); list.add(")"); list.add("_"); list.add("+"); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); list.add("g"); list.add("h"); list.add("i"); list.add("j"); list.add("k"); list.add("l"); list.add("m"); list.add("n"); list.add("o"); list.add("p"); list.add("q"); list.add("r"); list.add("s"); list.add("t"); list.add("u"); list.add("v"); list.add("w"); list.add("x"); list.add("y"); list.add("z"); return list; } public static boolean checkTimeEnough(long allTime,long nowTime) { long ex=nowTime-allTime; // 30sec if(ex>=-30000){ return true; } return false; } }
cruisechang/javautils
com/cruise/utils/CheckUtil.java
Java
apache-2.0
4,063
[ 30522, 7427, 4012, 1012, 8592, 1012, 21183, 12146, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 1008, 1025, 1013, 1008, 1008, 1008, 1030, 3166, 8592, 22305, 1008, 1030, 6412, 1008, 4638, 21183, 12146, 1012, 1008, 1013, 2270, 2465, 4638, 2182...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * Based on the Reverse Engineering work of Christophe Fontanel, * maintainer of the Dungeon Master Encyclopaedia (http://dmweb.free.fr/) */ #include "base/plugins.h" #include "engines/advancedDetector.h" #include "dm/detection.h" namespace DM { static const PlainGameDescriptor DMGames[] = { {"dm", "Dungeon Master"}, {0, 0} }; static const DMADGameDescription gameDescriptions[] = { { {"dm", "Amiga v2.0 English", AD_ENTRY2s("graphics.dat", "c2205f6225bde728417de29394f97d55", 411960, "Dungeon.dat", "43a213da8eda413541dd12f90ce202f6", 25006), Common::EN_ANY, Common::kPlatformAmiga, ADGF_NO_FLAGS, GUIO1(GUIO_NOMIDI) }, kDMSaveTargetDM21, kDMSaveFormatAmigaPC98FmTowns, kDMSavePlatformAmiga, { kDMSaveTargetDM21, kDMSaveTargetEndOfList }, { kDMSaveFormatAmigaPC98FmTowns, kDMSaveFormatEndOfList}, { kDMSavePlatformAcceptAny} }, { {"dm", "Atari v??? English", AD_ENTRY2s("graphics.dat", "6ffff2a17e2df0effa9a12fb4b1bf6b6", 271911, "Dungeon.dat", "be9468b460515741babec9a70501e2e9", 33286), Common::EN_ANY, Common::kPlatformAtariST, ADGF_NO_FLAGS, GUIO1(GUIO_NOMIDI), }, kDMSaveTargetDM21, kDMSaveFormatAmigaPC98FmTowns, kDMSavePlatformAtariSt, { kDMSaveTargetDM21, kDMSaveTargetEndOfList}, { kDMSaveFormatAmigaPC98FmTowns, kDMSaveFormatEndOfList}, { kDMSavePlatformAcceptAny } }, { // Added by Strangerke {"dm", "Amiga Demo v2.0 English", AD_ENTRY2s("graphics.dat", "3932c8359bb36c24291b09e915114d38", 192421, "DemoDun.dat", "78848e1a2d3d5a11e5954deb8c7b772b", 1209), Common::EN_ANY, Common::kPlatformAmiga, ADGF_DEMO, GUIO1(GUIO_NOMIDI), }, kDMSaveTargetDM21, kDMSaveFormatAmigaPC98FmTowns, kDMSavePlatformAtariSt, { kDMSaveTargetDM21, kDMSaveTargetEndOfList}, { kDMSaveFormatAmigaPC98FmTowns, kDMSaveFormatEndOfList}, { kDMSavePlatformAcceptAny } }, { AD_TABLE_END_MARKER, kDMSaveTargetNone, kDMSaveFormatNone, kDMSavePlatformNone, {kDMSaveTargetNone}, {kDMSaveFormatNone}, {kDMSavePlatformNone} } }; static const ADExtraGuiOptionsMap optionsList[] = { AD_EXTRA_GUI_OPTIONS_TERMINATOR }; class DMMetaEngineDetection : public AdvancedMetaEngineDetection { public: DMMetaEngineDetection() : AdvancedMetaEngineDetection(DM::gameDescriptions, sizeof(DMADGameDescription), DMGames, optionsList) { } const char *getEngineId() const override { return "dm"; } const char *getName() const override { return "Dungeon Master"; } const char *getOriginalCopyright() const override { return "Dungeon Master (C) 1987 FTL Games"; } }; } // End of namespace DM REGISTER_PLUGIN_STATIC(DM_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, DM::DMMetaEngineDetection);
somaen/scummvm
engines/dm/detection.cpp
C++
gpl-2.0
3,619
[ 30522, 1013, 1008, 8040, 2819, 2213, 2615, 2213, 1011, 8425, 6172, 3194, 1008, 1008, 8040, 2819, 2213, 2615, 2213, 2003, 1996, 3423, 3200, 1997, 2049, 9797, 1010, 3005, 3415, 1008, 2024, 2205, 3365, 2000, 2862, 2182, 1012, 3531, 6523, 200...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Footer */ #pie_de_pagina { background:#610B0B; background-image: none; color: #a5a5a5; margin-top: 0px; } #pie_de_pagina .innerWrapper { width: auto; } #pie_de_pagina .share { color: #fff; font-size: 0.9em; padding-left: 30px; width: 290px; } #pie_de_pagina .share dd{ padding-bottom:5px; } #pie_de_pagina .share span { font-size: 1.3em; } #pie_de_pagina .info { background-color: #333436; border-bottom: 1px solid rgba(0,0,0,0.20); border-top: 1px solid rgba(0,0,0,0.20); box-shadow: none; height: 50px; line-height: 50px; text-align: center; } #pie_de_pagina ul { clear: both; font-size: 14px; line-height: 18px; margin-bottom: 30px; margin-top: 4px; text-align: left; } #pie_de_pagina ul li { display:inline; margin-right: 14px; padding: 2px 0px; } #pie_de_pagina ul li p { font-size: 13px; padding: 0 20px; text-align: center; } .simpleLink, #pie_de_pagina ul li a { color: #aaa; display: inline; font-size: 12px; font-weight: 400; padding-bottom: 5px; text-transform: capitalize; } #pie_de_pagina ul li a:hover { color: #fff; text-decoration: none; } #pie_de_pagina .legend { border-right: 1px solid #484848; } #pie_de_pagina .contacts { background:url("/img/addressbook64.png") right center no-repeat; border-left:1px solid #484848; float:right; overflow: hidden; padding-right:60px; } #pie_de_pagina .contacts2 { border-right:1px solid #484848; padding-left: 25px; position: relative; width: 380px; } #pie_de_pagina .contacts2 dd{ display: block; margin-bottom: 5px; overflow: hidden; width: 100%; } #pie_de_pagina .contacts2 a, #pie_de_pagina .aboutus a, #pie_de_pagina .contacts a { color:#fff; white-space:nowrap; } #pie_de_pagina .contacts2 a:hover, #pie_de_pagina .aboutus a:hover, #pie_de_pagina .contacts a:hover { text-decoration:none; } #pie_de_pagina h3 { clear: both; color: #fff; display: inline-block; text-shadow: 1px 1px 12px red; font-size: 18px; margin-bottom: 10px; font-weight: bold; } #pie_de_pagina h2 { clear: both; color: #fff; text-align: center; text-shadow: 1px 1px 12px red; font-size: 18px; margin-bottom: 10px; font-weight: bold; } #pie_de_pagina .district { clear: both; font-size:12px; margin-top: 30px; padding-bottom:20px; } #pie_de_pagina .newsletterForm { text-align: center; } #pie_de_pagina .newsletterForm div.input { float: none; margin-bottom: 10px; padding: 10px 8px 0 8px; text-align: center; } #pie_de_pagina .newsletterForm input { border: 1px solid #000; box-sizing: border-box; font-family: Arial, sans-serif; font-size: 14px; line-height: 1.4em; padding: 8px 6px; } #pie_de_pagina .footerclm .button { border-radius: 4px; border: 1px solid #333; float: none; font-size: 14px; line-height: 18px; margin-right: 0; } .rowWithBorder { border-width: 1px 0; border: 1px solid #484848; clear: both; padding: 8px 0; text-align: center; } #pie_de_pagina .topsearchesLink a { color: #CCC; font-size: 15px; font-weight: bold; text-decoration: underline; } #pie_de_pagina .tryalso a { display: inline-block; margin: 0px; width: auto; } .topsearchesLink a:hover { text-decoration: none; } .topsearchesLink span { color: #aaa; font-size: 12px; } #pie_de_pagina .footer-about-us { padding-top: 20px; } #pie_de_pagina .footer-categories { display: inline-block; margin-bottom: 20px; text-align: left; width: 100%; } #pie_de_pagina .footer-categories h3 { padding-bottom: 0px; text-align: left; } #pie_de_pagina .footer-categories ul li { float: left; } /* Fin Footer */ .ctn-footer .col-md-3, .col-sm-6.e-services { padding-left: 45px; } .col-sm-6.e-services.offset { padding-left: 15px; } #pie_de_pagina.megafooter .container { max-width: 1146px; } #pie_de_pagina .megafooter { background: rgba(55, 0, 0, 0.9); color: #c1c1c1; font-size: 12px; line-height: 1.42857143; margin-top: 40px; overflow: hidden; } #pie_de_pagina.megafooter a { color: #fff; text-decoration: none; } #pie_de_pagina.megafooter a:hover { color: #f99; text-decoration: none; } #pie_de_pagina ul { list-style: none; padding-left: 0px; } #pie_de_pagina .ctn-footer { margin-bottom: 0px !important; padding-top: 35px; } #pie_de_pagina .ctn-footer h3 { color: #fff; font-size: 20px; font-size: 23px; letter-spacing: 0.015em; margin-bottom: 20px; text-align: left; } #pie_de_pagina.megafooter .footer-links ul { font-size: 12px; line-height: inherit; margin: 0; } #pie_de_pagina.megafooter .footer-links ul li { padding: 0; } #pie_de_pagina.megafooter .footer-links .escort-categories ul { columns: 3; -moz-columns: 3; -ms-columns: 3; -o-columns: 3; -webkit-columns: 3; } #pie_de_pagina.megafooter .footer-links .e-services ul { columns: 3; -moz-columns: 3; -ms-columns: 3; -o-columns: 3; -webkit-columns: 3; } #pie_de_pagina .ctn-footer p a { color: #f99; } #pie_de_pagina .ctn-footer p a:hover { text-decoration: underline; } #pie_de_pagina .legend { color: #fff; border: none; } #pie_de_pagina .legend p { margin-bottom: 15px; } #pie_de_pagina.megafooter .legend ul li .fa { color: #c1c1c1; font-size: 14px; } #pie_de_pagina.megafooter .legend ul li { display: inline-block; /*font-size: 17px;*/ line-height: 1.54em; padding-bottom: 10px; width: 100%; } #pie_de_pagina.megafooter .legend ul li .fa { background: none; font-size: 14px; margin: 0; } #pie_de_pagina svg#quality-mark { height: 12px; vertical-align: -2px; } svg#quality-mark path { fill: #c1c1c1 !important; } #pie_de_pagina.megafooter .redes-sociales ul li { position: relative; } #pie_de_pagina.megafooter .redes-sociales i { border-radius: 50%; border: 2px solid #fff; color: #fff; display: inline-block; font-size: 12px; height: 35px; margin: 0px 12px 4px 0px; padding: 10px; text-align: center; width: 35px; vertical-align: middle; } .icon-facebook { background: #800000; } .icon-google-plus { background: #600000; } .icon-twitter { background: #600000; } .icon-instagram { background: #800000; } /*.icon-facebook:hover { background: #3b5998; transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; -webkit-transition: 0.3s; } .icon-twitter:hover { background: #55acee; transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; -webkit-transition: 0.3s; } .icon-instagram:hover { background: #3f729b; transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; -webkit-transition: 0.3s; } .icon-google-plus:hover { background: #dd4b39; transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; -webkit-transition: 0.3s; }*/ #pie_de_pagina.megafooter .redes-sociales a:hover, #pie_de_pagina.megafooter .redes-sociales a:hover > .fa { color: #fc0; text-decoration: none; transform: rotateZ(360deg); -moz-transform: rotateZ(360deg); -ms-transform: rotateZ(360deg); -o-transform: rotateZ(360deg); -webkit-transform: rotateZ(360deg); transition: 0.9s; -moz-transition: 0.9s; -ms-transition: 0.9s; -o-transition: 0.9s; -webkit-transition: 0.9s; } .btn.submit { background: #710707; color: #fff; padding: 6px 24px; } .btn.submit:hover { background: #a60000; transition: 0.3s; -moz-transition: 0.3s; -ms-transition: 0.3s; -o-transition: 0.3s; -webkit-transition: 0.3s; } #pie_de_pagina .subscribe { background: rgba(166, 0, 0, 0.44); } #pie_de_pagina .subscribe .container { padding-bottom: 28px !important; padding-top: 30px !important; } #pie_de_pagina .subscribe h4 { color: #fff; float: left; letter-spacing: 0.03em; line-height: 34px; margin: 0; font-weight: 300; } #pie_de_pagina #newsletter-wrapper { margin-bottom: 0px; width: 300px; } .row.footer-links { margin-top: 20px; } .footer-links h5 { border-bottom: 1px solid #676666; height: 24px; letter-spacing: 0.05em; padding-bottom: 6px; text-transform: uppercase; } #pie_de_pagina .redes-sociales ul li, #pie_de_pagina .footer-links ul li { display: inline-block; width: 100%; } #pie_de_pagina .footer-links ul li { display: list-item; list-style: none; padding: 0px 0px 0px 3px; } .nav > li > a:hover, .nav > li > a:focus { background-color: inherit; text-decoration: underline; } .bottom-menu { border-top: 1px solid #656565; padding-bottom: 5px; padding-top: 20px; width: 100%; } .bottom-menu i { font-size: 32px; } .bottom-menu .navbar-nav > li > a { letter-spacing: 0.01em; line-height: 42px; padding-top: 0; } .navbar-brand { padding: 0; } .bottom-menu .navbar button { margin: 4px 0px; padding: 0 10px; } #pie_de_pagina-navbar { float: right; } #pie_de_pagina-navbar ul { list-style: none; margin-bottom: 0px; margin-top: 0px; } #pie_de_pagina-navbar ul li { margin-right: 0px; padding-top: 0px; } #pie_de_pagina-navbar ul li a:after { content: ""; } .pluginSkinDark a { color: #c1c1c1 !important; } .fb-share-button, fb\:share { transform: scale(1.1); -webkit-transform: scale(1.1); -moz-transform: scale(1.1); -o-transform: scale(1.1); -ms-transform: scale(1.1); } .fb-share-button span { vertical-align: middle !important; } /* Responive Footer*/ @media screen and (min-width: 375px) and (max-width: 1024px) { #pie_de_pagina { margin-bottom: -11117px; } #pie_de_pagina.megafooter .container { padding: 20px 20px 20px; } #pie_de_pagina .subscribe h4 { font-size: 14px; line-height: 1.5em; margin-bottom: 15px; width: 100%; } .ctn-footer .col-md-3, .col-sm-6.e-services { padding-left: 15px; } } @media (min-width: 1025px) { .pull-left-md { float: left; } .pull-right-md { float: right; } .navbar-right-md { float: right; margin-right: -15px; } } @media (min-width: 1200px) { .pull-right-lg { float: right; } .pull-left-lg { float: left; } .megafooter .container .legend { width: 28%; } .megafooter .container .redes-sociales { width: 22%; } } @media screen and (max-width : 667px) { #pie_de_pagina .ctn-footer { margin-bottom: 0px !important; } #pie_de_pagina.megafooter .container { padding: 20px 20px 20px; width: auto; } #pie_de_pagina .ctn-footer { margin-bottom: 0px !important; } #pie_de_pagina.megafooter .container { padding: 20px 20px 20px; width: auto; } #pie_de_pagina.megafooter .container .form-group { margin-bottom: 5px; } } @media screen and (max-width : 375px) { #pie_de_pagina .subscribe h4 { font-size: 14px; line-height: 1.5em; margin-bottom: 15px; } .ctn-footer .col-md-3, .col-sm-6.e-services { padding-left: 15px; } #pie_de_pagina .ctn-footer h3 { font-size: 18px; margin-top: 10px; } #pie_de_pagina.megafooter .fb_iframe_widget_fluid { display: inline-block; } #pie_de_pagina.megafooter .fb_iframe_widget_fluid span { height: 14px !important; } #pie_de_pagina.megafooter .bottom-menu { padding-top: 0px; } #pie_de_pagina.megafooter .navbar { margin-bottom: 0px; } } /* Fin Responive Footer*/
crianbluff-programming/ciudadplacer
dist/css/footer.css
CSS
mit
11,517
[ 30522, 1013, 1008, 3329, 2121, 1008, 1013, 1001, 11345, 1035, 2139, 1035, 6643, 20876, 1063, 4281, 1024, 1001, 19827, 2497, 2692, 2497, 1025, 4281, 1011, 3746, 1024, 3904, 1025, 3609, 1024, 1001, 1037, 2629, 2050, 2629, 2050, 2629, 1025, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Claudia Project * http://claudia.morfeo-project.org * * (C) Copyright 2010 Telefonica Investigacion y Desarrollo * S.A.Unipersonal (Telefonica I+D) * * See CREDITS file for info about members and contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License (AGPL) as * published by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the Affero 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. * * If you want to use this software an plan to distribute a * proprietary application in any way, and you are not licensing and * distributing your source code under AGPL, you probably need to * purchase a commercial license of the product. Please contact * claudia-support@lists.morfeo-project.org for more information. */ package com.telefonica.claudia.smi.deployment; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.log4j.Logger; import org.restlet.Context; import org.restlet.data.MediaType; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.restlet.resource.DomRepresentation; import org.restlet.resource.Representation; import org.restlet.resource.Resource; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.telefonica.claudia.smi.Main; import com.telefonica.claudia.smi.URICreation; public class ServiceItemResource extends Resource { private static Logger log = Logger.getLogger("com.telefonica.claudia.smi.ServiceItemResource"); String vdcId; String vappId; String orgId; public ServiceItemResource(Context context, Request request, Response response) { super(context, request, response); this.vappId = (String) getRequest().getAttributes().get("vapp-id"); this.vdcId = (String) getRequest().getAttributes().get("vdc-id"); this.orgId = (String) getRequest().getAttributes().get("org-id"); // Get the item directly from the "persistence layer". if (this.orgId != null && this.vdcId!=null && this.vappId!=null) { // Define the supported variant. getVariants().add(new Variant(MediaType.TEXT_XML)); // By default a resource cannot be updated. setModifiable(true); } else { // This resource is not available. setAvailable(false); } } /** * Handle GETS */ @Override public Representation represent(Variant variant) throws ResourceException { // Generate the right representation according to its media type. if (MediaType.TEXT_XML.equals(variant.getMediaType())) { try { DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(DeploymentApplication.ATTR_PLUGIN_DEPLOYMENT); String serviceInfo = actualDriver.getService(URICreation.getFQN(orgId, vdcId, vappId)); // Substitute the macros in the description serviceInfo = serviceInfo.replace("@HOSTNAME", "http://" + Main.serverHost + ":" + Main.serverPort); if (serviceInfo==null) { log.error("Null response from the SM."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(serviceInfo)); Document doc = db.parse(is); DomRepresentation representation = new DomRepresentation( MediaType.TEXT_XML, doc); log.info("Data returned for service "+ URICreation.getFQN(orgId, vdcId, vappId) + ": \n\n" + serviceInfo); // Returns the XML representation of this document. return representation; } catch (IOException e) { log.error("Time out waiting for the Lifecycle Controller."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } catch (SAXException e) { log.error("Retrieved data was not in XML format: " + e.getMessage()); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } catch (ParserConfigurationException e) { log.error("Error trying to configure parser."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return null; } } return null; } /** * Handle DELETE requests. */ @Override public void removeRepresentations() throws ResourceException { DeploymentDriver actualDriver= (DeploymentDriver) getContext().getAttributes().get(DeploymentApplication.ATTR_PLUGIN_DEPLOYMENT); try { actualDriver.undeploy(URICreation.getFQN(orgId, vdcId, vappId)); } catch (IOException e) { log.error("Time out waiting for the Lifecycle Controller."); getResponse().setStatus(Status.SERVER_ERROR_INTERNAL); return; } // Tells the client that the request has been successfully fulfilled. getResponse().setStatus(Status.SUCCESS_NO_CONTENT); } }
StratusLab/claudia
tcloud-server/src/main/java/com/telefonica/claudia/smi/deployment/ServiceItemResource.java
Java
agpl-3.0
6,138
[ 30522, 1013, 1008, 1008, 13479, 2622, 1008, 8299, 1024, 1013, 1013, 13479, 1012, 22822, 7959, 2080, 1011, 2622, 1012, 8917, 1008, 1008, 1006, 1039, 1007, 9385, 2230, 10093, 12879, 12356, 2050, 15697, 13340, 10446, 1061, 4078, 2906, 28402, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
use std::{error::Error as StdError, io::Write, str::FromStr}; use diesel::{backend::Backend, deserialize, serialize, sql_types::Text}; use url::Url as OrigUrl; #[derive(AsExpression, Clone, Debug, FromSqlRow)] #[sql_type = "Text"] pub struct Url(pub OrigUrl); impl<DB> serialize::ToSql<Text, DB> for Url where DB: Backend, { fn to_sql<W: Write>(&self, out: &mut serialize::Output<W, DB>) -> serialize::Result { serialize::ToSql::<Text, DB>::to_sql(self.0.as_str(), out) } } impl<DB> deserialize::FromSql<Text, DB> for Url where DB: Backend<RawValue = [u8]>, { fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> { deserialize::FromSql::<Text, DB>::from_sql(bytes).and_then(|s: String| { s.parse() .map(Url) .map_err(|e| Box::new(e) as Box<dyn StdError + Send + Sync>) }) } } impl From<OrigUrl> for Url { fn from(u: OrigUrl) -> Self { Url(u) } } impl FromStr for Url { type Err = <OrigUrl as FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { FromStr::from_str(s).map(Url) } }
BanjoFox/fedibook
aardwolf-models/src/sql_types/url.rs
Rust
agpl-3.0
1,144
[ 30522, 2224, 2358, 2094, 1024, 1024, 1063, 7561, 1024, 1024, 7561, 2004, 2358, 4063, 29165, 1010, 22834, 1024, 1024, 4339, 1010, 2358, 2099, 1024, 1024, 2013, 3367, 2099, 1065, 1025, 2224, 7937, 1024, 1024, 1063, 2067, 10497, 1024, 1024, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// <![CDATA[ /** * Creative Commons has made the contents of this file * available under a CC-GNU-GPL license: * * http://creativecommons.org/licenses/GPL/2.0/ * * A copy of the full license can be found as part of this * distribution in the file COPYING. * * You may use this software in accordance with the * terms of that license. You agree that you are solely * responsible for your use of this software and you * represent and warrant to Creative Commons that your use * of this software will comply with the CC-GNU-GPL. * * $Id: $ * * Copyright 2006, Creative Commons, www.creativecommons.org. * * This is code that is used to generate licenses. * */ function cc_js_$F(id) { if (cc_js_$(id)) { return cc_js_$(id).value; } return null; // if we can't find the form element, pretend it has no contents } function cc_js_$(id) { return document.getElementById("cc_js_" + id); } /* Inspired by Django. Thanks, guys. * http://code.djangoproject.com/browser/django/trunk/django/views/i18n.py * Our use of gettext is incomplete, so I'm just grabbing the one function. * And I've modified it, anyway. * Here is their license - it applies only to the following function: Copyright (c) 2005, the Lawrence Journal-World All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of Django nor the names of its contributors may 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 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function cc_js_gettext_style_interpolate(fmt, obj) { return fmt.replace(/\${\w+}/g, function(match){return String(obj[match.slice(2,-1)])}); }
DZielke/laudatio
app/webroot/js/creativecommons/js/cc-prereq.js
JavaScript
apache-2.0
2,890
[ 30522, 1013, 1013, 1026, 999, 1031, 3729, 6790, 1031, 1013, 1008, 1008, 1008, 5541, 7674, 2038, 2081, 1996, 8417, 1997, 2023, 5371, 1008, 2800, 2104, 1037, 10507, 1011, 27004, 1011, 14246, 2140, 6105, 1024, 1008, 1008, 8299, 1024, 1013, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'wsc', 'km', { btnIgnore: 'មិនផ្លាស់ប្តូរ', btnIgnoreAll: 'មិនផ្លាស់ប្តូរ ទាំងអស់', btnReplace: 'ជំនួស', btnReplaceAll: 'ជំនួសទាំងអស់', btnUndo: 'សារឡើងវិញ', changeTo: 'ផ្លាស់ប្តូរទៅ', errorLoading: 'Error loading application service host: %s.', ieSpellDownload: 'ពុំមានកម្មវិធីពិនិត្យអក្ខរាវិរុទ្ធ ។ តើចង់ទាញយកពីណា?', manyChanges: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: %1 ពាក្យបានផ្លាស់ប្តូរ', noChanges: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: ពុំមានផ្លាស់ប្តូរ', noMispell: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: គ្មានកំហុស', noSuggestions: '- គ្មានសំណើរ -', notAvailable: 'Sorry, but service is unavailable now.', notInDic: 'គ្មានក្នុងវចនានុក្រម', oneChange: 'ការពិនិត្យអក្ខរាវិរុទ្ធបានចប់: ពាក្យមួយត្រូចបានផ្លាស់ប្តូរ', progress: 'កំពុងពិនិត្យអក្ខរាវិរុទ្ធ...', title: 'Spell Checker', toolbar: 'ពិនិត្យអក្ខរាវិរុទ្ធ' });
janusnic/dj-21v
unit_15/mysite/public/static/ckeditor/ckeditor/plugins/wsc/lang/km.js
JavaScript
mit
1,772
[ 30522, 1013, 1008, 9385, 1006, 1039, 1007, 2494, 1011, 2325, 1010, 23616, 6499, 3126, 3401, 1011, 15296, 2080, 14161, 7875, 10609, 1012, 2035, 2916, 9235, 1012, 2005, 13202, 1010, 2156, 6105, 1012, 16129, 2030, 8299, 1024, 1013, 1013, 23616...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php include __DIR__ . '/vendor/autoload.php'; include __DIR__ . '/../../bootstrap.php'; $debugbarRenderer->setBaseUrl('../../../src/DebugBar/Resources'); use DebugBar\Bridge\PropelCollector; $debugbar->addCollector(new PropelCollector()); Propel::init('build/conf/demo-conf.php'); set_include_path("build/classes" . PATH_SEPARATOR . get_include_path()); PropelCollector::enablePropelProfiling(); $user = new User(); $user->setName('foo'); $user->save(); $firstUser = UserQuery::create()->findPK(1); render_demo_page();
Vrian7ipx/cascadadev
vendor/maximebf/debugbar/demo/bridge/propel/index.php
PHP
mit
530
[ 30522, 1026, 1029, 25718, 2421, 1035, 1035, 16101, 1035, 1035, 1012, 1005, 1013, 21431, 1013, 8285, 11066, 1012, 25718, 1005, 1025, 2421, 1035, 1035, 16101, 1035, 1035, 1012, 1005, 1013, 1012, 1012, 1013, 1012, 1012, 1013, 6879, 6494, 2361,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*<html><pre> -<a href="qh-merge.htm" >-------------------------------</a><a name="TOP">-</a> merge.h header file for merge.c see qh-merge.htm and merge.c copyright (c) 1993-2003, The Geometry Center */ #ifndef qhDEFmerge #define qhDEFmerge 1 /*============ -constants- ==============*/ /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="qh_ANGLEredundant">-</a> qh_ANGLEredundant indicates redundant merge in mergeT->angle */ #define qh_ANGLEredundant 6.0 /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="qh_ANGLEdegen">-</a> qh_ANGLEdegen indicates degenerate facet in mergeT->angle */ #define qh_ANGLEdegen 5.0 /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="qh_ANGLEconcave">-</a> qh_ANGLEconcave offset to indicate concave facets in mergeT->angle notes: concave facets are assigned the range of [2,4] in mergeT->angle roundoff error may make the angle less than 2 */ #define qh_ANGLEconcave 1.5 /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="MRG">-</a> MRG... (mergeType) indicates the type of a merge (mergeT->type) */ typedef enum { /* in sort order for facet_mergeset */ MRGnone= 0, MRGcoplanar, /* centrum coplanar */ MRGanglecoplanar, /* angle coplanar */ /* could detect half concave ridges */ MRGconcave, /* concave ridge */ MRGflip, /* flipped facet. facet1 == facet2 */ MRGridge, /* duplicate ridge (qh_MERGEridge) */ /* degen and redundant go onto degen_mergeset */ MRGdegen, /* degenerate facet (not enough neighbors) facet1 == facet2 */ MRGredundant, /* redundant facet (vertex subset) */ /* merge_degenredundant assumes degen < redundant */ MRGmirror, /* mirror facet from qh_triangulate */ ENDmrg } mergeType; /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="qh_MERGEapex">-</a> qh_MERGEapex flag for qh_mergefacet() to indicate an apex merge */ #define qh_MERGEapex True /*============ -structures- ====================*/ /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="mergeT">-</a> mergeT structure used to merge facets */ typedef struct mergeT mergeT; struct mergeT { /* initialize in qh_appendmergeset */ realT angle; /* angle between normals of facet1 and facet2 */ facetT *facet1; /* will merge facet1 into facet2 */ facetT *facet2; mergeType type; }; /*=========== -macros- =========================*/ /*-<a href="qh-merge.htm#TOC" >--------------------------------</a><a name="FOREACHmerge_">-</a> FOREACHmerge_( merges ) {...} assign 'merge' to each merge in merges notes: uses 'mergeT *merge, **mergep;' if qh_mergefacet(), restart since qh.facet_mergeset may change see <a href="qset.h#FOREACHsetelement_">FOREACHsetelement_</a> */ #define FOREACHmerge_( merges ) FOREACHsetelement_(mergeT, merges, merge) /*============ prototypes in alphabetical order after pre/postmerge =======*/ void qh_premerge (vertexT *apex, realT maxcentrum, realT maxangle); void qh_postmerge (const char *reason, realT maxcentrum, realT maxangle, boolT vneighbors); void qh_all_merges (boolT othermerge, boolT vneighbors); void qh_appendmergeset(facetT *facet, facetT *neighbor, mergeType mergetype, realT *angle); setT *qh_basevertices( facetT *samecycle); void qh_checkconnect (void /* qh new_facets */); boolT qh_checkzero (boolT testall); int qh_compareangle(const void *p1, const void *p2); int qh_comparemerge(const void *p1, const void *p2); int qh_comparevisit (const void *p1, const void *p2); void qh_copynonconvex (ridgeT *atridge); void qh_degen_redundant_facet (facetT *facet); void qh_degen_redundant_neighbors (facetT *facet, facetT *delfacet); vertexT *qh_find_newvertex (vertexT *oldvertex, setT *vertices, setT *ridges); void qh_findbest_test (boolT testcentrum, facetT *facet, facetT *neighbor, facetT **bestfacet, realT *distp, realT *mindistp, realT *maxdistp); facetT *qh_findbestneighbor(facetT *facet, realT *distp, realT *mindistp, realT *maxdistp); void qh_flippedmerges(facetT *facetlist, boolT *wasmerge); void qh_forcedmerges( boolT *wasmerge); void qh_getmergeset(facetT *facetlist); void qh_getmergeset_initial (facetT *facetlist); void qh_hashridge (setT *hashtable, int hashsize, ridgeT *ridge, vertexT *oldvertex); ridgeT *qh_hashridge_find (setT *hashtable, int hashsize, ridgeT *ridge, vertexT *vertex, vertexT *oldvertex, int *hashslot); void qh_makeridges(facetT *facet); void qh_mark_dupridges(facetT *facetlist); void qh_maydropneighbor (facetT *facet); int qh_merge_degenredundant (void); void qh_merge_nonconvex( facetT *facet1, facetT *facet2, mergeType mergetype); void qh_mergecycle (facetT *samecycle, facetT *newfacet); void qh_mergecycle_all (facetT *facetlist, boolT *wasmerge); void qh_mergecycle_facets( facetT *samecycle, facetT *newfacet); void qh_mergecycle_neighbors(facetT *samecycle, facetT *newfacet); void qh_mergecycle_ridges(facetT *samecycle, facetT *newfacet); void qh_mergecycle_vneighbors( facetT *samecycle, facetT *newfacet); void qh_mergefacet(facetT *facet1, facetT *facet2, realT *mindist, realT *maxdist, boolT mergeapex); void qh_mergefacet2d (facetT *facet1, facetT *facet2); void qh_mergeneighbors(facetT *facet1, facetT *facet2); void qh_mergeridges(facetT *facet1, facetT *facet2); void qh_mergesimplex(facetT *facet1, facetT *facet2, boolT mergeapex); void qh_mergevertex_del (vertexT *vertex, facetT *facet1, facetT *facet2); void qh_mergevertex_neighbors(facetT *facet1, facetT *facet2); void qh_mergevertices(setT *vertices1, setT **vertices); setT *qh_neighbor_intersections (vertexT *vertex); void qh_newvertices (setT *vertices); boolT qh_reducevertices (void); vertexT *qh_redundant_vertex (vertexT *vertex); boolT qh_remove_extravertices (facetT *facet); vertexT *qh_rename_sharedvertex (vertexT *vertex, facetT *facet); void qh_renameridgevertex(ridgeT *ridge, vertexT *oldvertex, vertexT *newvertex); void qh_renamevertex(vertexT *oldvertex, vertexT *newvertex, setT *ridges, facetT *oldfacet, facetT *neighborA); boolT qh_test_appendmerge (facetT *facet, facetT *neighbor); boolT qh_test_vneighbors (void /* qh newfacet_list */); void qh_tracemerge (facetT *facet1, facetT *facet2); void qh_tracemerging (void); void qh_updatetested( facetT *facet1, facetT *facet2); setT *qh_vertexridges (vertexT *vertex); void qh_vertexridges_facet (vertexT *vertex, facetT *facet, setT **ridges); void qh_willdelete (facetT *facet, facetT *replace); #endif /* qhDEFmerge */
iocroblab/coindesigner
src/qhulllib/qh_merge.h
C
gpl-3.0
7,072
[ 30522, 1013, 1008, 1026, 16129, 1028, 1026, 3653, 1028, 1011, 1026, 1037, 17850, 12879, 1027, 1000, 1053, 2232, 1011, 13590, 1012, 1044, 21246, 1000, 1028, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include <stdio.h> #include <stdlib.h> #include<limits.h> typedef struct Stack { int top; unsigned capacity; int* array; }Stack; Stack* createStack(unsigned capacity) { struct Stack* stack = (Stack*) malloc(sizeof(Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*) malloc(stack->capacity * sizeof(int)); return stack; } int Full(Stack* stack) { return stack->top == stack->capacity - 1; } int Empty(Stack* stack) { return stack->top == -1; } void push(Stack* stack, int item) { if (Full(stack)) return; stack->array[++stack->top] = item; printf("%d pushed to stack\n", item); } int pop(Stack* stack) { if (Empty(stack)) return INT_MIN; return stack->array[stack->top--]; } int peek(Stack* stack) { if (Empty(stack)) return INT_MIN; return stack->array[stack->top]; } int main() { Stack* stack = createStack(100); push(stack, 14); push(stack, 25); push(stack, 38); push(stack, 48); printf("%d popped from stack\n", pop(stack)); printf("Top item is %d\n", peek(stack)); return 0; } //output /*14 pushed to stack 25 pushed to stack 38 pushed to stack 48 pushed to stack 48 popped from stack Top item is 38*/
algobook/Algo_Ds_Notes
Dynamic_Stack_Arrays/Dynamic_Stack.c
C
gpl-3.0
1,266
[ 30522, 1001, 2421, 1026, 2358, 20617, 1012, 1044, 1028, 1001, 2421, 30524, 9140, 1025, 1065, 9991, 1025, 9991, 1008, 9005, 2696, 3600, 1006, 27121, 3977, 1007, 1063, 2358, 6820, 6593, 9991, 1008, 9991, 1027, 1006, 9991, 1008, 1007, 6670, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env node 'use strict'; const fs = require('fs'); const repl = require('repl'); const program = require('commander'); const esper = require('..'); const Engine = esper.Engine; function enterRepl() { function replEval(cmd, context, fn, cb) { engine.evalDetatched(cmd).then(function(result) { cb(null, result); }, function(err) { console.log(err.stack); cb(null); }); } return repl.start({ prompt: 'js> ', eval: replEval }); } program .version(esper.version) .usage('[options] [script...]') .option('-v, --version', 'print esper version') .option('-i, --interactive', 'enter REPL') .option('-s, --strict', 'force strict mode') .option('-d, --debug', 'turn on performance debugging') .option('-c, --compile <mode>', 'set compileing mode') .option('-e, --eval <script>', 'evaluate script') .option('-p, --print <script>', 'evaluate script and print result') .option('-l, --language <language>', `set langauge (${Object.keys(esper.languages).join(', ')})`) .parse(process.argv); if ( program.language ) esper.plugin('lang-' + program.language); if ( program.v ) { console.log("v" + esper.version); process.exit(); } let engine = new Engine({ strict: !!program.strict, debug: !!program.debug, runtime: true, addInternalStack: !!program.debug, compile: program.compile || 'pre', language: program.language || 'javascript', esposeESHostGlobal: true, esRealms: true, }); let toEval = program.args.slice(0).map((f) => ({type: 'file', value: f})); if ( program.eval ) toEval.push({type: 'str', value: program.eval + '\n'}); if ( program.print ) toEval.push({type: 'str', value: program.print + '\n', print: true}); if ( toEval.length < 1 ) program.interactive = true; function next() { if ( toEval.length === 0 ) { if ( program.interactive ) return enterRepl(); else return process.exit(); } var fn = toEval.shift(); var code; if ( fn.type === 'file' ) { code = fs.readFileSync(fn.value, 'utf8'); } else { code = fn.value; } return engine.evalDetatched(code).then(function(val) { if ( fn.print && val ) console.log(val.debugString); return next(); }).catch(function(e) { if ( e.stack ) { process.stderr.write(e.stack + "\n"); } else { process.stderr.write(`${e.name}: ${e.message}\n`); } }); } next(); /* Usage: node [options] [ -e script | script.js ] [arguments] node debug script.js [arguments] Options: -v, --version print Node.js version -e, --eval script evaluate script -p, --print evaluate script and print result -c, --check syntax check script without executing -i, --interactive always enter the REPL even if stdin does not appear to be a terminal -r, --require module to preload (option can be repeated) --no-deprecation silence deprecation warnings --throw-deprecation throw an exception anytime a deprecated function is used --trace-deprecation show stack traces on deprecations --trace-sync-io show stack trace when use of sync IO is detected after the first tick --track-heap-objects track heap object allocations for heap snapshots --v8-options print v8 command line options --tls-cipher-list=val use an alternative default TLS cipher list --icu-data-dir=dir set ICU data load path to dir (overrides NODE_ICU_DATA) Environment variables: NODE_PATH ':'-separated list of directories prefixed to the module search path. NODE_DISABLE_COLORS set to 1 to disable colors in the REPL NODE_ICU_DATA data path for ICU (Intl object) data NODE_REPL_HISTORY path to the persistent REPL history file Documentation can be found at https://nodejs.org/ */
codecombat/esper.js
contrib/cli.js
JavaScript
mit
3,797
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 13045, 1005, 2224, 9384, 1005, 1025, 9530, 3367, 1042, 2015, 1027, 5478, 1006, 1005, 1042, 2015, 1005, 1007, 1025, 9530, 3367, 16360, 2140, 1027, 5478, 1006, 1005, 16360, 2...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*---------------------------------------------------------------------------*\ * * bitpit * * Copyright (C) 2015-2021 OPTIMAD engineering Srl * * ------------------------------------------------------------------------- * License * This file is part of bitpit. * * bitpit is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License v3 (LGPL) * as published by the Free Software Foundation. * * bitpit is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with bitpit. If not, see <http://www.gnu.org/licenses/>. * \*---------------------------------------------------------------------------*/ #ifndef __BITPIT_ADAPTION_HPP__ #define __BITPIT_ADAPTION_HPP__ #include <vector> #include <unordered_map> #include <unordered_set> namespace bitpit { namespace adaption { enum Marker { MARKER_REFINE, MARKER_NONE, MARKER_COARSEN, MARKER_UNDEFINED }; enum Type { TYPE_UNKNOWN = -2, TYPE_NONE = -1, TYPE_CREATION = 0, TYPE_DELETION, TYPE_REFINEMENT, TYPE_COARSENING, TYPE_RENUMBERING, TYPE_PARTITION_SEND, TYPE_PARTITION_RECV, TYPE_PARTITION_NOTICE }; enum Entity { ENTITY_UNKNOWN = -1, ENTITY_CELL, ENTITY_INTERFACE }; struct Info { Info() : type(TYPE_UNKNOWN), entity(ENTITY_UNKNOWN), rank(-1) { } Info(Type user_type, Entity user_entity, int user_rank = -1) : type(user_type), entity(user_entity), rank(user_rank) { } Type type; Entity entity; int rank; std::vector<long> previous; std::vector<long> current; }; class InfoCollection { public: InfoCollection(); std::size_t create(); std::size_t create(Type type, Entity entity, int rank = -1); Info & at(std::size_t id); const Info & at(std::size_t id) const; const std::vector<Info> & data() const noexcept; std::vector<Info> & data() noexcept; Info & operator[](std::size_t id); const Info & operator[](std::size_t id) const; std::vector<Info> dump(); private: typedef std::tuple<int, int, int> infoData_t; std::unordered_map<infoData_t, std::size_t, utils::hashing::hash<infoData_t>> m_cache; std::unordered_set<int> m_cachedTypes; std::vector<Info> m_collection; }; } class PatchKernel; class FlatMapping { public: FlatMapping(); FlatMapping(PatchKernel *patch); virtual ~FlatMapping() = default; virtual void update(const std::vector<adaption::Info> &adaptionData) = 0; const std::vector<long> & getNumbering() const; const std::vector<long> & getMapping() const; protected: PatchKernel *m_patch; std::vector<long> m_numbering; std::vector<long> m_mapping; }; class CellFlatMapping : public FlatMapping { public: CellFlatMapping(); CellFlatMapping(PatchKernel *patch); void update(const std::vector<adaption::Info> &adaptionData) override; }; } #endif
optimad/bitpit
src/patchkernel/adaption.hpp
C++
lgpl-3.0
3,114
[ 30522, 1013, 1008, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 101...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# vim: set fileencoding=utf-8 : # ***********************IMPORTANT NMAP LICENSE TERMS************************ # * * # * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is * # * also a registered trademark of Insecure.Com LLC. This program is free * # * software; you may redistribute and/or modify it under the terms of the * # * GNU General Public License as published by the Free Software * # * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS * # * AND EXCEPTIONS DESCRIBED HEREIN. This guarantees your right to use, * # * modify, and redistribute this software under certain conditions. If * # * you wish to embed Nmap technology into proprietary software, we sell * # * alternative licenses (contact sales@nmap.com). Dozens of software * # * vendors already license Nmap technology such as host discovery, port * # * scanning, OS detection, version detection, and the Nmap Scripting * # * Engine. * # * * # * Note that the GPL places important restrictions on "derivative works", * # * yet it does not provide a detailed definition of that term. To avoid * # * misunderstandings, we interpret that term as broadly as copyright law * # * allows. For example, we consider an application to constitute a * # * derivative work for the purpose of this license if it does any of the * # * following with any software or content covered by this license * # * ("Covered Software"): * # * * # * o Integrates source code from Covered Software. * # * * # * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db * # * or nmap-service-probes. * # * * # * o Is designed specifically to execute Covered Software and parse the * # * results (as opposed to typical shell or execution-menu apps, which will * # * execute anything you tell them to). * # * * # * o Includes Covered Software in a proprietary executable installer. The * # * installers produced by InstallShield are an example of this. Including * # * Nmap with other software in compressed or archival form does not * # * trigger this provision, provided appropriate open source decompression * # * or de-archiving software is widely available for no charge. For the * # * purposes of this license, an installer is considered to include Covered * # * Software even if it actually retrieves a copy of Covered Software from * # * another source during runtime (such as by downloading it from the * # * Internet). * # * * # * o Links (statically or dynamically) to a library which does any of the * # * above. * # * * # * o Executes a helper program, module, or script to do any of the above. * # * * # * This list is not exclusive, but is meant to clarify our interpretation * # * of derived works with some common examples. Other people may interpret * # * the plain GPL differently, so we consider this a special exception to * # * the GPL that we apply to Covered Software. Works which meet any of * # * these conditions must conform to all of the terms of this license, * # * particularly including the GPL Section 3 requirements of providing * # * source code and allowing free redistribution of the work as a whole. * # * * # * As another special exception to the GPL terms, Insecure.Com LLC grants * # * permission to link the code of this program with any version of the * # * OpenSSL library which is distributed under a license identical to that * # * listed in the included docs/licenses/OpenSSL.txt file, and distribute * # * linked combinations including the two. * # * * # * Any redistribution of Covered Software, including any derived works, * # * must obey and carry forward all of the terms of this license, including * # * obeying all GPL rules and restrictions. For example, source code of * # * the whole work must be provided and free redistribution must be * # * allowed. All GPL references to "this License", are to be treated as * # * including the terms and conditions of this license text as well. * # * * # * Because this license imposes special exceptions to the GPL, Covered * # * Work may not be combined (even as part of a larger work) with plain GPL * # * software. The terms, conditions, and exceptions of this license must * # * be included as well. This license is incompatible with some other open * # * source licenses as well. In some cases we can relicense portions of * # * Nmap or grant special permissions to use it in other open source * # * software. Please contact fyodor@nmap.org with any such requests. * # * Similarly, we don't incorporate incompatible open source software into * # * Covered Software without special permission from the copyright holders. * # * * # * If you have any questions about the licensing restrictions on using * # * Nmap in other works, are happy to help. As mentioned above, we also * # * offer alternative license to integrate Nmap into proprietary * # * applications and appliances. These contracts have been sold to dozens * # * of software vendors, and generally include a perpetual license as well * # * as providing for priority support and updates. They also fund the * # * continued development of Nmap. Please email sales@nmap.com for further * # * information. * # * * # * If you have received a written license agreement or contract for * # * Covered Software stating terms other than these, you may choose to use * # * and redistribute Covered Software under those terms instead of these. * # * * # * Source is provided to this software because we believe users have a * # * right to know exactly what a program is going to do before they run it. * # * This also allows you to audit the software for security holes (none * # * have been found so far). * # * * # * Source code also allows you to port Nmap to new platforms, fix bugs, * # * and add new features. You are highly encouraged to send your changes * # * to the dev@nmap.org mailing list for possible incorporation into the * # * main distribution. By sending these changes to Fyodor or one of the * # * Insecure.Org development mailing lists, or checking them into the Nmap * # * source code repository, it is understood (unless you specify otherwise) * # * that you are offering the Nmap Project (Insecure.Com LLC) the * # * unlimited, non-exclusive right to reuse, modify, and relicense the * # * code. Nmap will always be available Open Source, but this is important * # * because the inability to relicense code has caused devastating problems * # * for other Free Software projects (such as KDE and NASM). We also * # * occasionally relicense the code to third parties as discussed above. * # * If you wish to specify special license conditions of your * # * contributions, just say so when you send them. * # * * # * 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 Nmap * # * license file for more details (it's in a COPYING file included with * # * Nmap, and also available from https://svn.nmap.org/nmap/COPYING * # * * # ***************************************************************************/ import gtk import pango import gobject from radialnet.bestwidgets.boxes import * from radialnet.bestwidgets.expanders import BWExpander from radialnet.bestwidgets.labels import * from radialnet.bestwidgets.textview import * import zenmapCore.I18N PORTS_HEADER = [ _('Port'), _('Protocol'), _('State'), _('Service'), _('Method')] EXTRAPORTS_HEADER = [_('Count'), _('State'), _('Reasons')] SERVICE_COLORS = {'open': '#ffd5d5', 'closed': '#d5ffd5', 'filtered': '#ffffd5', 'unfiltered': '#ffd5d5', 'open|filtered': '#ffd5d5', 'closed|filtered': '#d5ffd5'} UNKNOWN_SERVICE_COLOR = '#d5d5d5' TRACE_HEADER = [_('TTL'), _('RTT'), _('IP'), _('Hostname')] TRACE_TEXT = _( "Traceroute on port <b>%s/%s</b> totalized <b>%d</b> known hops.") NO_TRACE_TEXT = _("No traceroute information available.") HOP_COLOR = {'known': '#ffffff', 'unknown': '#cccccc'} SYSTEM_ADDRESS_TEXT = "[%s] %s" OSMATCH_HEADER = ['%', _('Name'), _('DB Line')] OSCLASS_HEADER = ['%', _('Vendor'), _('Type'), _('Family'), _('Version')] USED_PORTS_TEXT = "%d/%s %s" TCP_SEQ_NOTE = _("""\ <b>*</b> TCP sequence <i>index</i> equal to %d and <i>difficulty</i> is "%s".\ """) def get_service_color(state): color = SERVICE_COLORS.get(state) if color is None: color = UNKNOWN_SERVICE_COLOR return color class NodeNotebook(gtk.Notebook): """ """ def __init__(self, node): """ """ gtk.Notebook.__init__(self) self.set_tab_pos(gtk.POS_TOP) self.__node = node self.__create_widgets() def __create_widgets(self): """ """ # create body elements self.__services_page = ServicesPage(self.__node) self.__system_page = SystemPage(self.__node) self.__trace_page = TraceroutePage(self.__node) # packing notebook elements self.append_page(self.__system_page, BWLabel(_('General'))) self.append_page(self.__services_page, BWLabel(_('Services'))) self.append_page(self.__trace_page, BWLabel(_('Traceroute'))) class ServicesPage(gtk.Notebook): """ """ def __init__(self, node): """ """ gtk.Notebook.__init__(self) self.set_border_width(6) self.set_tab_pos(gtk.POS_TOP) self.__node = node self.__font = pango.FontDescription('Monospace') self.__create_widgets() def __create_widgets(self): """ """ self.__cell = gtk.CellRendererText() # texteditor widgets self.__texteditor = BWTextEditor() self.__texteditor.bw_modify_font(self.__font) self.__texteditor.bw_set_editable(False) self.__texteditor.set_border_width(0) self.__select_combobox = gtk.combo_box_new_text() self.__select_combobox.connect('changed', self.__change_text_value) self.__viewer = BWVBox(spacing=6) self.__viewer.set_border_width(6) self.__viewer.bw_pack_start_noexpand_nofill(self.__select_combobox) self.__viewer.bw_pack_start_expand_fill(self.__texteditor) self.__text = list() # ports information number_of_ports = len(self.__node.get_info('ports')) self.__ports_label = BWLabel(_('Ports (%s)') % number_of_ports) self.__ports_scroll = BWScrolledWindow() self.__ports_store = gtk.TreeStore(gobject.TYPE_INT, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN) self.__ports_treeview = gtk.TreeView(self.__ports_store) for port in self.__node.get_info('ports'): color = get_service_color(port['state']['state']) service_name = port['service'].get('name', _('<unknown>')) service_method = port['service'].get('method', _('<none>')) reference = self.__ports_store.append(None, [port['id'], port['protocol'], port['state']['state'], service_name, service_method, color, True]) for key in port['state']: self.__ports_store.append(reference, [port['id'], 'state', key, port['state'][key], '', 'white', True]) for key in port['service']: if key in ['servicefp']: text = _('[%d] service: %s') % (port['id'], key) self.__select_combobox.append_text(text) self.__text.append(port['service'][key]) value = _('<special field>') else: value = port['service'][key] self.__ports_store.append(reference, [port['id'], 'service', key, value, '', 'white', True]) #for script in port['scripts']: # text = _('[%d] script: %s') % (port['id'], script['id']) # self.__select_combobox.append_text(text) # self.__text.append(script['output']) # # self.__ports_store.append(reference, # [port['id'], # 'script', # 'id', # script['id'], # _('<special field>'), # 'white', # True]) self.__ports_column = list() for i in range(len(PORTS_HEADER)): column = gtk.TreeViewColumn(PORTS_HEADER[i], self.__cell, text=i) self.__ports_column.append(column) self.__ports_column[i].set_reorderable(True) self.__ports_column[i].set_resizable(True) self.__ports_column[i].set_sort_column_id(i) self.__ports_column[i].set_attributes(self.__cell, text=i, background=5, editable=6) self.__ports_treeview.append_column(self.__ports_column[i]) self.__ports_scroll.add_with_viewport(self.__ports_treeview) # extraports information number_of_xports = 0 self.__xports_scroll = BWScrolledWindow() self.__xports_store = gtk.TreeStore(gobject.TYPE_INT, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN) self.__xports_treeview = gtk.TreeView(self.__xports_store) for xports in self.__node.get_info('extraports'): color = get_service_color(xports['state']) number_of_xports += xports['count'] reference = self.__xports_store.append( None, [xports['count'], xports['state'], ", ".join(xports['reason']), color, True]) for xreason in xports['all_reason']: self.__xports_store.append(reference, [xreason['count'], xports['state'], xreason['reason'], 'white', True]) self.__xports_column = list() for i in range(len(EXTRAPORTS_HEADER)): column = gtk.TreeViewColumn(EXTRAPORTS_HEADER[i], self.__cell, text=i) self.__xports_column.append(column) self.__xports_column[i].set_reorderable(True) self.__xports_column[i].set_resizable(True) self.__xports_column[i].set_sort_column_id(i) self.__xports_column[i].set_attributes(self.__cell, text=i, background=3, editable=4) self.__xports_treeview.append_column(self.__xports_column[i]) xports_label_text = _('Extraports (%s)') % number_of_xports self.__xports_label = BWLabel(xports_label_text) self.__xports_scroll.add_with_viewport(self.__xports_treeview) self.append_page(self.__ports_scroll, self.__ports_label) self.append_page(self.__xports_scroll, self.__xports_label) self.append_page(self.__viewer, BWLabel(_('Special fields'))) if len(self.__text) > 0: self.__select_combobox.set_active(0) def __change_text_value(self, widget): """ """ id = self.__select_combobox.get_active() self.__texteditor.bw_set_text(self.__text[id]) class SystemPage(BWScrolledWindow): """ """ def __init__(self, node): """ """ BWScrolledWindow.__init__(self) self.__node = node self.__font = pango.FontDescription('Monospace') self.__create_widgets() def __create_widgets(self): """ """ self.__vbox = BWVBox() self.__vbox.set_border_width(6) self.__cell = gtk.CellRendererText() self.__general_frame = BWExpander(_('General information')) self.__sequences_frame = BWExpander(_('Sequences')) self.__os_frame = BWExpander(_('Operating System')) self.__sequences_frame.bw_add(gtk.Label(_('No sequence information.'))) self.__os_frame.bw_add(gtk.Label(_('No OS information.'))) # general information widgets self.__general = BWTable(3, 2) self.__address_label = BWSectionLabel(_('Address:')) self.__address_list = gtk.combo_box_entry_new_text() self.__address_list.child.set_editable(False) for address in self.__node.get_info('addresses'): params = address['type'], address['addr'] address_text = SYSTEM_ADDRESS_TEXT % params if address['vendor'] is not None and address['vendor'] != '': address_text += " (%s)" % address['vendor'] self.__address_list.append_text(address_text) self.__address_list.set_active(0) self.__general.bw_attach_next(self.__address_label, yoptions=gtk.FILL, xoptions=gtk.FILL) self.__general.bw_attach_next(self.__address_list, yoptions=gtk.FILL) if self.__node.get_info('hostnames') is not None: self.__hostname_label = BWSectionLabel(_('Hostname:')) self.__hostname_list = gtk.combo_box_entry_new_text() self.__hostname_list.child.set_editable(False) for hostname in self.__node.get_info('hostnames'): params = hostname['type'], hostname['name'] self.__hostname_list.append_text(SYSTEM_ADDRESS_TEXT % params) self.__hostname_list.set_active(0) self.__general.bw_attach_next(self.__hostname_label, yoptions=gtk.FILL, xoptions=gtk.FILL) self.__general.bw_attach_next(self.__hostname_list, yoptions=gtk.FILL) if self.__node.get_info('uptime') is not None: self.__uptime_label = BWSectionLabel(_('Last boot:')) seconds = self.__node.get_info('uptime')['seconds'] lastboot = self.__node.get_info('uptime')['lastboot'] text = _('%s (%s seconds).') % (lastboot, seconds) self.__uptime_value = BWLabel(text) self.__uptime_value.set_selectable(True) self.__uptime_value.set_line_wrap(False) self.__general.bw_attach_next(self.__uptime_label, yoptions=gtk.FILL, xoptions=gtk.FILL) self.__general.bw_attach_next(self.__uptime_value, yoptions=gtk.FILL) self.__general_frame.bw_add(self.__general) self.__general_frame.set_expanded(True) sequences = self.__node.get_info('sequences') if len(sequences) > 0: self.__sequences_frame.bw_add( self.__create_sequences_widget(sequences)) # operating system information widgets self.__os = gtk.Notebook() os = self.__node.get_info('os') if os is not None: if 'matches' in os: self.__match_scroll = BWScrolledWindow() self.__match_store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_INT, gobject.TYPE_BOOLEAN) self.__match_treeview = gtk.TreeView(self.__match_store) for os_match in os['matches']: self.__match_store.append([os_match['accuracy'], os_match['name'], #os_match['db_line'], 0, # unsupported True]) self.__match_column = list() for i in range(len(OSMATCH_HEADER)): column = gtk.TreeViewColumn(OSMATCH_HEADER[i], self.__cell, text=i) self.__match_column.append(column) self.__match_column[i].set_reorderable(True) self.__match_column[i].set_resizable(True) self.__match_column[i].set_attributes(self.__cell, text=i, editable=3) self.__match_column[i].set_sort_column_id(i) self.__match_treeview.append_column(self.__match_column[i]) self.__match_scroll.add_with_viewport(self.__match_treeview) self.__os.append_page(self.__match_scroll, BWLabel(_('Match'))) if 'classes' in os: self.__class_scroll = BWScrolledWindow() self.__class_store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN) self.__class_treeview = gtk.TreeView(self.__class_store) for os_class in os['classes']: os_gen = os_class.get('os_gen', '') self.__class_store.append([os_class['accuracy'], os_class['vendor'], os_class['type'], os_class['os_family'], os_gen, True]) self.__class_column = list() for i in range(len(OSCLASS_HEADER)): column = gtk.TreeViewColumn(OSCLASS_HEADER[i], self.__cell, text=i) self.__class_column.append(column) self.__class_column[i].set_reorderable(True) self.__class_column[i].set_resizable(True) self.__class_column[i].set_attributes(self.__cell, text=i, editable=5) self.__class_column[i].set_sort_column_id(i) self.__class_treeview.append_column(self.__class_column[i]) self.__class_scroll.add_with_viewport(self.__class_treeview) self.__os.append_page(self.__class_scroll, BWLabel(_('Class'))) self.__fp_viewer = BWTextEditor() self.__fp_viewer.bw_modify_font(self.__font) self.__fp_viewer.bw_set_editable(False) self.__fp_viewer.bw_set_text(os['fingerprint']) self.__fp_ports = BWHBox() self.__fp_label = BWSectionLabel(_('Used ports:')) self.__fp_ports_list = gtk.combo_box_entry_new_text() self.__fp_ports_list.child.set_editable(False) self.__fp_vbox = BWVBox() if 'used_ports' in os: used_ports = os['used_ports'] for port in used_ports: params = port['id'], port['protocol'], port['state'] self.__fp_ports_list.append_text(USED_PORTS_TEXT % params) self.__fp_ports_list.set_active(0) self.__fp_ports.bw_pack_start_noexpand_nofill(self.__fp_label) self.__fp_ports.bw_pack_start_expand_fill(self.__fp_ports_list) self.__fp_vbox.bw_pack_start_noexpand_nofill(self.__fp_ports) self.__os.append_page(self.__fp_viewer, BWLabel(_('Fingerprint'))) self.__fp_vbox.bw_pack_start_expand_fill(self.__os) self.__os_frame.bw_add(self.__fp_vbox) self.__os_frame.set_expanded(True) self.__vbox.bw_pack_start_noexpand_nofill(self.__general_frame) self.__vbox.bw_pack_start_expand_fill(self.__os_frame) self.__vbox.bw_pack_start_noexpand_nofill(self.__sequences_frame) self.add_with_viewport(self.__vbox) def __create_sequences_widget(self, sequences): """Return a widget representing various OS detection sequences. The sequences argument is a dict with zero or more of the keys 'tcp', 'ip_id', and 'tcp_ts'.""" # sequences information widgets table = BWTable(5, 3) table.attach(BWSectionLabel(_('Class')), 1, 2, 0, 1) table.attach(BWSectionLabel(_('Values')), 2, 3, 0, 1) table.attach(BWSectionLabel(_('TCP *')), 0, 1, 1, 2) table.attach(BWSectionLabel(_('IP ID')), 0, 1, 2, 3) table.attach(BWSectionLabel(_('TCP Timestamp')), 0, 1, 3, 4) tcp = sequences.get('tcp') if tcp is not None: tcp_class = BWLabel(tcp['class']) tcp_class.set_selectable(True) table.attach(tcp_class, 1, 2, 1, 2) tcp_values = gtk.combo_box_entry_new_text() for value in tcp['values']: tcp_values.append_text(value) tcp_values.set_active(0) table.attach(tcp_values, 2, 3, 1, 2) tcp_note = BWLabel() tcp_note.set_selectable(True) tcp_note.set_line_wrap(False) tcp_note.set_alignment(1.0, 0.5) tcp_note.set_markup( TCP_SEQ_NOTE % (tcp['index'], tcp['difficulty'])) table.attach(tcp_note, 0, 3, 4, 5) ip_id = sequences.get('ip_id') if ip_id is not None: ip_id_class = BWLabel(ip_id['class']) ip_id_class.set_selectable(True) table.attach(ip_id_class, 1, 2, 2, 3) ip_id_values = gtk.combo_box_entry_new_text() for value in ip_id['values']: ip_id_values.append_text(value) ip_id_values.set_active(0) table.attach(ip_id_values, 2, 3, 2, 3) tcp_ts = sequences.get('tcp_ts') if tcp_ts is not None: tcp_ts_class = BWLabel(tcp_ts['class']) tcp_ts_class.set_selectable(True) table.attach(tcp_ts_class, 1, 2, 3, 4) if tcp_ts['values'] is not None: tcp_ts_values = gtk.combo_box_entry_new_text() for value in tcp_ts['values']: tcp_ts_values.append_text(value) tcp_ts_values.set_active(0) table.attach(tcp_ts_values, 2, 3, 3, 4) return table class TraceroutePage(BWVBox): """ """ def __init__(self, node): """ """ BWVBox.__init__(self) self.set_border_width(6) self.__node = node self.__create_widgets() def __create_widgets(self): """ """ trace = self.__node.get_info('trace') hops = None if trace is not None: hops = trace.get("hops") if hops is None or len(hops) == 0: self.__trace_label = gtk.Label(NO_TRACE_TEXT) self.pack_start(self.__trace_label, True, True) else: # add hops hops = self.__node.get_info('trace')['hops'] ttls = [int(i['ttl']) for i in hops] self.__cell = gtk.CellRendererText() self.__trace_scroll = BWScrolledWindow() self.__trace_scroll.set_border_width(0) self.__trace_store = gtk.ListStore(gobject.TYPE_INT, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_BOOLEAN) self.__trace_treeview = gtk.TreeView(self.__trace_store) count = 0 for i in range(1, max(ttls) + 1): if i in ttls: hop = hops[count] count += 1 self.__trace_store.append([hop['ttl'], hop['rtt'], hop['ip'], hop['hostname'], HOP_COLOR['known'], True]) else: self.__trace_store.append([i, '', _('<unknown>'), '', HOP_COLOR['unknown'], True]) self.__trace_column = list() for i in range(len(TRACE_HEADER)): column = gtk.TreeViewColumn(TRACE_HEADER[i], self.__cell, text=i) self.__trace_column.append(column) self.__trace_column[i].set_reorderable(True) self.__trace_column[i].set_resizable(True) self.__trace_column[i].set_attributes(self.__cell, text=i, background=4, editable=5) self.__trace_treeview.append_column(self.__trace_column[i]) self.__trace_column[0].set_sort_column_id(0) self.__trace_scroll.add_with_viewport(self.__trace_treeview) self.__trace_info = (self.__node.get_info('trace')['port'], self.__node.get_info('trace')['protocol'], len(self.__node.get_info('trace')['hops'])) self.__trace_label = BWLabel(TRACE_TEXT % self.__trace_info) self.__trace_label.set_use_markup(True) self.bw_pack_start_expand_fill(self.__trace_scroll) self.bw_pack_start_noexpand_nofill(self.__trace_label)
markofu/scripts
nmap/nmap/zenmap/radialnet/gui/NodeNotebook.py
Python
gpl-2.0
34,656
[ 30522, 1001, 6819, 2213, 1024, 2275, 5371, 2368, 3597, 4667, 1027, 21183, 2546, 1011, 1022, 1024, 1001, 30524, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * 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. */ import {isLayoutSizeDefined} from '../../../src/layout'; import {tryParseJson} from '../../../src/json'; import {user} from '../../../src/log'; import {removeElement} from '../../../src/dom'; import { installVideoManagerForDoc, } from '../../../src/service/video-manager-impl'; import {isObject} from '../../../src/types'; import {listen} from '../../../src/event-helper'; import {VideoEvents} from '../../../src/video-interface'; import {videoManagerForDoc} from '../../../src/services'; /** * @implements {../../../src/video-interface.VideoInterface} */ class Amp3QPlayer extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?Element} */ this.iframe_ = null; /** @private {?Function} */ this.unlistenMessage_ = null; /** @private {?Promise} */ this.playerReadyPromise_ = null; /** @private {?Function} */ this.playerReadyResolver_ = null; this.dataId = null; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { this.preconnect.url('https://playout.3qsdn.com', opt_onLayout); } /** @override */ buildCallback() { this.dataId = user().assert( this.element.getAttribute('data-id'), 'The data-id attribute is required for <amp-3q-player> %s', this.element); this.playerReadyPromise_ = new Promise(resolve => { this.playerReadyResolver_ = resolve; }); installVideoManagerForDoc(this.element); videoManagerForDoc(this.element).register(this); } /** @override */ layoutCallback() { const iframe = this.element.ownerDocument.createElement('iframe'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowfullscreen', 'true'); this.iframe_ = iframe; this.unlistenMessage_ = listen( this.win, 'message', this.sdnBridge_.bind(this) ); this.applyFillContent(iframe, true); iframe.src = 'https://playout.3qsdn.com/' + encodeURIComponent(this.dataId) + '?autoplay=false&amp=true'; this.element.appendChild(iframe); return this.loadPromise(this.iframe_).then(() => this.playerReadyPromise_); } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; } if (this.unlistenMessage_) { this.unlistenMessage_(); } this.playerReadyPromise_ = new Promise(resolve => { this.playerReadyResolver_ = resolve; }); return true; } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ viewportCallback(visible) { this.element.dispatchCustomEvent(VideoEvents.VISIBILITY, {visible}); } /** @override */ pauseCallback() { if (this.iframe_) { this.pause(); } } sdnBridge_(event) { if (event.source) { if (event.source != this.iframe_.contentWindow) { return; } } const data = isObject(event.data) ? event.data : tryParseJson(event.data); if (data === undefined) { return; } switch (data.data) { case 'ready': this.element.dispatchCustomEvent(VideoEvents.LOAD); this.playerReadyResolver_(); break; case 'playing': this.element.dispatchCustomEvent(VideoEvents.PLAY); break; case 'paused': this.element.dispatchCustomEvent(VideoEvents.PAUSE); break; case 'muted': this.element.dispatchCustomEvent(VideoEvents.MUTED); break; case 'unmuted': this.element.dispatchCustomEvent(VideoEvents.UNMUTED); break; } } sdnPostMessage_(message) { this.playerReadyPromise_.then(() => { if (this.iframe_ && this.iframe_.contentWindow) { this.iframe_.contentWindow./*OK*/postMessage(message, '*'); } }); } // VideoInterface Implementation. See ../src/video-interface.VideoInterface /** @override */ play() { this.sdnPostMessage_('play2'); } /** @override */ pause() { this.sdnPostMessage_('pause'); } /** @override */ mute() { this.sdnPostMessage_('mute'); } /** @override */ unmute() { this.sdnPostMessage_('unmute'); } /** @override */ supportsPlatform() { return true; } /** @override */ isInteractive() { return true; } /** @override */ showControls() { this.sdnPostMessage_('showControlbar'); } /** @override */ hideControls() { this.sdnPostMessage_('hideControlbar'); } }; AMP.registerElement('amp-3q-player', Amp3QPlayer);
ecoron/amphtml
extensions/amp-3q-player/0.1/amp-3q-player.js
JavaScript
apache-2.0
5,238
[ 30522, 1013, 1008, 1008, 1008, 9385, 2418, 1996, 23713, 16129, 6048, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package org.semanticweb.elk.reasoner.indexing.model; import org.semanticweb.elk.owl.interfaces.ElkClassExpression; /* * #%L * ELK Reasoner * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2015 Department of Computer Science, University of Oxford * %% * 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. * #L% */ import org.semanticweb.elk.owl.interfaces.ElkObjectProperty; import org.semanticweb.elk.owl.interfaces.ElkObjectSomeValuesFrom; /** * An {@link IndexedContextRoot} constructed from an * {@link IndexedObjectProperty} and an {@link IndexedClassExpression}.<br> * * Notation: * * <pre> * C ⊓ ∃R- * </pre> * * It is logically equivalent to an OWL class expression * {@code ObjectIntersectionOf(C ObjectSomeValuesFrom(ObjectInverseOf(R) owl:Thing))} * <br> * * The parameters can be obtained as follows:<br> * * C = {@link #getFiller()}<br> * R = {@link #getProperty()}<br> * * @see IndexedObjectSomeValuesFrom#getRangeFiller() * */ public interface IndexedRangeFiller extends IndexedContextRoot { /** * @return The representation of the {@link ElkObjectProperty} which range * this {@link IndexedRangeFiller} subsumes. It is the property of * the {@link ElkObjectSomeValuesFrom} corresponding to this * {@link IndexedRangeFiller}. */ IndexedObjectProperty getProperty(); /** * @return The representation of the {@link ElkClassExpression} which this * {@link IndexedRangeFiller} subsumes. It is the filler of the * {@link ElkObjectSomeValuesFrom} corresponding to this * {@link IndexedRangeFiller}. */ IndexedClassExpression getFiller(); /** * The visitor pattern for instances * * @author Yevgeny Kazakov * * @param <O> * the type of the output */ interface Visitor<O> { O visit(IndexedRangeFiller element); } }
liveontologies/elk-reasoner
elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/indexing/model/IndexedRangeFiller.java
Java
apache-2.0
2,380
[ 30522, 7427, 8917, 1012, 21641, 8545, 2497, 1012, 18995, 1012, 3114, 2121, 1012, 5950, 2075, 1012, 2944, 1025, 12324, 8917, 1012, 21641, 8545, 2497, 1012, 18995, 1012, 13547, 1012, 19706, 1012, 18995, 26266, 10288, 20110, 3258, 1025, 1013, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/python import numpy as np mdir = "mesh3d/" fname = "out_p6-p4-p8" #################### print "input mesh data file" f1 = open(mdir+fname+".mesh", 'r') for line in f1: if line.startswith("Vertices"): break pcount = int(f1.next()) xyz = np.empty((pcount, 3), dtype=np.float) for t in range(pcount): xyz[t] = map(float,f1.next().split()[0:3]) for line in f1: if line.startswith("Triangles"): break trisc = int(f1.next()) tris = np.empty((trisc,4), dtype=int) for t in range(trisc): tris[t] = map(int,f1.next().split()) for line in f1: if line.startswith("Tetrahedra"): break tetsc = int(f1.next()) tets = np.empty((tetsc,5), dtype=int) for t in range(tetsc): tets[t] = map(int,f1.next().split()) f1.close() #################### print "identify geometry" ftype = [('v0', np.int),('v1', np.int),('v2', np.int),('label', 'S2')] faces = np.empty(trisc/2, dtype=ftype) for i in range(len(faces)): faces[i] = (tris[2*i][0],tris[2*i][1],tris[2*i][2],str(tris[2*i][3])+str(tris[2*i+1][3])) face_list,face_count = np.unique(faces['label'], return_counts=True) vtype = [('v0', np.int),('v1', np.int),('v2', np.int),('v3', np.int),('label', 'S1')] vols = np.empty(tetsc, dtype=vtype) for i in range(tetsc): vols[i] = (tets[i][0],tets[i][1],tets[i][2],tets[i][3],str(tets[i][4])) vol_list,vol_count = np.unique(vols['label'], return_counts=True) #################### print "output vtk data files for faces" for i, f in enumerate(face_list): f2 = open(mdir+fname+"_"+face_list[i]+".vtk", 'w') f2.write("# vtk DataFile Version 2.0\n") f2.write("mesh data\n") f2.write("ASCII\n") f2.write("DATASET UNSTRUCTURED_GRID\n") f2.write("POINTS "+str(pcount)+" float\n") # overkill, all points! for v in xyz: f2.write(str(v[0]-35.33)+' '+str(35.33-v[1])+' '+str(12.36-v[2])+'\n') f2.write("CELLS "+str(face_count[i])+" "+str(face_count[i]*4)+"\n") for v in faces: if v[3] == f: f2.write("3 "+str(v[0]-1)+' '+str(v[1]-1)+' '+str(v[2]-1)+'\n') f2.write("CELL_TYPES "+str(face_count[i])+"\n") for t in range(face_count[i]): f2.write("5 ") f2.write("\n") f2.close() #################### print "output vtk data files for volumes" for i, f in enumerate(vol_list): f2 = open(mdir+fname+"_"+vol_list[i]+".vtk", 'w') f2.write("# vtk DataFile Version 2.0\n") f2.write("mesh data\n") f2.write("ASCII\n") f2.write("DATASET UNSTRUCTURED_GRID\n") f2.write("POINTS "+str(pcount)+" float\n") # overkill, all points! for v in xyz: f2.write(str(v[0]-35.33)+' '+str(35.33-v[1])+' '+str(12.36-v[2])+'\n') f2.write("CELLS "+str(vol_count[i])+" "+str(vol_count[i]*5)+"\n") for v in vols: if v[4] == f: f2.write("4 "+str(v[0]-1)+' '+str(v[1]-1)+' '+str(v[2]-1)+' '+str(v[3]-1)+'\n') f2.write("CELL_TYPES "+str(vol_count[i])+"\n") for t in range(vol_count[i]): f2.write("10 ") f2.write("\n") f2.close() ####################
jrugis/cell_mesh
mesh2vtk.py
Python
gpl-3.0
2,909
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 18750, 12324, 16371, 8737, 2100, 2004, 27937, 9108, 4313, 1027, 1000, 20437, 29097, 1013, 1000, 1042, 18442, 1027, 1000, 2041, 1035, 1052, 2575, 1011, 1052, 2549, 1011, 1052, 2620, 1000,...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "annotator.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
richard-schwab/annotatorjs-django
manage.py
Python
gpl-2.0
252
[ 30522, 1001, 999, 1013, 2149, 2099, 1013, 8026, 1013, 4372, 2615, 18750, 12324, 9808, 12324, 25353, 2015, 2065, 1035, 1035, 2171, 1035, 30524, 1000, 1024, 9808, 1012, 4372, 21663, 2239, 1012, 2275, 3207, 7011, 11314, 1006, 1000, 6520, 23422...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.stats.nonparametric.RankCompareResult &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.stats.nonparametric.RankCompareResult.conf_int" href="statsmodels.stats.nonparametric.RankCompareResult.conf_int.html" /> <link rel="prev" title="statsmodels.stats.nonparametric.rank_compare_2ordinal" href="statsmodels.stats.nonparametric.rank_compare_2ordinal.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.stats.nonparametric.RankCompareResult" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.14.0.dev0 (+325)</span> <span class="md-header-nav__topic"> statsmodels.stats.nonparametric.RankCompareResult </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.14.0.dev0 (+325)</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.nonparametric.RankCompareResult.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-stats-nonparametric-rankcompareresult"> <h1 id="generated-statsmodels-stats-nonparametric-rankcompareresult--page-root">statsmodels.stats.nonparametric.RankCompareResult<a class="headerlink" href="#generated-statsmodels-stats-nonparametric-rankcompareresult--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py class"> <dt class="sig sig-object py" id="statsmodels.stats.nonparametric.RankCompareResult"> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">statsmodels.stats.nonparametric.</span></span><span class="sig-name descname"><span class="pre">RankCompareResult</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">tuple_</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwds</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/stats/nonparametric.html#RankCompareResult"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.stats.nonparametric.RankCompareResult" title="Permalink to this definition">¶</a></dt> <dd><p>Results for rank comparison</p> <p>This is a subclass of HolderTuple that includes results from intermediate computations, as well as methods for hypothesis tests, confidence intervals and summary.</p> <p class="rubric">Methods</p> <table class="longtable docutils align-default"> <colgroup> <col style="width: 10%"/> <col style="width: 90%"/> </colgroup> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.nonparametric.RankCompareResult.conf_int.html#statsmodels.stats.nonparametric.RankCompareResult.conf_int" title="statsmodels.stats.nonparametric.RankCompareResult.conf_int"><code class="xref py py-obj docutils literal notranslate"><span class="pre">conf_int</span></code></a>([value, alpha, alternative])</p></td> <td><p>Confidence interval for probability that sample 1 has larger values</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.stats.nonparametric.RankCompareResult.confint_lintransf.html#statsmodels.stats.nonparametric.RankCompareResult.confint_lintransf" title="statsmodels.stats.nonparametric.RankCompareResult.confint_lintransf"><code class="xref py py-obj docutils literal notranslate"><span class="pre">confint_lintransf</span></code></a>([const, slope, alpha, ...])</p></td> <td><p>confidence interval of a linear transformation of prob1</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.nonparametric.RankCompareResult.effectsize_normal.html#statsmodels.stats.nonparametric.RankCompareResult.effectsize_normal" title="statsmodels.stats.nonparametric.RankCompareResult.effectsize_normal"><code class="xref py py-obj docutils literal notranslate"><span class="pre">effectsize_normal</span></code></a>([prob])</p></td> <td><p>Cohen's d, standardized mean difference under normality assumption.</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.stats.nonparametric.RankCompareResult.summary.html#statsmodels.stats.nonparametric.RankCompareResult.summary" title="statsmodels.stats.nonparametric.RankCompareResult.summary"><code class="xref py py-obj docutils literal notranslate"><span class="pre">summary</span></code></a>([alpha, xname])</p></td> <td><p>summary table for probability that random draw x1 is larger than x2</p></td> </tr> <tr class="row-odd"><td><p><a class="reference internal" href="statsmodels.stats.nonparametric.RankCompareResult.test_prob_superior.html#statsmodels.stats.nonparametric.RankCompareResult.test_prob_superior" title="statsmodels.stats.nonparametric.RankCompareResult.test_prob_superior"><code class="xref py py-obj docutils literal notranslate"><span class="pre">test_prob_superior</span></code></a>([value, alternative])</p></td> <td><p>test for superiority probability</p></td> </tr> <tr class="row-even"><td><p><a class="reference internal" href="statsmodels.stats.nonparametric.RankCompareResult.tost_prob_superior.html#statsmodels.stats.nonparametric.RankCompareResult.tost_prob_superior" title="statsmodels.stats.nonparametric.RankCompareResult.tost_prob_superior"><code class="xref py py-obj docutils literal notranslate"><span class="pre">tost_prob_superior</span></code></a>(low, upp)</p></td> <td><p>test of stochastic (non-)equivalence of p = P(x1 &gt; x2)</p></td> </tr> </tbody> </table> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.stats.nonparametric.rank_compare_2ordinal.html" title="statsmodels.stats.nonparametric.rank_compare_2ordinal" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.stats.nonparametric.rank_compare_2ordinal </span> </div> </a> <a href="statsmodels.stats.nonparametric.RankCompareResult.conf_int.html" title="statsmodels.stats.nonparametric.RankCompareResult.conf_int" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.stats.nonparametric.RankCompareResult.conf_int </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 23, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 4.4.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
devel/generated/statsmodels.stats.nonparametric.RankCompareResult.html
HTML
bsd-3-clause
22,373
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1013, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 100...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
$:.unshift(File.join(File.dirname(__FILE__), "..", "..", "lib")) require "voltdb" java_import Java::OrgVoltdbClient::ClientResponse config = Voltdb::ClientConfig.new() config.set_reconnect_on_connection_loss(true) client = Voltdb::Client.create_client(config) client.create_connection("localhost") client.call_procedure("@AdHoc", "DELETE FROM helloworld") client.call_procedure("Insert", "English", "Hello", "World") client.call_procedure("Insert", "French", "Bonjour", "Monde") client.call_procedure("Insert", "Spanish", "Hola", "Mundo") client.call_procedure("Insert", "Danish", "Hej", "Verden") client.call_procedure("Insert", "Italian", "Ciao", "Mondo") response = client.call_procedure("Select", "Spanish") if response.get_status != ClientResponse.SUCCESS puts response.get_status_string exit 1 end results = response.get_results if results.length == 0 || results[0].get_row_count != 1 puts "I can't say Hello in that language.\n" exit 1 end result_table = results[0] row = result_table.fetch_row(0) puts "#{row.get_string("hello")}, #{row.get_string("world")}!\n"
full360/voltdb-client-jruby
examples/helloworld/helloworld.rb
Ruby
mit
1,086
[ 30522, 1002, 1024, 1012, 4895, 6182, 6199, 1006, 5371, 1012, 3693, 1006, 5371, 1012, 16101, 18442, 1006, 1035, 1035, 5371, 1035, 1035, 1007, 1010, 1000, 1012, 1012, 1000, 1010, 1000, 1012, 1012, 1000, 1010, 1000, 5622, 2497, 1000, 1007, 1...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
namespace TeamElderberryProject { using System; using System.Windows.Forms; public struct TransactionData { private decimal amount; private DateTime date; public TransactionData(decimal amount, DateTime date) : this() { this.Amount = amount; this.Date = date; } public decimal Amount { get { return this.amount; } private set { this.amount = value; } } public DateTime Date { get { return this.date; } private set { this.date = value; } } } }
DimitarSD/ElderberryTeam
LevelMoney/TeamElderberryProject/TransactionData.cs
C#
mit
803
[ 30522, 3415, 15327, 2136, 14273, 2121, 9766, 21572, 20614, 1063, 2478, 2291, 1025, 2478, 2291, 1012, 3645, 1012, 3596, 1025, 2270, 2358, 6820, 6593, 12598, 2850, 2696, 1063, 2797, 26066, 3815, 1025, 2797, 3058, 7292, 3058, 1025, 2270, 12598...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace spec\Sylius\Bundle\CoreBundle\EventListener; use Doctrine\ORM\Event\LifecycleEventArgs; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Sylius\Component\Core\Model\CustomerInterface; use Sylius\Component\Core\Model\ShopUserInterface; use Sylius\Component\User\Canonicalizer\CanonicalizerInterface; /** * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com> */ final class CanonicalizerListenerSpec extends ObjectBehavior { function let(CanonicalizerInterface $canonicalizer): void { $this->beConstructedWith($canonicalizer); } function it_canonicalize_user_username_on_pre_persist_doctrine_event($canonicalizer, LifecycleEventArgs $event, ShopUserInterface $user): void { $event->getEntity()->willReturn($user); $user->getUsername()->willReturn('testUser'); $user->getEmail()->willReturn('test@email.com'); $user->setUsernameCanonical('testuser')->shouldBeCalled(); $user->setEmailCanonical('test@email.com')->shouldBeCalled(); $canonicalizer->canonicalize('testUser')->willReturn('testuser')->shouldBeCalled(); $canonicalizer->canonicalize('test@email.com')->willReturn('test@email.com')->shouldBeCalled(); $this->prePersist($event); } function it_canonicalize_customer_email_on_pre_persist_doctrine_event($canonicalizer, LifecycleEventArgs $event, CustomerInterface $customer): void { $event->getEntity()->willReturn($customer); $customer->getEmail()->willReturn('testUser@Email.com'); $customer->setEmailCanonical('testuser@email.com')->shouldBeCalled(); $canonicalizer->canonicalize('testUser@Email.com')->willReturn('testuser@email.com')->shouldBeCalled(); $this->prePersist($event); } function it_canonicalize_user_username_on_pre_update_doctrine_event($canonicalizer, LifecycleEventArgs $event, ShopUserInterface $user): void { $event->getEntity()->willReturn($user); $user->getUsername()->willReturn('testUser'); $user->getEmail()->willReturn('test@email.com'); $user->setUsernameCanonical('testuser')->shouldBeCalled(); $user->setEmailCanonical('test@email.com')->shouldBeCalled(); $canonicalizer->canonicalize('testUser')->willReturn('testuser')->shouldBeCalled(); $canonicalizer->canonicalize('test@email.com')->willReturn('test@email.com')->shouldBeCalled(); $this->preUpdate($event); } function it_canonicalize_customer_email_on_pre_update_doctrine_event($canonicalizer, LifecycleEventArgs $event, CustomerInterface $customer): void { $event->getEntity()->willReturn($customer); $customer->getEmail()->willReturn('testUser@Email.com'); $customer->setEmailCanonical('testuser@email.com')->shouldBeCalled(); $canonicalizer->canonicalize('testUser@Email.com')->willReturn('testuser@email.com')->shouldBeCalled(); $this->preUpdate($event); } function it_canonicalize_only_user_or_customer_interface_implementation_on_pre_presist($canonicalizer, LifecycleEventArgs $event): void { $item = new \stdClass(); $event->getEntity()->willReturn($item); $canonicalizer->canonicalize(Argument::any())->shouldNotBeCalled(); $this->prePersist($event); } function it_canonicalize_only_user_or_customer_interface_implementation_on_pre_update($canonicalizer, LifecycleEventArgs $event): void { $item = new \stdClass(); $event->getEntity()->willReturn($item); $canonicalizer->canonicalize(Argument::any())->shouldNotBeCalled(); $this->preUpdate($event); } }
rainlike/justshop
vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/spec/EventListener/CanonicalizerListenerSpec.php
PHP
mit
3,904
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 1996, 25353, 15513, 7427, 1012, 1008, 1008, 1006, 1039, 1007, 22195, 2063, 18818, 24401, 15378, 20518, 7974, 5488, 1008, 1008, 2005, 1996, 2440, 9385, 1998, 6105, 259...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module.exports = function verify(check) { if (typeof check !== 'object') { throw new Error('check is not an object'); } var errors = []; Object.keys(check).forEach(_verify, check); if (errors.length > 0) { throw new Error('Health checks failed: '+ errors.join(', ')); } return true; function _verify(key, i) { if (this[key] === false || this[key] instanceof Error) { errors.push(key); } else if (this[key] && typeof this[key] === 'object' && !Array.isArray(this[key])) { Object.keys(this[key]).forEach(_verify, this[key]); } } };
super-useful/su-healthcheck
lib/verify.js
JavaScript
mit
644
[ 30522, 11336, 1012, 14338, 1027, 3853, 20410, 1006, 4638, 1007, 1063, 2065, 1006, 2828, 11253, 4638, 999, 1027, 1027, 1005, 4874, 1005, 1007, 1063, 5466, 2047, 7561, 1006, 1005, 4638, 2003, 2025, 2019, 4874, 1005, 1007, 1025, 1065, 13075, ...
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...