text
stringlengths
2
1.04M
meta
dict
#ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include <gst/gst.h> #include <gtk/gtk.h> /* global pointer for the scale widget */ static GtkWidget *elapsed; static GtkWidget *scale; #ifndef M_LN10 #define M_LN10 (log(10.0)) #endif static void value_changed_callback (GtkWidget * widget, GstElement * volume) { gdouble value; gdouble level; value = gtk_range_get_value (GTK_RANGE (widget)); level = exp (value / 20.0 * M_LN10); g_print ("Value: %f dB, level: %f\n", value, level); g_object_set (volume, "volume", level, NULL); } static void setup_gui (GstElement * volume) { GtkWidget *window; GtkWidget *vbox; GtkWidget *label, *hbox; window = gtk_window_new (GTK_WINDOW_TOPLEVEL); g_signal_connect (window, "destroy", gtk_main_quit, NULL); vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); gtk_container_add (GTK_CONTAINER (window), vbox); /* elapsed widget */ hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); label = gtk_label_new ("Elapsed: "); elapsed = gtk_label_new ("0.0"); gtk_container_add (GTK_CONTAINER (hbox), label); gtk_container_add (GTK_CONTAINER (hbox), elapsed); gtk_container_add (GTK_CONTAINER (vbox), hbox); /* volume */ hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); label = gtk_label_new ("volume"); gtk_container_add (GTK_CONTAINER (hbox), label); scale = gtk_scale_new_with_range (GTK_ORIENTATION_HORIZONTAL, -90.0, 10.0, 0.2); gtk_range_set_value (GTK_RANGE (scale), 0.0); gtk_widget_set_size_request (scale, 100, -1); gtk_container_add (GTK_CONTAINER (hbox), scale); gtk_container_add (GTK_CONTAINER (vbox), hbox); g_signal_connect (scale, "value-changed", G_CALLBACK (value_changed_callback), volume); gtk_widget_show_all (GTK_WIDGET (window)); } static gboolean progress_update (gpointer data) { GstElement *pipeline = (GstElement *) data; gint64 position; gchar *position_str; if (gst_element_query_position (pipeline, GST_FORMAT_TIME, &position)) position_str = g_strdup_printf ("%.1f", (gfloat) position / GST_SECOND); else position_str = g_strdup_printf ("n/a"); gtk_label_set_text (GTK_LABEL (elapsed), position_str); g_free (position_str); return TRUE; } static void message_received (GstBus * bus, GstMessage * message, GstPipeline * pipeline) { const GstStructure *s; s = gst_message_get_structure (message); g_print ("message from \"%s\" (%s): ", GST_STR_NULL (GST_ELEMENT_NAME (GST_MESSAGE_SRC (message))), gst_message_type_get_name (GST_MESSAGE_TYPE (message))); if (s) { gchar *sstr; sstr = gst_structure_to_string (s); g_print ("%s\n", sstr); g_free (sstr); } else { g_print ("no message details\n"); } } static void eos_message_received (GstBus * bus, GstMessage * message, GstPipeline * pipeline) { message_received (bus, message, pipeline); gtk_main_quit (); } int main (int argc, char *argv[]) { GstElement *pipeline = NULL; #ifndef GST_DISABLE_PARSE GError *error = NULL; #endif GstElement *volume; GstBus *bus; #ifdef GST_DISABLE_PARSE g_print ("GStreamer was built without pipeline parsing capabilities.\n"); g_print ("Please rebuild GStreamer with pipeline parsing capabilities activated to use this example.\n"); return 1; #else gst_init (&argc, &argv); gtk_init (&argc, &argv); pipeline = gst_parse_launchv ((const gchar **) &argv[1], &error); if (error) { g_print ("pipeline could not be constructed: %s\n", error->message); g_print ("Please give a complete pipeline with a 'volume' element.\n"); g_print ("Example: audiotestsrc ! volume ! %s\n", DEFAULT_AUDIOSINK); g_error_free (error); return 1; } #endif volume = gst_bin_get_by_name (GST_BIN (pipeline), "volume0"); if (volume == NULL) { g_print ("Please give a pipeline with a 'volume' element in it\n"); return 1; } /* setup message handling */ bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); gst_bus_add_signal_watch_full (bus, G_PRIORITY_HIGH); g_signal_connect (bus, "message::error", (GCallback) message_received, pipeline); g_signal_connect (bus, "message::warning", (GCallback) message_received, pipeline); g_signal_connect (bus, "message::eos", (GCallback) eos_message_received, pipeline); /* setup GUI */ setup_gui (volume); /* go to main loop */ gst_element_set_state (pipeline, GST_STATE_PLAYING); g_timeout_add (100, progress_update, pipeline); gtk_main (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_object_unref (volume); gst_object_unref (pipeline); gst_object_unref (bus); return 0; }
{ "content_hash": "7e2865ac2bc419ce59c2781826ddb8a7", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 103, "avg_line_length": 26.735632183908045, "alnum_prop": 0.6642304385210662, "repo_name": "google/aistreams", "id": "a3ca3d758439c6a4d6543f157d9366b8a2828a0b", "size": "5562", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "third_party/gst-plugins-base/tests/examples/audio/volume.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "77741" }, { "name": "C++", "bytes": "626396" }, { "name": "Python", "bytes": "41809" }, { "name": "Starlark", "bytes": "56595" } ], "symlink_target": "" }
// Copyright © 2021 GGG KILLER <gggkiller2@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the “Software”), to deal in the Software without // restriction, including without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom // the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING // BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Tsu.Parsing.BBCode.Lexing; namespace Tsu.Parsing.BBCode.Tests { [TestClass] public class BBLexerTests { [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Static field.")] private static readonly BBToken s_lbracket = new BBToken(BBTokenType.LBracket); [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Static field.")] private static readonly BBToken s_rbracket = new BBToken(BBTokenType.RBracket); [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Static field.")] private static readonly BBToken s_equals = new BBToken(BBTokenType.Equals); [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "Static field.")] private static readonly BBToken s_slash = new BBToken(BBTokenType.Slash); private static void AssertTokenStream(string str, params BBToken[] expectedTokens) { using var reader = new StringReader(str); var gottenTokens = BBLexer.Lex(reader).ToArray(); foreach ((var expected, var gotten) in expectedTokens.Zip(gottenTokens, (a, b) => (a, b))) Assert.AreEqual(expected, gotten); Assert.AreEqual(expectedTokens.Length, gottenTokens.Length, "Got a different amount of tokens than expected"); } [TestMethod] public void ShouldLexBrackets() => AssertTokenStream("[][][]", s_lbracket, s_rbracket, s_lbracket, s_rbracket, s_lbracket, s_rbracket); [TestMethod] public void ShouldLexText() => AssertTokenStream("some=text/for=you", new BBToken("some=text/for=you")); [TestMethod] public void ShouldLexEmptyString() => AssertTokenStream(""); [TestMethod] public void ShouldLexTagWithoutValue() => AssertTokenStream("[a][/a]", s_lbracket, new BBToken("a"), s_rbracket, s_lbracket, s_slash, new BBToken("a"), s_rbracket); [TestMethod] public void ShouldLexTagWithValue() => AssertTokenStream("[a=a][/a]", s_lbracket, new BBToken("a"), s_equals, new BBToken("a"), s_rbracket, s_lbracket, s_slash, new BBToken("a"), s_rbracket); [TestMethod] public void ShouldLexSelfClosingTagWithoutValue() => AssertTokenStream("[a/]", s_lbracket, new BBToken("a"), s_slash, s_rbracket); [DataTestMethod] [DataRow("[[a]")] [DataRow("[a[a]")] [DataRow("[a=[a]")] public void ShouldNotLex(string text) => Assert.ThrowsException<FormatException>(() => { using var reader = new StringReader(text); _ = BBLexer.Lex(reader).ToArray(); }); } }
{ "content_hash": "9ea7b41349209452c562fa363352e72c", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 164, "avg_line_length": 48.70238095238095, "alnum_prop": 0.6790515766316304, "repo_name": "GGG-KILLER/GUtils.NET", "id": "ea33283a7c63575046537ffd80b46dd0bb2f1faf", "size": "4102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tsu.Parsing.BBCode.Tests/BBLexerTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "342694" } ], "symlink_target": "" }
Drawing with Kinect on any surface ================== A new degree of freedom. ------- This project is intended to allow to everyone with a depth sensor and a projector to create interactive drawings on any surface, expanding the idea of blackboard and creating new horizons for creativity. It offers an immersive experience, upgrading simple gestures to drawing actions that can make any crazy idea come to life. Dependencies/Requirements ---- 0. Currently, a **Kinect v2 Sensor** hardware is required, along with a **Kinect Adapter** cable. In future releases these requirements will be made optional. If you do not own such a device, you can test it offline, either by feeding it with recorded frames from a directory or by feeding it with a rosbag file. 1. **Linux OS** , due to the fact that ROS platform is needed for all the tools to cooperate synchronously. My OS is Ubuntu 16.04, but any setup can work, as long as all the dependencies can be fullfilled. I am planning to make a preconfigured VM for Windows some day, till then anyone can try to get it working. 0. **Various preinstallation packages**: sudo apt-get install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev cmake-qt-gui 1. If NVIDIA GPU is available, one can install **CUDA** beforehand, after verifying that his GPU is supported in https://developer.nvidia.com/cuda-gpus , but **Caution**, the installation is hard and many problems may arise if the NVIDIA drivers are not installed correctly on the system, which are not very well documented and much experimentation migh be needed if luck is absent. If you are not an experienced user or lack of patience, skip this step, although take into consideration that this step can not be done after completion of the next steps, but the procedure will have to be repeated. Installing CUDA will make everything run faster. To install CUDA, visit https://developer.nvidia.com/cuda-downloads 2. **ROS Kinetic** Installation Instructions: http://wiki.ros.org/kinetic/Installation/Ubuntu 3. **OpenCV 3.1.0 dev** You have to install from source due to a bug of contour approximation in image edges. Clone either commit from Nov 18, 2016 for safety: https://github.com/opencv/opencv/tree/12569dc73058686d3e0d7724aafa70cf524f8e26 , or clone current version: https://github.com/opencv/opencv : git clone <selected_repository> To compile(assume DIR is the Path where you cloned OPENCV) : cd DIR cd opencv mkdir build cd build cmake-gui .. When cmake-gui runs, if you have CUDA installed check if all CUDA flags are set correctly. In `CMAKE_INSTALL_PREFIX` add the directory where you want OPENCV to be installed (let's name it INSTALL_DIR). Set `CMAKE_BUILD_TYPE` to `RELEASE`. Search of any flags starting with "WITH_" prefix and tick whatever you might need, while I urge you to tick `WITH_QT` , `WITH_TBB`, `WITH_OPENCL`, `WITH_PNG`, `WITH_EIGEN`, `WITH_CUFFT` and `WITH_CUBLAS`. If you have NVIDIA GPU you might want to tick `WITH_NVCUVID` and if MATLAB is available, `WITH_MATLAB` should be ticked too. Check if every other directory is set correctly, press Configure and after that, if no errors arise, press Generate. After Generate finishes close cmake-gui window, go to terminal and: make -j4 make install This will generally take 30 minutes and above. You can change the -j4 to -j5 or above, but the computer might hang and be almost unusable during installation, while the speed of the installation might decrease due to memory and hardware bottlenecks. Due to the fact that ROS installation will have probably dominated your Python environment after installation, the easiest way to make OPENCV library accessible from Python is to copy cv2.so file from INSTALL_DIR/lib/python2.7/dist-packages to /opt/ros/kinetic/lib/python2.7/dist-packages. You can check if everything went ok by running Python console and trying: import cv2 print cv2.__version__ If the above prints ` '3.1.0-dev' `, then the installation was successful 4. **Some Python libraries** might be required. As I did not hold record of this requirement, some troubleshooting is needed. One can run `python init_code.py` . If any module error is raised, then he should should `pip install` the selected module and, if he wants, he can name it in the issues page of the repository, so that I can add it in this section. Currently I am using wxPython for the GUI part. To install wxPython the following is needed: sudo apt-get install libwebkit-dev sudo pip install --upgrade --trusted-host wxpython.org --pre -f http://wxpython.org/Phoenix/snapshot-builds/ wxPython_Phoenix For the coding book stage I am using scikit-fuzzy toolbox: sudo pip install scikit-fuzzy It is suggested to also install progressbar2: sudo pip install progressbar2 5. **Kinect 2 Libraries** are required, although this will change in upcoming releases, so that to remove this requirement and make it optional. Actually, any depth device with a software that can publish to ROS can be used in this project, so there is no reason to demand those specific libraries to start with. To install them, visit https://github.com/code-iai/iai_kinect2 and follow the installation instructions, skipping ROS installation. Usage ---- The basic configuration can be done through the `config.yaml` file. The primary program to run is `init_code.py` . Report Issues/ Feedback/ Copyright --- Any issue that anyone has can be reported, as I am a solo team and some things might have skipped my attention, but I do not guarantee immediate response.
{ "content_hash": "ecd259c33db6f1a2202267edda1bb5d5", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 383, "avg_line_length": 57.17821782178218, "alnum_prop": 0.7669264069264069, "repo_name": "VasLem/KinectPainting", "id": "8d6be55772432e14917f22e6580831362a4b3784", "size": "5775", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "130926" }, { "name": "Python", "bytes": "763393" } ], "symlink_target": "" }
using System; using QUEBB.Core.Boundary; using QUEBB.Core.Entities; using QUEBB.Core.Infrastructure; namespace QUEBB.Core.AddPost { public class AddPostHandler { private readonly IRepository _repository; public AddPostHandler(IRepository repository) { if (repository == null) { throw new ArgumentNullException("repository"); } _repository = repository; } public AddPostResponse Handle(AddPostRequest request) { if (request == null) { throw new ArgumentNullException("request"); } //validation if (request.Post.Id != null) { throw new ValidationException(); } if (request.Post.Title == null) { throw new ValidationException(); } //Handle var id = _repository.StorePost(new Post {Title = request.Post.Title}); var post = _repository.GetPost(id); return new AddPostResponse(post); } } }
{ "content_hash": "1d2ac14635d7e26b5d974429d10027dd", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 82, "avg_line_length": 25.47826086956522, "alnum_prop": 0.5110921501706485, "repo_name": "csMACnz/QUEBB", "id": "bdc7c7985d21c1921edb841afc97da61493ce792", "size": "1174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/QUEBB.Core/AddPost/AddPostHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "26879" } ], "symlink_target": "" }
@implementation SampleAppCurrentSession @synthesize issuer = _issuer; @synthesize client_id = _client_id; @synthesize nonce = _nonce; @synthesize OIDCImplicitProfile = _OIDCImplicitProfile; NSDictionary *_allAttributes; +(SampleAppCurrentSession *)session { static SampleAppCurrentSession *sess; if(sess == nil) { sess = [[SampleAppCurrentSession alloc] init]; } return sess; } -(id)init { self = [super init]; if (self) { } return self; } -(NSArray *)getAllAttributes { return [_allAttributes allKeys]; } -(NSString *)getValueForAttribute:(NSString *)attribute { return [_allAttributes valueForKey:attribute]; } -(void)createSession { if(![self inErrorState]) { NSString *id_token = [_OIDCImplicitProfile getOAuthParameter:kOAuth2ParamIdToken]; _allAttributes = [OpenIDConnectLibrary parseIDToken:id_token forClient:_client_id withNonce:_nonce]; NSLog(@"Created Session: %@", _allAttributes); } } -(BOOL)isAuthenticated { if([_allAttributes count] > 0) { return YES; } else { return NO; } } -(void)logout { _allAttributes = nil; } -(BOOL)inErrorState { if([_OIDCImplicitProfile getOAuthParameter:kOAuth2ParamError] != nil) { return YES; } return NO; } -(NSString *)getLastError { if ([self inErrorState]) { return [_OIDCImplicitProfile getOAuthParameter:kOAuth2ParamErrorDescription]; } else { return @""; } } @end
{ "content_hash": "f5148a483cdc2ca6e314c4351f1e4438", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 108, "avg_line_length": 17.18888888888889, "alnum_prop": 0.6354234001292824, "repo_name": "depl0y/iOSSample-OIDC-Implicit", "id": "e061bc326a772a197e50970b484232bff04d2460", "size": "1769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SampleApp/SampleApp/SampleApp/SampleAppCurrentSession.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "92781" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" /> <link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/> <link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/> <!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]--> <style type="text/css" media="all"> @import url('../../../../../style.css'); @import url('../../../../../tree.css'); </style> <script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script> <script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script> <script src="../../../../../package-nodes-tree.js" type="text/javascript"></script> <script src="../../../../../clover-tree.js" type="text/javascript"></script> <script src="../../../../../clover.js" type="text/javascript"></script> <script src="../../../../../clover-descriptions.js" type="text/javascript"></script> <script src="../../../../../cloud.js" type="text/javascript"></script> <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title> </head> <body> <div id="page"> <header id="header" role="banner"> <nav class="aui-header aui-dropdown2-trigger-group" role="navigation"> <div class="aui-header-inner"> <div class="aui-header-primary"> <h1 id="logo" class="aui-header-logo aui-header-logo-clover"> <a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a> </h1> </div> <div class="aui-header-secondary"> <ul class="aui-nav"> <li id="system-help-menu"> <a class="aui-nav-link" title="Open online documentation" target="_blank" href="http://openclover.org/documentation"> <span class="aui-icon aui-icon-small aui-iconfont-help">&#160;Help</span> </a> </li> </ul> </div> </div> </nav> </header> <div class="aui-page-panel"> <div class="aui-page-panel-inner"> <div class="aui-page-panel-nav aui-page-panel-nav-clover"> <div class="aui-page-header-inner" style="margin-bottom: 20px;"> <div class="aui-page-header-image"> <a href="http://cardatechnologies.com" target="_top"> <div class="aui-avatar aui-avatar-large aui-avatar-project"> <div class="aui-avatar-inner"> <img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/> </div> </div> </a> </div> <div class="aui-page-header-main" > <h1> <a href="http://cardatechnologies.com" target="_top"> ABA Route Transit Number Validator 1.0.1-SNAPSHOT </a> </h1> </div> </div> <nav class="aui-navgroup aui-navgroup-vertical"> <div class="aui-navgroup-inner"> <ul class="aui-nav"> <li class=""> <a href="../../../../../dashboard.html">Project overview</a> </li> </ul> <div class="aui-nav-heading packages-nav-heading"> <strong>Packages</strong> </div> <div class="aui-nav project-packages"> <form method="get" action="#" class="aui package-filter-container"> <input type="text" autocomplete="off" class="package-filter text" placeholder="Type to filter packages..." name="package-filter" id="package-filter" title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/> </form> <p class="package-filter-no-results-message hidden"> <small>No results found.</small> </p> <div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator"> <div class="packages-tree-container"></div> <div class="clover-packages-lozenges"></div> </div> </div> </div> </nav> </div> <section class="aui-page-panel-content"> <div class="aui-page-panel-content-clover"> <div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs"> <li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li> <li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li> <li><a href="test-Test_AbaRouteValidator_03.html">Class Test_AbaRouteValidator_03</a></li> </ol></div> <h1 class="aui-h2-clover"> Test testAbaNumberCheck_2557_good </h1> <table class="aui"> <thead> <tr> <th>Test</th> <th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th> <th><label title="When the test execution was started">Start time</label></th> <th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th> <th><label title="A failure or error message if the test is not successful.">Message</label></th> </tr> </thead> <tbody> <tr> <td> <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_03.html?line=1432#src-1432" >testAbaNumberCheck_2557_good</a> </td> <td> <span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span> </td> <td> 7 Aug 12:32:46 </td> <td> 0.001 </td> <td> <div></div> <div class="errorMessage"></div> </td> </tr> </tbody> </table> <div>&#160;</div> <table class="aui aui-table-sortable"> <thead> <tr> <th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th> <th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_2557_good</th> </tr> </thead> <tbody> <tr> <td> <span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span> &#160;&#160;<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=26495#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a> </td> <td> <span class="sortValue">0.7352941</span>73.5% </td> <td class="align-middle" style="width: 100%" colspan="3"> <div> <div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td> </tr> </tbody> </table> </div> <!-- class="aui-page-panel-content-clover" --> <footer id="footer" role="contentinfo"> <section class="footer-body"> <ul> <li> Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1 on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT. </li> </ul> <ul> <li>OpenClover is free and open-source software. </li> </ul> </section> </footer> </section> <!-- class="aui-page-panel-content" --> </div> <!-- class="aui-page-panel-inner" --> </div> <!-- class="aui-page-panel" --> </div> <!-- id="page" --> </body> </html>
{ "content_hash": "2d5e135174a7ad28e899e43139082d09", "timestamp": "", "source": "github", "line_count": 209, "max_line_length": 297, "avg_line_length": 43.91387559808612, "alnum_prop": 0.5095881455654827, "repo_name": "dcarda/aba.route.validator", "id": "f2a5eb14884789d1722fe724bc3a306fb3729954", "size": "9178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_03_testAbaNumberCheck_2557_good_kfz.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18715254" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class RubyXL::OLESize - rubyXL 3.3.15</title> <script type="text/javascript"> var rdoc_rel_prefix = "../"; </script> <script src="../js/jquery.js"></script> <script src="../js/darkfish.js"></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"><a href="OOXMLObject.html">RubyXL::OOXMLObject</a> </div> </div> </nav> <main role="main" aria-labelledby="class-RubyXL::OLESize"> <h1 id="class-RubyXL::OLESize" class="class"> class RubyXL::OLESize </h1> <section class="description"> <p><a href="http://www.schemacentral.com/sc/ooxml/e-ssml_oleSize-1.html">www.schemacentral.com/sc/ooxml/e-ssml_oleSize-1.html</a></p> </section> <section id="5Buntitled-5D" class="documentation-section"> </section> </main> <footer id="validator-badges" role="contentinfo"> <p><a href="http://validator.w3.org/check/referer">Validate</a> <p>Generated by <a href="http://docs.seattlerb.org/rdoc/">RDoc</a> 4.2.0. <p>Based on <a href="http://deveiate.org/projects/Darkfish-RDoc/">Darkfish</a> by <a href="http://deveiate.org">Michael Granger</a>. </footer>
{ "content_hash": "26169e19ef959c84b3589152d4a63950", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 134, "avg_line_length": 24.18095238095238, "alnum_prop": 0.6325324931075227, "repo_name": "parallel588/rubyXL", "id": "4135fe89346771423d2d71cb52ee66aa1085f28e", "size": "2539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rdoc/RubyXL/OLESize.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15702" }, { "name": "HTML", "bytes": "1703684" }, { "name": "JavaScript", "bytes": "17924" }, { "name": "Ruby", "bytes": "383515" } ], "symlink_target": "" }
package com.knight.arch.events; /** * @author andyiac * @date 15-10-19 * @web http://blog.andyiac.com * @github https://github.com/andyiac */ public class TrendingReposTimeSpanTextMsg { String timeSpan; public String getTimeSpan() { return timeSpan; } public void setTimeSpan(String timeSpan) { this.timeSpan = timeSpan; } }
{ "content_hash": "75d6618de3477bc86842069d9662e512", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 46, "avg_line_length": 18.45, "alnum_prop": 0.6558265582655827, "repo_name": "andyiac/githot", "id": "6ec3f85d559dd7b033afe94477dd3107b87903be", "size": "369", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/knight/arch/events/TrendingReposTimeSpanTextMsg.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "158070" } ], "symlink_target": "" }
<html> <title>messaging v1 Client Library for Java</title> <body> <h1>Overview</h1> <p>This is a client library bundle using Google Cloud Endpoints. In order to use this API client library in your project, you need to build the library using Gradle.</p> <h2>How to build API client library using Gradle</h2> <p>Under the root directory of the client bundle, run <b><i>"gradle install"</i></b> in the command console. By running this command, this API client bundle would be build by Gradle, and be deployed to local Maven repository. (Gradle doesn't have native repository system, but could leverage repository systems like maven repository.)</p> <h2>How to use API client library in Gradle project</h2> <p><b>Step 1</b>: Add the following <i>compile</i> section to your <b><i>build.gradle</i></b> file.</p> <ul> <pre style="background-color: #eee;"> compile ([group: 'net.nfiniteloop.loqale.server', name: 'messaging', version: 'v1-1.19.0-SNAPSHOT']) </pre> </ul> <p><b>Step 2</b>: Add one of the following <i>compile</i> sections to your <b><i>build.gradle</i></b> file, based on your platform (Android/App Engine/Servlet). Google Cloud Endpoints API client is compatible with all supported Java platforms (with minimum Java version 5).</p> <ul> <li> <b>For Android</b> <pre style="background-color: #eee;"> compile ([group: 'com.google.api-client', name: 'google-api-client-android', version: '1.19.0']) </pre> </li> <li> <b>For App Engine</b> <pre style="background-color: #eee;"> compile ([group: 'com.google.api-client', name: 'google-api-client-appengine', version: '1.19.0']) </pre> </li> <li> <b>For Java Servlet</b> <pre style="background-color: #eee;"> compile ([group: 'com.google.api-client', name: 'google-api-client-servlet', version: '1.19.0']) </pre> </li> </ul> <p><b>Step 3</b>: Add one of the following <i>compile</i> sections to your <b><i>build.gradle</i></b> file, or directly import AndroidJsonFactory into your Java source, based on your JsonFactory implementation (GSON/Jackson/AndroidJson).</p> <ul> <li> <b>Using GsonFactory</b> <pre style="background-color: #eee;"> compile ([group: 'com.google.api-client', name: 'google-http-client-gson', version: '1.19.0']) </pre> </li> <li> <b>Using JacksonFactory</b> <pre style="background-color: #eee;"> compile ([group: 'com.google.api-client', name: 'google-http-client-jackson2', version: '1.19.0']) </pre> </li> <li> <b>Using AndroidJsonFactory (Android with minimum API level 11)</b><br/> For Andoird with minimum API level 11, import AndroidJsonFactory into your Java source. <pre style="background-color: #eee;"> import com.google.api.client.extensions.android.json.AndroidJsonFactory; </pre> </li> </ul> <p><b>Step 4</b>: Make sure local Maven repository is added to the repository section of <b><i>build.gradle</i></b> file. <ul> <pre style="background-color: #eee;"> repositories { mavenCentral() <b>mavenLocal()</b> } </pre> </ul> <p><b>Step 5</b>: Refer to the "Creating the service object" and "Calling the API exposed by the Endpoint" sections of this <a href="https://developers.google.com/appengine/docs/java/endpoints/consume_android">Endpoints Java Documentation</a> to see how to use the client library in Android.</p> </html>
{ "content_hash": "4dad874d5ecf77368969fdded8262c12", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 338, "avg_line_length": 43.891891891891895, "alnum_prop": 0.707820197044335, "repo_name": "vaektor/Loqale", "id": "bd729c730aad83dfcdccb74bc6383f4907582e34", "size": "3248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/build/tmp/appengineEndpointsExpandClientLibs/messaging-v1-java.zip-unzipped/messaging/readme.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "215816" } ], "symlink_target": "" }
package org.vitrivr.cineast.core.features; import org.vitrivr.cineast.core.features.abstracts.SolrTextRetriever; public class OCRSearch extends SolrTextRetriever { @Override protected String getEntityName() { return "features_ocr"; } }
{ "content_hash": "257b668aa3fdaaaf247e070f44e46fdf", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 69, "avg_line_length": 19.307692307692307, "alnum_prop": 0.7729083665338645, "repo_name": "silvanheller/cineast", "id": "34566dc90c972c4ada81b078d8f5881132048d59", "size": "251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/vitrivr/cineast/core/features/OCRSearch.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2034460" } ], "symlink_target": "" }
First Timer's GameBoy Emulator I definitely don't own SDL.
{ "content_hash": "f5b3e962a95972a6ec1a44ac98e0f5ab", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 30, "avg_line_length": 19.666666666666668, "alnum_prop": 0.7966101694915254, "repo_name": "thebeardphantom/FTGBE", "id": "6bed8e222b4320c03d8fe357710c417c33eda013", "size": "67", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1504317" }, { "name": "C++", "bytes": "35297" }, { "name": "Objective-C", "bytes": "8426" } ], "symlink_target": "" }
'------------------------------------------------------------------------------ ' <auto-generated> ' Dieser Code wurde von einem Tool generiert. ' Laufzeitversion:4.0.30319.1 ' ' Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn ' der Code erneut generiert wird. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "Funktion zum automatischen Speichern von My.Settings" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.COMAddinClassicExampleVB4.My.MySettings Get Return Global.COMAddinClassicExampleVB4.My.MySettings.Default End Get End Property End Module End Namespace
{ "content_hash": "7a532e4d558f986e8f79dfcd2c20a09d", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 179, "avg_line_length": 40.917808219178085, "alnum_prop": 0.6575159022430532, "repo_name": "NetOfficeFw/NetOffice", "id": "773310e9f988c7fe57e6a2001508877501c39b4f", "size": "2991", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "Examples/Excel/VB/IExtensibility COMAddin Examples/ClassicUI/My Project/Settings.Designer.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "951" }, { "name": "C#", "bytes": "47700257" }, { "name": "Rich Text Format", "bytes": "230731" }, { "name": "VBA", "bytes": "1389" }, { "name": "Visual Basic .NET", "bytes": "212815" } ], "symlink_target": "" }
import Model, { attr } from '@ember-data/model'; export default class PageModel extends Model { @attr('string') title; }
{ "content_hash": "2a27438c9a5363895b6803708a0cb5ad", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 48, "avg_line_length": 20.833333333333332, "alnum_prop": 0.696, "repo_name": "ef4/ember-resource-metadata", "id": "db559f956f021fe9215697c6612e44e5ec18cdd8", "size": "125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/dummy/app/models/page.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1894" }, { "name": "JavaScript", "bytes": "17705" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"><title>Programmation defensive avec assert()</title> <meta http-equiv="CONTENT-TYPE" content="text/html; charset=ISO-8859-1"> <meta name="author" content="rachid koucha"> <meta name="Category" content="langage C, programmation defensive, debug, assert, heisenbug, schrodinbug, instrumentation"> <meta name="language" content="fr"> <meta http-equiv="Content-Language" content="fr"> <meta name="description" content="Programmation defensive a l'aide de la macro assert()"> <meta name="keywords" content="langage C, programmation defensive, debug, assert, heisenbug, schrodinbug, instrumentation"> <meta name="GENERATOR" content="OpenOffice.org 2.3 (Linux)"> <meta name="GENERATOR" content="OpenOffice.org 2.4 (Linux)"> <style type="text/css"> <!-- @page { size: 21cm 29.7cm; margin: 2cm } P { margin-bottom: 0.21cm } H1.western { font-family: "Tahoma", sans-serif; font-size: 16pt; font-weight: medium } H1.cjk { font-family: "Lucida Sans Unicode" } H1.ctl { font-family: "Tahoma" } H2.western { font-family: "Tahoma", sans-serif; font-size: 14pt; font-weight: medium } H2.cjk { font-family: "Lucida Sans Unicode" } H2.ctl { font-family: "Tahoma" } --> </style> <script type="text/javascript" src="https://apis.google.com/js/plusone.js"> {lang: 'fr'} </script></head><body> <a href="../../index.html"><small>Retour à la page d'accueil</small></a><br> <a href="../documents_techniques.html"><small>Retour à la page précédente</small></a> <span style="font-weight: bold;"><br> <br> </span><small><small><span style="text-decoration: underline;">Auteur</span> : R. Koucha<br> <span style="text-decoration: underline;">Dernière mise à jour</span> : 29-Mai-2008<br> <br> </small></small> <div style="text-align: center;"><font face="Arial Black, sans-serif"><font size="6"><b>Utiliser "assert()" pour mettre au point les programmes&nbsp;en langage C</b></font></font></div> <table style="background-color: silver; text-align: left; margin-left: auto; margin-right: auto;"> <tbody> <tr> <td> <script type="text/javascript"><!-- google_ad_client = "pub-9113501896220746"; /* 728x90, date de création 29/03/08 */ google_ad_slot = "7632855209"; google_ad_width = 728; google_ad_height = 90; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script><br> </td> </tr> </tbody> </table> <br> <table style="text-align: left; width: 100%;" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="vertical-align: top; height: 50%; width: 50%;"><br> </td> <td style="vertical-align: top;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Frachid.koucha.free.fr%2Ftech_corner%2Fprog_assert_fr.html&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80" style="border: medium none ; overflow: hidden; width: 450px; height: 80px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe> <br> </td> </tr> <tr> <td style="vertical-align: top;"><br> </td> <td style="vertical-align: top;"><g:plusone size="medium"></g:plusone> <br> </td> </tr> <tr> <td style="vertical-align: top;"><br> </td> <td style="vertical-align: top;"><a href="mailto:?body=http%3A%2F%2Frachid.koucha.free.fr%2Ftech_corner%2Fprog_assert_fr.html&amp;subject=Programmation%20defensive%20avec%20assert%28%29"><img alt="s" src="../send_to_a_friend.gif" style="border: 0px solid ; width: 30px; height: 21px;"></a></td> </tr> </tbody> </table> <br> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><a href="ftp_api_fr.html#Avant_propos"><span class="western"></span></a> </p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> </p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm;" align="justify"><font face="Arial Black, sans-serif"><font style="font-size: 11pt;" size="2"><i><b>Aussi simple soit-elle, la macro assert() peut-être d'une redoutable efficacité pour la mise au point lorsqu'elle est utilisée de manière systématique dans les programmes écrits en langage C.</b></i></font></font></p> <a href="#Avant_propos"><span class="western"></span></a> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><a href="#Avant_propos"><span class="western">Avant propos</span></a></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><a href="#Avant_propos"><span class="western"></span></a></p> <a href="#1._Pr%E9sentation">1. Présentation</a><br> <a href="#2._Assert_ou_retour_erreur_">2. Assert ou retour erreur ? </a><br> <a href="#3._Mise_au_point_dun_programme">3. Mise au point d'un programme</a><br> <div style="margin-left: 40px;"><a href="#3.1._Premi%E8re_mouture_du_programme">3.1. Première mouture du programme</a><br> <a href="#3.2._Prot%E9ger_lAPI_contre_les_erreurs">3.2. Protéger l'API contre les erreurs d'utilisation</a><br> <a href="#3.3._Prot%E9ger_lAPI_contre_les_erreurs">3.3. Protéger l'API contre les erreurs de programmation</a><br> <a href="#3.4._Instrumentation">3.4. Instrumentation</a><br> </div> <a href="#4._Conclusion">4. Conclusion</a><a href="#Liens"><br> Liens</a><br> <a href="#A_propos_de_lauteur">A propos de l'auteur</a> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm;" align="justify"><a href="ftp_api_fr.html#Avant_propos"><span class="western"></span></a></p> <h2><a name="Avant_propos"></a><span class="western">Avant propos</span></h2> <font face="Arial, sans-serif"><font size="2">Cet article a été publié dans <a href="http://www.unixgarden.com/index.php/gnu-linux-magazine/utiliser-assert-pour-mettre-au-point-les-programmes-en-langage-c"><span style="text-decoration: underline;"><img alt="glmf_logo" src="../glmf_logo.jpg" style="border: 0px solid ; width: 100px; height: 30px;"></span></a> numéro 105.<br> </font></font> <h1 class="western"><a name="1._Présentation"></a>1. Présentation</h1> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Dans <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>&lt;assert.h&gt;</b></font></font>, la macro <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> est le plus souvent définie sous la forme d'un opérateur ternaire&nbsp;:</font></font></p> <table style="text-align: left; background-color: silver; font-family: monospace; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#define assert(expr) &nbsp;\<br> &nbsp; &nbsp; &nbsp; ((expr)&nbsp;? __ASSERT_VOID_CAST (0)&nbsp;: __assert_fail (__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION))</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Si l'expression passée en paramètre est vraie, la macro ne fait rien (l'appel <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>__ASSERT_VOID_CAST(0)</b></font></font> se traduit par la génération de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>(void)0</b></font></font>) par contre si l'expression est fausse, un arrêt du programme est provoqué par l'appel à la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>__assert_fail()</b></font></font> qui affiche un message d'erreur (avec l'expression en cause, le nom du fichier, le numéro de ligne et le nom de la fonction où s'est produite l'erreur) avant d'appeler le service <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>abort()</b></font></font>. Pour mémoire, en langage C une expression est vraie si son résultat donne une valeur différente de 0. Voici un exemple de déclenchement d'un assert&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">1 &nbsp;#include &lt;assert.h&gt;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">2 </font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">3 &nbsp;int fct(int n)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">4 &nbsp;{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">5 &nbsp; &nbsp;assert(n != 0);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">6 &nbsp;}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">7 </font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">8 &nbsp;int main(int ac, char *av[])</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">9 &nbsp;{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">10 &nbsp; fct(0);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">11 }</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Le programme va déclencher un assert dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>fct()</b></font></font> car cette dernière est appelée avec un paramètre égal à 0&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">&gt; gcc -g exemple0.c</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&gt; ./a.out </font> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">a.out: <font color="#ff0000"><font style="font-size: 9pt;" size="2">exemple0.c:5: fct: Assertion `n != 0' failed.</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">Abandon (core dumped)</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">On voit un message d'erreur s'afficher avec toutes les informations utiles pour retrouver l'assert en question dans le code&nbsp;: fichier <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>exemple0.c</b></font></font>, ligne 5, expression «&nbsp;<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>n != 0</b></font></font>&nbsp;». Pour corriger le programme, on aimerait avoir la valeur de la variable <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>n</b></font></font> car tout ce que l'on sait à la lecture du message d'erreur c'est que la variable est différente de 0. Comme <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> appelle la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>abort()</b></font></font> pour terminer le programme, cela provoque l'émission du signal <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>SIGABRT</b></font></font> (numéro 6) qui par défaut génère un fichier <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>core</b></font></font>. On peut lancer le debugger <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>gdb</b></font></font> pour retrouver l'état de la mémoire et afficher la valeur de la variable au moment de l'erreur. Pour la mise au point dans de bonnes conditions, il faut compiler le programme avec les informations de debug (option «&nbsp;-g&nbsp;») et activer la génération des fichiers <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>core</b></font></font> («&nbsp;<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>ulimit -c unlimited&nbsp;»</b></font></font> sous bash).</font></font></p> <table style="text-align: left; background-color: silver; font-family: monospace; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">&gt; ulimit -c unlimited</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&gt; gdb ./a.out core </font> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">Core was generated by `./a.out'.</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">Program terminated with signal 6, Aborted.</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#0 0xffffe410 in __kernel_vsyscall ()</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">(gdb) where</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#0 0xffffe410 in __kernel_vsyscall ()</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#1 0xb7dc8875 in raise () from /lib/tls/i686/cmov/libc.so.6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#2 0xb7dca201 in abort () from /lib/tls/i686/cmov/libc.so.6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#3 0xb7dc1b6e in __assert_fail () from /lib/tls/i686/cmov/libc.so.6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#4 0x080483a4 in fct (n=0) at exemple0.c:5</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#5 0x080483c3 in main () at exemple0.c:10</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">(gdb) <font color="#ff0000"><font style="font-size: 9pt;" size="2">up 4</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#4 0x080483a4 in fct (n=0) at exemple0.c:5</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">6 assert(n != 0);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">(gdb) <font color="#ff0000"><font style="font-size: 9pt;" size="2">print n</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">$1 = 0</font></font></font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Il est possible de modifier le comportement par défaut de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> en capturant le signal <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>SIGABRT</b></font></font> pour déclencher une fonction ad hoc.</font></font> </p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">On notera que la macro <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> n'est définie que si la drapeau de compilation <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NDEBUG</b></font></font> n'est pas positionné. C'est le comportement par défaut. Si ce drapeau est positionné sur la ligne de compilation, alors la macro <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> est expansée en une instruction vide : <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>(void)0</b></font></font>. On a coutume de faire disparaître les asserts dans le programme final destiné à la production pour le rendre plus efficace car les asserts déroulent du code supplémentaire pour tester des expressions.</font></font></p> <h1 class="western"><a name="2._Assert_ou_retour_erreur_"></a>2. Assert ou retour erreur ?</h1> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Il est courant de considérer un retour en erreur comme alternative à l'assert. En fait, ils ne désservent pas le même objectif.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Un retour erreur est utilisé lorsque le dysfonctionnement constaté ne porte pas atteinte à l'intégrité du programme. C'est-à-dire que l'on a détecté une mauvaise utilisation d'une fonction mais les structures de données restent cohérentes donc on refuse le service mais on se tient à disposition pour un nouvel appel. Un retour erreur est par conséquent typiquement utilisé dans les fonctions de service quand elle reçoivent des données non conformes à l'interface&nbsp;:</font></font></p> <ul> <li><font face="Arial, sans-serif"><font size="2">Message de type inattendu venant du réseau;</font></font></li> <li><font face="Arial, sans-serif"><font size="2">Mauvaise valeur d'un paramètre passé à une API;</font></font></li> <li><font face="Arial, sans-serif"><font size="2">L'allocateur mémoire a retourné NULL car il n'y a plus de mémoire;</font></font></li> <li><font face="Arial, sans-serif"><font size="2">...</font></font></li> </ul> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Un assert est utilisé lorsque l'on constate que le programme n'est plus en état de fonctionner correctement. Un retour erreur ne suffit pas car tout nouvel appel mènera à la même constatation ou à une aggravation du désordre constaté&nbsp;:</font></font></p> <ul> <li><font face="Arial, sans-serif"><font size="2">La valeur d'une variable n'est pas dans une plage attendue;</font></font></li> <li><font face="Arial, sans-serif"><font size="2">Une chaîne de caractères n'est pas finie par le caractère <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NUL</b></font></font> (<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>'\0'</b></font></font>);</font></font></li> <li><font face="Arial, sans-serif"><font size="2">Une liste chaînée ne se termine pas par le pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>;</font></font></li> <li><font face="Arial, sans-serif"><font size="2">...</font></font></li> </ul> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">En d'autres termes, l'assert a pour but de détecter des erreurs de programmation alors que le retour erreur détecte les mauvaises utilisations des services d'un programme. Le retour erreur est un garde-fou pour l'utilisateur tandis que l'assert est un garde-fou pour le développeur.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Mais il faut quand même reconnaître que la frontière entre les deux résulte souvent d'un choix d'implémentation. En effet, s'il n'est pas conseillé de provoquer un assert qui arrête un serveur quand il reçoit un message erroné de la part d'une machine distante (souvent synonyme d'attaque de la part d'un «&nbsp;hacker&nbsp;» ou d'un problème de version de protocole), on peut tout de même provoquer un assert lorsqu'un utilisateur utilise mal une API dans le but d'aider à la mise au point du programme appelant. Dans ce dernier cas, on parle de programme instrumenté.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">L'implémentation peut aussi consister à générer un retour erreur en mode nominal (drapeau <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NDEBUG</b></font></font> défini) et un assert en mode mise au point (drapeau <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NDEBUG</b></font></font> non défini). Au risque de se retrouver confronté a des problèmes du type&nbsp;:</font></font></p> <ul> <li><font face="Arial, sans-serif"><font size="2"><a href="http://fr.wikipedia.org/wiki/Heisenbug">heisenbug</a>&nbsp;où le programme fonctionne dans un mode mais pas dans l'autre;</font></font></li> <li><font face="Arial, sans-serif"><font size="2"><a href="http://fr.wikipedia.org/wiki/Schr%C3%B6dinbug">schrödinbug</a>&nbsp;où l'instrumentation destinée à la mise au point contient une erreur de codage.</font></font></li> </ul> <h1 class="western"><a name="3._Mise_au_point_dun_programme"></a>3. Mise au point d'un programme</h1> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Pour comprendre l'utilité des asserts par rapport aux retours erreur. Nous allons écrire une petite API simple qui gère une liste d'entiers doublement chaînée comme indiqué en <a href="#Figure_1">figure 1</a>.</font></font></p> <div style="text-align: center;"><font face="Arial Narrow, sans-serif"><font size="2"><i><a name="Figure_1"></a>Figure 1&nbsp;: Liste d'entiers doublement chaînée</i></font></font></div> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto; text-align: center;"><font face="Arial, sans-serif"><font size="2"><img style="height: 331px; width: 726px;" alt="figure_1" src="prog_assert_fr_figure_1.jpg"><br> </font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial Narrow, sans-serif"><font size="2"><i><br> </i></font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">L'API est composée des fonctions et données simples suivantes&nbsp;:</font></font></p> <ul> <li><font face="Arial, sans-serif"><font size="2"><font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>entier_t</b></font></font> est la structure utilisée pour le chaînage des entiers;</font></font></li> <li><font face="Arial, sans-serif"><font size="2"><font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>tete</b></font></font> est le pointeur de début de liste;</font></font></li> <li><font face="Arial, sans-serif"><font size="2"><font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>insere()</b></font></font> pour insérer un élément en tête de liste;</font></font></li> <li><font face="Arial, sans-serif"><font size="2"><font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>enleve()</b></font></font> pour supprimer un élément de la liste;</font></font></li> <li><font face="Arial, sans-serif"><font size="2"><font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>liste()</b></font></font> pour afficher le contenu de la liste de la tête vers la queue.</font></font></li> </ul> <h2 class="western"><a name="3.1._Première_mouture_du_programme"></a>3.1. Première mouture du programme</h2> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Voici le fichier d'interface de l'API (<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>list.h</b></font></font>)&nbsp;:</font></font></p> <table style="text-align: left; background-color: silver; font-family: monospace; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#ifndef LIST_H</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#define LIST_H</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">typedef struct entier</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; int i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; struct entier *suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; struct entier *prec;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">} entier_t;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern entier_t *tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern void insere(entier_t *e);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern void enleve(entier_t *e);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Affiche la liste des elements</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern void liste(void);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#endif // LIST_H</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Voici le code source de l'API (<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>list.c</b></font></font>)&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"><font style="font-size: 9pt;" size="2">#include &lt;stdio.h&gt;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">#include "list.h"</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">// Tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">entier_t *tete = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">void insere(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si la liste est vide</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; if (NULL == tete)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; else // Nouvel element dans la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">void enleve(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si ce n'est pas le dernier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; if (e-&gt;suiv)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv-&gt;prec = e-&gt;prec;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"><font style="font-size: 9pt;" size="2">&nbsp; // Si ce n'est pas le premier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; if (e-&gt;prec)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec-&gt;suiv = e-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">else // C'est le premier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">tete = e-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">// Affiche la liste des elements</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">void liste(void)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">entier_t *p;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; while(p)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; printf("%d\n", p-&gt;i);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = p-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto; font-family: monospace;"> <font style="font-size: 9pt;" size="2">}</font></p> <br> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font size="2">Voici un petit programme qui utilise cette API (<font style="font-size: 9pt; font-weight: bold;" size="2">main.c</font>)&nbsp;:</font></p> <table style="text-align: left; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#include &lt;stdlib.h&gt;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#include "list.h"</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">int main(int ac, char *av[])</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">entier_t *p;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">unsigned int i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Remplissage de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; for (i = 0; i &lt; 10; i ++)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = (entier_t *)malloc(sizeof(entier_t));</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; insere(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p-&gt;i = i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Affichage du contenu de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; liste();</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Liberation de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; for (i = 0; i &lt; 10; i ++)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; enleve(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; free(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <font face="Arial, sans-serif"><font size="2">A l'exécution, le programme fonctionne comme espéré à savoir qu'on affiche la liste des entiers de 0 à 9 dans l'ordre décroissant&nbsp;:<br> </font></font> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">&gt; gcc -g list.c main.c</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&gt; ./a.out</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">9</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">8</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">7</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">5</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">4</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">3</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">2</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">1</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">0</font></p> </td> </tr> </tbody> </table> <br> <h2 class="western"><a name="3.2._Protéger_lAPI_contre_les_erreurs"></a>3.2. Protéger l'API contre les erreurs d'utilisation</h2> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">A y regarder de plus près, on remarque que l'utilisateur de l'API (l'auteur du fichier <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>main.c</b></font></font>) n'est pas très prudent car il fait appel à <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>malloc()</b></font></font> sans vérifier que le pointeur retourné est différent de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>. Par conséquent, l'API risque de recevoir un pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font> dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>insere()</b></font></font>. Il convient d'apporter des améliorations pour accroître la robustesse en testant la valeur du pointeur passé aux services.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Si on décide de garder l'interface de l'API en l'état, on considère implicitement que les fonctions <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>insere()</b></font></font> et <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>enleve()</b></font></font> ne sont pas supposées recevoir un pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>. Donc il faut mettre un assert&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">void insere(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL != e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">void enleve(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL != e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Mais on peut aussi modifier l'interface pour retourner une erreur en cas de paramètre égal à NULL&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">int</font></font> insere(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; if (NULL == e)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; errno = EINVAL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return -1;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; return 0;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">int</font></font> enleve(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; if (NULL == e)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; errno = EINVAL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return -1;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; return 0;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Les deux solutions se valent car il s'agit d'un choix de spécification de l'interface. La solution avec assert ne contraint pas l'utilisateur à tester le retour des services mais au cas ou <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>malloc()</b></font></font> retournerait <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>, l'assert se déclenchera. La solution avec retour erreur oblige normalement l'utilisateur à tester le retour des services. S'il ne le fait pas et que <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>malloc()</b></font></font> retourne <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>, alors son programme provoquera une erreur en dehors de l'API (en fait au niveau de l'instruction «&nbsp;<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>p-&gt;i = i;</b></font></font>&nbsp;» dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>main()</b></font></font>). L'essentiel dans ce dernier cas est que l'API est restée saine car elle s'est protégée.</font></font> </p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Une autre solution consisterait à combiner les deux précédentes&nbsp;: en mode mise au point, on provoque un assert et en mode nominal, on provoque un retour erreur.</font></font></p> <h2 class="western"><a name="3.3._Protéger_lAPI_contre_les_erreurs"></a>3.3. Protéger l'API contre les erreurs de programmation</h2> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">En relisant le source de l'API, on constate que l'on peut effectuer des vérifications «&nbsp;de routine&nbsp;» à divers endroits pour s'assurer que la liste chaînée est bien dans l'état attendu. Pour cela, on ajoute des asserts à des emplacements stratégiques afin d'aider au debug de l'API.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>enleve()</b></font></font>, on peut vérifier que le premier élément de la liste est bien pointé par <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>tete</b></font></font>&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">int enleve(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (NULL == e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; errno = EINVAL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return -1;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si ce n'est pas le dernier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (e-&gt;suiv)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv-&gt;prec = e-&gt;prec;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si ce n'est pas le premier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (e-&gt;prec)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec-&gt;suiv = e-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; else // C'est le premier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(tete == e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; return 0;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>liste()</b></font></font>, on peut vérifier que le premier élément a son pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>prec</b></font></font> à <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL </b></font></font>et que les éléments intermédiaires ont des pointeurs différents de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">// Affiche la liste des elements</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">void liste(void)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">entier_t *p;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; while(p)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; if (tete == p)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; &nbsp; assert(NULL == p-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; else</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; &nbsp; assert(NULL != p-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; printf("%d\n", p-&gt;i);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = p-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Si on relance la compilation et l'exécution du programme, on tombe sur un assert&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">&gt; gcc -g list.c main.c</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&gt; ./a.out</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">9</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">a.out: <font color="#ff0000"><font style="font-size: 9pt;" size="2">list.c:78: liste: Assertion `((void *)0) != p-&gt;prec' failed.</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">Abandon (core dumped)</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">L'erreur s'est produite dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>liste()</b></font></font> juste après l'affichage du premier élément (entier 9). A la lecture du message d'erreur, on déduit que le pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>prec</b></font></font> du deuxième élément est <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font> alors qu'il devrait pointer sur le premier élément. En allant voir dans la fonction <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>insere()</b></font></font> dans le cas «&nbsp;<font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>else</b></font></font>&nbsp;» qui concerne l'insertion d'un élément quand la liste n'est pas vide, on pourra voir qu'on a oublié d'assigner le pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>prec</b></font></font> de l'ancienne tête de liste avec l'adresse de la nouvelle tête de liste. En passant, on voit aussi que l'on peut ajouter un assert pour vérifier que le pointeur <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>prec</b></font></font> de la tête de liste est bien <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font>. D'où la correction suivante&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">int insere(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (NULL == e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; errno = EINVAL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return -1;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si la liste est vide</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (NULL == tete)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; else // Nouvel element dans la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(NULL == tete-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete-&gt;prec = e;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; return 0;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">On a ainsi démontré à quel point l'ajout d'asserts peut révéler des bugs de programmation à priori invisibles et surtout comment ils peuvent aider à la corrections des problèmes. Dans cet exemple, on n'a même pas eu besoin de lancer le debugger pour retrouver l'origine du problème !</font></font> </p> <h2 class="western"><a name="3.4._Instrumentation"></a>3.4. Instrumentation</h2> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Pour être le plus efficace possible en termes de debug, les asserts montrent toute leur puissance quand ils sont accompagnés d'une instrumentation du code. Précédemment, l'API a été augmentée de tests sur les paramètres et d'asserts sur les chaînages de la liste. Mais il faut prévoir des erreurs du style : on essaie d'insérer plusieurs fois le même élément, de retirer plusieurs fois le même élément, la mémoire a été corrompue de sorte à écraser un ou plusieurs éléments de la liste, un élément continue d'être utilisé alors qu'il a été désalloué par <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>free()</b></font></font>...</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Considérons par exemple une évolution du programme qui insère le deuxième élément de la liste une seconde fois&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#include &lt;stdlib.h&gt;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#include "list.h"</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">int main(int ac, char *av[])</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">entier_t *p;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">unsigned int i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Remplissage de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; for (i = 0; i &lt; 10; i ++)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = (entier_t *)malloc(sizeof(entier_t));</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; insere(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p-&gt;i = i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // BUG ! On insere le 2eme element une nouvelle fois</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; p = tete-&gt;suiv;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; insere(p);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Affichage du contenu de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; liste();</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Liberation de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; for (i = 0; i &lt; 10; i ++)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; enleve(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; free(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">A l'exécution, ce programme entre dans une boucle infinie malgré les asserts précédemment ajoutés car on se retrouve avec une liste où le premier élément pointe sur le deuxième qui lui même pointe sur le premier. D'où l'affichage des chiffres 8 et 9 en continu...</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">&gt; ./a.out</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">8</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">9</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">8</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">9</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Pour rendre l'API plus robuste (en mode mise au point tout au moins), il est nécessaire d'ajouter une instrumentation du code source. Celle-ci ne doit pas être trop intrusive dans le sens où elle ne doit pas nuire aux performances.</font></font> </p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Pour se protéger contre les insertions et retraits multiples d'un même élément, on peut forcer à <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font> les pointeurs <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>prec</b></font></font> et <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>suiv</b></font></font> au moment du retrait et s'assurer que ces pointeurs sont bien <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font> au moment de l'insertion. Mais lors de la première insertion, un élément résulte d'un <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>malloc()</b></font></font> et il n'est donc pas initialisé. Il faut ajouter à l'API une fonction d'allocation d'un élément pour garder la maîtrise sur l'initialisation des pointeurs&nbsp;: <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>alloue()</b></font></font>. Et par conséquent, il faut ajouter sa contre-partie pour désallouer un élément&nbsp;: <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>desalloue()</b></font></font>.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Pour se protéger contre les corruptions mémoire, un moyen efficace consiste à ajouter un «&nbsp;magic number&nbsp;» dans la structure de l'élément. C'est un champ initialisé à une valeur différente en fonction de l'état de la structure&nbsp;: alloué, chaîné, déchaîné ou désalloué. Cela fait double emploi avec les pointeurs mis à <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font> mais c'est que l'on peut appeler de la protection «&nbsp;ceinture-bretelles&nbsp;»&nbsp;: pour être sûr que le pantalon tiendra, on met à la fois une ceinture et des bretelles.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Pour se protéger contre des erreurs de programmation, on peut aussi introduire un compteur interne du nombre d'éléments dans la liste pour s'assurer que le pointeur à <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NULL</b></font></font> signifie bien que la liste est vide.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Tout le code d'instrumentation est sous le contrôle du drapeau <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NDEBUG</b></font></font> pour se donner la possibilité de le faire disparaître en mode «&nbsp;non debug&nbsp;».</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Voici le nouveau fichier <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>list.h </b></font></font>avec les modifications par rapport à la première mouture du programme&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#ifndef LIST_H</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#define LIST_H</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">typedef struct entier</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; int i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#ifndef NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; int magic;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#define ALLOUE 0x552F7AC8</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#define CHAINE 0x2C2F7BC8</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#define DECHAINE 0x5D4FCA71</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#define DESALLOUE 0x254B837C</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#endif // NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; struct entier *suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; struct entier *prec;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">} entier_t;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern entier_t *tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">// Alloue un element</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">extern entier_t *alloue(void);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">// Desalloue un element</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">extern void desalloue(entier_t *e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern <font color="#ff0000"><font style="font-size: 9pt;" size="2">int</font></font> insere(entier_t *e);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern <font color="#ff0000"><font style="font-size: 9pt;" size="2">int</font></font> enleve(entier_t *e);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Affiche la liste des elements</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">extern void liste(void);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#endif // LIST_H</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Voici le fichier <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>list.c</b></font></font> avec ses modifications également mises en relief&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#include &lt;stdio.h&gt;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#include &lt;assert.h&gt;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#include &lt;errno.h&gt;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#include &lt;stdlib.h&gt;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#include "list.h"</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">entier_t *tete = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#ifndef NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">// Nombre d'elements dans la liste</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">static unsigned int nb_elements = 0;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#endif // NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">// Alloue un element</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">entier_t *alloue(void)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">{</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">entier_t *p;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; p = (entier_t *)malloc(sizeof(entier_t));</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; if (NULL == p)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return NULL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#ifndef NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; p-&gt;suiv = p-&gt;prec = NULL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; p-&gt;magic = ALLOUE;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#endif // NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; return p;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">}</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">// Desalloue un element</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">void desalloue(entier_t *e)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">{</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // S'assurer que le parametre est valide</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL != e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // S'assurer que l'element n'est pas chaine</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(DECHAINE == e-&gt;magic);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL == e-&gt;suiv);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL == e-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // Detruire le magic number pour protection</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // contre reutilisation apres liberation</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#ifndef NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; e-&gt;magic = DESALLOUE;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#endif // NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // Desallocation</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; free(e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">}</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Insere un nouvel element en tete de liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">int </font></font>insere(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; if (NULL == e)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; errno = EINVAL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return -1;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // S'assurer que c'est bien un element alloue par nos service</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(ALLOUE == e-&gt;magic);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // S'assurer que l'element n'est pas deja chaine</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL == e-&gt;suiv);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(NULL == e-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si la liste est vide</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (NULL == tete)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(0 == nb_elements);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; else // Nouvel element dans la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(nb_elements &gt; 0);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> </font> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec = NULL;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(NULL == tete-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete-&gt;prec = e;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#ifndef NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // Un element supplementaire dans la liste</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; nb_elements ++;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // L'element est maintenant chaine</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; e-&gt;magic = CHAINE;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#endif // NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; return 0;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Enleve un element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">int</font></font> enleve(entier_t *e)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; if (NULL == e)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; errno = EINVAL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; return -1;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // S'assurer que c'est bien un element alloue par nos service</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert(CHAINE == e-&gt;magic);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si ce n'est pas le dernier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (e-&gt;suiv)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;suiv-&gt;prec = e-&gt;prec;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Si ce n'est pas le premier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; if (e-&gt;prec)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; e-&gt;prec-&gt;suiv = e-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; else // C'est le premier element de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(tete == e);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; tete = e-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#ifndef NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // Un element en moins dans la liste</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; nb_elements --;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // Changer l'etat de l'element</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; e-&gt;magic = DECHAINE;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; e-&gt;prec = e-&gt;suiv = NULL;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">#endif // NDEBUG</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // Verification du nombre d'elements dans la liste</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; // par rapport a la valeur du pointeur de tete</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert((NULL == tete) || (nb_elements &gt; 0));</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; assert((0 == nb_elements) || (NULL != tete));</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; return 0;</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">// Affiche la liste des elements</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">void liste(void)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">entier_t *p;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; while(p)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; // Verifier qu'il n'y a pas eu de corruption memoire</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; assert(CHAINE == p-&gt;magic);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; if (tete == p)</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; &nbsp; assert(NULL == p-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; else</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; {</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; &nbsp; assert(NULL != p-&gt;prec);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font color="#ff0000"> <font style="font-size: 9pt;" size="2"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; }</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; printf("%d\n", p-&gt;i);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = p-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Le programme <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>main.c</b></font></font> est modifié pour utiliser respectivement <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>alloue()</b></font></font> et <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>desalloue()</b></font></font> en lieu et place de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>malloc()</b></font></font> et <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>free()</b></font></font>&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">#include "list.h"</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">int main(int ac, char *av[])</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">{</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">entier_t *p;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">unsigned int i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Remplissage de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; for (i = 0; i &lt; 10; i ++)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = alloue();</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; insere(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p-&gt;i = i;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // BUG ! On insere le 2eme element une nouvelle fois</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete-&gt;suiv;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; insere(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Affichage du contenu de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; liste();</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <br> </p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; // Liberation de la liste</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; for (i = 0; i &lt; 10; i ++)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; {</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; enleve(p);</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2"><font color="#ff0000"><font style="font-size: 9pt;" size="2">&nbsp; &nbsp; desalloue(p);</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; &nbsp; p = tete;</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&nbsp; }</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">}</font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><font face="Arial, sans-serif"><font size="2">Après recompilation et exécution, il se produit, comme espéré, un assert au niveau de la double insertion&nbsp;:</font></font></p> <table style="text-align: left; font-family: monospace; background-color: silver; margin-left: auto; margin-right: auto;" border="1" cellpadding="2" cellspacing="2"> <tbody> <tr> <td style="white-space: nowrap;"> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"><font style="font-size: 9pt;" size="2">&gt; gcc -g list.c main.c</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&gt; ./a.out</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">a.out: list.c:65: insere: <font color="#ff0000"><font style="font-size: 9pt;" size="2">Assertion `0x552F7AC8 == e-&gt;magic' failed</font></font>.</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">Abandon (core dumped)</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">&gt; gdb ./a.out core</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">[...]</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">(gdb) where</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#0 0xffffe410 in __kernel_vsyscall ()</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#1 0xb7dbf875 in raise () from /lib/tls/i686/cmov/libc.so.6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#2 0xb7dc1201 in abort () from /lib/tls/i686/cmov/libc.so.6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#3 0xb7db8b6e in __assert_fail () from /lib/tls/i686/cmov/libc.so.6</font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#4 0x080485cb in <font color="#ff0000"><font style="font-size: 9pt;" size="2">insere (e=0x804a0c8) at list.c:65</font></font></font></p> <p style="background: transparent none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; margin-bottom: 0cm; page-break-before: auto;"> <font style="font-size: 9pt;" size="2">#5 0x080489b9 in <font color="#ff0000"><font style="font-size: 9pt;" size="2">main () at main.c:19</font></font></font></p> </td> </tr> </tbody> </table> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"><br> </p> <h1 class="western"><a name="4._Conclusion"></a>4. Conclusion</h1> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Grâce à l'introduction d'asserts et d'une instrumentation comme des compteurs, des «&nbsp;magic numbers&nbsp;» pour marquer les structures de données et d'autres mécanismes qui aident à détecter les corruptions de toute sorte, on a pu mettre en évidence des erreurs de programmation pernicieuses. L'introduction d'asserts va bien-sûr de pair avec un environnement de test car le programme cité dans cet article contient peut-être d'autres problèmes qui pourraient être mis en évidence avec des tests dignes de ce nom.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Certains reprocheront à la macro <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> de porter atteinte aux performances car elle provoque l'exécution de tests supplémentaires. On peut aussi lui reprocher de nuire à la lisibilité du code source à cause des instrumentations. Pour ne pas en abuser, il faut les positionner à des endroits stratégiques. De plus, on a vu qu'il est possible de supprimer les asserts en compilant le programme avec la définition de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NDEBUG</b></font></font> (au risque de se retrouver confronté à des bugs du type <a href="http://fr.wikipedia.org/wiki/Heisenbug">heisenbug</a>). Toutefois, l'expérience montre que de plus en plus d'éditeurs de logiciels livrent leurs programmes avec les asserts de sorte à ce que le client puisse remonter les messages d'erreurs qui se seraient déclenchés lors d'une utilisation non prévue (<a href="http://fr.wikipedia.org/wiki/Schr%C3%B6dinbug">schrödinbug</a>). En effet, plus un logiciel est complexe, plus il est difficile d'avoir un environnement de test capable de prouver que le code est exempt de «&nbsp;bugs&nbsp;».</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">L'utilisation des asserts est aussi un moyen efficace de se protéger contre le vieillissement d'un code source. Pour un logiciel donné, il n'est pas rare que le ou les développeurs d'origine ne soient plus les mêmes qui le modifient plusieurs mois ou années après. Les corrections ou améliorations peuvent ne pas être très rigoureuses par manque de compréhension. En conséquence, le code peut devenir de moins en moins lisible et donc souvent de plus en plus fragile pour devenir un programme qui génère de plus en plus de problèmes. Si les asserts sont systématiquement utilisés, ils vont servir de garde-fous pour aider les développeurs à comprendre et à mettre au point le logiciel car tout écart de leurs parts va provoquer des erreurs.</font></font></p> <h1 class="western"><a name="Liens"></a>Liens</h1> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;"> <font face="Arial, sans-serif"><font size="2">[1] Heisenbug&nbsp;: <a href="http://fr.wikipedia.org/wiki/Heisenbug">http://fr.wikipedia.org/wiki/Heisenbug</a></font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;"> <font face="Arial, sans-serif"><font size="2">[2] Schrödinbug&nbsp;: <a href="http://fr.wikipedia.org/wiki/Schr%C3%B6dinbug">http://fr.wikipedia.org/wiki/Schrödinbug</a></font></font></p> <h1 class="western"><a name="A_propos_de_lauteur"></a>A propos de l'auteur</h1> <font face="Arial, sans-serif"><font size="2">L'auteur est ingénieur en informatique travaillant en France. Il peut être contacté <a href="http://rachid.koucha.free.fr/contact/contact.html">ici</a> ou vous pouvez consulter son site <a href="http://rachid.koucha.free.fr/">WEB</a>.<br> </font></font> <br> <div style="text-align: right;"><a href="../../index.html"><small>Retour à la page d'accueil</small></a><br> <a href="../documents_techniques.html"><small>Retour à la page précédente</small></a> <span style="font-weight: bold;"></span><br> <span style="font-weight: bold;"></span></div> <span style="font-weight: bold;"></span><br> <br> </body></html></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">Certains reprocheront &agrave; la macro <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>assert()</b></font></font> de porter atteinte aux performances car elle provoque l'ex&eacute;cution de tests suppl&eacute;mentaires. On peut aussi lui reprocher de nuire &agrave; la lisibilit&eacute; du code source &agrave; cause des instrumentations. Pour ne pas en abuser, il faut les positionner &agrave; des endroits strat&eacute;giques. De plus, on a vu qu'il est possible de supprimer les asserts en compilant le programme avec la d&eacute;finition de <font face="Bitstream Vera Sans Mono, monospace"><font style="font-size: 9pt;" size="2"><b>NDEBUG</b></font></font> (au risque de se retrouver confront&eacute; &agrave; des bugs du type <a href="http://fr.wikipedia.org/wiki/Heisenbug">heisenbug</a>). Toutefois, l'exp&eacute;rience montre que de plus en plus d'&eacute;diteurs de logiciels livrent leurs programmes avec les asserts de sorte &agrave; ce que le client puisse remonter les messages d'erreurs qui se seraient d&eacute;clench&eacute;s lors d'une utilisation non pr&eacute;vue (<a href="http://fr.wikipedia.org/wiki/Schr%C3%B6dinbug">schr&ouml;dinbug</a>). En effet, plus un logiciel est complexe, plus il est difficile d'avoir un environnement de test capable de prouver que le code est exempt de &laquo;&nbsp;bugs&nbsp;&raquo;.</font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;" align="justify"> <font face="Arial, sans-serif"><font size="2">L'utilisation des asserts est aussi un moyen efficace de se prot&eacute;ger contre le vieillissement d'un code source. Pour un logiciel donn&eacute;, il n'est pas rare que le ou les d&eacute;veloppeurs d'origine ne soient plus les m&ecirc;mes qui le modifient plusieurs mois ou ann&eacute;es apr&egrave;s. Les corrections ou am&eacute;liorations peuvent ne pas &ecirc;tre tr&egrave;s rigoureuses par manque de compr&eacute;hension. En cons&eacute;quence, le code peut devenir de moins en moins lisible et donc souvent de plus en plus fragile pour devenir un programme qui g&eacute;n&egrave;re de plus en plus de probl&egrave;mes. Si les asserts sont syst&eacute;matiquement utilis&eacute;s, ils vont servir de garde-fous pour aider les d&eacute;veloppeurs &agrave; comprendre et &agrave; mettre au point le logiciel car tout &eacute;cart de leurs parts va provoquer des erreurs.</font></font></p> <h1 class="western"><a name="Liens"></a>Liens</h1> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;"> <font face="Arial, sans-serif"><font size="2">[1] Heisenbug&nbsp;: <a href="http://fr.wikipedia.org/wiki/Heisenbug">http://fr.wikipedia.org/wiki/Heisenbug</a></font></font></p> <p style="margin-top: 0.2cm; margin-bottom: 0.1cm; page-break-before: auto;"> <font face="Arial, sans-serif"><font size="2">[2] Schr&ouml;dinbug&nbsp;: <a href="http://fr.wikipedia.org/wiki/Schr%C3%B6dinbug">http://fr.wikipedia.org/wiki/Schr&ouml;dinbug</a></font></font></p> <h1 class="western"><a name="A_propos_de_lauteur"></a>A propos de l'auteur</h1> <font face="Arial, sans-serif"><font size="2">L'auteur est ing&eacute;nieur en informatique travaillant en France. Il peut &ecirc;tre contact&eacute; <a href="http://rachid.koucha.free.fr/contact/contact.html">ici</a> ou vous pouvez consulter son site <a href="http://rachid.koucha.free.fr/">WEB</a>.<br> </font></font> <br> <div style="text-align: right;"><a href="../../index.html"><small>Retour &agrave; la page d'accueil</small></a><br> <a href="../documents_techniques.html"><small>Retour &agrave; la page pr&eacute;c&eacute;dente</small></a> <span style="font-weight: bold;"></span><br> <span style="font-weight: bold;"></span></div> <span style="font-weight: bold;"></span><br> <br> </body> </html>
{ "content_hash": "05221e2bcfebfc18c25d16e7eb0ae36f", "timestamp": "", "source": "github", "line_count": 2707, "max_line_length": 422, "avg_line_length": 85.49021056520132, "alnum_prop": 0.6917751985550207, "repo_name": "yubo/program", "id": "e992936ddba81c6eba9ad86e49a90edcb99a8f6a", "size": "231422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmake/projects/rachid.koucha.free.fr/tech_corner/prog_assert_fr.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "75417" }, { "name": "Awk", "bytes": "5739" }, { "name": "C", "bytes": "3346469" }, { "name": "C++", "bytes": "867833" }, { "name": "CMake", "bytes": "46139" }, { "name": "E", "bytes": "744" }, { "name": "GDB", "bytes": "86" }, { "name": "Gnuplot", "bytes": "122" }, { "name": "Go", "bytes": "541317" }, { "name": "Groovy", "bytes": "768" }, { "name": "HTML", "bytes": "1706744" }, { "name": "Java", "bytes": "5363664" }, { "name": "JavaScript", "bytes": "30531" }, { "name": "Lex", "bytes": "4326" }, { "name": "Lua", "bytes": "421" }, { "name": "M4", "bytes": "3025" }, { "name": "Makefile", "bytes": "238992" }, { "name": "Objective-C", "bytes": "4254" }, { "name": "PHP", "bytes": "41" }, { "name": "Python", "bytes": "22955" }, { "name": "Roff", "bytes": "271184" }, { "name": "Shell", "bytes": "60487" }, { "name": "Smarty", "bytes": "706" }, { "name": "Yacc", "bytes": "9248" } ], "symlink_target": "" }
typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; #define MDFN_FASTCALL #define INLINE inline #define MDFN_COLD #define MDFN_HOT #define NO_INLINE #define NO_CLONE #define MDFN_WARN_UNUSED_RESULT #define MDFN_NOWARN_UNUSED __attribute__((unused)) #define MDFN_UNLIKELY(p) (p) #define MDFN_LIKELY(p) (p) //#define MDFN_ASSUME_ALIGNED(p, align) ((decltype(p))__builtin_assume_aligned((p), (align))) #define MDFN_ASSUME_ALIGNED(p, align) (p) #define trio_snprintf snprintf #define trio_vprintf vprintf #define trio_printf printf #define trio_sprintf sprintf #define TRUE true #define FALSE false #ifndef __alignas_is_defined #define alignas(p) #endif #define override // remove for gcc 4.7 #define final #define gettext_noop(s) (s) #define MDFN_MASTERCLOCK_FIXED(n) ((int64)((double)(n) * (1LL << 32))) static INLINE void MDFN_FastArraySet(uint32 *dst, const uint32 value, const size_t count) { uint32 *const end = dst + count; while (dst < end) *dst++ = value; } #define _(a) (a) typedef struct { // Pitch(32-bit) must be equal to width and >= the "fb_width" specified in the MDFNGI struct for the emulated system. // Height must be >= to the "fb_height" specified in the MDFNGI struct for the emulated system. // The framebuffer pointed to by surface->pixels is written to by the system emulation code. uint32 *pixels; int pitch32; // Pointer to an array of int32, number of elements = fb_height, set by the driver code. Individual elements written // to by system emulation code. If the emulated system doesn't support multiple screen widths per frame, or if you handle // such a situation by outputting at a constant width-per-frame that is the least-common-multiple of the screen widths, then // you can ignore this. If you do wish to use this, you must set all elements every frame. int32 *LineWidths; // Pointer to sound buffer, set by the driver code, that the emulation code should render sound to. int16 *SoundBuf; // Number of cycles that this frame consumed, using MDFNGI::MasterClock as a time base. // Set by emulation code. int64 MasterCycles; // Maximum size of the sound buffer, in frames. Set by the driver code. int32 SoundBufMaxSize; // Number of frames currently in internal sound buffer. Set by the system emulation code, to be read by the driver code. int32 SoundBufSize; // Set by the system emulation code every frame, to denote the horizontal and vertical offsets of the image, and the size // of the image. If the emulated system sets the elements of LineWidths, then the width(w) of this structure // is ignored while drawing the image. int32 y, w, h; // Set(optionally) by emulation code. If InterlaceOn is true, then assume field height is 1/2 DisplayRect.h, and // only every other line in surface (with the start line defined by InterlacedField) has valid data // (it's up to internal Mednafen code to deinterlace it). bool InterlaceOn; bool InterlaceField; // if true, sip rendering bool skip; } EmulateSpecStruct; #define MDFN_printf printf #define MDFN_PrintError(...) printf #include "endian.h" #include "math_ops.h" #include "../emulibc/emulibc.h" #include "../emulibc/waterboxcore.h" // settings extern int Setting_HighDotclockWidth; extern int Setting_CdSpeed; extern int Setting_SlStart; extern int Setting_SlEnd; extern double Setting_ResampRateError; extern int Setting_ResampQuality; extern int Setting_CpuEmulation; // 0 = fast, 1 = accurate, 2 = auto extern bool Setting_NoSpriteLimit; extern bool Setting_AdpcmBuggy; extern bool Setting_AdpcmNoClicks; extern bool Setting_ChromaInterpolate; extern int Setting_PortDevice[2]; extern bool Setting_PixelPro;
{ "content_hash": "1a54a9e6b965338ea43bbe8052b4a301", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 125, "avg_line_length": 33.892857142857146, "alnum_prop": 0.7510537407797682, "repo_name": "ircluzar/RTC3", "id": "16f349b2fb32fc4385ed597a7651e752cdbb9844", "size": "3945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/defs.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "77250" }, { "name": "Batchfile", "bytes": "11077" }, { "name": "C", "bytes": "10464062" }, { "name": "C#", "bytes": "14062504" }, { "name": "C++", "bytes": "15252473" }, { "name": "CSS", "bytes": "74" }, { "name": "GLSL", "bytes": "6610" }, { "name": "HTML", "bytes": "426873" }, { "name": "Limbo", "bytes": "15313" }, { "name": "Lua", "bytes": "312676" }, { "name": "Makefile", "bytes": "127427" }, { "name": "Objective-C", "bytes": "40789" }, { "name": "PHP", "bytes": "863004" }, { "name": "POV-Ray SDL", "bytes": "206" }, { "name": "Python", "bytes": "27842" }, { "name": "Shell", "bytes": "19693" }, { "name": "Smalltalk", "bytes": "1719" } ], "symlink_target": "" }
#import "AppDelegate.h" #import <React/RCTBundleURLProvider.h> #import <React/RCTRootView.h> @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"reactNativeDemo" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } @end
{ "content_hash": "bbdfcce6729bb79b946bf43004ca180f", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 118, "avg_line_length": 36.2, "alnum_prop": 0.6850828729281768, "repo_name": "zhanglizhao/react-native-knowledge", "id": "4bbd493c80ea336d2534f36b6328a01e076d0887", "size": "1394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nativeExample/reactNativeDemo/ios/reactNativeDemo/AppDelegate.m", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "36913" }, { "name": "HTML", "bytes": "74551" }, { "name": "Java", "bytes": "4206" }, { "name": "JavaScript", "bytes": "4103257" }, { "name": "Objective-C", "bytes": "13302" }, { "name": "Python", "bytes": "4947" } ], "symlink_target": "" }
package blv.util; import java.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Timer extends Thread { ActionListener target; int delay; public Timer(ActionListener target, int delay){ this.target = target; this.delay = delay; } public void run(){ while (true){ if (delay > 0){ try { sleep(delay); target.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Timer")); } catch (Exception e){ break; } } else { // Will end the thread. break; } } } }
{ "content_hash": "2fb5a466a7a5150cff153d9727e4db09", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 90, "avg_line_length": 16.4, "alnum_prop": 0.6428571428571429, "repo_name": "bvarner/javashare", "id": "481840e42531982f0b8243aeb11713802a6cdbc7", "size": "574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/blv/util/Timer.java", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "380316" } ], "symlink_target": "" }
from rest_framework.filters import ( FilterSet ) from csacompendium.research.models import Diversity class DiversityListFilter(FilterSet): """ Filter query list from diversity database table """ class Meta: model = Diversity fields = { 'diversity': ['iexact', 'icontains'], } order_by = ['diversity']
{ "content_hash": "795221887754f109787fbd745465d658", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 51, "avg_line_length": 22.9375, "alnum_prop": 0.6212534059945504, "repo_name": "nkoech/csacompendium", "id": "bc873a4059a65abdcb27d698675af294686707b0", "size": "367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "csacompendium/research/api/diversity/filters.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8694" }, { "name": "HTML", "bytes": "29087" }, { "name": "JavaScript", "bytes": "11616" }, { "name": "Python", "bytes": "527150" } ], "symlink_target": "" }
begin require 'simplecov' SimpleCov.start do add_filter "/spec/" end rescue LoadError => e end # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # Require this file using `require "spec_helper"` to ensure that it is only # loaded once. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' end require File.join(File.dirname(__FILE__), '..', 'lib', 'ofcp_scoring.rb')
{ "content_hash": "68f87959a9a44607d2dfa3a68c38df62", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 77, "avg_line_length": 32.714285714285715, "alnum_prop": 0.7194323144104804, "repo_name": "clayton/ofcp_scoring", "id": "e5a78c975df05e55085a7ff6e4f298579f386274", "size": "916", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "34241" } ], "symlink_target": "" }
X509 *parse_b64der_cert(const char* cert_data) { std::vector<unsigned char> data = DecodeBase64(cert_data); assert(data.size() > 0); const unsigned char* dptr = &data[0]; X509 *cert = d2i_X509(NULL, &dptr, data.size()); assert(cert); return cert; } // // Test payment request handling // static SendCoinsRecipient handleRequest(PaymentServer* server, std::vector<unsigned char>& data) { RecipientCatcher sigCatcher; QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), &sigCatcher, SLOT(getRecipient(SendCoinsRecipient))); // Write data to a temp file: QTemporaryFile f; f.open(); f.write((const char*)&data[0], data.size()); f.close(); // Create a QObject, install event filter from PaymentServer // and send a file open event to the object QObject object; object.installEventFilter(server); QFileOpenEvent event(f.fileName()); // If sending the event fails, this will cause sigCatcher to be empty, // which will lead to a test failure anyway. QCoreApplication::sendEvent(&object, &event); QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)), &sigCatcher, SLOT(getRecipient(SendCoinsRecipient))); // Return results from sigCatcher return sigCatcher.recipient; } void PaymentServerTests::paymentServerTests() { SelectParams(CBaseChainParams::MAIN); OptionsModel optionsModel; PaymentServer* server = new PaymentServer(NULL, false); X509_STORE* caStore = X509_STORE_new(); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64)); PaymentServer::LoadRootCAs(caStore); server->setOptionsModel(&optionsModel); server->uiReady(); std::vector<unsigned char> data; SendCoinsRecipient r; QString merchant; // Now feed PaymentRequests to server, and observe signals it produces // This payment request validates directly against the // caCert1 certificate authority: data = DecodeBase64(paymentrequest1_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("testmerchant.org")); // Signed, but expired, merchant cert in the request: data = DecodeBase64(paymentrequest2_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // 10-long certificate chain, all intermediates valid: data = DecodeBase64(paymentrequest3_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("testmerchant8.org")); // Long certificate chain, with an expired certificate in the middle: data = DecodeBase64(paymentrequest4_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // Validly signed, but by a CA not in our root CA list: data = DecodeBase64(paymentrequest5_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // Try again with no root CA's, verifiedMerchant should be empty: caStore = X509_STORE_new(); PaymentServer::LoadRootCAs(caStore); data = DecodeBase64(paymentrequest1_cert1_BASE64); r = handleRequest(server, data); r.paymentRequest.getMerchant(caStore, merchant); QCOMPARE(merchant, QString("")); // Load second root certificate caStore = X509_STORE_new(); X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64)); PaymentServer::LoadRootCAs(caStore); QByteArray byteArray; // For the tests below we just need the payment request data from // paymentrequestdata.h parsed + stored in r.paymentRequest. // // These tests require us to bypass the following normal client execution flow // shown below to be able to explicitly just trigger a certain condition! // // handleRequest() // -> PaymentServer::eventFilter() // -> PaymentServer::handleURIOrFile() // -> PaymentServer::readPaymentRequestFromFile() // -> PaymentServer::processPaymentRequest() // Contains a testnet paytoaddress, so payment request network doesn't match client network: data = DecodeBase64(paymentrequest1_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized, because network "main" is default, even for // uninizialized payment requests and that will fail our test here. QVERIFY(r.paymentRequest.IsInitialized()); QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false); // Expired payment request (expires is set to 1 = 1970-01-01 00:00:01): data = DecodeBase64(paymentrequest2_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // compares 1 < GetTime() == false (treated as expired payment request) QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true); // Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t): // 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t) // -1 is 1969-12-31 23:59:59 (for a 32 bit time values) data = DecodeBase64(paymentrequest3_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request) QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false); // Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64): // 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t) // 0 is 1970-01-01 00:00:00 (for a 32 bit time values) data = DecodeBase64(paymentrequest4_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // compares -9223372036854775808 < GetTime() == true (treated as expired payment request) QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true); // Test BIP70 DoS protection: unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1]; GetRandBytes(randData, sizeof(randData)); // Write data to a temp file: QTemporaryFile tempFile; tempFile.open(); tempFile.write((const char*)randData, sizeof(randData)); tempFile.close(); QCOMPARE(PaymentServer::readPaymentRequestFromFile(tempFile.fileName(), r.paymentRequest), false); // Payment request with amount overflow (amount is set to 21000001 SRI): data = DecodeBase64(paymentrequest5_cert2_BASE64); byteArray = QByteArray((const char*)&data[0], data.size()); r.paymentRequest.parse(byteArray); // Ensure the request is initialized QVERIFY(r.paymentRequest.IsInitialized()); // Extract address and amount from the request QList<std::pair<CScript, CAmount> > sendingTos = r.paymentRequest.getPayTo(); foreach (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) { CTxDestination dest; if (ExtractDestination(sendingTo.first, dest)) QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false); } delete server; } void RecipientCatcher::getRecipient(SendCoinsRecipient r) { recipient = r; }
{ "content_hash": "0291d43bf7d9c9f1aeb2c5b30e0b2275", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 103, "avg_line_length": 41.58510638297872, "alnum_prop": 0.7111793297518547, "repo_name": "CoinAge-DAO/solari", "id": "089c13950b1301f052cf93b7625e468224f3e7b6", "size": "8392", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/test/paymentservertests.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "448543" }, { "name": "C++", "bytes": "3558773" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "19722" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2099" }, { "name": "Makefile", "bytes": "58619" }, { "name": "Objective-C", "bytes": "2020" }, { "name": "Objective-C++", "bytes": "7300" }, { "name": "Protocol Buffer", "bytes": "2304" }, { "name": "Python", "bytes": "220621" }, { "name": "QMake", "bytes": "2018" }, { "name": "Shell", "bytes": "37774" } ], "symlink_target": "" }
<?php namespace GoogleApi\Service; use GoogleApi\Io\HttpRequest; use GoogleApi\Io\REST; use GoogleApi\Client; use GoogleApi\Config; /** * Implements the actual methods/resources of the discovered Google API using magic function * calling overloading (__call()), which on call will see if the method name (plus.activities.list) * is available in this service, and if so construct an HttpRequest representing it. * * @author Chris Chabot <chabotc@google.com> * @author Chirag Shah <chirags@google.com> * */ class ServiceResource { // Valid query parameters that work, but don't appear in discovery. private $stackParameters = array( 'alt' => array('type' => 'string', 'location' => 'query'), 'boundary' => array('type' => 'string', 'location' => 'query'), 'fields' => array('type' => 'string', 'location' => 'query'), 'trace' => array('type' => 'string', 'location' => 'query'), 'userIp' => array('type' => 'string', 'location' => 'query'), 'userip' => array('type' => 'string', 'location' => 'query'), 'file' => array('type' => 'complex', 'location' => 'body'), 'data' => array('type' => 'string', 'location' => 'body'), 'mimeType' => array('type' => 'string', 'location' => 'header'), 'uploadType' => array('type' => 'string', 'location' => 'query'), 'mediaUpload' => array('type' => 'complex', 'location' => 'query'), ); /** @var Service $service */ private $service; /** @var string $serviceName */ private $serviceName; /** @var string $resourceName */ private $resourceName; /** @var array $methods */ private $methods; public function __construct($service, $serviceName, $resourceName, $resource) { $this->service = $service; $this->serviceName = $serviceName; $this->resourceName = $resourceName; $this->methods = isset($resource['methods']) ? $resource['methods'] : array($resourceName => $resource); } /** * @param $name * @param $arguments * @return HttpRequest|array * @throws \GoogleApi\Exception */ public function __call($name, $arguments) { if (!isset($this->methods[$name])) { throw new \GoogleApi\Exception("Unknown function: {$this->serviceName}->{$this->resourceName}->{$name}()"); } $method = $this->methods[$name]; $parameters = $arguments[0]; // postBody is a special case since it's not defined in the discovery document as parameter, but we abuse the param entry for storing it $postBody = null; if (isset($parameters['postBody'])) { if (is_object($parameters['postBody'])) { $this->stripNull($parameters['postBody']); } // Some APIs require the postBody to be set under the data key. if (is_array($parameters['postBody']) && 'latitude' == $this->serviceName) { if (!isset($parameters['postBody']['data'])) { $rawBody = $parameters['postBody']; unset($parameters['postBody']); $parameters['postBody']['data'] = $rawBody; } } $postBody = is_array($parameters['postBody']) || is_object($parameters['postBody']) ? json_encode($parameters['postBody']) : $parameters['postBody']; unset($parameters['postBody']); if (isset($parameters['optParams'])) { $optParams = $parameters['optParams']; unset($parameters['optParams']); $parameters = array_merge($parameters, $optParams); } } if (!isset($method['parameters'])) { $method['parameters'] = array(); } $method['parameters'] = array_merge($method['parameters'], $this->stackParameters); foreach ($parameters as $key => $val) { if ($key != 'postBody' && !isset($method['parameters'][$key])) { throw new \GoogleApi\Exception("($name) unknown parameter: '$key'"); } } if (isset($method['parameters'])) { foreach ($method['parameters'] as $paramName => $paramSpec) { if (isset($paramSpec['required']) && $paramSpec['required'] && !isset($parameters[$paramName])) { throw new \GoogleApi\Exception("($name) missing required param: '$paramName'"); } if (isset($parameters[$paramName])) { $value = $parameters[$paramName]; $parameters[$paramName] = $paramSpec; $parameters[$paramName]['value'] = $value; unset($parameters[$paramName]['required']); } else { unset($parameters[$paramName]); } } } // Discovery v1.0 puts the canonical method id under the 'id' field. if (!isset($method['id'])) { $method['id'] = $method['rpcMethod']; } // Discovery v1.0 puts the canonical path under the 'path' field. if (!isset($method['path'])) { $method['path'] = $method['restPath']; } $restBasePath = $this->service->restBasePath; // Process Media Request $contentType = false; if (isset($method['mediaUpload'])) { $media = MediaFileUpload::process($postBody, $parameters); if ($media) { $contentType = isset($media['content-type']) ? $media['content-type'] : null; $postBody = isset($media['postBody']) ? $media['postBody'] : null; $restBasePath = $method['mediaUpload']['protocols']['simple']['path']; $method['path'] = ''; } } $url = REST::createRequestUri($restBasePath, $method['path'], $parameters); $httpRequest = new HttpRequest($url, $method['httpMethod'], null, $postBody); if ($postBody) { $contentTypeHeader = array(); if (isset($contentType) && $contentType) { $contentTypeHeader['content-type'] = $contentType; } else { $contentTypeHeader['content-type'] = 'application/json; charset=UTF-8'; $contentTypeHeader['content-length'] = Utils::getStrLen($postBody); } $httpRequest->setRequestHeaders($contentTypeHeader); } $httpRequest = Client::$auth->sign($httpRequest); if (Client::$useBatch) { return $httpRequest; } // Terminate immediatly if this is a resumable request. if (isset($parameters['uploadType']['value']) && 'resumable' == $parameters['uploadType']['value'] ) { return $httpRequest; } return REST::execute($httpRequest); } protected function useObjects() { return Config::get('use_objects', false); } protected function stripNull(&$o) { $o = (array)$o; foreach ($o as $k => $v) { if ($v === null || strstr($k, "\0*\0__")) { unset($o[$k]); } elseif (is_object($v) || is_array($v)) { $this->stripNull($o[$k]); } } } }
{ "content_hash": "f332aaccbbdecae04fd15de3ad21093f", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 144, "avg_line_length": 37.9119170984456, "alnum_prop": 0.5339620062867295, "repo_name": "Sorien/google-api", "id": "f6d50bd8bac3ca3585ffe7beb14ea246c2240001", "size": "7912", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/GoogleApi/Service/ServiceResource.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "967609" } ], "symlink_target": "" }
package org.neo4j.ogm.domain.canonical.hierarchies; import org.neo4j.ogm.annotation.RelationshipEntity; /** * @author vince */ @RelationshipEntity(type = "CR") public class CR extends R { //some stuff here ... }
{ "content_hash": "423daf2f3b5fc017ae423a72d26d10f8", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 51, "avg_line_length": 18.416666666666668, "alnum_prop": 0.7149321266968326, "repo_name": "neo4j/neo4j-ogm", "id": "51e1c91c30050bb60e9145d16d4f47077e283301", "size": "893", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "neo4j-ogm-tests/neo4j-ogm-integration-tests/src/test/java/org/neo4j/ogm/domain/canonical/hierarchies/CR.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "59863" }, { "name": "Java", "bytes": "3445039" }, { "name": "JavaScript", "bytes": "30397" }, { "name": "Kotlin", "bytes": "33151" }, { "name": "Shell", "bytes": "450" }, { "name": "Slim", "bytes": "672" }, { "name": "sed", "bytes": "550" } ], "symlink_target": "" }
require 'google/storage/network/base' module Google module Storage module Network # A wrapper class for a Get Request class Get < Google::Storage::Network::Base end end end end
{ "content_hash": "6691f8457143cfc0a60fe7114f618ee6", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 48, "avg_line_length": 18.90909090909091, "alnum_prop": 0.6730769230769231, "repo_name": "GoogleCloudPlatform/puppet-google-storage", "id": "bf0da734e2b044549dce425999cf1541851d04b6", "size": "1364", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/google/storage/network/get.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Puppet", "bytes": "16506" }, { "name": "Ruby", "bytes": "428522" } ], "symlink_target": "" }
title: "v0.28.2 - 2018-07-23" linkTitle: "v0.28.2 - 2018-07-23" weight: -42 --- <html> <head> <title>kubernetes/minikube - Leaderboard</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap" rel="stylesheet"> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load("current", {packages:["corechart"]}); </script> <style> body { font-family: 'Open Sans', sans-serif; background-color: #f7f7fa; padding: 1em; } h1 { color: rgba(66,133,244); margin-bottom: 0em; } .subtitle { color: rgba(23,90,201); font-size: small; } pre { white-space: pre-wrap; word-wrap: break-word; color: #666; font-size: small; } h2.cli { color: #666; } h2 { color: #333; } .board p { font-size: small; color: #999; text-align: center; } .board { clear: right; display: inline-block; padding: 0.5em; margin: 0.5em; background-color: #fff; } .board:nth-child(4n+3) { border: 2px solid rgba(66,133,244,0.25); color: rgba(66,133,244); } .board:nth-child(4n+2) { border: 2px solid rgba(219,68,55,0.25); color: rgba rgba(219,68,55); } .board:nth-child(4n+1) { border: 2px solid rgba(244,160,0,0.25); color: rgba(244,160,0); } .board:nth-child(4n) { border: 2px solid rgba(15,157,88,0.25); color: rgba(15,157,88); } h3 { text-align: center; } </style> </head> <body> <h1>kubernetes/minikube</h1> <div class="subtitle">2018-07-16 &mdash; 2018-07-23</div> <h2>Reviewers</h2> <div class="board"> <h3>Most Influential</h3> <p># of Merged PRs reviewed</p> <div id="chart_reviewCounts" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawreviewCounts); function drawreviewCounts() { var data = new google.visualization.arrayToDataTable([ ['', '# of Merged PRs reviewed', { role: 'annotation' }], ["dlorenc", 2, "2"], ["vishh", 1, "1"], ["aaron-prindle", 1, "1"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_reviewCounts')); chart.draw(data, options); }; </script> </div> <div class="board"> <h3>Most Helpful</h3> <p># of words written in merged PRs</p> <div id="chart_reviewWords" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawreviewWords); function drawreviewWords() { var data = new google.visualization.arrayToDataTable([ ['', '# of words written in merged PRs', { role: 'annotation' }], ["aaron-prindle", 19, "19"], ["dlorenc", 15, "15"], ["vishh", 1, "1"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_reviewWords')); chart.draw(data, options); }; </script> </div> <div class="board"> <h3>Most Demanding</h3> <p># of Review Comments in merged PRs</p> <div id="chart_reviewComments" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawreviewComments); function drawreviewComments() { var data = new google.visualization.arrayToDataTable([ ['', '# of Review Comments in merged PRs', { role: 'annotation' }], ["aaron-prindle", 1, "1"], ["vishh", 0, "0"], ["dlorenc", 0, "0"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_reviewComments')); chart.draw(data, options); }; </script> </div> <h2>Pull Requests</h2> <div class="board"> <h3>Most Active</h3> <p># of Pull Requests Merged</p> <div id="chart_prCounts" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawprCounts); function drawprCounts() { var data = new google.visualization.arrayToDataTable([ ['', '# of Pull Requests Merged', { role: 'annotation' }], ["dlorenc", 5, "5"], ["rohitagarwal003", 2, "2"], ["kairen", 1, "1"], ["dustyrip", 1, "1"], ["kkaneda", 1, "1"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_prCounts')); chart.draw(data, options); }; </script> </div> <div class="board"> <h3>Big Movers</h3> <p>Lines of code (delta)</p> <div id="chart_prDeltas" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawprDeltas); function drawprDeltas() { var data = new google.visualization.arrayToDataTable([ ['', 'Lines of code (delta)', { role: 'annotation' }], ["dlorenc", 196, "196"], ["kairen", 118, "118"], ["rohitagarwal003", 45, "45"], ["dustyrip", 2, "2"], ["kkaneda", 2, "2"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_prDeltas')); chart.draw(data, options); }; </script> </div> <div class="board"> <h3>Most difficult to review</h3> <p>Average PR size (added+changed)</p> <div id="chart_prSize" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawprSize); function drawprSize() { var data = new google.visualization.arrayToDataTable([ ['', 'Average PR size (added+changed)', { role: 'annotation' }], ["kairen", 116, "116"], ["dlorenc", 25, "25"], ["rohitagarwal003", 8, "8"], ["dustyrip", 2, "2"], ["kkaneda", 1, "1"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_prSize')); chart.draw(data, options); }; </script> </div> <h2>Issues</h2> <div class="board"> <h3>Most Active</h3> <p># of comments</p> <div id="chart_comments" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawcomments); function drawcomments() { var data = new google.visualization.arrayToDataTable([ ['', '# of comments', { role: 'annotation' }], ["ekimia", 2, "2"], ["dlorenc", 1, "1"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_comments')); chart.draw(data, options); }; </script> </div> <div class="board"> <h3>Most Helpful</h3> <p># of words (excludes authored)</p> <div id="chart_commentWords" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawcommentWords); function drawcommentWords() { var data = new google.visualization.arrayToDataTable([ ['', '# of words (excludes authored)', { role: 'annotation' }], ["ekimia", 83, "83"], ["dlorenc", 18, "18"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_commentWords')); chart.draw(data, options); }; </script> </div> <div class="board"> <h3>Top Closers</h3> <p># of issues closed (excludes authored)</p> <div id="chart_issueCloser" style="width: 450px; height: 350px;"></div> <script type="text/javascript"> google.charts.setOnLoadCallback(drawissueCloser); function drawissueCloser() { var data = new google.visualization.arrayToDataTable([ ['', '# of issues closed (excludes authored)', { role: 'annotation' }], ["dlorenc", 7, "7"], ]); var options = { axisTitlesPosition: 'none', bars: 'horizontal', // Required for Material Bar Charts. axes: { x: { y: { side: 'top'} // Top x-axis. } }, legend: { position: "none" }, bar: { groupWidth: "85%" } }; var chart = new google.visualization.BarChart(document.getElementById('chart_issueCloser')); chart.draw(data, options); }; </script> </div> </body> </html>
{ "content_hash": "1a709e640cf9111091e608f945d0394d", "timestamp": "", "source": "github", "line_count": 422, "max_line_length": 119, "avg_line_length": 33.97867298578199, "alnum_prop": 0.4132087314317595, "repo_name": "warmchang/minikube", "id": "705b59133045d999c758b0321b1ac18e04ac1d12", "size": "14343", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "site/content/en/docs/contrib/leaderboard/v0.28.2.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1299" }, { "name": "C", "bytes": "156" }, { "name": "CSS", "bytes": "4799" }, { "name": "Dockerfile", "bytes": "6590" }, { "name": "Go", "bytes": "1448419" }, { "name": "HTML", "bytes": "7866" }, { "name": "JavaScript", "bytes": "958" }, { "name": "Makefile", "bytes": "49924" }, { "name": "NSIS", "bytes": "8081" }, { "name": "PHP", "bytes": "1598" }, { "name": "PowerShell", "bytes": "7807" }, { "name": "Python", "bytes": "10043" }, { "name": "Shell", "bytes": "72319" } ], "symlink_target": "" }
/* * This Java source file was auto generated by running 'gradle buildInit --type java-library' * by 'steve' at '20/11/14 21:10' with Gradle 2.1 * * @author steve, @date 20/11/14 21:10 */ public class Library { public boolean someLibraryMethod() { return true; } }
{ "content_hash": "691bcb7795d6e42d138168dabab8de25", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 93, "avg_line_length": 26, "alnum_prop": 0.6538461538461539, "repo_name": "WeaSeLworks/ChromeDriver", "id": "8cc88e66f247c5e98aa4042cc4d060def69cdadb", "size": "286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/Library.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8972" } ], "symlink_target": "" }
class Therapeutor::Questionnaire::RecommendationLevel include ActiveModel::Validations attr_accessor :name, :label, :description, :color, :banning, :last, :previously_discarded_level validates :name, presence: {allow_blank: false} validates :label, presence: {allow_blank: false} validates :color, presence: {allow_blank: false} def initialize(opts={}) opts.symbolize_keys! @name = opts[:name] @label = opts[:label] @description = opts[:description] @color = opts[:color] @banning = !!opts[:banning] @previously_discarded_level = opts[:previously_discarded_level] end def previously_discarded_levels if previously_discarded_level.nil? [] else previously_discarded_level.previously_discarded_levels + [previously_discarded_level] end end def code_suitable_name name.tr('^A-Za-z0-9','') end def inspect properties = %w(name label description color banning).map do |key| "#{key}=#{send(key).inspect}" end.join(' ') "<#{self.class.name} #{properties}>" end def self.validate_name_uniqueness(recommendation_levels) recommendation_levels.map(&:name).group_by{ |i| i }.map do |recommendation_level, times_declared| if v.size > 1 "#{times_declared} recommendation levels have been declared with name #{recommendation_level}" end end.compact end def self.validate_set(recommendation_levels) (recommendation_levels.map.with_index do |recommendation_level, i| unless recommendation_level.valid? error_to_add = recommendation_level.errors.full_messages.join(', ') "Recommendation level ##{i+1} invalid: #{error_to_add}" end end + recommendation_levels.map(&:name).compact.group_by{ |i| i }.map do |recommendation_level, appearances| times_declared = appearances.size if times_declared > 1 "#{times_declared} recommendation levels have been declared with name #{recommendation_level}" end end).compact end end
{ "content_hash": "bac3fa6d4d8ae55c15d2c87b6983e3e8", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 112, "avg_line_length": 33.45, "alnum_prop": 0.6841056302939711, "repo_name": "pbanos/therapeutor", "id": "9388951d87db6df730847fccf4a13f0e52a3ec75", "size": "2007", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/therapeutor/questionnaire/recommendation_level.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "1410" }, { "name": "CoffeeScript", "bytes": "2336" }, { "name": "HTML", "bytes": "22809" }, { "name": "JavaScript", "bytes": "11674" }, { "name": "Ruby", "bytes": "33201" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example6-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-app="drag"> <span draggable>Drag ME</span> </body> </html>
{ "content_hash": "d6e41cbb0dd7add52650e9e943a6d46f", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 88, "avg_line_length": 19.58823529411765, "alnum_prop": 0.6516516516516516, "repo_name": "luucasAlbuq/ClinicaMaisSorriso", "id": "84d423f6daad5dd3da8338c1c768d93e8bfe4c5f", "size": "333", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "SCP/lib/angular/docs/examples/example-example6/index-production.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ApacheConf", "bytes": "916" }, { "name": "CSS", "bytes": "306968" }, { "name": "CoffeeScript", "bytes": "161106" }, { "name": "Go", "bytes": "13426" }, { "name": "HTML", "bytes": "3837657" }, { "name": "JavaScript", "bytes": "1386269" }, { "name": "Makefile", "bytes": "326" }, { "name": "PHP", "bytes": "66794" }, { "name": "Python", "bytes": "10346" } ], "symlink_target": "" }
import { Util } from './util'; describe('Util => parseBoolean', () => { it('"yes" return true', () => { expect(Util.parseBoolean('yes')).toEqual(true); }); it('"true" return true', () => { expect(Util.parseBoolean('true')).toEqual(true); }); it('"no" return false', () => { expect(Util.parseBoolean('no')).toEqual(false); }); it('"false" return false', () => { expect(Util.parseBoolean('false')).toEqual(false); }); it('invalid value return false', () => { expect(Util.parseBoolean('xxx')).toEqual(false); }); it('invalid value using defaultValue return defaultValue', () => { expect(Util.parseBoolean('xxx', true)).toEqual(true); }); }); describe('Util => parseArray', () => { let empty: string = ''; let arrayData: string = 'one;two;three;three;;'; it('empty array', () => { expect(Util.parseArray(empty)).toEqual([]); }); it('array with repeated elements', () => { expect(Util.parseArray(arrayData)).toEqual(['one', 'two', 'three', 'three', '', '']); }); it('array without repeated elements', () => { expect(Util.parseArray(arrayData, true)).toEqual(['one', 'two', 'three', '']); }); });
{ "content_hash": "679f5588abf06d53de7b4619974af473", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 89, "avg_line_length": 26.177777777777777, "alnum_prop": 0.5764006791171478, "repo_name": "OntimizeWeb/ontimize-web-ngx", "id": "f6ab7e4d4db7f51c6ec9323ca94ad719477cc7f9", "size": "1178", "binary": false, "copies": "2", "ref": "refs/heads/8.x.x", "path": "projects/ontimize-web-ngx/src/lib/util/util.spec.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "190381" }, { "name": "JavaScript", "bytes": "7594" }, { "name": "SCSS", "bytes": "125972" }, { "name": "TypeScript", "bytes": "1533764" } ], "symlink_target": "" }
""" conference.py -- Udacity conference server-side Python App Engine API; uses Google Cloud Endpoints $Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $ created by wesc on 2014 apr 21 """ __author__ = 'wesc+api@google.com (Wesley Chun)' from datetime import datetime from datetime import date from datetime import timedelta import endpoints from protorpc import messages from protorpc import message_types from protorpc import remote from google.appengine.api import memcache from google.appengine.api import taskqueue from google.appengine.ext import ndb from models import ConflictException from models import Profile from models import ProfileMiniForm from models import ProfileForm from models import StringMessage from models import BooleanMessage from models import Conference from models import ConferenceForm from models import ConferenceForms from models import ConferenceQueryForm from models import ConferenceQueryForms from models import TeeShirtSize from models import Session from models import SessionForm from models import SessionForms from models import UserWishlist from models import UserWishlistForm from models import FeaturedSpeakerMemcacheEntry from models import FeaturedSpeakerMemcacheEntryForm from models import FeaturedSpeakerMemcacheEntryForms from models import FeaturedSpeakerMemcacheKeys from settings import WEB_CLIENT_ID from settings import ANDROID_CLIENT_ID from settings import IOS_CLIENT_ID from settings import ANDROID_AUDIENCE from utils import getUserId EMAIL_SCOPE = endpoints.EMAIL_SCOPE API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT_ANNOUNCEMENTS" ANNOUNCEMENT_TPL = ('Last chance to attend! The following conferences ' 'are nearly sold out: %s') MEMCACHE_FEATURED_SPEAKER_KEY = "FeaturedSpeaker" # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CONFERENCE_DEFAULTS = { "city": "Default City", "maxAttendees": 0, "seatsAvailable": 0, "topics": [ "Default", "Topic" ], } SESSION_DEFAULTS = { "name": "Test Session", "highlights": [ "good stuff", "better stuff" ], "speaker": "Jesse", "duration": 0, "typeOfSession": "Test Session", "startDate": str(date.today()), "startTime": str(datetime.now()), } OPERATORS = { 'EQ': '=', 'GT': '>', 'GTEQ': '>=', 'LT': '<', 'LTEQ': '<=', 'NE': '!=' } FIELDS = { 'CITY': 'city', 'TOPIC': 'topics', 'MONTH': 'month', 'MAX_ATTENDEES': 'maxAttendees', } CONF_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1) ) CONF_POST_REQUEST = endpoints.ResourceContainer( ConferenceForm, websafeConferenceKey=messages.StringField(1) ) CONF_GET_BY_CITY = endpoints.ResourceContainer( message_types.VoidMessage, conferenceCity=messages.StringField(1) ) CONF_GET_BY_TOPIC = endpoints.ResourceContainer( message_types.VoidMessage, conferenceTopic=messages.StringField(2) ) SESS_POST_REQUEST = endpoints.ResourceContainer( SessionForm, websafeConferenceKey=messages.StringField(1) ) SESS_GET_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeSessionKey=messages.StringField(1) ) SESS_GET_BY_TYPE_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeConferenceKey=messages.StringField(1), sessionType=messages.StringField(2) ) SESS_GET_BY_SPEAKER_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, speaker=messages.StringField(1) ) SESS_ADD_TO_WISHLIST_REQUEST = endpoints.ResourceContainer( message_types.VoidMessage, websafeSessionKey=messages.StringField(1) ) GET_SESSIONS_BY_NONTYPE_AND_BEFORE_TIME = endpoints.ResourceContainer( message_types.VoidMessage, sessionType=messages.StringField(1, required=True), endTime=messages.StringField(2, required=True) ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @endpoints.api(name='conference', version='v1', audiences=[ANDROID_AUDIENCE], allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID], scopes=[EMAIL_SCOPE]) class ConferenceApi(remote.Service): """Conference API v0.1""" # Helper functions def _getLoggedInUser(self): user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') return user; # - - - Conference objects - - - - - - - - - - - - - - - - - def _copyConferenceToForm(self, conf, displayName): """Copy relevant fields from Conference to ConferenceForm.""" cf = ConferenceForm() for field in cf.all_fields(): if hasattr(conf, field.name): # convert Date to date string; just copy others if field.name.endswith('Date') or field.name.endswith('Time'): setattr(cf, field.name, str(getattr(conf, field.name))) else: setattr(cf, field.name, getattr(conf, field.name)) elif field.name == "websafeKey": setattr(cf, field.name, conf.key.urlsafe()) if displayName: setattr(cf, 'organizerDisplayName', displayName) cf.check_initialized() return cf def _copySessionToForm(self, theSession): wl = SessionForm() for field in wl.all_fields(): if hasattr(theSession, field.name): # Same as above; convert date or time to string if field.name.endswith('Date') or field.name.endswith('Time'): setattr(wl, field.name, str(getattr(theSession, field.name))) else: setattr(wl, field.name, getattr(theSession, field.name)) elif field.name == "websafeKey": setattr(wl, field.name, theSession.key.urlsafe()) wl.check_initialized() return wl def _createConferenceObject(self, request): """Create or update Conference object, returning ConferenceForm/request.""" # preload necessary data items user = self._getLoggedInUser() user_id = getUserId(user) if not request.name: raise endpoints.BadRequestException("Conference 'name' field required") # copy ConferenceForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} del data['websafeKey'] del data['organizerDisplayName'] # add default values for those missing (both data model & outbound Message) for df in CONFERENCE_DEFAULTS: if data[df] in (None, []): data[df] = CONFERENCE_DEFAULTS[df] setattr(request, df, CONFERENCE_DEFAULTS[df]) # convert dates from strings to Date objects; set month based on start_date if data['startDate']: data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date() data['month'] = data['startDate'].month else: data['month'] = 0 if data['endDate']: data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date() # set seatsAvailable to be same as maxAttendees on creation if data["maxAttendees"] > 0: data["seatsAvailable"] = data["maxAttendees"] # generate Profile Key based on user ID and Conference # ID based on Profile key get Conference key from ID p_key = ndb.Key(Profile, user_id) c_id = Conference.allocate_ids(size=1, parent=p_key)[0] c_key = ndb.Key(Conference, c_id, parent=p_key) data['key'] = c_key data['organizerUserId'] = request.organizerUserId = user_id # create Conference, send email to organizer confirming # creation of Conference & return (modified) ConferenceForm Conference(**data).put() taskqueue.add(params={'email': user.email(), 'conferenceInfo': repr(request)}, url='/tasks/send_confirmation_email' ) return request def _getUserWishlistByProfile(self, profile): #Given a profile, get its key and return the sessions on the wishlist if not profile: raise endpoints.BadRequestException("Invalid profile!") #Get the wishlist entries and add them to the wishlist to return. wishlistEntries = UserWishlist.query(ancestor=profile.key).fetch(limit=None) finishedWishlist = SessionForms() if wishlistEntries: for entry in wishlistEntries: theSession = ndb.Key(urlsafe=getattr(entry, "wishlistedSessionKey")).get() sf = self._copySessionToForm(theSession) sf.check_initialized() finishedWishlist.items.append(sf) return finishedWishlist #TODO def _addSessionToWishlist(self, request): #Check if the user is logged in user = self._getLoggedInUser() user_id = getUserId(user) #Check if the theSession exists theSession = ndb.Key(urlsafe=request.websafeSessionKey).get() if not theSession: raise endpoints.BadRequestException("Invalid session key") #Get user profile prof = ndb.Key(Profile, user_id).get() if not prof: raise endpoints.BadRequestException("Unable to find user profile") wishlistEntry = UserWishlist.query(ancestor=prof.key).filter( getattr(UserWishlist, "wishlistedSessionKey") == request.websafeSessionKey ).get() print wishlistEntry #If the desired wishlist entry doesn't already exist, create it. if not wishlistEntry: wishlistEntry = UserWishlist(parent=prof.key) setattr(wishlistEntry, "wishlistedSessionKey", request.websafeSessionKey) wishlistEntry.put() return self._getUserWishlistByProfile(prof) #Same as above, but for sessions. def _createSessionObject(self, request): self._getLoggedInUser() if not request.websafeConferenceKey: raise endpoints.BadRequestException("Websafe Conference Key field required") theConference = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not theConference: raise endpoints.BadRequestException("That conference doesn't exist!") # Same as above, copy SessionForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} theConferenceWebsafeKey = data['websafeConferenceKey'] del data['websafeKey'] del data['websafeConferenceKey'] # Defaults for missing values for df in SESSION_DEFAULTS: if data[df] in (None, []): data[df] = SESSION_DEFAULTS[df] setattr(request, df, SESSION_DEFAULTS[df]) # Convert date and time try: if data['startDate']: data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date() except ValueError: data['startDate'] = date.today() try: if data['startTime']: data['startTime'] = datetime.strptime(data['startTime'], "%H:%M:%S") except ValueError: data['startTime'] = datetime.now() # Generate keys Session(parent=theConference.key, **data).put() if (data['speaker']): # Check speaker name at this conference for the Featured Speaker memcaches speakerSessions = Session.query(ancestor=theConference.key).filter(Session.speaker == data['speaker']).fetch(limit=None) if (speakerSessions) and (len(speakerSessions) > 1): #Check if the memcache entry exists for this speaker and this conference. theEntry = memcache.get(data['speaker'] + "_" + theConferenceWebsafeKey) theKeys = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY) entryKey = key = (data['speaker'] + "_" + theConferenceWebsafeKey) if theKeys is None: theKeys = FeaturedSpeakerMemcacheKeys() if theEntry is None: theEntry = FeaturedSpeakerMemcacheEntry() theEntry.speaker = data['speaker'] theEntry.conferenceWebsafeKey = theConferenceWebsafeKey theEntry.sessions = [] for speakerSession in speakerSessions: theEntry.sessions.append(speakerSession.name) memcache.set(key = entryKey, value = theEntry) if entryKey not in theKeys.items: theKeys.items.append(entryKey) memcache.set(key = MEMCACHE_FEATURED_SPEAKER_KEY, value = theKeys) return request def _getFeaturedSpeakersFromMemcache(self): # inserted via key MEMCACHE_FEATURED_SPEAKER_KEY theKeys = memcache.get(key = MEMCACHE_FEATURED_SPEAKER_KEY) thingsToReturn = FeaturedSpeakerMemcacheEntryForms() thingsToReturn.check_initialized() if theKeys: for speakerKey in theKeys.items: entry = memcache.get(key = speakerKey) if entry: thingsToReturn.items.append(self._copyFeaturedSpeakerToForm(entry)) return thingsToReturn def _copyFeaturedSpeakerToForm(self, Speaker): toReturn = FeaturedSpeakerMemcacheEntryForm() toReturn.check_initialized() toReturn.speaker = Speaker.speaker toReturn.conferenceWebsafeKey = Speaker.conferenceWebsafeKey toReturn.sessions = Speaker.sessions return toReturn @ndb.transactional() def _updateConferenceObject(self, request): user = self._getLoggedInUser() user_id = getUserId(user) # copy ConferenceForm/ProtoRPC Message into dict data = {field.name: getattr(request, field.name) for field in request.all_fields()} # update existing conference conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() # check that conference exists if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) # check that user is owner if user_id != conf.organizerUserId: raise endpoints.ForbiddenException( 'Only the owner can update the conference.') # Not getting all the fields, so don't create a new object; just # copy relevant fields from ConferenceForm to Conference object for field in request.all_fields(): data = getattr(request, field.name) # only copy fields where we get data if data not in (None, []): # special handling for dates (convert string to Date) if field.name in ('startDate', 'endDate'): data = datetime.strptime(data, "%Y-%m-%d").date() if field.name == 'startDate': conf.month = data.month # write to Conference object setattr(conf, field.name, data) conf.put() prof = ndb.Key(Profile, user_id).get() return self._copyConferenceToForm(conf, getattr(prof, 'displayName')) @endpoints.method(ConferenceForm, ConferenceForm, path='conference', http_method='POST', name='createConference') def createConference(self, request): """Create new conference.""" return self._createConferenceObject(request) # createSession(SessionForm, websafeConferenceKey) @endpoints.method(SESS_POST_REQUEST, SessionForm, path='session', http_method='POST', name='createSession') def createSession(self, request): """Create new session.""" return self._copySessionToForm(self._createSessionObject(request)) @endpoints.method(CONF_POST_REQUEST, ConferenceForm, path='conference/{websafeConferenceKey}', http_method='PUT', name='updateConference') def updateConference(self, request): """Update conference w/provided fields & return w/updated info.""" return self._updateConferenceObject(request) @endpoints.method(message_types.VoidMessage, FeaturedSpeakerMemcacheEntryForms, http_method="GET", name="getFeaturedSpeaker", path="getFeaturedSpeaker") def getFeaturedSpeaker(self, request): """Get the featured speaker for each conference.""" return self._getFeaturedSpeakersFromMemcache() @endpoints.method(CONF_GET_REQUEST, ConferenceForm, path='conference/{websafeConferenceKey}', http_method='GET', name='getConference') def getConference(self, request): """Return requested conference (by websafeConferenceKey).""" # get Conference object from request; bail if not found conf = ndb.Key(urlsafe=request.websafeConferenceKey).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % request.websafeConferenceKey) prof = conf.key.parent().get() return self._copyConferenceToForm(conf, getattr(prof, 'displayName')) #Return sessions by conference. @endpoints.method(CONF_GET_REQUEST, SessionForms, path='getConferenceSessions/{websafeConferenceKey}', http_method='GET', name='getConferenceSessions') def getConferenceSessions(self, request): """Get conference sessions by websafe conference key.""" self._getLoggedInUser() theConference = ndb.Key(urlsafe=request.websafeConferenceKey).get() theSessions = Session.query(ancestor=theConference.key) return SessionForms( items=[self._copySessionToForm(oneSession) for oneSession in theSessions] ) @endpoints.method(message_types.VoidMessage, ConferenceForms, path='getConferencesCreated', http_method='POST', name='getConferencesCreated') def getConferencesCreated(self, request): """Return conferences created by user.""" # make sure user is authed user = self._getLoggedInUser() user_id = getUserId(user) # create ancestor query for all key matches for this user confs = Conference.query(ancestor=ndb.Key(Profile, user_id)) prof = ndb.Key(Profile, user_id).get() # return set of ConferenceForm objects per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs] ) @endpoints.method(CONF_GET_BY_CITY, ConferenceForms, path="getConferencesByCity", http_method="POST", name="getConferencesByCity") def getConferencesByCity(self, request): """Get conferences by city.""" confs = Conference.query().filter(getattr(Conference, "city") == request.conferenceCity) prof = self._getProfileFromUser() return ConferenceForms( items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs] ) @endpoints.method(CONF_GET_BY_TOPIC, ConferenceForms, path="getConferencesByExactTopic", http_method="POST", name="getConferencesByExactTopic") def getConferencesByExactTopic(self, request): """Get conferences by topic. Must be a complete match; use getConferencesCreated and copy a topic from there.""" confs = Conference.query(Conference.topics == request.conferenceTopic) prof = self._getProfileFromUser() return ConferenceForms( items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs] ) @endpoints.method(GET_SESSIONS_BY_NONTYPE_AND_BEFORE_TIME, SessionForms, path="getSessionsNotOfTypeAndBeforeTime", http_method="POST", name="getSessionsNotOfTypeAndBeforeTime") def getSessionsNotOfTypeAndBeforeTime(self, request): """Get sessions that are NOT a given type, and that finish before the given 24H time.""" sessions = Session.query(Session.typeOfSession != request.sessionType) sessionsToReturn = SessionForms() sessionsToReturn.check_initialized() cutoffTime = datetime.strptime(request.endTime, "%H:%M:%S") for sess in sessions: #For each session that finishes before the cutoff time, add it to the list to return. if (cutoffTime > (sess.startTime + timedelta(minutes = sess.duration))): sessionsToReturn.items.append(self._copySessionToForm(sess)) return sessionsToReturn @endpoints.method(SESS_GET_BY_TYPE_REQUEST, SessionForms, path='getConferenceSessionsByType', http_method='POST', name='getConferenceSessionsByType') def getConferenceSessionsByType(self, request): """Get conference sessions by conference and session type.""" self._getLoggedInUser() theConference = ndb.Key(urlsafe=request.websafeConferenceKey).get() theSessions = Session.query(ancestor=theConference.key).filter( getattr(Session, "typeOfSession") == request.sessionType) return SessionForms( items=[self._copySessionToForm(oneSession) for oneSession in theSessions] ) @endpoints.method(SESS_GET_BY_SPEAKER_REQUEST, SessionForms, path='getConferenceSessionsBySpeaker', http_method='POST', name='getConferenceSessionsBySpeaker') def getConferenceSessionsBySpeaker(self, request): """Get conference sessions by speaker.""" self._getLoggedInUser() theSessions = Session.query(getattr(Session, "speaker") == request.speaker) return SessionForms( items=[self._copySessionToForm(oneSession) for oneSession in theSessions] ) @endpoints.method(SESS_GET_REQUEST, SessionForms, path='addSessionToWishlist', http_method="POST", name="addSessionToWishlist") def addSessionToWishlist(self, request): """Add a session to a user's wishist by session websafe key.""" return self._addSessionToWishlist(request) @endpoints.method(message_types.VoidMessage, SessionForms, path='getSessionsInWishlist', http_method="GET", name="getSessionsInWishlist") def getSessionsInWishlist(self, request): """Get the sessions on your wishlist.""" # Get user profile, and pass it to _getUserWishlistByProfile() user = self._getLoggedInUser() user_id = getUserId(user) prof = ndb.Key(Profile, user_id).get() return self._getUserWishlistByProfile(prof) def _getQuery(self, request): """Return formatted query from the submitted filters.""" q = Conference.query() inequality_filter, filters = self._formatFilters(request.filters) # If exists, sort on inequality filter first if not inequality_filter: q = q.order(Conference.name) else: q = q.order(ndb.GenericProperty(inequality_filter)) q = q.order(Conference.name) for filtr in filters: if filtr["field"] in ["month", "maxAttendees"]: filtr["value"] = int(filtr["value"]) formatted_query = ndb.query.FilterNode(filtr["field"], filtr["operator"], filtr["value"]) q = q.filter(formatted_query) return q def _formatFilters(self, filters): """Parse, check validity and format user supplied filters.""" formatted_filters = [] inequality_field = None for f in filters: filtr = {field.name: getattr(f, field.name) for field in f.all_fields()} try: filtr["field"] = FIELDS[filtr["field"]] filtr["operator"] = OPERATORS[filtr["operator"]] except KeyError: raise endpoints.BadRequestException("Filter contains invalid field or operator.") # Every operation except "=" is an inequality if filtr["operator"] != "=": # check if inequality operation has been used in previous filters # disallow the filter if inequality was performed on a different field before # track the field on which the inequality operation is performed if inequality_field and inequality_field != filtr["field"]: raise endpoints.BadRequestException("Inequality filter is allowed on only one field.") else: inequality_field = filtr["field"] formatted_filters.append(filtr) return (inequality_field, formatted_filters) @endpoints.method(ConferenceQueryForms, ConferenceForms, path='queryConferences', http_method='POST', name='queryConferences') def queryConferences(self, request): """Query for conferences.""" conferences = self._getQuery(request) # need to fetch organiser displayName from profiles # get all keys and use get_multi for speed organisers = [(ndb.Key(Profile, conf.organizerUserId)) for conf in conferences] profiles = ndb.get_multi(organisers) # put display names in a dict for easier fetching names = {} for profile in profiles: names[profile.key.id()] = profile.displayName # return individual ConferenceForm object per Conference return ConferenceForms( items=[self._copyConferenceToForm(conf, names[conf.organizerUserId]) for conf in \ conferences] ) # - - - Profile objects - - - - - - - - - - - - - - - - - - - def _copyProfileToForm(self, prof): """Copy relevant fields from Profile to ProfileForm.""" # copy relevant fields from Profile to ProfileForm pf = ProfileForm() for field in pf.all_fields(): if hasattr(prof, field.name): # convert t-shirt string to Enum; just copy others if field.name == 'teeShirtSize': setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name))) else: setattr(pf, field.name, getattr(prof, field.name)) pf.check_initialized() return pf def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # make sure user is authed user = self._getLoggedInUser() # get Profile from datastore user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # create new Profile if not there if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile def _doProfile(self, save_request=None): """Get user Profile and return to user, possibly updating it first.""" # get user Profile prof = self._getProfileFromUser() # if saveProfile(), process user-modifyable fields if save_request: for field in ('displayName', 'teeShirtSize'): if hasattr(save_request, field): val = getattr(save_request, field) if val: setattr(prof, field, str(val)) prof.put() return self._copyProfileToForm(prof) @endpoints.method(message_types.VoidMessage, ProfileForm, path='profile', http_method='GET', name='getProfile') def getProfile(self, request): """Return user profile.""" return self._doProfile() @endpoints.method(ProfileMiniForm, ProfileForm, path='profile', http_method='POST', name='saveProfile') def saveProfile(self, request): """Update & return user profile.""" return self._doProfile(request) # - - - Announcements - - - - - - - - - - - - - - - - - - - - @staticmethod def _cacheAnnouncement(): """Create Announcement & assign to memcache; used by memcache cron job & putAnnouncement(). """ confs = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0) ).fetch(projection=[Conference.name]) if confs: # If there are almost sold out conferences, # format announcement and set it in memcache announcement = ANNOUNCEMENT_TPL % ( ', '.join(conf.name for conf in confs)) memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement) else: # If there are no sold out conferences, # delete the memcache announcements entry announcement = "" memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY) return announcement @endpoints.method(message_types.VoidMessage, StringMessage, path='conference/announcement/get', http_method='GET', name='getAnnouncement') def getAnnouncement(self, request): """Return Announcement from memcache.""" return StringMessage(data=memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY) or "") # - - - Registration - - - - - - - - - - - - - - - - - - - - @ndb.transactional(xg=True) def _conferenceRegistration(self, request, reg=True): """Register or unregister user for selected conference.""" retval = None prof = self._getProfileFromUser() # get user Profile # check if conf exists given websafeConfKey # get conference; check that it exists wsck = request.websafeConferenceKey conf = ndb.Key(urlsafe=wsck).get() if not conf: raise endpoints.NotFoundException( 'No conference found with key: %s' % wsck) # register if reg: # check if user already registered otherwise add if wsck in prof.conferenceKeysToAttend: raise ConflictException( "You have already registered for this conference") # check if seats avail if conf.seatsAvailable <= 0: raise ConflictException( "There are no seats available.") # register user, take away one seat prof.conferenceKeysToAttend.append(wsck) conf.seatsAvailable -= 1 retval = True # unregister else: # check if user already registered if wsck in prof.conferenceKeysToAttend: # unregister user, add back one seat prof.conferenceKeysToAttend.remove(wsck) conf.seatsAvailable += 1 retval = True else: retval = False # write things back to the datastore & return prof.put() conf.put() return BooleanMessage(data=retval) @endpoints.method(message_types.VoidMessage, ConferenceForms, path='conferences/attending', http_method='GET', name='getConferencesToAttend') def getConferencesToAttend(self, request): """Get list of conferences that user has registered for.""" prof = self._getProfileFromUser() # get user Profile conf_keys = [ndb.Key(urlsafe=wsck) for wsck in prof.conferenceKeysToAttend] conferences = ndb.get_multi(conf_keys) # get organizers organisers = [ndb.Key(Profile, conf.organizerUserId) for conf in conferences] profiles = ndb.get_multi(organisers) # put display names in a dict for easier fetching names = {} for profile in profiles: names[profile.key.id()] = profile.displayName # return set of ConferenceForm objects per Conference return ConferenceForms(items=[self._copyConferenceToForm(conf, names[conf.organizerUserId])\ for conf in conferences] ) @endpoints.method(CONF_GET_REQUEST, BooleanMessage, path='conference/{websafeConferenceKey}', http_method='POST', name='registerForConference') def registerForConference(self, request): """Register user for selected conference.""" return self._conferenceRegistration(request) @endpoints.method(CONF_GET_REQUEST, BooleanMessage, path='conference/{websafeConferenceKey}', http_method='DELETE', name='unregisterFromConference') def unregisterFromConference(self, request): """Unregister user for selected conference.""" return self._conferenceRegistration(request, reg=False) @endpoints.method(message_types.VoidMessage, ConferenceForms, path='filterPlayground', http_method='GET', name='filterPlayground') def filterPlayground(self, request): """Filter Playground""" q = Conference.query() q = q.filter(Conference.city=="London") q = q.filter(Conference.topics=="Medical Innovations") q = q.filter(Conference.month==6) return ConferenceForms( items=[self._copyConferenceToForm(conf, "") for conf in q] ) api = endpoints.api_server([ConferenceApi]) # register API
{ "content_hash": "585931cef6f46368e5d2a63b65360612", "timestamp": "", "source": "github", "line_count": 894, "max_line_length": 132, "avg_line_length": 38.4675615212528, "alnum_prop": 0.6191334690316953, "repo_name": "preveyj/Udacity-FSWDND-Project-4", "id": "4a0bc23eff2dc97f638c6e4ffd1b8fd49aa94f0b", "size": "34413", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "conference.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "23913" }, { "name": "JavaScript", "bytes": "32836" }, { "name": "Python", "bytes": "43410" } ], "symlink_target": "" }
package com.amazonaws.services.cloudformation.model; /** * Resource Status */ public enum ResourceStatus { CREATE_IN_PROGRESS("CREATE_IN_PROGRESS"), CREATE_FAILED("CREATE_FAILED"), CREATE_COMPLETE("CREATE_COMPLETE"), DELETE_IN_PROGRESS("DELETE_IN_PROGRESS"), DELETE_FAILED("DELETE_FAILED"), DELETE_COMPLETE("DELETE_COMPLETE"); private String value; private ResourceStatus(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return ResourceStatus corresponding to the value */ public static ResourceStatus fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } else if ("CREATE_IN_PROGRESS".equals(value)) { return ResourceStatus.CREATE_IN_PROGRESS; } else if ("CREATE_FAILED".equals(value)) { return ResourceStatus.CREATE_FAILED; } else if ("CREATE_COMPLETE".equals(value)) { return ResourceStatus.CREATE_COMPLETE; } else if ("DELETE_IN_PROGRESS".equals(value)) { return ResourceStatus.DELETE_IN_PROGRESS; } else if ("DELETE_FAILED".equals(value)) { return ResourceStatus.DELETE_FAILED; } else if ("DELETE_COMPLETE".equals(value)) { return ResourceStatus.DELETE_COMPLETE; } else { throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } } }
{ "content_hash": "9d300cdc5a75707aae5a3c6a2edd1372", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 95, "avg_line_length": 30.527272727272727, "alnum_prop": 0.6098868374032163, "repo_name": "apetresc/aws-sdk-for-java-on-gae", "id": "8ed106351d739a78a837c38d974a5fd2222024d5", "size": "2266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/amazonaws/services/cloudformation/model/ResourceStatus.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10870469" } ], "symlink_target": "" }
<html> <head> <title>Angular QuickStart</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 1. Load libraries --> <!-- Polyfill(s) for older browsers --> <script src="assets/vendor/core-js/client/shim.min.js"></script> <script src="assets/vendor/zone.js/zone.js"></script> <script src="assets/vendor/reflect-metadata/Reflect.js"></script> <script src="assets/vendor/systemjs/system.src.js"></script> <!-- 2. Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.set('electron', System.newModule(require('electron'))); System.import('app').catch(function(err){ console.error(err); }); </script> </head> <!-- 3. Display the application --> <body> <my-app>Loading...</my-app> </body> </html>
{ "content_hash": "bcb6692d2de037054dd1513b8c12e2e5", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 72, "avg_line_length": 32.92307692307692, "alnum_prop": 0.6238317757009346, "repo_name": "c4wrd/angular2-electron-boilerplate", "id": "1e3ad7aaa887e9031b05acb413555a92c01604ae", "size": "856", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1051" }, { "name": "JavaScript", "bytes": "6032" }, { "name": "TypeScript", "bytes": "1882" } ], "symlink_target": "" }
package com.intel.analytics.bigdl.dllib.nn.tf import com.intel.analytics.bigdl.dllib.tensor.Tensor import com.intel.analytics.bigdl.dllib.utils.T import com.intel.analytics.bigdl.dllib.utils.serializer.ModuleSerializationTest import org.scalatest.{FlatSpec, Matchers} import scala.util.Random @com.intel.analytics.bigdl.tags.Parallel class StridedSliceSpec extends FlatSpec with Matchers { "StrideSlice " should "compute correct output and gradient" in { val module1 = new StridedSlice[Double, Double]() val inputTensor = Tensor[Double](2, 2, 2) inputTensor(Array(1, 1, 1)) = -0.17020166106522 inputTensor(Array(1, 1, 2)) = 0.57785657607019 inputTensor(Array(1, 2, 1)) = -1.3404131438583 inputTensor(Array(1, 2, 2)) = 1.0938102817163 inputTensor(Array(2, 1, 1)) = 1.120370157063 inputTensor(Array(2, 1, 2)) = -1.5014141565189 inputTensor(Array(2, 2, 1)) = 0.3380249235779 inputTensor(Array(2, 2, 2)) = -0.625677742064 val begin = Tensor[Int](3).fill(1) val end = Tensor[Int](3).fill(3) end.setValue(1, 2) val strides = Tensor[Int](3).fill(1) val expectOutput1 = Tensor[Double](1, 2, 2) expectOutput1(Array(1, 1, 1)) = -0.17020166106522 expectOutput1(Array(1, 1, 2)) = 0.57785657607019 expectOutput1(Array(1, 2, 1)) = -1.3404131438583 expectOutput1(Array(1, 2, 2)) = 1.0938102817163 val expectedGradInput = Tensor[Double](2, 2, 2) expectedGradInput(Array(1, 1, 1)) = -0.17020166106522 expectedGradInput(Array(1, 1, 2)) = 0.57785657607019 expectedGradInput(Array(1, 2, 1)) = -1.3404131438583 expectedGradInput(Array(1, 2, 2)) = 1.0938102817163 expectedGradInput(Array(2, 1, 1)) = 0.0 expectedGradInput(Array(2, 1, 2)) = 0.0 expectedGradInput(Array(2, 2, 1)) = 0.0 expectedGradInput(Array(2, 2, 2)) = 0.0 val input = T(inputTensor, begin, end, strides) val output1 = module1.forward(input) val gradInput = module1.backward(input, output1).toTable[Tensor[Double]](1) output1 should be(expectOutput1) gradInput should be(expectedGradInput) } } class StridedSliceSerialTest extends ModuleSerializationTest { override def test(): Unit = { val stridedSlice = StridedSlice[Float, Float]().setName("stridedSlice") val input = Tensor[Float](2, 2, 2).apply1(_ => Random.nextFloat()) val begin = Tensor[Int](3).fill(1) val end = Tensor[Int](3).fill(3) end.setValue(1, 2) val strides = Tensor[Int](3).fill(1) runSerializationTest(stridedSlice, T(input, begin, end, strides)) } }
{ "content_hash": "f3f41729fa8a25ddecaf72c4ac6527fa", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 79, "avg_line_length": 38.54545454545455, "alnum_prop": 0.6922169811320755, "repo_name": "intel-analytics/BigDL", "id": "f63c8dfefb8684ab9b68d651fb77c22b9cd64ec5", "size": "3145", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/nn/tf/StridedSliceSpec.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5342" }, { "name": "Dockerfile", "bytes": "139304" }, { "name": "Java", "bytes": "1321348" }, { "name": "Jupyter Notebook", "bytes": "54112822" }, { "name": "Lua", "bytes": "1904" }, { "name": "Makefile", "bytes": "19253" }, { "name": "PowerShell", "bytes": "1137" }, { "name": "PureBasic", "bytes": "593" }, { "name": "Python", "bytes": "8825782" }, { "name": "RobotFramework", "bytes": "16117" }, { "name": "Scala", "bytes": "13216148" }, { "name": "Shell", "bytes": "848241" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>MageParams - FAKE - F# Make</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull"> <script src="https://code.jquery.com/jquery-1.8.0.js"></script> <script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" /> <script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="http://github.com/fsharp/fake">github page</a></li> </ul> <h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>MageParams</h1> <div class="xmldoc"> <p>Needed information to call MAGE</p> </div> <h3>Record Fields</h3> <table class="table table-bordered member-list"> <thead> <tr><td>Record Field</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1959', 1959)" onmouseover="showTip(event, '1959', 1959)"> ApplicationFile </code> <div class="tip" id="1959"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L32-32" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1960', 1960)" onmouseover="showTip(event, '1960', 1960)"> CertFile </code> <div class="tip" id="1960"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L34-34" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1961', 1961)" onmouseover="showTip(event, '1961', 1961)"> CertHash </code> <div class="tip" id="1961"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L37-37" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1962', 1962)" onmouseover="showTip(event, '1962', 1962)"> CodeBase </code> <div class="tip" id="1962"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L42-42" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1963', 1963)" onmouseover="showTip(event, '1963', 1963)"> FromDirectory </code> <div class="tip" id="1963"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L31-31" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1964', 1964)" onmouseover="showTip(event, '1964', 1964)"> IconFile </code> <div class="tip" id="1964"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L27-27" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1965', 1965)" onmouseover="showTip(event, '1965', 1965)"> IconPath </code> <div class="tip" id="1965"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L26-26" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1966', 1966)" onmouseover="showTip(event, '1966', 1966)"> IncludeProvider </code> <div class="tip" id="1966"> <strong>Signature:</strong> bool option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L38-38" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1967', 1967)" onmouseover="showTip(event, '1967', 1967)"> Install </code> <div class="tip" id="1967"> <strong>Signature:</strong> bool option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L39-39" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1968', 1968)" onmouseover="showTip(event, '1968', 1968)"> Manifest </code> <div class="tip" id="1968"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L30-30" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1969', 1969)" onmouseover="showTip(event, '1969', 1969)"> Name </code> <div class="tip" id="1969"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L25-25" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1970', 1970)" onmouseover="showTip(event, '1970', 1970)"> Password </code> <div class="tip" id="1970"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L36-36" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1971', 1971)" onmouseover="showTip(event, '1971', 1971)"> Processor </code> <div class="tip" id="1971"> <strong>Signature:</strong> MageProcessor<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L28-28" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1972', 1972)" onmouseover="showTip(event, '1972', 1972)"> ProjectFiles </code> <div class="tip" id="1972"> <strong>Signature:</strong> seq&lt;string&gt;<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L24-24" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1973', 1973)" onmouseover="showTip(event, '1973', 1973)"> ProviderURL </code> <div class="tip" id="1973"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L43-43" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1974', 1974)" onmouseover="showTip(event, '1974', 1974)"> Publisher </code> <div class="tip" id="1974"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L41-41" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1975', 1975)" onmouseover="showTip(event, '1975', 1975)"> SupportURL </code> <div class="tip" id="1975"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L44-44" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1976', 1976)" onmouseover="showTip(event, '1976', 1976)"> TmpCertFile </code> <div class="tip" id="1976"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L35-35" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1977', 1977)" onmouseover="showTip(event, '1977', 1977)"> ToolsPath </code> <div class="tip" id="1977"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L23-23" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1978', 1978)" onmouseover="showTip(event, '1978', 1978)"> TrustLevel </code> <div class="tip" id="1978"> <strong>Signature:</strong> MageTrustLevels option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L33-33" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1979', 1979)" onmouseover="showTip(event, '1979', 1979)"> UseManifest </code> <div class="tip" id="1979"> <strong>Signature:</strong> bool option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L40-40" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1980', 1980)" onmouseover="showTip(event, '1980', 1980)"> Version </code> <div class="tip" id="1980"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MageHelper.fs#L29-29" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> </td> </tr> </tbody> </table> </div> <div class="span3"> <a href="http://fsharp.github.io/FAKE/index.html"> <img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" /> </a> <ul class="nav nav-list" id="menu"> <li class="nav-header">FAKE - F# Make</li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li> <li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li> <li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li> <li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li> <li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li> <li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li> <li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li> <li class="nav-header">Tutorials</li> <li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li> <li><a href="http://fsharp.github.io/FAKE/cache.html">Build script caching</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li> <li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li> <li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li> <li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li> <li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li> <li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li> <li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li> <li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li> <li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li> <li><a href="http://fsharp.github.io/FAKE/soft-dependencies.html">Soft dependencies</a></li> <li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li> <li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li> <li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li> <li><a href="http://fsharp.github.io/FAKE/fluentmigrator.html">FluentMigrator support</a></li> <li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li> <li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li> <li><a href="http://fsharp.github.io/FAKE/wix.html">WiX Setup Generation</a></li> <li><a href="http://fsharp.github.io/FAKE/chocolatey.html">Using Chocolatey</a></li> <li><a href="http://fsharp.github.io/FAKE/slacknotification.html">Using Slack</a></li> <li><a href="http://fsharp.github.io/FAKE/sonarcube.html">Using SonarQube</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/iis.html">Fake.IIS</a></li> <li class="nav-header">Reference</li> <li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li> </ul> </div> </div> </div> <a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a> </body> </html>
{ "content_hash": "e34083a09ffc3bd9c31356435674fb91", "timestamp": "", "source": "github", "line_count": 509, "max_line_length": 209, "avg_line_length": 42.776031434184674, "alnum_prop": 0.5146741376934736, "repo_name": "kirill-gerasimenko/fseye", "id": "2c1954324f17d6f04d4516594723be6349ef75c0", "size": "21773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/FAKE/docs/apidocs/fake-magehelper-mageparams.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1800" }, { "name": "CSS", "bytes": "4399" }, { "name": "F#", "bytes": "133658" }, { "name": "HTML", "bytes": "6695232" }, { "name": "JavaScript", "bytes": "1340" } ], "symlink_target": "" }
/** * Subprocess library, modeled after Python's subprocess module * (http://docs.python.org/2/library/subprocess.html) * * This library defines one class (Subprocess) which represents a child * process. Subprocess has two constructors: one that takes a vector<string> * and executes the given executable without using the shell, and one * that takes a string and executes the given command using the shell. * Subprocess allows you to redirect the child's standard input, standard * output, and standard error to/from child descriptors in the parent, * or to create communication pipes between the child and the parent. * * The simplest example is a thread-safe [1] version of the system() library * function: * Subprocess(cmd).wait(); * which executes the command using the default shell and waits for it * to complete, returning the exit status. * * A thread-safe [1] version of popen() (type="r", to read from the child): * Subprocess proc(cmd, Subprocess::pipeStdout()); * // read from proc.stdout() * proc.wait(); * * A thread-safe [1] version of popen() (type="w", to write to the child): * Subprocess proc(cmd, Subprocess::pipeStdin()); * // write to proc.stdin() * proc.wait(); * * If you want to redirect both stdin and stdout to pipes, you can, but note * that you're subject to a variety of deadlocks. You'll want to use * nonblocking I/O, like the callback version of communicate(). * * The string or IOBuf-based variants of communicate() are the simplest way * to communicate with a child via its standard input, standard output, and * standard error. They buffer everything in memory, so they are not great * for large amounts of data (or long-running processes), but they are much * simpler than the callback version. * * == A note on thread-safety == * * [1] "thread-safe" refers ONLY to the fact that Subprocess is very careful * to fork in a way that does not cause grief in multithreaded programs. * * Caveat: If your system does not have the atomic pipe2 system call, it is * not safe to concurrently call Subprocess from different threads. * Therefore, it is best to have a single thread be responsible for spawning * subprocesses. * * A particular instances of Subprocess is emphatically **not** thread-safe. * If you need to simultaneously communicate via the pipes, and interact * with the Subprocess state, your best bet is to: * - takeOwnershipOfPipes() to separate the pipe I/O from the subprocess. * - Only interact with the Subprocess from one thread at a time. * * The current implementation of communicate() cannot be safely interrupted. * To do so correctly, one would need to use EventFD, or open a dedicated * pipe to be messaged from a different thread -- in particular, kill() will * not do, since a descendant may keep the pipes open indefinitely. * * So, once you call communicate(), you must wait for it to return, and not * touch the pipes from other threads. closeParentFd() is emphatically * unsafe to call concurrently, and even sendSignal() is not a good idea. * You can perhaps give the Subprocess's PID to a different thread before * starting communicate(), and use that PID to send a signal without * accessing the Subprocess object. In that case, you will need a mutex * that ensures you don't wait() before you sent said signal. In a * nutshell, don't do this. * * In fact, signals are inherently concurrency-unsafe on Unix: if you signal * a PID, while another thread is in waitpid(), the signal may fire either * before or after the process is reaped. This means that your signal can, * in pathological circumstances, be delivered to the wrong process (ouch!). * To avoid this, you should only use non-blocking waits (i.e. poll()), and * make sure to serialize your signals (i.e. kill()) with the waits -- * either wait & signal from the same thread, or use a mutex. */ #ifndef FOLLY_SUBPROCESS_H_ #define FOLLY_SUBPROCESS_H_ #include <sys/types.h> #include <signal.h> #if __APPLE__ #include <sys/wait.h> #else #include <wait.h> #endif #include <exception> #include <vector> #include <string> #include <boost/container/flat_map.hpp> #include <boost/operators.hpp> #include <folly/File.h> #include <folly/FileUtil.h> #include <folly/gen/String.h> #include <folly/io/IOBufQueue.h> #include <folly/MapUtil.h> #include <folly/Portability.h> #include <folly/Range.h> namespace folly { /** * Class to wrap a process return code. */ class Subprocess; class ProcessReturnCode { friend class Subprocess; public: enum State { NOT_STARTED, RUNNING, EXITED, KILLED }; // Trivially copyable ProcessReturnCode(const ProcessReturnCode& p) = default; ProcessReturnCode& operator=(const ProcessReturnCode& p) = default; // Non-default move: In order for Subprocess to be movable, the "moved // out" state must not be "running", or ~Subprocess() will abort. ProcessReturnCode(ProcessReturnCode&& p) noexcept; ProcessReturnCode& operator=(ProcessReturnCode&& p) noexcept; /** * Process state. One of: * NOT_STARTED: process hasn't been started successfully * RUNNING: process is currently running * EXITED: process exited (successfully or not) * KILLED: process was killed by a signal. */ State state() const; /** * Helper wrappers around state(). */ bool notStarted() const { return state() == NOT_STARTED; } bool running() const { return state() == RUNNING; } bool exited() const { return state() == EXITED; } bool killed() const { return state() == KILLED; } /** * Exit status. Only valid if state() == EXITED; throws otherwise. */ int exitStatus() const; /** * Signal that caused the process's termination. Only valid if * state() == KILLED; throws otherwise. */ int killSignal() const; /** * Was a core file generated? Only valid if state() == KILLED; throws * otherwise. */ bool coreDumped() const; /** * String representation; one of * "not started" * "running" * "exited with status <status>" * "killed by signal <signal>" * "killed by signal <signal> (core dumped)" */ std::string str() const; /** * Helper function to enforce a precondition based on this. * Throws std::logic_error if in an unexpected state. */ void enforce(State state) const; private: explicit ProcessReturnCode(int rv) : rawStatus_(rv) { } static constexpr int RV_NOT_STARTED = -2; static constexpr int RV_RUNNING = -1; int rawStatus_; }; /** * Base exception thrown by the Subprocess methods. */ class SubprocessError : public std::exception {}; /** * Exception thrown by *Checked methods of Subprocess. */ class CalledProcessError : public SubprocessError { public: explicit CalledProcessError(ProcessReturnCode rc); ~CalledProcessError() throw() { } const char* what() const throw() FOLLY_OVERRIDE { return what_.c_str(); } ProcessReturnCode returnCode() const { return returnCode_; } private: ProcessReturnCode returnCode_; std::string what_; }; /** * Exception thrown if the subprocess cannot be started. */ class SubprocessSpawnError : public SubprocessError { public: SubprocessSpawnError(const char* executable, int errCode, int errnoValue); ~SubprocessSpawnError() throw() {} const char* what() const throw() FOLLY_OVERRIDE { return what_.c_str(); } int errnoValue() const { return errnoValue_; } private: int errnoValue_; std::string what_; }; /** * Subprocess. */ class Subprocess { public: static const int CLOSE = -1; static const int PIPE = -2; static const int PIPE_IN = -3; static const int PIPE_OUT = -4; /** * Class representing various options: file descriptor behavior, and * whether to use $PATH for searching for the executable, * * By default, we don't use $PATH, file descriptors are closed if * the close-on-exec flag is set (fcntl FD_CLOEXEC) and inherited * otherwise. */ class Options : private boost::orable<Options> { friend class Subprocess; public: Options() {} // E.g. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58328 /** * Change action for file descriptor fd. * * "action" may be another file descriptor number (dup2()ed before the * child execs), or one of CLOSE, PIPE_IN, and PIPE_OUT. * * CLOSE: close the file descriptor in the child * PIPE_IN: open a pipe *from* the child * PIPE_OUT: open a pipe *to* the child * * PIPE is a shortcut; same as PIPE_IN for stdin (fd 0), same as * PIPE_OUT for stdout (fd 1) or stderr (fd 2), and an error for * other file descriptors. */ Options& fd(int fd, int action); /** * Shortcut to change the action for standard input. */ Options& stdin(int action) { return fd(STDIN_FILENO, action); } /** * Shortcut to change the action for standard output. */ Options& stdout(int action) { return fd(STDOUT_FILENO, action); } /** * Shortcut to change the action for standard error. * Note that stderr(1) will redirect the standard error to the same * file descriptor as standard output; the equivalent of bash's "2>&1" */ Options& stderr(int action) { return fd(STDERR_FILENO, action); } Options& pipeStdin() { return fd(STDIN_FILENO, PIPE_IN); } Options& pipeStdout() { return fd(STDOUT_FILENO, PIPE_OUT); } Options& pipeStderr() { return fd(STDERR_FILENO, PIPE_OUT); } /** * Close all other fds (other than standard input, output, error, * and file descriptors explicitly specified with fd()). * * This is potentially slow; it's generally a better idea to * set the close-on-exec flag on all file descriptors that shouldn't * be inherited by the child. * * Even with this option set, standard input, output, and error are * not closed; use stdin(CLOSE), stdout(CLOSE), stderr(CLOSE) if you * desire this. */ Options& closeOtherFds() { closeOtherFds_ = true; return *this; } /** * Use the search path ($PATH) when searching for the executable. */ Options& usePath() { usePath_ = true; return *this; } /** * Change the child's working directory, after the vfork. */ Options& chdir(const std::string& dir) { childDir_ = dir; return *this; } #if __linux__ /** * Child will receive a signal when the parent exits. */ Options& parentDeathSignal(int sig) { parentDeathSignal_ = sig; return *this; } #endif /** * Child will be made a process group leader when it starts. Upside: one * can reliably all its kill non-daemonizing descendants. Downside: the * child will not receive Ctrl-C etc during interactive use. */ Options& processGroupLeader() { processGroupLeader_ = true; return *this; } /** * Helpful way to combine Options. */ Options& operator|=(const Options& other); private: typedef boost::container::flat_map<int, int> FdMap; FdMap fdActions_; bool closeOtherFds_{false}; bool usePath_{false}; std::string childDir_; // "" keeps the parent's working directory #if __linux__ int parentDeathSignal_{0}; #endif bool processGroupLeader_{false}; }; static Options pipeStdin() { return Options().stdin(PIPE); } static Options pipeStdout() { return Options().stdout(PIPE); } static Options pipeStderr() { return Options().stderr(PIPE); } // Non-copiable, but movable Subprocess(const Subprocess&) = delete; Subprocess& operator=(const Subprocess&) = delete; Subprocess(Subprocess&&) = default; Subprocess& operator=(Subprocess&&) = default; /** * Create a subprocess from the given arguments. argv[0] must be listed. * If not-null, executable must be the actual executable * being used (otherwise it's the same as argv[0]). * * If env is not-null, it must contain name=value strings to be used * as the child's environment; otherwise, we inherit the environment * from the parent. env must be null if options.usePath is set. */ explicit Subprocess( const std::vector<std::string>& argv, const Options& options = Options(), const char* executable = nullptr, const std::vector<std::string>* env = nullptr); ~Subprocess(); /** * Create a subprocess run as a shell command (as shell -c 'command') * * The shell to use is taken from the environment variable $SHELL, * or /bin/sh if $SHELL is unset. */ explicit Subprocess( const std::string& cmd, const Options& options = Options(), const std::vector<std::string>* env = nullptr); //// //// The methods below only manipulate the process state, and do not //// affect its communication pipes. //// /** * Return the child's pid, or -1 if the child wasn't successfully spawned * or has already been wait()ed upon. */ pid_t pid() const; /** * Return the child's status (as per wait()) if the process has already * been waited on, -1 if the process is still running, or -2 if the * process hasn't been successfully started. NOTE that this does not call * waitpid() or Subprocess::poll(), but simply returns the status stored * in the Subprocess object. */ ProcessReturnCode returnCode() const { return returnCode_; } /** * Poll the child's status and return it, return -1 if the process * is still running. NOTE that it is illegal to call poll again after * poll indicated that the process has terminated, or to call poll on a * process that hasn't been successfully started (the constructor threw an * exception). */ ProcessReturnCode poll(); /** * Poll the child's status. If the process is still running, return false. * Otherwise, return true if the process exited with status 0 (success), * or throw CalledProcessError if the process exited with a non-zero status. */ bool pollChecked(); /** * Wait for the process to terminate and return its status. * Similarly to poll, it is illegal to call wait after the process * has already been reaped or if the process has not successfully started. */ ProcessReturnCode wait(); /** * Wait for the process to terminate, throw if unsuccessful. */ void waitChecked(); /** * Send a signal to the child. Shortcuts for the commonly used Unix * signals are below. */ void sendSignal(int signal); void terminate() { sendSignal(SIGTERM); } void kill() { sendSignal(SIGKILL); } //// //// The methods below only affect the process's communication pipes, but //// not its return code or state (they do not poll() or wait()). //// /** * Communicate with the child until all pipes to/from the child are closed. * * The input buffer is written to the process' stdin pipe, and data is read * from the stdout and stderr pipes. Non-blocking I/O is performed on all * pipes simultaneously to avoid deadlocks. * * The stdin pipe will be closed after the full input buffer has been written. * An error will be thrown if a non-empty input buffer is supplied but stdin * was not configured as a pipe. * * Returns a pair of buffers containing the data read from stdout and stderr. * If stdout or stderr is not a pipe, an empty IOBuf queue will be returned * for the respective buffer. * * Note that communicate() and communicateIOBuf() both return when all * pipes to/from the child are closed; the child might stay alive after * that, so you must still wait(). * * communicateIOBuf() uses IOBufQueue for buffering (which has the * advantage that it won't try to allocate all data at once), but it does * store the subprocess's entire output in memory before returning. * * communicate() uses strings for simplicity. */ std::pair<IOBufQueue, IOBufQueue> communicateIOBuf( IOBufQueue input = IOBufQueue()); std::pair<std::string, std::string> communicate( StringPiece input = StringPiece()); /** * Communicate with the child until all pipes to/from the child are closed. * * == Semantics == * * readCallback(pfd, cfd) will be called whenever there's data available * on any pipe *from* the child (PIPE_OUT). pfd is the file descriptor * in the parent (that you use to read from); cfd is the file descriptor * in the child (used for identifying the stream; 1 = child's standard * output, 2 = child's standard error, etc) * * writeCallback(pfd, cfd) will be called whenever a pipe *to* the child is * writable (PIPE_IN). pfd is the file descriptor in the parent (that you * use to write to); cfd is the file descriptor in the child (used for * identifying the stream; 0 = child's standard input, etc) * * The read and write callbacks must read from / write to pfd and return * false during normal operation. Return true to tell communicate() to * close the pipe. For readCallback, this might send SIGPIPE to the * child, or make its writes fail with EPIPE, so you should generally * avoid returning true unless you've reached end-of-file. * * communicate() returns when all pipes to/from the child are closed; the * child might stay alive after that, so you must still wait(). * Conversely, the child may quit long before its pipes are closed, since * its descendants can keep them alive forever. * * Most users won't need to use this callback version; the simpler version * of communicate (which buffers data in memory) will probably work fine. * * == Things you must get correct == * * 1) You MUST consume all data passed to readCallback (or return true to * close the pipe). Similarly, you MUST write to a writable pipe (or * return true to close the pipe). To do otherwise is an error that can * result in a deadlock. You must do this even for pipes you are not * interested in. * * 2) pfd is nonblocking, so be prepared for read() / write() to return -1 * and set errno to EAGAIN (in which case you should return false). Use * readNoInt() from FileUtil.h to handle interrupted reads for you. * * 3) Your callbacks MUST NOT call any of the Subprocess methods that * manipulate the pipe FDs. Check the docblocks, but, for example, * neither closeParentFd (return true instead) nor takeOwnershipOfPipes * are safe. Stick to reading/writing from pfd, as appropriate. * * == Good to know == * * 1) See ReadLinesCallback for an easy way to consume the child's output * streams line-by-line (or tokenized by another delimiter). * * 2) "Wait until the descendants close the pipes" is usually the behavior * you want, since the descendants may have something to say even if the * immediate child is dead. If you need to be able to force-close all * parent FDs, communicate() will NOT work for you. Do it your own way by * using takeOwnershipOfPipes(). * * Why not? You can return "true" from your callbacks to sever active * pipes, but inactive ones can remain open indefinitely. It is * impossible to safely close inactive pipes while another thread is * blocked in communicate(). This is BY DESIGN. Racing communicate()'s * read/write callbacks can result in wrong I/O and data corruption. This * class would need internal synchronization and timeouts, a poor and * expensive implementation choice, in order to make closeParentFd() * thread-safe. */ typedef std::function<bool(int, int)> FdCallback; void communicate(FdCallback readCallback, FdCallback writeCallback); /** * A readCallback for Subprocess::communicate() that helps you consume * lines (or other delimited pieces) from your subprocess's file * descriptors. Use the readLinesCallback() helper to get template * deduction. For example: * * auto read_cb = Subprocess::readLinesCallback( * [](int fd, folly::StringPiece s) { * std::cout << fd << " said: " << s; * return false; // Keep reading from the child * } * ); * subprocess.communicate( * // ReadLinesCallback contains StreamSplitter contains IOBuf, making * // it noncopyable, whereas std::function must be copyable. So, we * // keep the callback in a local, and instead pass a reference. * std::ref(read_cb), * [](int pdf, int cfd){ return true; } // Don't write to the child * ); * * If a file line exceeds maxLineLength, your callback will get some * initial chunks of maxLineLength with no trailing delimiters. The final * chunk of a line is delimiter-terminated iff the delimiter was present * in the input. In particular, the last line in a file always lacks a * delimiter -- so if a file ends on a delimiter, the final line is empty. * * Like a regular communicate() callback, your fdLineCb() normally returns * false. It may return true to tell Subprocess to close the underlying * file descriptor. The child process may then receive SIGPIPE or get * EPIPE errors on writes. */ template <class Callback> class ReadLinesCallback { private: // Binds an FD to the client-provided FD+line callback struct StreamSplitterCallback { StreamSplitterCallback(Callback& cb, int fd) : cb_(cb), fd_(fd) { } // The return value semantics are inverted vs StreamSplitter bool operator()(StringPiece s) { return !cb_(fd_, s); } Callback& cb_; int fd_; }; typedef gen::StreamSplitter<StreamSplitterCallback> LineSplitter; public: explicit ReadLinesCallback( Callback&& fdLineCb, uint64_t maxLineLength = 0, // No line length limit by default char delimiter = '\n', uint64_t bufSize = 1024 ) : fdLineCb_(std::move(fdLineCb)), maxLineLength_(maxLineLength), delimiter_(delimiter), bufSize_(bufSize) {} bool operator()(int pfd, int cfd) { // Make a splitter for this cfd if it doesn't already exist auto it = fdToSplitter_.find(cfd); auto& splitter = (it != fdToSplitter_.end()) ? it->second : fdToSplitter_.emplace(cfd, LineSplitter( delimiter_, StreamSplitterCallback(fdLineCb_, cfd), maxLineLength_ )).first->second; // Read as much as we can from this FD char buf[bufSize_]; while (true) { ssize_t ret = readNoInt(pfd, buf, bufSize_); if (ret == -1 && errno == EAGAIN) { // No more data for now return false; } if (ret == 0) { // Reached end-of-file splitter.flush(); // Ignore return since the file is over anyway return true; } if (!splitter(StringPiece(buf, ret))) { return true; // The callback told us to stop } } } private: Callback fdLineCb_; const uint64_t maxLineLength_; const char delimiter_; const uint64_t bufSize_; // We lazily make splitters for all cfds that get used. std::unordered_map<int, LineSplitter> fdToSplitter_; }; // Helper to enable template deduction template <class Callback> static ReadLinesCallback<Callback> readLinesCallback( Callback&& fdLineCb, uint64_t maxLineLength = 0, // No line length limit by default char delimiter = '\n', uint64_t bufSize = 1024) { return ReadLinesCallback<Callback>( std::move(fdLineCb), maxLineLength, delimiter, bufSize ); } /** * communicate() callbacks can use this to temporarily enable/disable * notifications (callbacks) for a pipe to/from the child. By default, * all are enabled. Useful for "chatty" communication -- you want to * disable write callbacks until you receive the expected message. * * Disabling a pipe does not free you from the requirement to consume all * incoming data. Failing to do so will easily create deadlock bugs. * * Throws if the childFd is not known. */ void enableNotifications(int childFd, bool enabled); /** * Are notifications for one pipe to/from child enabled? Throws if the * childFd is not known. */ bool notificationsEnabled(int childFd) const; //// //// The following methods are meant for the cases when communicate() is //// not suitable. You should not need them when you call communicate(), //// and, in fact, it is INHERENTLY UNSAFE to use closeParentFd() or //// takeOwnershipOfPipes() from a communicate() callback. //// /** * Close the parent file descriptor given a file descriptor in the child. * DO NOT USE from communicate() callbacks; make them return true instead. */ void closeParentFd(int childFd); /** * Set all pipes from / to child to be non-blocking. communicate() does * this for you. */ void setAllNonBlocking(); /** * Get parent file descriptor corresponding to the given file descriptor * in the child. Throws if childFd isn't a pipe (PIPE_IN / PIPE_OUT). * Do not close() the returned file descriptor; use closeParentFd, above. */ int parentFd(int childFd) const { return pipes_[findByChildFd(childFd)].pipe.fd(); } int stdin() const { return parentFd(0); } int stdout() const { return parentFd(1); } int stderr() const { return parentFd(2); } /** * The child's pipes are logically separate from the process metadata * (they may even be kept alive by the child's descendants). This call * lets you manage the pipes' lifetime separetely from the lifetime of the * child process. * * After this call, the Subprocess instance will have no knowledge of * these pipes, and the caller assumes responsibility for managing their * lifetimes. Pro-tip: prefer to explicitly close() the pipes, since * folly::File would otherwise silently suppress I/O errors. * * No, you may NOT call this from a communicate() callback. */ struct ChildPipe { int childFd; folly::File pipe; // Owns the parent FD }; std::vector<ChildPipe> takeOwnershipOfPipes(); private: static const int RV_RUNNING = ProcessReturnCode::RV_RUNNING; static const int RV_NOT_STARTED = ProcessReturnCode::RV_NOT_STARTED; // spawn() sets up a pipe to read errors from the child, // then calls spawnInternal() to do the bulk of the work. Once // spawnInternal() returns it reads the error pipe to see if the child // encountered any errors. void spawn( std::unique_ptr<const char*[]> argv, const char* executable, const Options& options, const std::vector<std::string>* env); void spawnInternal( std::unique_ptr<const char*[]> argv, const char* executable, Options& options, const std::vector<std::string>* env, int errFd); // Actions to run in child. // Note that this runs after vfork(), so tread lightly. // Returns 0 on success, or an errno value on failure. int prepareChild(const Options& options, const sigset_t* sigmask, const char* childDir) const; int runChild(const char* executable, char** argv, char** env, const Options& options) const; /** * Read from the error pipe, and throw SubprocessSpawnError if the child * failed before calling exec(). */ void readChildErrorPipe(int pfd, const char* executable); // Returns an index into pipes_. Throws std::invalid_argument if not found. size_t findByChildFd(const int childFd) const; pid_t pid_; ProcessReturnCode returnCode_; /** * Represents a pipe between this process, and the child process (or its * descendant). To interact with these pipes, you can use communicate(), * or use parentFd() and related methods, or separate them from the * Subprocess instance entirely via takeOwnershipOfPipes(). */ struct Pipe : private boost::totally_ordered<Pipe> { folly::File pipe; // Our end of the pipe, wrapped in a File to auto-close. int childFd = -1; // Identifies the pipe: what FD is this in the child? int direction = PIPE_IN; // one of PIPE_IN / PIPE_OUT bool enabled = true; // Are notifications enabled in communicate()? bool operator<(const Pipe& other) const { return childFd < other.childFd; } bool operator==(const Pipe& other) const { return childFd == other.childFd; } }; // Populated at process start according to fdActions, empty after // takeOwnershipOfPipes(). Sorted by childFd. Can only have elements // erased, but not inserted, after being populated. // // The number of pipes between parent and child is assumed to be small, // so we're happy with a vector here, even if it means linear erase. std::vector<Pipe> pipes_; }; inline Subprocess::Options& Subprocess::Options::operator|=( const Subprocess::Options& other) { if (this == &other) return *this; // Replace for (auto& p : other.fdActions_) { fdActions_[p.first] = p.second; } closeOtherFds_ |= other.closeOtherFds_; usePath_ |= other.usePath_; processGroupLeader_ |= other.processGroupLeader_; return *this; } } // namespace folly #endif /* FOLLY_SUBPROCESS_H_ */
{ "content_hash": "1a01918d41d3b82c0f0e52f375d8a6e5", "timestamp": "", "source": "github", "line_count": 794, "max_line_length": 80, "avg_line_length": 36.714105793450884, "alnum_prop": 0.6792219820932387, "repo_name": "bsampath/folly", "id": "da2b560241fdf80eb9160648d6f5746487b18cc4", "size": "29746", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "folly/Subprocess.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "29710" }, { "name": "C++", "bytes": "5262656" }, { "name": "CSS", "bytes": "165" }, { "name": "Makefile", "bytes": "700" }, { "name": "Python", "bytes": "8495" }, { "name": "Ruby", "bytes": "1531" }, { "name": "Shell", "bytes": "1064" } ], "symlink_target": "" }
const debug = require('debug')('ali-oss'); const sendToWormhole = require('stream-wormhole'); const xml = require('xml2js'); const AgentKeepalive = require('agentkeepalive'); const HttpsAgentKeepalive = require('agentkeepalive').HttpsAgent; const merge = require('merge-descriptors'); const platform = require('platform'); const utility = require('utility'); const urllib = require('urllib'); const pkg = require('../package.json'); const bowser = require('bowser'); const signUtils = require('./common/signUtils'); const _initOptions = require('./common/client/initOptions'); const { createRequest } = require('./common/utils/createRequest'); const { encoder } = require('./common/utils/encoder'); const { getReqUrl } = require('./common/client/getReqUrl'); const { setSTSToken } = require('./common/utils/setSTSToken'); const { retry } = require('./common/utils/retry'); const { isFunction } = require('./common/utils/isFunction'); const globalHttpAgent = new AgentKeepalive(); const globalHttpsAgent = new HttpsAgentKeepalive(); function Client(options, ctx) { if (!(this instanceof Client)) { return new Client(options, ctx); } if (options && options.inited) { this.options = options; } else { this.options = Client.initOptions(options); } // support custom agent and urllib client if (this.options.urllib) { this.urllib = this.options.urllib; } else { this.urllib = urllib; if (this.options.maxSockets) { globalHttpAgent.maxSockets = this.options.maxSockets; globalHttpsAgent.maxSockets = this.options.maxSockets; } this.agent = this.options.agent || globalHttpAgent; this.httpsAgent = this.options.httpsAgent || globalHttpsAgent; } this.ctx = ctx; this.userAgent = this._getUserAgent(); this.stsTokenFreshTime = new Date(); } /** * Expose `Client` */ module.exports = Client; Client.initOptions = function initOptions(options) { return _initOptions(options); }; /** * prototype */ const proto = Client.prototype; /** * Object operations */ merge(proto, require('./common/object')); merge(proto, require('./object')); merge(proto, require('./common/image')); /** * Bucket operations */ merge(proto, require('./common/bucket')); merge(proto, require('./bucket')); // multipart upload merge(proto, require('./managed-upload')); /** * RTMP operations */ merge(proto, require('./rtmp')); /** * common multipart-copy support node and browser */ merge(proto, require('./common/multipart-copy')); /** * Common module parallel */ merge(proto, require('./common/parallel')); /** * Multipart operations */ merge(proto, require('./common/multipart')); /** * ImageClient class */ Client.ImageClient = require('./image')(Client); /** * Cluster Client class */ Client.ClusterClient = require('./cluster')(Client); /** * STS Client class */ Client.STS = require('./sts'); /** * get OSS signature * @param {String} stringToSign * @return {String} the signature */ proto.signature = function signature(stringToSign) { debug('authorization stringToSign: %s', stringToSign); return signUtils.computeSignature(this.options.accessKeySecret, stringToSign, this.options.headerEncoding); }; proto._getReqUrl = getReqUrl; /** * get author header * * "Authorization: OSS " + Access Key Id + ":" + Signature * * Signature = base64(hmac-sha1(Access Key Secret + "\n" * + VERB + "\n" * + CONTENT-MD5 + "\n" * + CONTENT-TYPE + "\n" * + DATE + "\n" * + CanonicalizedOSSHeaders * + CanonicalizedResource)) * * @param {String} method * @param {String} resource * @param {Object} header * @return {String} * * @api private */ proto.authorization = function authorization(method, resource, subres, headers) { const stringToSign = signUtils.buildCanonicalString(method.toUpperCase(), resource, { headers, parameters: subres }); return signUtils.authorization( this.options.accessKeyId, this.options.accessKeySecret, stringToSign, this.options.headerEncoding ); }; /** * request oss server * @param {Object} params * - {String} object * - {String} bucket * - {Object} [headers] * - {Object} [query] * - {Buffer} [content] * - {Stream} [stream] * - {Stream} [writeStream] * - {String} [mime] * - {Boolean} [xmlResponse] * - {Boolean} [customResponse] * - {Number} [timeout] * - {Object} [ctx] request context, default is `this.ctx` * * @api private */ proto.request = async function (params) { if (this.options.retryMax) { return await retry(request.bind(this), this.options.retryMax, { errorHandler: err => { const _errHandle = _err => { if (params.stream) return false; const statusErr = [-1, -2].includes(_err.status); const requestErrorRetryHandle = this.options.requestErrorRetryHandle || (() => true); return statusErr && requestErrorRetryHandle(_err); }; if (_errHandle(err)) return true; return false; } })(params); } else { return await request.call(this, params); } }; async function request(params) { if (this.options.stsToken && isFunction(this.options.refreshSTSToken)) { await setSTSToken.call(this); } const reqParams = createRequest.call(this, params); let result; let reqErr; try { result = await this.urllib.request(reqParams.url, reqParams.params); debug('response %s %s, got %s, headers: %j', params.method, reqParams.url, result.status, result.headers); } catch (err) { reqErr = err; } let err; if (result && params.successStatuses && params.successStatuses.indexOf(result.status) === -1) { err = await this.requestError(result); err.params = params; } else if (reqErr) { err = await this.requestError(reqErr); } if (err) { if (params.customResponse && result && result.res) { // consume the response stream await sendToWormhole(result.res); } if (err.name === 'ResponseTimeoutError') { err.message = `${err.message.split(',')[0]}, please increase the timeout or use multipartDownload.`; } throw err; } if (params.xmlResponse) { result.data = await this.parseXML(result.data); } return result; } proto._getResource = function _getResource(params) { let resource = '/'; if (params.bucket) resource += `${params.bucket}/`; if (params.object) resource += encoder(params.object, this.options.headerEncoding); return resource; }; proto._escape = function _escape(name) { return utility.encodeURIComponent(name).replace(/%2F/g, '/'); }; /* * Get User-Agent for browser & node.js * @example * aliyun-sdk-nodejs/4.1.2 Node.js 5.3.0 on Darwin 64-bit * aliyun-sdk-js/4.1.2 Safari 9.0 on Apple iPhone(iOS 9.2.1) * aliyun-sdk-js/4.1.2 Chrome 43.0.2357.134 32-bit on Windows Server 2008 R2 / 7 64-bit */ proto._getUserAgent = function _getUserAgent() { const agent = process && process.browser ? 'js' : 'nodejs'; const sdk = `aliyun-sdk-${agent}/${pkg.version}`; let plat = platform.description; if (!plat && process) { plat = `Node.js ${process.version.slice(1)} on ${process.platform} ${process.arch}`; } return this._checkUserAgent(`${sdk} ${plat}`); }; proto._checkUserAgent = function _checkUserAgent(ua) { const userAgent = ua.replace(/\u03b1/, 'alpha').replace(/\u03b2/, 'beta'); return userAgent; }; /* * Check Browser And Version * @param {String} [name] browser name: like IE, Chrome, Firefox * @param {String} [version] browser major version: like 10(IE 10.x), 55(Chrome 55.x), 50(Firefox 50.x) * @return {Bool} true or false * @api private */ proto.checkBrowserAndVersion = function checkBrowserAndVersion(name, version) { return bowser.name === name && bowser.version.split('.')[0] === version; }; /** * thunkify xml.parseString * @param {String|Buffer} str * * @api private */ proto.parseXML = function parseXMLThunk(str) { return new Promise((resolve, reject) => { if (Buffer.isBuffer(str)) { str = str.toString(); } xml.parseString( str, { explicitRoot: false, explicitArray: false }, (err, result) => { if (err) { reject(err); } else { resolve(result); } } ); }); }; /** * generater a request error with request response * @param {Object} result * * @api private */ proto.requestError = async function requestError(result) { let err = null; if (result.name === 'ResponseTimeoutError') { err = new Error(result.message); err.name = result.name; } else if (!result.data || !result.data.length) { if (result.status === -1 || result.status === -2) { // -1 is net error , -2 is timeout err = new Error(result.message); err.name = result.name; err.status = result.status; err.code = result.name; } else { // HEAD not exists resource if (result.status === 404) { err = new Error('Object not exists'); err.name = 'NoSuchKeyError'; err.status = 404; err.code = 'NoSuchKey'; } else if (result.status === 412) { err = new Error('Pre condition failed'); err.name = 'PreconditionFailedError'; err.status = 412; err.code = 'PreconditionFailed'; } else { err = new Error(`Unknow error, status: ${result.status}`); err.name = 'UnknownError'; err.status = result.status; } err.requestId = result.headers['x-oss-request-id']; err.host = ''; } } else { const message = String(result.data); debug('request response error data: %s', message); let info; try { info = (await this.parseXML(message)) || {}; } catch (error) { debug(message); error.message += `\nraw xml: ${message}`; error.status = result.status; error.requestId = result.headers['x-oss-request-id']; return error; } let msg = info.Message || `unknow request error, status: ${result.status}`; if (info.Condition) { msg += ` (condition: ${info.Condition})`; } err = new Error(msg); err.name = info.Code ? `${info.Code}Error` : 'UnknownError'; err.status = result.status; err.code = info.Code; err.requestId = info.RequestId; err.hostId = info.HostId; } debug('generate error %j', err); return err; }; proto.setSLDEnabled = function setSLDEnabled(enable) { this.options.sldEnable = !!enable; return this; };
{ "content_hash": "a20f9ff916524e5df70e54f45b3acc34", "timestamp": "", "source": "github", "line_count": 387, "max_line_length": 110, "avg_line_length": 27.041343669250647, "alnum_prop": 0.6394648829431439, "repo_name": "ali-sdk/ali-oss", "id": "5203237141a99009ae68cd60015812e8aff0a82b", "size": "10465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/client.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "267" }, { "name": "HTML", "bytes": "204474" }, { "name": "JavaScript", "bytes": "685520" }, { "name": "Shell", "bytes": "141" }, { "name": "TypeScript", "bytes": "34276" } ], "symlink_target": "" }
package org.apache.tapestry5.ioc.internal.services; import org.apache.tapestry5.beaneditor.DataType; import org.apache.tapestry5.beaneditor.Validate; public class Bean { public static final Double PI = 3.14; @DataType("fred") @Validate("field-value-overridden") private int value; @Validate("getter-value-overrides") public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public String toString() { return "PropertyAccessImplSpecBean"; } public void setWriteOnly(boolean b) { } public String getReadOnly() { return null; } }
{ "content_hash": "266e3c0e7fb3e14db461efee971413e7", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 51, "avg_line_length": 17.94871794871795, "alnum_prop": 0.6357142857142857, "repo_name": "agileowl/tapestry-5", "id": "3fae5a641a2dc23fb3dc530378665b2b0fdd622b", "size": "700", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tapestry-ioc/src/test/java/org/apache/tapestry5/ioc/internal/services/Bean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Clojure", "bytes": "98" }, { "name": "Groovy", "bytes": "413014" }, { "name": "Java", "bytes": "7942669" }, { "name": "JavaScript", "bytes": "239297" }, { "name": "Shell", "bytes": "5079" } ], "symlink_target": "" }
<?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.view'); class GantryViewTemplate extends GantryLegacyJView { protected $_version = '4.1.8'; protected $item; protected $form; protected $state; protected $override = false; protected $gantryForm; protected $tabs; protected $activeTab; protected $assignmentCount; function display($tpl = null) { /** @var $gantry Gantry */ global $gantry; $language = JFactory::getLanguage(); $language->load('com_templates'); $this->item = $this->get('Item'); JHtml::_('behavior.framework', true); require_once(JPATH_LIBRARIES . "/gantry/gantry.php"); gantry_import('core.config.gantryform'); GantryForm::addFormPath(JPATH_COMPONENT_ADMINISTRATOR); GantryForm::addFormPath($gantry->templatePath); GantryForm::addFieldPath($gantry->gantryPath . '/admin/forms/fields'); GantryForm::addFieldPath($gantry->templatePath . '/fields'); GantryForm::addFieldPath($gantry->templatePath . '/admin/forms/fields'); GantryForm::addGroupPath($gantry->gantryPath . '/admin/forms/groups'); GantryForm::addGroupPath($gantry->templatePath . '/admin/forms/groups'); $this->state = $this->get('State'); $this->form = $this->get('Form'); $this->override = $this->get('Override'); $this->gantryForm = $this->get('GantryForm'); $this->activeTab = (isset($_COOKIE['gantry-admin-tab'])) ? $_COOKIE['gantry-admin-tab'] + 1 : 1; $this->tabs = $this->getTabs($this->gantryForm); $this->assignmentCount = $this->getAssignmentCount($this->item->id); $model = $this->getModel(); $model->checkForGantryUpdate(); //$this->addToolbar(); JToolBarHelper::title(''); ob_start(); parent::display($tpl); $buffer = ob_get_clean(); echo $buffer; } private function getAssignmentCount($id) { require_once JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php'; $assignment_count = 0; $menuTypes = MenusHelper::getMenuLinks(); foreach ($menuTypes as &$type) { foreach ($type->links as $link) { if ($link->template_style_id == $id) $assignment_count++; } } return $assignment_count; } protected function getTabs($gantryForm) { $tabs = array(); $fieldSets = $gantryForm->getFieldsets(); $i = 1; $activeTab = $this->activeTab; if ($activeTab > count($fieldSets) - 1) $activeTab = 1; $fieldsetCount = count($fieldSets); foreach ($fieldSets as $name => $fieldSet) { if ($name == 'toolbar-panel') { $fieldsetCount--; continue; } $classes = ''; if ($i == 1) $classes .= "first"; if ($i == $fieldsetCount) $classes .= "last"; if ($i == $activeTab) $classes .= " active "; $tabs[$name] = $classes; $i++; } return $tabs; } /** * Add the page title and toolbar. * * @since 1.6 */ protected function addToolbar() { JFactory::getApplication()->input->set('hidemainmenu', true); $user = JFactory::getUser(); $isNew = ($this->item->id == 0); $canDo = $this->getActions(); JToolBarHelper::title($isNew ? JText::_('Templates Manager: Add Style') : JText::_('Templates Manager: Edit Style'), 'thememanager'); // If not checked out, can save the item. if ($canDo->get('core.edit')) { JToolBarHelper::apply('template.apply', 'JTOOLBAR_APPLY'); JToolBarHelper::save('template.save', 'JTOOLBAR_SAVE'); } // If an existing item, can save to a copy. // If an existing item, can save to a copy. if (!$isNew && $canDo->get('core.create')) { JToolBarHelper::custom('template.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); } JToolBarHelper::divider(); if (!$isNew && $canDo->get('core.create')) { if (!$this->override) JToolBarHelper::custom('template.reset', 'purge.png', 'purge_f2.png', 'Reset to Defaults', false); else JToolBarHelper::custom('template.reset', 'purge.png', 'purge_f2.png', 'Reset to Master', false); } if (!$isNew && $canDo->get('core.create')) { JToolBarHelper::custom('template.reset', 'new-style.png', 'new-style_f2.png', 'Save Preset', false); } if (!$isNew && $canDo->get('core.create')) { JToolBarHelper::custom('', 'delete-style.png', 'new-style_f2.png', 'Show Presets', false); } JToolBarHelper::divider(); if (empty($this->item->id)) { JToolBarHelper::cancel('template.cancel', 'JTOOLBAR_CANCEL'); } else { JToolBarHelper::cancel('template.cancel', 'JTOOLBAR_CLOSE'); } JToolBarHelper::divider(); // Get the help information for the template item. $lang = JFactory::getLanguage(); $help = $this->get('Help'); JToolBarHelper::help($help->key, false, $lang->hasKey($help->url) ? JText::_($help->url) : null); } /** * Gets a list of the actions that can be performed. * * @return JObject */ public function getActions() { $user = JFactory::getUser(); $result = new JObject; $actions = JAccess::getActions('com_templates'); foreach ($actions as $action) { $result->set($action->name, $user->authorise($action->name, 'com_templates')); } return $result; } protected function _appendCacheToken() { return '?cache=' . $this->_version; } protected function compileLess() { /** @var $gantry Gantry */ global $gantry; $less_path = JPATH_COMPONENT_ADMINISTRATOR . '/assets/less'; if (is_dir($less_path)) { $gantry->addLess($less_path . '/global.less', JURI::root(true) . '/libraries/gantry/admin/widgets/gantry-administrator.css'); if ($gantry->browser->name == 'ie'){ $gantry->addLess($less_path . '/fixes-ie.less', JURI::root(true) . '/libraries/gantry/admin/widgets/fixes-ie.css'); } } else { $gantry->addStyle(JURI::root(true) . '/libraries/gantry/admin/widgets/gantry-administrator.css'); if ($gantry->browser->name == 'ie'){ $gantry->addStyle(JURI::root(true) . '/libraries/gantry/admin/widgets/fixes-ie.css'); } } } }
{ "content_hash": "a5d04e7bcd52972d9e1ec1b7e688bf54", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 135, "avg_line_length": 29.170731707317074, "alnum_prop": 0.6413043478260869, "repo_name": "creative2020/f4u", "id": "316e0496abc0d54ee2b4ee5cfb785d679911a43f", "size": "6356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "administrator/components/com_gantry/views/template/view.html.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3575" }, { "name": "CSS", "bytes": "1833367" }, { "name": "HTML", "bytes": "437498" }, { "name": "JavaScript", "bytes": "1933348" }, { "name": "PHP", "bytes": "19706784" } ], "symlink_target": "" }
''' Run ParRes dgemm with the monitor agent. ''' import argparse from experiment.monitor import monitor from experiment import machine from apps.parres import parres if __name__ == '__main__': parser = argparse.ArgumentParser() monitor.setup_run_args(parser) parres.setup_run_args(parser) args, extra_args = parser.parse_known_args() mach = machine.init_output_dir(args.output_dir) app_conf = parres.create_dgemm_appconf_cuda(mach, args) monitor.launch(app_conf=app_conf, args=args, experiment_cli_args=extra_args)
{ "content_hash": "382cc6ca92c3fc849033907b8f4f2ca7", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 59, "avg_line_length": 28.3, "alnum_prop": 0.6978798586572438, "repo_name": "geopm/geopm", "id": "df4927ba8d36c1b6976194afb99c75f8cfadf7db", "size": "683", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "integration/experiment/monitor/run_monitor_parres_dgemm_cuda.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "342266" }, { "name": "C++", "bytes": "3265994" }, { "name": "Fortran", "bytes": "106333" }, { "name": "HTML", "bytes": "1251" }, { "name": "M4", "bytes": "50970" }, { "name": "Makefile", "bytes": "171548" }, { "name": "Nasal", "bytes": "2898" }, { "name": "Python", "bytes": "1180435" }, { "name": "Shell", "bytes": "148018" } ], "symlink_target": "" }
import * as request from 'superagent'; import * as _ from 'lodash'; export class APIClient { constructor() { } get(url: string, query: {}) { return request.get(url).query(query); } } export class SlackAPIClient extends APIClient{ private url = 'https://slack.com/api/'; constructor(private token) { super() } public listChannels(excludeArchived: number = 0) { let query = _.extend({ exclude_archived: excludeArchived.toString() }, { token: this.token }); return this.get(this.url + 'channels.list', query); } }
{ "content_hash": "342191ecbf6b916a3cce7d19f7fb4d03", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 96, "avg_line_length": 21.4, "alnum_prop": 0.6766355140186916, "repo_name": "hideto0710/slack-trend-redux", "id": "6c2860bb4e1df84dbe525b143d53b1ae7da00bbc", "size": "650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/classes/SlackAPIClient.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "40" }, { "name": "HTML", "bytes": "350" }, { "name": "JavaScript", "bytes": "11011" }, { "name": "TypeScript", "bytes": "3219" } ], "symlink_target": "" }
; (function() { window.require(["ace/snippets/xml"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
{ "content_hash": "88eed5c125a61e9179e8a49c041e8377", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 76, "avg_line_length": 23.625, "alnum_prop": 0.544973544973545, "repo_name": "TeamSPoon/logicmoo_workspace", "id": "2fb3aeba798d7b47b16102d0e59af1f4d1d8544f", "size": "189", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packs_web/swish/web/node_modules/ace/build/src-min/snippets/xml.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "342" }, { "name": "C", "bytes": "1" }, { "name": "C++", "bytes": "1" }, { "name": "CSS", "bytes": "126627" }, { "name": "HTML", "bytes": "839172" }, { "name": "Java", "bytes": "11116" }, { "name": "JavaScript", "bytes": "238700" }, { "name": "PHP", "bytes": "42253" }, { "name": "Perl 6", "bytes": "23" }, { "name": "Prolog", "bytes": "440882" }, { "name": "PureBasic", "bytes": "1334" }, { "name": "Rich Text Format", "bytes": "3436542" }, { "name": "Roff", "bytes": "42" }, { "name": "Shell", "bytes": "61603" }, { "name": "TeX", "bytes": "99504" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b5b199e0d8e52998ee5bf4e48eaf6f6e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "2e21ea59bb19d6a99804b7275603c8e97832d46e", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Hieracium/Hieracium parile/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module ActionCable module Channel # The channel provides the basic structure of grouping behavior into logical units when communicating over the websocket connection. # You can think of a channel like a form of controller, but one that's capable of pushing content to the subscriber in addition to simply # responding to the subscriber's direct requests. # # Channel instances are long-lived. A channel object will be instantiated when the cable consumer becomes a subscriber, and then # lives until the consumer disconnects. This may be seconds, minutes, hours, or even days. That means you have to take special care # not to do anything silly in a channel that would balloon its memory footprint or whatever. The references are forever, so they won't be released # as is normally the case with a controller instance that gets thrown away after every request. # # Long-lived channels (and connections) also mean you're responsible for ensuring that the data is fresh. If you hold a reference to a user # record, but the name is changed while that reference is held, you may be sending stale data if you don't take precautions to avoid it. # # The upside of long-lived channel instances is that you can use instance variables to keep reference to objects that future subscriber requests # can interact with. Here's a quick example: # # class ChatChannel < ApplicationChannel # def subscribed # @room = Chat::Room[params[:room_number]] # end # # def speak(data) # @room.speak data, user: current_user # end # end # # The #speak action simply uses the Chat::Room object that was created when the channel was first subscribed to by the consumer when that # subscriber wants to say something in the room. # # == Action processing # # Unlike Action Controllers, channels do not follow a REST constraint form for its actions. It's an remote-procedure call model. You can # declare any public method on the channel (optionally taking a data argument), and this method is automatically exposed as callable to the client. # # Example: # # class AppearanceChannel < ApplicationCable::Channel # def subscribed # @connection_token = generate_connection_token # end # # def unsubscribed # current_user.disappear @connection_token # end # # def appear(data) # current_user.appear @connection_token, on: data['appearing_on'] # end # # def away # current_user.away @connection_token # end # # private # def generate_connection_token # SecureRandom.hex(36) # end # end # # In this example, subscribed/unsubscribed are not callable methods, as they were already declared in ActionCable::Channel::Base, but #appear/away # are. #generate_connection_token is also not callable as its a private method. You'll see that appear accepts a data parameter, which it then # uses as part of its model call. #away does not, it's simply a trigger action. class Base include Callbacks include PeriodicTimers include Streams on_subscribe :subscribed on_unsubscribe :unsubscribed attr_reader :params, :connection delegate :logger, to: :connection def initialize(connection, identifier, params = {}) @connection = connection @identifier = identifier @params = params subscribe_to_channel end # Extract the action name from the passed data and process it via the channel. The process will ensure # that the action requested is a public method on the channel declared by the user (so not one of the callbacks # like #subscribed). def perform_action(data) action = extract_action(data) if processable_action?(action) dispatch_action(action, data) else logger.error "Unable to process #{action_signature(action, data)}" end end # Called by the cable connection when its cut so the channel has a chance to cleanup with callbacks. # This method is not intended to be called directly by the user. Instead, overwrite the #unsubscribed callback. def unsubscribe_from_channel run_unsubscribe_callbacks logger.info "#{self.class.name} unsubscribed" end protected # Called once a consumer has become a subscriber of the channel. Usually the place to setup any streams # you want this channel to be sending to the subscriber. def subscribed # Override in subclasses end # Called once a consumer has cut its cable connection. Can be used for cleaning up connections or marking # people as offline or the like. def unsubscribed # Override in subclasses end # Transmit a hash of data to the subscriber. The hash will automatically be wrapped in a JSON envelope with # the proper channel identifier marked as the recipient. def transmit(data, via: nil) logger.info "#{self.class.name} transmitting #{data.inspect}".tap { |m| m << " (via #{via})" if via } connection.transmit({ identifier: @identifier, message: data }.to_json) end private def subscribe_to_channel logger.info "#{self.class.name} subscribing" run_subscribe_callbacks end def extract_action(data) (data['action'].presence || :receive).to_sym end def processable_action?(action) self.class.instance_methods(false).include?(action) end def dispatch_action(action, data) logger.info action_signature(action, data) if method(action).arity == 1 public_send action, data else public_send action end end def action_signature(action, data) "#{self.class.name}##{action}".tap do |signature| if (arguments = data.except('action')).any? signature << "(#{arguments.inspect})" end end end def run_subscribe_callbacks self.class.on_subscribe_callbacks.each { |callback| send(callback) } end def run_unsubscribe_callbacks self.class.on_unsubscribe_callbacks.each { |callback| send(callback) } end end end end
{ "content_hash": "894ed3c1dfd5cc9086bcd5fe6d441659", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 151, "avg_line_length": 39.17857142857143, "alnum_prop": 0.6496505621391674, "repo_name": "cristianbica/actioncable", "id": "f389e360f6e42efa894b0d304927054846d17a55", "size": "6582", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/action_cable/channel/base.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "9010" }, { "name": "Ruby", "bytes": "45735" } ], "symlink_target": "" }
package resources import ( "context" "os" "testing" "github.com/google/go-cmp/cmp" "github.com/tektoncd/triggers/pkg/apis/triggers/v1beta1" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" reconcilersource "knative.dev/eventing/pkg/reconciler/source" duckv1 "knative.dev/pkg/apis/duck/v1" "knative.dev/pkg/kmeta" "knative.dev/pkg/ptr" ) func TestDeployment(t *testing.T) { err := os.Setenv("METRICS_PROMETHEUS_PORT", "9000") if err != nil { t.Fatal(err) } err = os.Setenv("SYSTEM_NAMESPACE", "tekton-pipelines") if err != nil { t.Fatal(err) } config := *MakeConfig() labels := map[string]string{ "app.kubernetes.io/managed-by": "EventListener", "app.kubernetes.io/part-of": "Triggers", "eventlistener": eventListenerName, } tests := []struct { name string el *v1beta1.EventListener want *appsv1.Deployment }{{ name: "vanilla", el: makeEL(), want: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "", Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(makeEL())}, }, Spec: appsv1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ ServiceAccountName: "sa", Containers: []corev1.Container{ MakeContainer(makeEL(), &reconcilersource.EmptyVarsGenerator{}, config, mustAddDeployBits(t, makeEL(), config), addCertsForSecureConnection(config)), }, SecurityContext: &strongerSecurityPolicy, }, }, }, }, }, { name: "with replicas", el: makeEL(func(el *v1beta1.EventListener) { el.Spec.Resources.KubernetesResource = &v1beta1.KubernetesResource{ Replicas: ptr.Int32(5), } }), want: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "", Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(makeEL())}, }, Spec: appsv1.DeploymentSpec{ Replicas: ptr.Int32(5), Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ ServiceAccountName: "sa", Containers: []corev1.Container{ MakeContainer(makeEL(), &reconcilersource.EmptyVarsGenerator{}, config, mustAddDeployBits(t, makeEL(), config), addCertsForSecureConnection(config)), }, SecurityContext: &strongerSecurityPolicy, }, }, }, }, }, { name: "with tolerations", el: makeEL(func(el *v1beta1.EventListener) { el.Spec.Resources.KubernetesResource = &v1beta1.KubernetesResource{ WithPodSpec: duckv1.WithPodSpec{ Template: duckv1.PodSpecable{ Spec: corev1.PodSpec{ Tolerations: []corev1.Toleration{{ Key: "foo", Value: "bar", }}, }, }, }, } }), want: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "", Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(makeEL())}, }, Spec: appsv1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ ServiceAccountName: "sa", Containers: []corev1.Container{ MakeContainer(makeEL(), &reconcilersource.EmptyVarsGenerator{}, config, mustAddDeployBits(t, makeEL(), config), addCertsForSecureConnection(config)), }, SecurityContext: &strongerSecurityPolicy, Tolerations: []corev1.Toleration{{ Key: "foo", Value: "bar", }}, }, }, }, }, }, { name: "with node selector", el: makeEL(func(el *v1beta1.EventListener) { el.Spec.Resources.KubernetesResource = &v1beta1.KubernetesResource{ WithPodSpec: duckv1.WithPodSpec{ Template: duckv1.PodSpecable{ Spec: corev1.PodSpec{ NodeSelector: map[string]string{ "foo": "bar", }, }, }, }, } }), want: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "", Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(makeEL())}, }, Spec: appsv1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ ServiceAccountName: "sa", Containers: []corev1.Container{ MakeContainer(makeEL(), &reconcilersource.EmptyVarsGenerator{}, config, mustAddDeployBits(t, makeEL(), config), addCertsForSecureConnection(config)), }, SecurityContext: &strongerSecurityPolicy, NodeSelector: map[string]string{ "foo": "bar", }, }, }, }, }, }, { name: "with service account", el: makeEL(func(el *v1beta1.EventListener) { el.Spec.Resources.KubernetesResource = &v1beta1.KubernetesResource{ WithPodSpec: duckv1.WithPodSpec{ Template: duckv1.PodSpecable{ Spec: corev1.PodSpec{ ServiceAccountName: "bob", }, }, }, } }), want: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "", Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(makeEL())}, }, Spec: appsv1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ ServiceAccountName: "bob", Containers: []corev1.Container{ MakeContainer(makeEL(), &reconcilersource.EmptyVarsGenerator{}, config, mustAddDeployBits(t, makeEL(), config), addCertsForSecureConnection(config)), }, SecurityContext: &strongerSecurityPolicy, }, }, }, }, }, { name: "with TLS", el: makeEL(withTLSEnvFrom("Bill")), want: &appsv1.Deployment{ ObjectMeta: metav1.ObjectMeta{ Name: "", Namespace: namespace, Labels: labels, OwnerReferences: []metav1.OwnerReference{*kmeta.NewControllerRef(makeEL())}, }, Spec: appsv1.DeploymentSpec{ Selector: &metav1.LabelSelector{ MatchLabels: labels, }, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: labels, }, Spec: corev1.PodSpec{ ServiceAccountName: "sa", Containers: []corev1.Container{ MakeContainer(makeEL(withTLSEnvFrom("Bill")), &reconcilersource.EmptyVarsGenerator{}, config, mustAddDeployBits(t, makeEL(withTLSEnvFrom("Bill")), config), addCertsForSecureConnection(config)), }, Volumes: []corev1.Volume{{ Name: "https-connection", VolumeSource: corev1.VolumeSource{ Secret: &corev1.SecretVolumeSource{ SecretName: "Bill", }, }, }}, SecurityContext: &strongerSecurityPolicy, }, }, }, }, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := MakeDeployment(context.Background(), tt.el, &reconcilersource.EmptyVarsGenerator{}, config) if err != nil { t.Fatalf("MakeDeployment() = %v", err) } if diff := cmp.Diff(tt.want, got); diff != "" { t.Errorf("MakeDeployment() did not return expected. -want, +got: %s", diff) } }) } } func TestDeploymentError(t *testing.T) { err := os.Setenv("METRICS_PROMETHEUS_PORT", "bad") if err != nil { t.Fatal(err) } got, err := MakeDeployment(context.Background(), makeEL(), &reconcilersource.EmptyVarsGenerator{}, *MakeConfig()) if err == nil { t.Fatalf("MakeDeployment() = %v, wanted error", got) } } func withTLSEnvFrom(name string) func(*v1beta1.EventListener) { return func(el *v1beta1.EventListener) { el.Spec.Resources.KubernetesResource = &v1beta1.KubernetesResource{ WithPodSpec: duckv1.WithPodSpec{ Template: duckv1.PodSpecable{ Spec: corev1.PodSpec{ Containers: []corev1.Container{{ Env: []corev1.EnvVar{{ Name: "TLS_CERT", ValueFrom: &corev1.EnvVarSource{ SecretKeyRef: &corev1.SecretKeySelector{ Key: "cert", LocalObjectReference: corev1.LocalObjectReference{ Name: name, }, }, }, }, { Name: "TLS_KEY", ValueFrom: &corev1.EnvVarSource{ SecretKeyRef: &corev1.SecretKeySelector{ Key: "key", LocalObjectReference: corev1.LocalObjectReference{ Name: name, }, }, }, }}, }}, }, }, }, } } } func mustAddDeployBits(t *testing.T, el *v1beta1.EventListener, c Config) ContainerOption { opt, err := addDeploymentBits(el, c) if err != nil { t.Fatalf("addDeploymentBits() = %v", err) } return opt }
{ "content_hash": "015707bd8433e30d3ce00a58067dc21a", "timestamp": "", "source": "github", "line_count": 345, "max_line_length": 114, "avg_line_length": 27.089855072463767, "alnum_prop": 0.619944361224053, "repo_name": "tektoncd/triggers", "id": "32c9a671f19411221e972e6fbaac87c8f6801184", "size": "9910", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/reconciler/eventlistener/resources/deployment_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "1081483" }, { "name": "Makefile", "bytes": "5967" }, { "name": "Shell", "bytes": "42793" }, { "name": "Smarty", "bytes": "3940" } ], "symlink_target": "" }
/** * @Class * Calendar entity * * @property {year} Ano do calendário * @property {events} Vetor com todos os eventos * @property {events.code} * @property {events.name} * @property {events.date} * * @since: 2014-05 * @author: Rafael Almeida Erthal Hermano */ var mongoose, Schema, schema; mongoose = require('mongoose'); Schema = mongoose.Schema; schema = new Schema({ 'year' : { 'type' : Number, 'required' : true, 'unique' : true }, 'events' : [{ 'code' : { 'type' : String, 'required' : true }, 'name' : { 'type' : String, 'required' : true }, 'date' : { 'type' : Date, 'required' : true } }], 'createdAt' : { 'type' : Date, 'default' : Date.now }, 'updatedAt' : { 'type' : Date } }); /** * @callback * @summary Setups createdAt and updatedAt * * @param next * * @since 2013-05 * @author Rafael Almeida Erthal Hermano */ schema.pre('save', function (next) { 'use strict'; if (!this.createdAt) { this.createdAt = this.updatedAt = new Date(); } else { this.updatedAt = new Date(); } next(); }); module.exports = mongoose.model('Enrollment', schema);
{ "content_hash": "8c298ca1328c8a635a79a5c851217b6a", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 54, "avg_line_length": 19.33823529411765, "alnum_prop": 0.5110266159695818, "repo_name": "rodrigoeg/calendar", "id": "020dcd4cdbaa68d3e9d1e82b11714b9870c1c1ff", "size": "1316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/calendar.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "25689" } ], "symlink_target": "" }
If you want to contribute please follow this instruction. 1. Fork repository. 2. Clone to your PC or Mac. 3. Navigate to repository directory 4. Run npm install 5. Create new `fix` or `feature` branch 6. Make modifications to `calendar.es6` Please do not build compiled version of `calendar.js` 8. Pull to github and send Pull Request.
{ "content_hash": "3e93fbb3f8deb073b2c6b01134b31460", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 57, "avg_line_length": 25.142857142857142, "alnum_prop": 0.7357954545454546, "repo_name": "fluffels/calendar", "id": "3b1e5df2cdd9fa59cce5b75ee2d9e00785865c30", "size": "352", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CONTRIBUTING.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "8473" }, { "name": "JavaScript", "bytes": "166341" } ], "symlink_target": "" }
package bupt.tiantian.weibo.statuslistshow; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.request.ImageRequest; import bupt.tiantian.weibo.R; import bupt.tiantian.weibo.imgshow.PicUrl; import bupt.tiantian.weibo.imgshow.PicUrlHolder; /** * Created by tiantian on 16-7-5. */ public class ImgGridAdapter extends BaseAdapter { private PicUrlHolder mPicUrlHolder; private Context mContext; private LayoutInflater mInflater; public ImgGridAdapter(Context context, PicUrlHolder picUrlHolder) { mContext = context; mInflater = LayoutInflater.from(mContext); mPicUrlHolder = picUrlHolder; } @Override public int getCount() { return mPicUrlHolder.getLength(); } @Override public Object getItem(int position) { if (position < getCount()) { return mPicUrlHolder.getPicUrlList().get(position); } else { return null; } } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { PicUrl picUrl = (PicUrl) getItem(position); View view; ViewHolder holder; if (convertView == null) { view = mInflater.inflate(R.layout.image_in_grid, parent, false); holder = new ViewHolder(R.id.ivStatusInGrid, view); view.setTag(holder); } else { view = convertView; holder = (ViewHolder) view.getTag(); } DraweeController statusImgController = Fresco.newDraweeControllerBuilder() .setOldController(holder.ivStatusInGrid.getController()) .setLowResImageRequest(ImageRequest.fromUri(picUrl.getThumbnailUrl())) .setImageRequest(ImageRequest.fromUri(picUrl.getMiddleUrl())) .setAutoPlayAnimations(false) .build(); holder.ivStatusInGrid.setController(statusImgController); return view; } class ViewHolder { SimpleDraweeView ivStatusInGrid; public ViewHolder(int draweeViewId, View view) { ivStatusInGrid = (SimpleDraweeView) view.findViewById(draweeViewId); } } }
{ "content_hash": "9ba37cca11f89c447a7333b610ae881f", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 86, "avg_line_length": 31.024390243902438, "alnum_prop": 0.6717767295597484, "repo_name": "xietiantian/Weibo", "id": "cb5fd03bebf3e9069c41cf8f302ca8c878589cfe", "size": "2544", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/bupt/tiantian/weibo/statuslistshow/ImgGridAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "472014" } ], "symlink_target": "" }
using System; using SFA.DAS.EAS.Domain.Models.Payments; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.EAS.Infrastructure.Data { [DbConfigurationType(typeof(SqlAzureDbConfiguration))] public class EmployerFinanceDbContext : DbContext { public virtual DbSet<PeriodEnd> PeriodEnds { get; set; } public virtual DbSet<Payment> Payments { get; set; } static EmployerFinanceDbContext() { Database.SetInitializer<EmployerFinanceDbContext>(null); } public EmployerFinanceDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } public EmployerFinanceDbContext(DbConnection connection, DbTransaction transaction = null) : base(connection, false) { if (transaction != null) Database.UseTransaction(transaction); else Database.BeginTransaction(); } protected EmployerFinanceDbContext() { } public override int SaveChanges() { throw new Exception($"The {GetType().FullName} is for read only operations"); } public override Task<int> SaveChangesAsync() { throw new Exception($"The {GetType().FullName} is for read only operations"); } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken) { throw new Exception($"The {GetType().FullName} is for read only operations"); } public virtual Task<List<T>> SqlQueryAsync<T>(string query, params object[] parameters) { return Database.SqlQuery<T>(query, parameters).ToListAsync(); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.HasDefaultSchema("employer_financial"); modelBuilder.Entity<Payment>().Ignore(a => a.StandardCode).Ignore(a => a.FrameworkCode).Ignore(a => a.ProgrammeType).Ignore(a => a.PathwayCode).Ignore(a => a.PathwayName); modelBuilder.Entity<Payment>().Property(a => a.EmployerAccountId).HasColumnName("AccountId"); modelBuilder.Ignore<PaymentDetails>(); } protected override void Dispose(bool disposing) { this.Database.Connection.Dispose(); base.Dispose(disposing); } } }
{ "content_hash": "faa126882ba0521cfd3fb6e0e1795b81", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 183, "avg_line_length": 34.88, "alnum_prop": 0.6536697247706422, "repo_name": "SkillsFundingAgency/das-employerapprenticeshipsservice", "id": "2246c394b7ec4794e7516d145883a6a7f30f41bf", "size": "2618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SFA.DAS.EmployerApprenticeshipsService.Infrastructure/Data/EmployerFinanceDbContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "808" }, { "name": "Batchfile", "bytes": "92" }, { "name": "C#", "bytes": "5033158" }, { "name": "CSS", "bytes": "282148" }, { "name": "Dockerfile", "bytes": "1137" }, { "name": "Gherkin", "bytes": "54605" }, { "name": "HTML", "bytes": "1299641" }, { "name": "JavaScript", "bytes": "219328" }, { "name": "PLpgSQL", "bytes": "4731" }, { "name": "PowerShell", "bytes": "2478" }, { "name": "SCSS", "bytes": "476673" }, { "name": "TSQL", "bytes": "138159" } ], "symlink_target": "" }
title: Heroku deployment --- ## Generating Heroku Procfile `msgflo-procfile` can automatically generate a [Procfile](https://devcenter.heroku.com/articles/procfile) for running as a Heroku service, based on the MsgFlo graph and component information. This ensures that the production service runs in the same way as when using MsgFlo locally. msgflo-procfile graphs/myservice.fbp > Procfile You can also selectively ignore certain roles in the graph, by using `--ignore role`. Or you can include additional process stanzas by using `--include="guv: node ./node_modules/.bin/guv"`. A real-life example can be found [in imgflo-server](https://github.com/imgflo/imgflo-server/blob/master/Makefile#L67).
{ "content_hash": "87cf4d94be334a57563ea2f35421ba63", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 118, "avg_line_length": 47.266666666666666, "alnum_prop": 0.7785613540197461, "repo_name": "msgflo/msgflo", "id": "78486540536dfdabbd69d81df3fee3fa88e7834c", "size": "713", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "site/_documentation/heroku.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9029" }, { "name": "CoffeeScript", "bytes": "131053" }, { "name": "HTML", "bytes": "5123" }, { "name": "JavaScript", "bytes": "557" }, { "name": "Ruby", "bytes": "73" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Threading; using System.Reflection; using System.Resources; namespace SoukeyNetget { public partial class frmUpdate : Form { private string Old_Copy; private string New_Copy; private string SCode = ""; private bool OnShow = false; private ResourceManager rm; //¶¨ÒåÒ»¸ö´úÀí£¬ÓÃÓÚÏÂÔØ×îа汾ʱ¿ÉÒÔ²»¶ÏË¢ÐÂÒ³Ãæ //µÈ´ýÏûÏ¢£¬ÒÔ¸æËßÓû§ÕýÔÚÏÂÔØÈí¼þ£¬¶ø²¢·ÇϵͳËÀ»ú delegate void IsDownloadDelegate(bool Done); private bool IsDownloading = false; public frmUpdate() { InitializeComponent(); } private void GetCopy() { Gather.cGatherWeb gData = new Gather.cGatherWeb(); this.textBox1.Text =rm.GetString ("Info90"); Application.DoEvents(); Old_Copy = Assembly.GetExecutingAssembly().GetName().Version.ToString(); this.textBox1.Text += "\r\n" + rm.GetString("Info91") + Assembly.GetExecutingAssembly().GetName().Version; Application.DoEvents(); this.textBox1.Text += "\r\n" + rm.GetString("Info92"); Application.DoEvents(); SCode = cTool.GetHtmlSource("http://www.yijie.net/user/soft/updatesoukey.html", true); if (SCode == "" || SCode == null) { this.textBox1.Text += "\r\n" + rm.GetString("Info93") + "\r\n" + rm.GetString("Info94"); Application.DoEvents(); return; } this.textBox1.Text += "\r\n" + rm.GetString("Info95") + "\r\n" + rm.GetString("Info96"); Application.DoEvents(); //Ôö¼Ó²É¼¯µÄ±êÖ¾ Task.cWebpageCutFlag c; c = new Task.cWebpageCutFlag(); c.id =0; c.Title = "°æ±¾"; c.DataType =(int) cGlobalParas.GDataType.Txt; c.StartPos = "°æ±¾£º"; c.EndPos = "</p>"; c.LimitSign =(int) cGlobalParas.LimitSign.NoLimit; gData.CutFlag.Add(c); c = null; //Ôö¼Ó°æ±¾ËµÃ÷µÄ±êÖ¾ c = new Task.cWebpageCutFlag(); c.id = 1; c.Title = "˵Ã÷"; c.DataType = (int)cGlobalParas.GDataType.Txt; c.StartPos = "˵Ã÷£º"; c.EndPos = "</p>"; c.LimitSign = (int)cGlobalParas.LimitSign.NoLimit; gData.CutFlag.Add(c); c = null; DataTable dGather = gData.GetGatherData("http://www.yijie.net/user/soft/updatesoukey.html", cGlobalParas.WebCode.utf8, "", "", "", Program.getPrjPath(),false); New_Copy = dGather.Rows[0][0].ToString(); this.textBox1.Text += "\r\n" + rm.GetString("Info97") + New_Copy; Application.DoEvents(); ///°æ±¾ºÅ±È½ÏÐèÒª±È½ÏÈý¸ö½ç±ð£º00.00.00£¬ËùÓа汾±ØÐë×ñÕմ˸ñʽ£¬·ñÔò»á³öÏÖ´íÎó¡£ ///±È½Ï˳ÐòΪ£ºÖ÷°æ±¾->µÍ°æ±¾£¬Ö»ÒªÓÐÒ»¸öа汾ºÅ´óÓھɰ汾ºÅ£¬Ôò¾Í½øÐÐÉý¼¶²Ù×÷ int Old_V; int New_V; for (int i = 0; i < 3; i++) { Old_V=int.Parse ( Old_Copy .Substring(0,Old_Copy .IndexOf ("."))); Old_Copy =Old_Copy .Substring (Old_Copy .IndexOf (".")+1,Old_Copy .Length -Old_Copy .IndexOf (".")-1); New_V = int.Parse(New_Copy.Substring(0, New_Copy.IndexOf("."))); New_Copy = New_Copy.Substring(New_Copy.IndexOf(".")+1, New_Copy.Length - New_Copy.IndexOf(".")-1); if (New_V >Old_V ) { this.textBox1.Text += "\r\n" + rm.GetString("Info98"); Application.DoEvents(); this.textBox1.Text += "\r\n" + dGather.Rows [0][1].ToString (); Application.DoEvents(); gData = null; this.button2.Enabled = true; this.button1.Enabled = true; return; } } this.textBox1.Text += "\r\n" + rm.GetString("Info99"); Application.DoEvents(); this.button1.Enabled = true; } ContainerControl m_sender = null; Delegate m_senderDelegate = null; private void IsDownloadSoft( bool done) { if (done) { this.textBox1.Text += "\r\n" + rm.GetString("Info100"); Application.DoEvents(); this.button1.Enabled = true; } } private void DownloadSoft() { Gather.cGatherWeb gData = new Gather.cGatherWeb(); //Ôö¼Ó²É¼¯µÄ±êÖ¾ Task.cWebpageCutFlag c; c = new Task.cWebpageCutFlag(); c.id = 0; c.Title = "°æ±¾"; c.DataType = (int)cGlobalParas.GDataType.File; c.StartPos = "<a href=\""; c.EndPos = "\""; c.LimitSign = (int)cGlobalParas.LimitSign.NoLimit; gData.CutFlag.Add(c); c = null; DataTable dGather = gData.GetGatherData("http://www.yijie.net/user/soft/updatesoukey.html", cGlobalParas.WebCode.utf8, "", "", "", Program.getPrjPath(),false); dGather = null; gData = null; m_sender.BeginInvoke(m_senderDelegate, new object[] { true }); } private void frmUpdate_Activated(object sender, EventArgs e) { if (OnShow == false) { OnShow = true; try { GetCopy(); } catch (System.Exception ex) { this.textBox1.Text += "\r\n" + rm.GetString("Info101") + ex.Message; Application.DoEvents(); } if (IsDownloading == false) { this.button1.Enabled = true; } } } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void button2_Click(object sender, EventArgs e) { this.textBox1.Text += "\r\n" + rm.GetString("Info102"); Application.DoEvents(); this.button2.Enabled = false; this.button1.Enabled = false; //¶¨ÒåÒ»¸öºǫ́Ïß³ÌÓÃÓÚµ¼³öÊý¾Ý²Ù×÷ IsDownloadDelegate IsDownload = new IsDownloadDelegate(IsDownloadSoft); m_sender = this; m_senderDelegate = IsDownload; IsDownloading = true; Thread t = new Thread(new ThreadStart(DownloadSoft)); t.IsBackground = true; t.Start(); return; } private void frmUpdate_Load(object sender, EventArgs e) { rm = new ResourceManager("SoukeyNetget.Resources.globalUI", Assembly.GetExecutingAssembly()); } private void frmUpdate_FormClosed(object sender, FormClosedEventArgs e) { rm = null; } } }
{ "content_hash": "599c5909b3932c06f57e0a13998454db", "timestamp": "", "source": "github", "line_count": 230, "max_line_length": 171, "avg_line_length": 31.308695652173913, "alnum_prop": 0.5110401333148173, "repo_name": "zhouweiaccp/code", "id": "b54a0aba51772f00f0811a03a2eb230a6b8f7f3e", "size": "7201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SoukeyNetget/frmUpdate.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "987944" } ], "symlink_target": "" }
<!DOCTYPE html > <html> <head> <link rel="stylesheet" href="demos.css" type="text/css" media="screen" /> <script src="../libraries/RGraph.common.core.js" ></script> <script src="../libraries/RGraph.common.csv.js" ></script> <script src="../libraries/RGraph.bar.js" ></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]--> <title>A Bar chart using the CSV reader</title> <meta name="robots" content="noindex,nofollow" /> <meta name="description" content="A Bar chart using the CSV reader" /> </head> <body> <h1>A Bar chart using the CSV reader</h1> <div style="background-color: #ffc; border: 2px solid #cc0; border-radius: 5px; padding: 5px;"> <b>Note:</b> For browser security reasons the AJAX demos don't work offline. You can view the demos on the RGraph website here: <a href="http://www.rgraph.net/demos/" target="_blank" rel="nofollow">http://www.rgraph.net/demos</a> </div> <canvas id="cvs" width="500" height="250">[No canvas support]</canvas> <script> $(document).ready(function () { RGraph.CSV('id:klkl', function (csv) //RGraph.CSV('/sample.csv', function (csv) { /** * Fetch the first row of the CSV file, starting at the second column */ var data = csv.getRow(0, 1); /** * Fetch the first column which become the labels */ var labels = csv.getCol(0) labels.push('Fred') var bar = new RGraph.Bar({ id: 'cvs', data: data, options: { labels: { self: labels, above: { specific: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'], size: 8 } }, noxaxis: true, shadow: { offsetx: 2, offsety: 2, blur: 5 }, hmargin: 15, background: { grid: { autofit: { numvlines: 7 } } }, colors: ['Gradient(#DDF:#01B4FF)'], linewidth: 2, strokestyle: 'white' } }).draw(); }) }) </script> <p> <a href="https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net" target="_blank" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net', null, 'top=50,left=50,width=600,height=368'); return false"><img src="../images/facebook-large.png" width="200" height="43" alt="Share on Facebook" border="0" title="Visit the RGraph Facebook page" /></a> <a href="https://twitter.com/_rgraph" target="_blank" onclick="window.open('https://twitter.com/_rgraph', null, 'top=50,left=50,width=700,height=400'); return false"><img src="../images/twitter-large.png" width="200" height="43" alt="Share on Twitter" border="0" title="Mention RGraph on Twitter" /></a> </p> <p> <a href="./">&laquo; Back</a> </p> <div id="klkl" style="display: none"> Richard,8,4,7,6,5,3,4 Dave,7,4,6,9,5,8,7 Luis,4,3,5,2,6,5,4 Kevin,4,2,8,9,6,7,3 Joel,4,5,1,3,5,8,6 Pete,4,5,6,3,5,8,6 </div> </body> </html>
{ "content_hash": "ec4e32a04f23f9578c5c59e73e1b0735", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 396, "avg_line_length": 39.306930693069305, "alnum_prop": 0.46574307304785895, "repo_name": "ubiss2015d/alpha", "id": "d701a280d62fe9405af4b9f803640a6617db0bd9", "size": "3970", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "WebParser2/RGraph4/demos/bar-csv-reader.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "144776" }, { "name": "HTML", "bytes": "1998507" }, { "name": "JavaScript", "bytes": "4517504" }, { "name": "PHP", "bytes": "1297" }, { "name": "Python", "bytes": "7433" } ], "symlink_target": "" }
inline float gl_height() {return fltk::glgetascent()+fltk::glgetdescent();} #define gl_descent fltk::glgetdescent #define gl_width fltk::glgetwidth #define gl_draw fltk::gldrawtext //void gl_measure(const char*, int& x, int& y); #define gl_draw_image fltk::gldrawimage #endif // !FL_gl_H
{ "content_hash": "7e9d377c228e4487e6392c5beb8cdefd", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 75, "avg_line_length": 36.25, "alnum_prop": 0.7310344827586207, "repo_name": "easion/os_sdk", "id": "b6cba63d60fffd402e2865af019064ad73141c34", "size": "546", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "uclibc/include/fltk/compat/FL/gl.h", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "980392" }, { "name": "Awk", "bytes": "1743" }, { "name": "Bison", "bytes": "113274" }, { "name": "C", "bytes": "60384056" }, { "name": "C++", "bytes": "6888586" }, { "name": "CSS", "bytes": "3092" }, { "name": "Component Pascal", "bytes": "295471" }, { "name": "D", "bytes": "275403" }, { "name": "Erlang", "bytes": "130334" }, { "name": "Groovy", "bytes": "15362" }, { "name": "JavaScript", "bytes": "437486" }, { "name": "Logos", "bytes": "6575" }, { "name": "Makefile", "bytes": "145054" }, { "name": "Max", "bytes": "4350" }, { "name": "Nu", "bytes": "1315315" }, { "name": "Objective-C", "bytes": "209666" }, { "name": "PHP", "bytes": "246706" }, { "name": "Perl", "bytes": "1767429" }, { "name": "Prolog", "bytes": "1387207" }, { "name": "Python", "bytes": "14909" }, { "name": "R", "bytes": "46561" }, { "name": "Ruby", "bytes": "290155" }, { "name": "Scala", "bytes": "184297" }, { "name": "Shell", "bytes": "5748626" }, { "name": "TeX", "bytes": "346362" }, { "name": "XC", "bytes": "6266" } ], "symlink_target": "" }
FILE(REMOVE_RECURSE "CMakeFiles/example_MatrixExponential.dir/MatrixExponential.cpp.o" "example_MatrixExponential.pdb" "example_MatrixExponential" ) # Per-language clean rules from dependency scanning. FOREACH(lang CXX) INCLUDE(CMakeFiles/example_MatrixExponential.dir/cmake_clean_${lang}.cmake OPTIONAL) ENDFOREACH(lang)
{ "content_hash": "8a2d17d5c35781d9bbf205013e152fb1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 86, "avg_line_length": 33.1, "alnum_prop": 0.8096676737160121, "repo_name": "cmeon/Simplex", "id": "b0f480f4cd74769deb75654dcc912a5cf15b07d1", "size": "331", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/unsupported/doc/examples/CMakeFiles/example_MatrixExponential.dir/cmake_clean.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2192597" }, { "name": "C++", "bytes": "3497542" }, { "name": "CSS", "bytes": "5151" }, { "name": "FORTRAN", "bytes": "1462981" }, { "name": "JavaScript", "bytes": "7839" }, { "name": "Objective-C", "bytes": "2089" }, { "name": "Python", "bytes": "8750" }, { "name": "Shell", "bytes": "15472" }, { "name": "Tcl", "bytes": "2329" } ], "symlink_target": "" }
\documentclass[a4paper, 12pt, KOMAold]{scrlttr2} \usepackage[utf8]{inputenc} % this is needed for umlauts \usepackage[ngerman]{babel} % this is needed for umlauts \usepackage[T1]{fontenc} % needed for right umlaut output in pdf \usepackage[ngerman, num]{isodate} % get DD.MM.YYYY dates \usepackage{csquotes} % Anpassen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newcommand{\Vorname}{Martin} % Vorname % \newcommand{\Nachname}{Thoma} % Nachname % \newcommand{\Strasse}{Thalkirchner Str.} % Deine Straße % \newcommand{\Hausnummer}{25} % Deine Hausnummer % \newcommand{\PLZ}{80337} % Deine PLZ % \newcommand{\Ort}{München} % Dein Ort % \newcommand{\Mietobjekt}{Thalkirchner Str. 25, 80337 München} % % \newcommand{\Empfaenger}{M-net Telekommunikations GmbH} % Der Empfänger % \newcommand{\EStrasse}{Emmy-Noether-Strasse 2} % Straße des Empfängers % \newcommand{\EPLZ}{80992} % PLZ des Empfängers % \newcommand{\EOrt}{München} % Ort des Empfängers % % \newcommand{\DocTitle}{Sonderkündigung wegen Umzug} %Titel des Dokuments% \newcommand{\Kundennr}{1234567} % Deine Kundennummer % % Datum der Kündigung % \newcommand{\Kuendigungsdatum}{31.03.2018} % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pdfinfo \pdfinfo{ /Author (\Nachname, \Vorname) /Title (\DocTitle) /Subject (\DocTitle) /Keywords (Kündigung) } % set letter variables \signature{\Vorname~\Nachname} \backaddress{\Vorname~\Nachname, \Strasse~\Hausnummer, \PLZ~\Ort} \customer{\Kundennr} \setlength\parindent{0pt} % Begin document %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{document} \begin{letter}{\Empfaenger \\ \EStrasse \\ \EPLZ~\EOrt} \date{\today}%Change this if you want a different date than today \subject{\DocTitle} \opening{Sehr geehrter \Empfaenger,} hiermit mache ich von meinem Sonderkündigungsrecht gebrauch und kündige den Vertrag~1234567 unter Einhaltung der 3-Monats-Frist zum 31.~Mai aufgrund eines Umzuges des Vertragsinhabers.\\ Ich ziehe zum 1.~April 2018 in die Alte Allee 107 in 81245~München um. Dort ist laut shop.m-net.de nur eine Downloadgeschwindigkeit von 18~Mbit/s verfügbar. Der Vertrag~1234567 \enquote{Surf-Flat} ist jedoch über 25~Mbit/s.\\ % Ihre neue Anschlussadresse % Einen Umzugsnachweis (Mietvertrag oder Meldebescheinigung) Bitte senden Sie mir eine schriftliche Bestätigung der Kündigung unter Angabe des Beendigungszeitpunktes zu. Gleichzeitig widerrufe ich die vorliegende Einzugsermächtigung zum 31. Mai 2018. \closing{Mit freundlichen Grüßen,} \end{letter} \end{document}
{ "content_hash": "4d64a87a650d7547ab743ed6e9d7b521", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 83, "avg_line_length": 46.83076923076923, "alnum_prop": 0.5959264126149802, "repo_name": "MartinThoma/LaTeX-examples", "id": "d21d00128a68fdc9c2042b6ab970e5e2192b4e06", "size": "3066", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "documents/internet-sonderkuendigung/internet-sonderkuendigung.tex", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "104" }, { "name": "Asymptote", "bytes": "16054" }, { "name": "Batchfile", "bytes": "187" }, { "name": "C", "bytes": "7885" }, { "name": "Gnuplot", "bytes": "383" }, { "name": "HTML", "bytes": "10585" }, { "name": "Haskell", "bytes": "9401" }, { "name": "Java", "bytes": "95574" }, { "name": "JavaScript", "bytes": "33665" }, { "name": "Jupyter Notebook", "bytes": "15400" }, { "name": "Makefile", "bytes": "403103" }, { "name": "Prolog", "bytes": "4515" }, { "name": "Python", "bytes": "58056" }, { "name": "Raku", "bytes": "357" }, { "name": "Scala", "bytes": "6990" }, { "name": "Shell", "bytes": "2783" }, { "name": "ShellSession", "bytes": "3837" }, { "name": "Smarty", "bytes": "572" }, { "name": "Tcl", "bytes": "250" }, { "name": "TeX", "bytes": "5244843" }, { "name": "X10", "bytes": "2354" } ], "symlink_target": "" }
package io.druid.storage.s3; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.google.inject.Inject; import com.metamx.emitter.EmittingLogger; import io.druid.segment.SegmentUtils; import io.druid.segment.loading.DataSegmentPusher; import io.druid.timeline.DataSegment; import io.druid.utils.CompressionUtils; import org.jets3t.service.ServiceException; import org.jets3t.service.acl.gs.GSAccessControlList; import org.jets3t.service.impl.rest.httpclient.RestS3Service; import org.jets3t.service.model.S3Object; import java.io.File; import java.io.IOException; import java.util.concurrent.Callable; public class S3DataSegmentPusher implements DataSegmentPusher { private static final EmittingLogger log = new EmittingLogger(S3DataSegmentPusher.class); private final RestS3Service s3Client; private final S3DataSegmentPusherConfig config; private final ObjectMapper jsonMapper; @Inject public S3DataSegmentPusher( RestS3Service s3Client, S3DataSegmentPusherConfig config, ObjectMapper jsonMapper ) { this.s3Client = s3Client; this.config = config; this.jsonMapper = jsonMapper; } @Override public String getPathForHadoop(String dataSource) { return String.format("s3n://%s/%s/%s", config.getBucket(), config.getBaseKey(), dataSource); } @Override public DataSegment push(final File indexFilesDir, final DataSegment inSegment) throws IOException { log.info("Uploading [%s] to S3", indexFilesDir); final String s3Path = S3Utils.constructSegmentPath(config.getBaseKey(), inSegment); final File zipOutFile = File.createTempFile("druid", "index.zip"); final long indexSize = CompressionUtils.zip(indexFilesDir, zipOutFile); try { return S3Utils.retryS3Operation( new Callable<DataSegment>() { @Override public DataSegment call() throws Exception { S3Object toPush = new S3Object(zipOutFile); final String outputBucket = config.getBucket(); final String s3DescriptorPath = S3Utils.descriptorPathForSegmentPath(s3Path); toPush.setBucketName(outputBucket); toPush.setKey(s3Path); if (!config.getDisableAcl()) { toPush.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL); } log.info("Pushing %s.", toPush); s3Client.putObject(outputBucket, toPush); final DataSegment outSegment = inSegment.withSize(indexSize) .withLoadSpec( ImmutableMap.<String, Object>of( "type", "s3_zip", "bucket", outputBucket, "key", toPush.getKey() ) ) .withBinaryVersion(SegmentUtils.getVersionFromDir(indexFilesDir)); File descriptorFile = File.createTempFile("druid", "descriptor.json"); Files.copy(ByteStreams.newInputStreamSupplier(jsonMapper.writeValueAsBytes(inSegment)), descriptorFile); S3Object descriptorObject = new S3Object(descriptorFile); descriptorObject.setBucketName(outputBucket); descriptorObject.setKey(s3DescriptorPath); if (!config.getDisableAcl()) { descriptorObject.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL); } log.info("Pushing %s", descriptorObject); s3Client.putObject(outputBucket, descriptorObject); log.info("Deleting zipped index File[%s]", zipOutFile); zipOutFile.delete(); log.info("Deleting descriptor file[%s]", descriptorFile); descriptorFile.delete(); return outSegment; } } ); } catch (ServiceException e) { throw new IOException(e); } catch (Exception e) { throw Throwables.propagate(e); } } }
{ "content_hash": "7c987b73a0cf416021948b1a70e5ce13", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 120, "avg_line_length": 37.89430894308943, "alnum_prop": 0.5936494314524781, "repo_name": "minewhat/druid", "id": "78b02e42bbb0a02cdbebe2a2b3d7812a9dd2a6c7", "size": "5312", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "extensions/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPusher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "11757" }, { "name": "CSS", "bytes": "41177" }, { "name": "Groff", "bytes": "3617" }, { "name": "HTML", "bytes": "54820" }, { "name": "Java", "bytes": "5886420" }, { "name": "JavaScript", "bytes": "292689" }, { "name": "Makefile", "bytes": "501" }, { "name": "PostScript", "bytes": "5" }, { "name": "Protocol Buffer", "bytes": "552" }, { "name": "R", "bytes": "8501" }, { "name": "Shell", "bytes": "8055" }, { "name": "TeX", "bytes": "281722" } ], "symlink_target": "" }
/** * Colors */ /** * Breakpoints & Media Queries */ /** * SCSS Variables. * * Please use variables from this sheet to ensure consistency across the UI. * Don't add to this sheet unless you're pretty sure the value will be reused in many places. * For example, don't add rules to this sheet that affect block visuals. It's purely for UI. */ /** * Colors */ /** * Fonts & basic variables. */ /** * Grid System. * https://make.wordpress.org/design/2019/10/31/proposal-a-consistent-spacing-system-for-wordpress/ */ /** * Dimensions. */ /** * Shadows. */ /** * Editor widths. */ /** * Block & Editor UI. */ /** * Block paddings. */ /** * React Native specific. * These variables do not appear to be used anywhere else. */ /** * Converts a hex value into the rgb equivalent. * * @param {string} hex - the hexadecimal value to convert * @return {string} comma separated rgb values */ /** * Breakpoint mixins */ /** * Long content fade mixin * * Creates a fading overlay to signify that the content is longer * than the space allows. */ /** * Focus styles. */ /** * Applies editor left position to the selector passed as argument */ /** * Styles that are reused verbatim in a few places */ /** * Allows users to opt-out of animations via OS-level preferences. */ /** * Reset default styles for JavaScript UI based pages. * This is a WP-admin agnostic reset */ /** * Reset the WP Admin page styles for Gutenberg-like pages. */ .block-editor-block-list__block[data-type="core/spacer"]::before { content: ""; display: block; position: absolute; z-index: 1; width: 100%; min-height: 8px; min-width: 8px; height: 100%; } .wp-block-spacer.is-hovered .block-library-spacer__resize-container, .block-library-spacer__resize-container.has-show-handle { background: rgba(0, 0, 0, 0.1); } .is-dark-theme .wp-block-spacer.is-hovered .block-library-spacer__resize-container, .is-dark-theme .block-library-spacer__resize-container.has-show-handle { background: rgba(255, 255, 255, 0.15); } .block-library-spacer__resize-container { clear: both; } .block-library-spacer__resize-container:not(.is-resizing) { height: 100% !important; width: 100% !important; } .block-library-spacer__resize-container .components-resizable-box__handle::before { content: none; } .block-library-spacer__resize-container.resize-horizontal { margin-bottom: 0; }
{ "content_hash": "8629767741ae728805dc34d6a59d015c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 99, "avg_line_length": 22.009174311926607, "alnum_prop": 0.6798666110879533, "repo_name": "electric-eloquence/fepper-wordpress", "id": "366480c30e84660f7757748c9d6017d5ef59c387", "size": "2399", "binary": false, "copies": "40", "ref": "refs/heads/dev", "path": "backend/wordpress/wp-includes/blocks/spacer/editor.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2545314" }, { "name": "HTML", "bytes": "79" }, { "name": "JavaScript", "bytes": "5170950" }, { "name": "Mustache", "bytes": "17516" }, { "name": "PHP", "bytes": "15896768" }, { "name": "PowerShell", "bytes": "755" }, { "name": "SCSS", "bytes": "25910" }, { "name": "Shell", "bytes": "1124" }, { "name": "Stylus", "bytes": "28810" }, { "name": "VBScript", "bytes": "466" } ], "symlink_target": "" }
Those are old projects in many programming languages that I don't need any more whether I completed it or not . ## Projects list : * c_projects (all not docced but very simple I think all are completed ): projects that are written in c language . * cal : a calculator in terminal * db : takes data from a file and prints it * db2 : I don't know waht is the different between this and the above one * Fardi : lists the single numbers * main : I think it is hello world * qassem : The greatest common divisor * postit (partial not docced) : a try to beat facebook :P * SiTeFoS (completed , partial docced) : a wordpress template , many versions (link(It won't work fast because it is free hosting) : http://sample-sitefos.rhcloud.com/ ) * tryhtml (completed docced) : I think it is the first version of SiTeFoS * myarabicmarkdownstyle.css (completed ) : very very very simple style file for rtl pages I used it when I am compiling markdown . ## THE LICENSE : All the projects are under MIT License except SiTeFoS is under BSD License (the License templates are included)
{ "content_hash": "180ef0f619f799774ca51834b2e2b099", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 170, "avg_line_length": 63.529411764705884, "alnum_prop": 0.7462962962962963, "repo_name": "Abdulla2/junkcode", "id": "8b9250c2793843fa40b5d2388576a81b4d6a4cfb", "size": "1111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7460" }, { "name": "C++", "bytes": "13290" }, { "name": "CSS", "bytes": "143661" }, { "name": "HTML", "bytes": "44226" }, { "name": "PHP", "bytes": "142715" }, { "name": "Shell", "bytes": "501" } ], "symlink_target": "" }
<?php namespace Detail\Commanding\Command\Listing; use Detail\Commanding\Exception; class Filter { const OPERATOR_SMALLER_THAN = '<'; const OPERATOR_SMALLER_THAN_OR_EQUALS = '<='; const OPERATOR_EQUALS = '='; const OPERATOR_GREATER_THAN_OR_EQUALS = '>='; const OPERATOR_GREATER_THAN = '>'; const OPERATOR_NOT_EQUALS = '!='; const OPERATOR_IN = 'in'; const OPERATOR_NOT_IN = 'notIn'; const OPERATOR_LIKE = 'like'; /** * @var string */ protected $property; /** * @var string */ protected $operator = self::OPERATOR_EQUALS; /** * @var mixed */ protected $value; /** * @var string|null */ protected $type; /** * @return array */ protected static function getSupportedTypes() { return array( 'boolean' => array('bool', 'boolean'), 'integer' => array('int', 'digit', 'integer'), 'float' => array('float', 'decimal', 'double', 'real'), 'string' => array('str', 'string', 'uuid'), 'array' => array('array', 'hash'), ); } /** * @param string $property * @param mixed $value * @param string|null $operator * @param string|null $type */ public function __construct($property, $value, $operator = null, $type = null) { $this->setProperty($property); $this->setValue($value, $type); if ($operator !== null) { $this->setOperator($operator); } } /** * @return string */ public function getProperty() { return $this->property; } /** * @param string $property */ public function setProperty($property) { $this->property = $property; } /** * @return string */ public function getOperator() { return $this->operator; } /** * @param string $operator */ public function setOperator($operator) { $this->operator = $operator; } /** * @return mixed */ public function getValue() { return $this->value; } /** * @param mixed $value * @param string|null $type */ public function setValue($value, $type = null) { if ($type !== null) { $this->setType($type); } // If type is set cast value to it if ($this->getType() !== null) { // No need to check that getMainType result is not null settype($value, $this->getMainType($this->getType())); } $this->value = $value; } /** * @return string */ public function getType() { return $this->type; } /** * @param $type * @return string|null */ protected function getMainType($type) { foreach (static::getSupportedTypes() as $mainType => $mapping) { if (in_array($type, $mapping)) { return $mainType; } } return null; } /** * @param string $type */ private function setType($type) { if ($this->getMainType($type) === null) { throw new Exception\InvalidArgumentException( sprintf('Unsupported type "%s"', $type) ); } $this->type = $type; } }
{ "content_hash": "b15a99e83f0a67dc58fbfd2a82a83b05", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 82, "avg_line_length": 21.195121951219512, "alnum_prop": 0.48504027617951667, "repo_name": "ivan-wolf/dfw-commanding", "id": "56ad2b1948edac059da0209a3574b46495b9c746", "size": "3476", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Detail/Commanding/Command/Listing/Filter.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "26662" } ], "symlink_target": "" }
using Microsoft.Practices.ServiceLocation; using NUnit.Framework; using SEV.FWK.Service.Tests; using SEV.Service.Contract; using SEV.UI.Model; using SEV.UI.Model.Contract; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace SEV.FWK.UI.Model.Tests { [TestFixture] public class SEVModelsTests : ModelsSysTestBase { private const int ParentId = 1; private const string ParentValue = "Parent"; [Test] public void WhenCallLoadOfListModel_ThenShouldLoadFullCollectionForRequestedEntity() { var listModel = ServiceLocator.Current.GetInstance<ITestListModel>(); listModel.Load(); Assert.That(listModel.IsValid, Is.True); Assert.That(listModel.Items.Count, Is.EqualTo(ChildCount + 1)); } [Test] public void GivenParentEntityExpressionIsSpecified_WhenCallLoadByIdOfListModel_ThenShouldLoadCollectionOfEntitiesAttachedToParentEntityWithRequestedId() { // ReSharper disable SpecifyACultureInStringConversionExplicitly string id = ParentId.ToString(); var listModel = ServiceLocator.Current.GetInstance<ITestListModel>(); listModel.Load(id); Assert.That(listModel.IsValid, Is.True); int count = 0; foreach (var model in listModel.Items) { Assert.That(model.Parent, Is.Not.Null); Assert.That(model.Parent.Id, Is.EqualTo(id)); count++; } Assert.That(count, Is.EqualTo(ChildCount)); } [Test] public void WhenCallLoadByIdOfSingleModel_ThenShouldLoadEntityWithRequestedId() { string id = ParentId.ToString(); var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.Load(id); Assert.That(model.IsValid, Is.True); Assert.That(model.Id, Is.EqualTo(id)); Assert.That(model.Value, Is.EqualTo(ParentValue)); } [Test] public void GivenParentEntityIsSpecifiedInGetIncludes_WhenCallLoadByIdOfSingleModel_ThenShouldLoadEntityByRequestedIdWithParentEntity() { string id = ChildCount.ToString(); var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.Load(id); Assert.That(model.IsValid, Is.True); Assert.That(model.Id, Is.EqualTo(id)); Assert.That(model.Value, Is.StringStarting(ChildValue)); Assert.That(model.Parent, Is.Not.Null); Assert.That(model.Parent.Id, Is.EqualTo(ParentId.ToString())); } [Test] public void GivenRelatedEntitiesAreSpecifiedInGetIncludes_WhenCallLoadByIdOfSingleModel_ThenShouldLoadEntityByRequestedIdWithRelatedEntities() { string id = ParentId.ToString(); var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.Load(id); Assert.That(model.IsValid, Is.True); Assert.That(model.Parent, Is.Null); Assert.That(model.Children.Count, Is.EqualTo(ChildCount)); } [Test] public void GivenNewModel_WhenCallSaveOfEditableModel_ThenShouldCreateNewEntity() { const string testValue = "Create Test"; var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.New(); model.Value = testValue; model.Save(); string id = (ChildCount + 2).ToString(); var testModel = ServiceLocator.Current.GetInstance<ITestModel>(); testModel.Load(id); Assert.That(testModel.IsValid, Is.True); Assert.That(testModel.Value, Is.EqualTo(testValue)); } [Test] public void GivenExistingModel_WhenCallSaveOfEditableModel_ThenShouldUpdateModelEntity() { var entity = ServiceLocator.Current.GetInstance<ICommandService>().Create(new TestEntity { Value = "new" }); const string updated = "Update Test"; string id = entity.Id.ToString(); var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.Load(id); model.Value = updated; var parentModel = ServiceLocator.Current.GetInstance<ITestModel>(); parentModel.Load(ParentId.ToString()); model.Parent = parentModel; model.Save(); var testModel = ServiceLocator.Current.GetInstance<ITestModel>(); testModel.Load(id); Assert.That(testModel.IsValid, Is.True); Assert.That(testModel.Value, Is.EqualTo(updated)); Assert.That(testModel.Parent, Is.Not.Null); Assert.That(testModel.Parent.Id, Is.EqualTo(ParentId.ToString())); } [Test] public void WhenCallDeleteOfEditableModel_ThenShouldDeleteModelEntity() { string id = (ChildCount - 1).ToString(); // ReSharper restore SpecifyACultureInStringConversionExplicitly var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.Load(id); Assert.That(model.IsValid, Is.True); model.Delete(); var testModel = ServiceLocator.Current.GetInstance<ITestModel>(); testModel.Load(id); Assert.That(testModel.IsValid, Is.False); } [Test] public void GivenModelEntityIsAggregateRoot_WhenCreateModelEntity_ThenShouldCreateChildModelEntities() { const int count = 3; const string testValue = "New Test Parent"; var parentModel = ServiceLocator.Current.GetInstance<ITestModel>(); parentModel.New(); parentModel.Value = testValue; Enumerable.Range(1, count).Select(x => { var model = ServiceLocator.Current.GetInstance<ITestModel>(); model.New(); model.Value = "New Child " + x; return model; }).ToList().ForEach(c => parentModel.Children.Add(c)); parentModel.Save(); var testModel = ServiceLocator.Current.GetInstance<ITestModel>(); testModel.Load(parentModel.Id); Assert.That(testModel.IsValid, Is.True); Assert.That(testModel.Children.Count, Is.EqualTo(count)); } [Test] public void GivenModelEntityIsAggregateRoot_WhenDeleteModel_ThenShouldDeleteChildEntities() { var parentModel = ServiceLocator.Current.GetInstance<ITestModel>(); parentModel.Load(ParentId.ToString()); parentModel.Delete(); var testModel = ServiceLocator.Current.GetInstance<ITestListModel>(); testModel.Load(); Assert.That(testModel.IsValid, Is.True); Assert.That(testModel.Items.Any(), Is.False); } [Test] public void GivenModelEntityIsAggregateRootAndChildModelIsRemoved_WhenUpdateModel_ThenShouldDeleteChildEntity() { var parentModel = ServiceLocator.Current.GetInstance<ITestModel>(); parentModel.Load(ParentId.ToString()); int childrenCount = parentModel.Children.Count; var childModel = parentModel.Children.First(); parentModel.Children.Remove(childModel); parentModel.Save(); var testModel = ServiceLocator.Current.GetInstance<ITestModel>(); testModel.Load(ParentId.ToString()); Assert.That(testModel.IsValid, Is.True); Assert.That(testModel.Children.Count, Is.EqualTo(childrenCount - 1)); } } #region Test Models public interface ITestModel : IEditableModel { string Value { get; set; } ITestModel Parent { get; set; } IList<ITestModel> Children { get; } } public interface ITestListModel : IListModel<ITestModel> { } public class TestModel : EditableModel<TestEntity>, ITestModel { public TestModel(IQueryService queryService, ICommandService commandService, IValidationService validationService) : base(queryService, commandService, validationService) { } public string Value { get { return GetValue(x => x.Value); } set { SetValue(value); } } public ITestModel Parent { get { return GetReference<ITestModel, TestEntity>(); } set { SetReference<ITestModel, TestEntity> (value); } } public IList<ITestModel> Children => GetCollection<ITestModel, TestEntity>(); protected override List<Expression<Func<TestEntity, object>>> GetIncludes() { var includes = base.GetIncludes(); includes.Add(x => x.Parent); includes.Add(x => x.Children); return includes; } } public class TestListModel : ListModel<ITestModel, TestEntity>, ITestListModel { public TestListModel(IQueryService queryService, IParentEntityFilterProvider filterProvider) : base(queryService, filterProvider) { ParentEntityExpression = x => x.Parent; } } #endregion }
{ "content_hash": "1ee66270fa698ae3d3cb6ab61ece3a7a", "timestamp": "", "source": "github", "line_count": 260, "max_line_length": 160, "avg_line_length": 35.784615384615385, "alnum_prop": 0.6211306964746346, "repo_name": "sev15/SEVFramework", "id": "c375f2a6b12fe06558818e4bbd745c87fdad804c", "size": "9306", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Tests/SEV.FWK.UI.Model.Tests/SEVModelsTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "404108" } ], "symlink_target": "" }
var path = require('path'), fs = require('fs'), _assign = require('lodash.assign'), _template = require('lodash.template'), Deferred = require('deferred'), readdir = Deferred.promisify(fs.readdir), writeFile = Deferred.promisify(fs.writeFile), mkdir = Deferred.promisify(fs.mkdir), minify = require('html-minifier').minify, currentDir = path.join(path.dirname(process.mainModule.filename)), outDir = path.join(currentDir, 'out'), headerRegex = /^<!--\s*(\{[\s\S]*\})\s*-->([\s\S]*)/m, //by default . does not match new-lines but \s does, and [^] matches anything minifyOptions = { removeComments: true, removeCommentsFromCDATA: true, collapseWhitespace: true, conservativeCollapse: true, collapseInlineTagWhitespace: true, minifyCSS: true, sortAttributes: true, sortClassName: true }; function ensureDir(dir) { return new Promise(function(resolve, reject) { fs.stat(dir, function(err) { if (err) { mkdir(dir).then(resolve, reject); return; } resolve(); }); }); } function collectTemplates(templatesDir) { return readdir(templatesDir) //map all the files into objects if they're not a directory .map(function(fileName) { return new Promise(function(resolve, reject) { var filePath = path.join(templatesDir, fileName); fs.stat(filePath, function(err, stat) { if (err) { reject('Error reading "' + file.path + '": ' + err); return; } var res = null; if (!stat.isDirectory()) { res = { name: fileName.replace(/\.ejs$/, ''), path: filePath, header: null, content: null, template: null, dependencies: null }; } resolve(res); }); }); }) //remove all the nulls (directories) from the array .invoke('filter', function(f) { return f !== null; }) //read all the files .map(function(file) { return new Promise(function(resolve, reject) { fs.readFile(file.path, function(err, content) { if (err) { reject('Error reading "' + file.path + '": ' + err); return; } file.content = content; resolve(file); }); }); }) //now parse all the headers .map(function(file) { return new Promise(function(resolve, reject) { var match = null; if (Buffer.isBuffer(file.content)) { file.content = file.content.toString(); } match = file.content.match(headerRegex); if (match === null || !match[1]) { reject(new Error('Failed to find header in ' + file.path)); return; } try { file.header = JSON.parse(match[1]); file.name = file.header.name || file.name; resolve(file); } catch (e) { reject('Error reading header from "' + file.name + '": ' + e); } file.content = match[2].trim(); }); }); } //helper function for renderAndMinifyTemplates function singlePassProcessTemplates(templates) { var file = null, name = '', unresolved = false, params = null, parent = null; for (name in templates) { if (!templates.hasOwnProperty(name)) { continue; } params = {}; file = templates[name]; //if we already have a template for the file then don't render it again if (file.template) { continue; } if (file.header.subject && typeof file.header.subject !== 'string') { throw new Error('Invalid subject in header in "' + file.path + '"'); } if (file.header.parent) { parent = file.header.parent; if (!templates.hasOwnProperty(parent.name)) { throw new Error('Reference to not found parent "' + parent.name + '" in "' + file.path + '"'); } if (templates[parent.name].template === null) { unresolved = true; continue; } if (parent.args) { params = _assign(params, parent.args); } if (parent.include_var) { params[parent.include_var] = file.content; } file.content = templates[parent.name].templateize(params)(params); file.templateize = (function(pn, p, incv) { return function(overrideParams) { var newParams = _assign({}, p, overrideParams), content = ''; // don't allow them to override the include_var's params if (incv) { newParams[incv] = p[incv]; } content = templates[pn].templateize(newParams)(newParams); return _template(minify(content, minifyOptions)); }; }(parent.name, params, parent.include_var)); } else { (function(f) { f.templateize = function() { return _template(minify(f.content, minifyOptions)); }; }(file)); } file.template = file.templateize(params); } return unresolved; } function renderAndMinifyTemplates(templates) { var i = 0; while (singlePassProcessTemplates(templates) && i++ < 5){} if (i === 5) { throw new Error('Failed to resolve parents after 5 iterations'); } return templates; } function mapTemplates(templates) { var arr = [], n = ''; for (n in templates) { if (!templates.hasOwnProperty(n)) { continue; } arr.push(templates[n]); } return Deferred.map(arr); } function writeBodies(file) { if (!file.template) { return Promise.reject(new Error(file.file + " has no associated bodies")); } var dest = path.join(outDir, file.name) + '.js', funcLine = 'module.exports = ' + file.template, paramsLine = 'module.exports.params = ' + JSON.stringify(file.header.params || []), subjectLine = 'module.exports.subject = "' + (file.header.subject || '') + '"'; return writeFile(dest, [funcLine, paramsLine, subjectLine, ''].join(';\n')); } function compile(dir) { //we need to use to deferred chain to utilize the map/reduce methods return Deferred.resolve(). then(function() { return ensureDir(outDir); }) .then(function() { return collectTemplates(dir); //this returns a collection of files }) .reduce(function(templates, file) { templates[file.name] = file; return templates; }, {}) .then(renderAndMinifyTemplates) //this returns a collection of files .then(mapTemplates) .map(writeBodies); } module.exports = compile;
{ "content_hash": "3684835a8170d4c8c42c079c773b3607", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 136, "avg_line_length": 35.7196261682243, "alnum_prop": 0.49529042386185246, "repo_name": "levenlabs/robthebuilder", "id": "7c0bb9c3e7eb30aa05060f0295587bf0ba7c78a8", "size": "7644", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/compile.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "843" }, { "name": "JavaScript", "bytes": "44168" } ], "symlink_target": "" }
package com.amazonaws.services.simplesystemsmanagement.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * GetMaintenanceWindowTaskRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class GetMaintenanceWindowTaskRequestProtocolMarshaller implements Marshaller<Request<GetMaintenanceWindowTaskRequest>, GetMaintenanceWindowTaskRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("AmazonSSM.GetMaintenanceWindowTask").serviceName("AWSSimpleSystemsManagement").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public GetMaintenanceWindowTaskRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<GetMaintenanceWindowTaskRequest> marshall(GetMaintenanceWindowTaskRequest getMaintenanceWindowTaskRequest) { if (getMaintenanceWindowTaskRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<GetMaintenanceWindowTaskRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, getMaintenanceWindowTaskRequest); protocolMarshaller.startMarshalling(); GetMaintenanceWindowTaskRequestMarshaller.getInstance().marshall(getMaintenanceWindowTaskRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "fe7b3753ecf0023c6def3e8eb931a476", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 161, "avg_line_length": 43.86538461538461, "alnum_prop": 0.7799210872424376, "repo_name": "jentfoo/aws-sdk-java", "id": "28b7056e6ae02f09a226cf9f6a1a6abc7898cf4a", "size": "2861", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/GetMaintenanceWindowTaskRequestProtocolMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
/** * Editor for the js tab of a spec. Inherits from Editor. * * @module explorer/widgets/editorarea/JSEditor * @requires module:explorer/widgets/editorarea/Editor */ define(['dojo/_base/declare', './Editor'], function(declare, Editor, template) { return declare('JSEditorWidget', [ Editor ], { mode : 'text/javascript' }); });
{ "content_hash": "95c9676e4e583b8fea764be4271fb248", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 57, "avg_line_length": 25.642857142857142, "alnum_prop": 0.649025069637883, "repo_name": "OpenSocial/explorer", "id": "d4a296c0c0c2b022d21100553cf893633e49916d", "size": "1185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "opensocial-explorer-webcontent/src/main/javascript/modules/widgets/editorarea/JSEditor.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19954" }, { "name": "CSS", "bytes": "3636857" }, { "name": "Java", "bytes": "343402" }, { "name": "JavaScript", "bytes": "20745458" }, { "name": "PHP", "bytes": "38090" }, { "name": "Shell", "bytes": "5416" }, { "name": "XSLT", "bytes": "47380" } ], "symlink_target": "" }
#ifndef CRAS_CLIENT_H_ #define CRAS_CLIENT_H_ #ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <sys/select.h> #include "cras_iodev_info.h" #include "cras_types.h" #include "cras_util.h" struct cras_client; struct cras_stream_params; /* Callback for audio received or transmitted. * Args (All pointer will be valid - except user_arg, that's up to the user): * client: The client requesting service. * stream_id - Unique identifier for the stream needing data read/written. * samples - Read or write samples to/form here. * frames - Maximum number of frames to read or write. * sample_time - Playback time for the first sample read/written. * user_arg - Value passed to add_stream; * Return: * 0 on success, or a negative number if there is a stream-fatal error. */ typedef int (*cras_playback_cb_t)(struct cras_client *client, cras_stream_id_t stream_id, uint8_t *samples, size_t frames, const struct timespec *sample_time, void *user_arg); /* Callback for audio received and/or transmitted. * Args (All pointer will be valid - except user_arg, that's up to the user): * client: The client requesting service. * stream_id - Unique identifier for the stream needing data read/written. * captured_samples - Read samples form here. * playback_samples - Read or write samples to here. * frames - Maximum number of frames to read or write. * captured_time - Time the first sample was read. * playback_time - Playback time for the first sample written. * user_arg - Value passed to add_stream; * Return: * 0 on success, or a negative number if there is a stream-fatal error. */ typedef int (*cras_unified_cb_t)(struct cras_client *client, cras_stream_id_t stream_id, uint8_t *captured_samples, uint8_t *playback_samples, unsigned int frames, const struct timespec *captured_time, const struct timespec *playback_time, void *user_arg); /* Callback for handling errors. */ typedef int (*cras_error_cb_t)(struct cras_client *client, cras_stream_id_t stream_id, int error, void *user_arg); /* * Client handling. */ /* Creates a new client. * Args: * client - Filled with a pointer to the new client. * Returns: * 0 on success (*client is filled with a valid cras_client pointer). * Negative error code on failure(*client will be NULL). */ int cras_client_create(struct cras_client **client); /* Destroys a client. * Args: * client - returned from "cras_client_create". */ void cras_client_destroy(struct cras_client *client); /* Connects a client to the running server. * Args: * client - pointer returned from "cras_client_create". * Returns: * 0 on success, or a negative error code on failure (from errno.h). */ int cras_client_connect(struct cras_client *client); /* Waits for the server to indicate that the client is connected. Useful to * ensure that any information about the server is up to date. * Args: * client - pointer returned from "cras_client_create". * Returns: * 0 on success, or a negative error code on failure (from errno.h). */ int cras_client_connected_wait(struct cras_client *client); /* Begins running a client. * Args: * client - the client to start (from cras_client_create). * Returns: * 0 on success, -EINVAL if the client pointer is NULL, or -ENOMEM if there * isn't enough memory to start the thread. */ int cras_client_run_thread(struct cras_client *client); /* Stops running a client. * Args: * client - the client to stop (from cras_client_create). * Returns: * 0 on success, -EINVAL if the client isn't valid or isn't running. */ int cras_client_stop(struct cras_client *client); /* Returns the current list of output devices. * Args: * client - The client to stop (from cras_client_create). * devs - Array that will be filled with device info. * nodes - Array that will be filled with node info. * *num_devs - Maximum number of devices to put in the array. * *num_nodes - Maximum number of nodes to put in the array. * Returns: * 0 on success, -EINVAL if the client isn't valid or isn't running. * *num_devs is set to the actual number of devices info filled. * *num_nodes is set to the actual number of nodes info filled. */ int cras_client_get_output_devices(const struct cras_client *client, struct cras_iodev_info *devs, struct cras_ionode_info *nodes, size_t *num_devs, size_t *num_nodes); /* Returns the current list of input devices. * Args: * client - The client to stop (from cras_client_create). * devs - Array that will be filled with device info. * nodes - Array that will be filled with node info. * *num_devs - Maximum number of devices to put in the array. * *num_nodes - Maximum number of nodes to put in the array. * Returns: * 0 on success, -EINVAL if the client isn't valid or isn't running. * *num_devs is set to the actual number of devices info filled. * *num_nodes is set to the actual number of nodes info filled. */ int cras_client_get_input_devices(const struct cras_client *client, struct cras_iodev_info *devs, struct cras_ionode_info *nodes, size_t *num_devs, size_t *num_nodes); /* Returns the current list of clients attached to the server. * Args: * client - This client (from cras_client_create). * clients - Array that will be filled with a list of attached clients. * max_clients - Maximum number of clients to put in the array. * Returns: * The number of attached clients. This may be more that max_clients passed * in, this indicates that all of the clients wouldn't fit in the provided * array. */ int cras_client_get_attached_clients(const struct cras_client *client, struct cras_attached_client_info *clients, size_t max_clients); /* Checks if the output device with the given name is currently plugged in. For * internal devices this checks that jack state, for USB devices this will * always be true if they are present. The name parameter can be the * complete name or any unique prefix of the name. If the name is not unique * the first matching name will be checked. * Args: * client - The client from cras_client_create. * name - Name of the device to check. * Returns: * 1 if the device exists and is plugged, 0 otherwise. */ int cras_client_output_dev_plugged(const struct cras_client *client, const char *name); /* Sets an attribute of an ionode on a device. * Args: * client - The client from cras_client_create. * node_id - The id of the ionode. * attr - the attribute we want to change. * value - the value we want to set. */ int cras_client_set_node_attr(struct cras_client *client, cras_node_id_t node_id, enum ionode_attr attr, int value); /* Select the preferred node for playback/capture. * Args: * client - The client from cras_client_create. * direction - The direction of the ionode. * node_id - The id of the ionode. If node_id is the special value 0, the * the preference is cleared and cras will choose automatically. */ int cras_client_select_node(struct cras_client *client, enum CRAS_STREAM_DIRECTION direction, cras_node_id_t node_id); /* Asks the server to reload dsp plugin configuration from the ini file. * Args: * client - The client from cras_client_create. * Returns: * 0 on success, -EINVAL if the client isn't valid or isn't running. */ int cras_client_reload_dsp(struct cras_client *client); /* Asks the server to dump current dsp information to syslog. * Args: * client - The client from cras_client_create. * Returns: * 0 on success, -EINVAL if the client isn't valid or isn't running. */ int cras_client_dump_dsp_info(struct cras_client *client); /* Asks the server to dump current audio thread information. * Args: * client - The client from cras_client_create. * cb - A function to call when the data is received. * Returns: * 0 on success, -EINVAL if the client isn't valid or isn't running. */ int cras_client_update_audio_debug_info( struct cras_client *client, void (*cb)(struct cras_client *)); /* * Stream handling. */ /* Setup stream configuration parameters. * Args: * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT). * buffer_frames - total number of audio frames to buffer (dictates latency). * cb_threshold - For playback, call back for more data when the buffer * reaches this level. For capture, this is ignored (Audio callback will * be called when buffer_frames have been captured). * min_cb_level - For playback, the minimum amout of frames that must be able * to be written before calling back for more data (useful if you are * processing audio in blocks of a certain size(e.g. 512 or 1024 frames). * Ignored for capture streams. * stream_type - media or talk (currently only support "default"). * flags - None currently used. * user_data - Pointer that will be passed to the callback. * aud_cb - Called when audio is needed(playback) or ready(capture). Allowed * return EOF to indicate that the stream should terminate. * err_cb - Called when there is an error with the stream. * format - The format of the audio stream. Specifies bits per sample, * number of channels, and sample rate. */ struct cras_stream_params *cras_client_stream_params_create( enum CRAS_STREAM_DIRECTION direction, size_t buffer_frames, size_t cb_threshold, size_t min_cb_level, enum CRAS_STREAM_TYPE stream_type, uint32_t flags, void *user_data, cras_playback_cb_t aud_cb, cras_error_cb_t err_cb, struct cras_audio_format *format); /* Setup stream configuration parameters. * Args: * direction - playback(CRAS_STREAM_OUTPUT) or capture(CRAS_STREAM_INPUT) or * both(CRAS_STREAM_UNIFIED). * block_size - The number of frames per callback(dictates latency). * stream_type - media or talk (currently only support "default"). * flags - None currently used. * user_data - Pointer that will be passed to the callback. * unified_cd - Called for streams that do simultaneous input/output. * err_cb - Called when there is an error with the stream. * format - The format of the audio stream. Specifies bits per sample, * number of channels, and sample rate. */ struct cras_stream_params *cras_client_unified_params_create( enum CRAS_STREAM_DIRECTION direction, unsigned int block_size, enum CRAS_STREAM_TYPE stream_type, uint32_t flags, void *user_data, cras_unified_cb_t unified_cb, cras_error_cb_t err_cb, struct cras_audio_format *format); /* Destroy stream params created with cras_client_stream_params_create. */ void cras_client_stream_params_destroy(struct cras_stream_params *params); /* Creates a new stream and return the stream id or < 0 on error. * Args: * client - The client to add the stream to (from cras_client_create). * stream_id_out - On success will be filled with the new stream id. * Guaranteed to be set before any callbacks are made. * config - The cras_stream_params struct specifying the parameters for the * stream. * Returns: * 0 on success, negative error code on failure (from errno.h). */ int cras_client_add_stream(struct cras_client *client, cras_stream_id_t *stream_id_out, struct cras_stream_params *config); /* Removes a currently playing/capturing stream. * Args: * client - Client to remove the stream (returned from cras_client_create). * stream_id - ID returned from add_stream to identify the stream to remove. * Returns: * 0 on success negative error code on failure (from errno.h). */ int cras_client_rm_stream(struct cras_client *client, cras_stream_id_t stream_id); /* Sets the volume scaling factor for the given stream. * Args: * client - Client owning the stream. * stream_id - ID returned from add_stream. * volume_scaler - 0.0-1.0 the new value to scale this stream by. */ int cras_client_set_stream_volume(struct cras_client *client, cras_stream_id_t stream_id, float volume_scaler); /* Moves stream type to a different input or output. * Args: * client - The client connected to the server with client_connect. * stream_type - The type of stream to move. * iodev - The index of the device to move the stream to. * Returns: * 0 if the message was sent to the server successfully. A negative error * code if there was a communication error (from errno.h). */ int cras_client_switch_iodev(struct cras_client *client, enum CRAS_STREAM_TYPE stream_type, uint32_t iodev); /* * System level functions. */ /* Sets the volume of the system. Volume here ranges from 0 to 100, and will be * translated to dB based on the output-specific volume curve. * Args: * client - Client owning the stream. * volume - 0-100 the new volume index. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_system_volume(struct cras_client *client, size_t volume); /* Sets the capture gain of the system. Gain is specified in dBFS * 100. For * example 5dB of gain would be specified with an argument of 500, while -10 * would be specified with -1000. * Args: * client - Client owning the stream. * gain - The gain in dBFS * 100. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_system_capture_gain(struct cras_client *client, long gain); /* Sets the mute state of the system. * Args: * client - Client owning the stream. * mute - 0 is un-mute, 1 is muted. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_system_mute(struct cras_client *client, int mute); /* Sets the user mute state of the system. This is used for mutes caused by * user interaction. Like the mute key. * Args: * client - Client owning the stream. * mute - 0 is un-mute, 1 is muted. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_user_mute(struct cras_client *client, int mute); /* Sets the mute locked state of the system. Changing mute state is impossible * when this flag is set to locked. * Args: * client - Client owning the stream. * locked - 0 is un-locked, 1 is locked. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_system_mute_locked(struct cras_client *client, int locked); /* Sets the capture mute state of the system. Recordings will be muted when * this is set. * Args: * client - Client owning the stream. * mute - 0 is un-mute, 1 is muted. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_system_capture_mute(struct cras_client *client, int mute); /* Sets the capture mute locked state of the system. Changing mute state is * impossible when this flag is set to locked. * Args: * client - Client owning the stream. * locked - 0 is un-locked, 1 is locked. * Returns: * 0 for success, -EPIPE if there is an I/O error talking to the server, or * -EINVAL if 'client' is invalid. */ int cras_client_set_system_capture_mute_locked(struct cras_client *client, int locked); /* Gets the current system volume. * Args: * client - The client from cras_client_create. * Returns: * The current system volume between 0 and 100. */ size_t cras_client_get_system_volume(struct cras_client *client); /* Gets the current system capture gain. * Args: * client - The client from cras_client_create. * Returns: * The current system capture volume in dB * 100. */ long cras_client_get_system_capture_gain(struct cras_client *client); /* Gets the current system mute state. * Args: * client - The client from cras_client_create. * Returns: * 0 if not muted, 1 if it is. */ int cras_client_get_system_muted(struct cras_client *client); /* Gets the current system captue mute state. * Args: * client - The client from cras_client_create. * Returns: * 0 if capture is not muted, 1 if it is. */ int cras_client_get_system_capture_muted(struct cras_client *client); /* Gets the current minimum system volume. * Args: * client - The client from cras_client_create. * Returns: * The minimum value for the current output device in dBFS * 100. This is * the level of attenuation at volume == 1. */ long cras_client_get_system_min_volume(struct cras_client *client); /* Gets the current maximum system volume. * Args: * client - The client from cras_client_create. * Returns: * The maximum value for the current output device in dBFS * 100. This is * the level of attenuation at volume == 100. */ long cras_client_get_system_max_volume(struct cras_client *client); /* Gets the current minimum system capture gain. * Args: * client - The client from cras_client_create. * Returns: * The minimum capture gain for the current input device in dBFS * 100. */ long cras_client_get_system_min_capture_gain(struct cras_client *client); /* Gets the current maximum system capture gain. * Args: * client - The client from cras_client_create. * Returns: * The maximum capture gain for the current input device in dBFS * 100. */ long cras_client_get_system_max_capture_gain(struct cras_client *client); /* Gets audio debug info. * Args: * client - The client from cras_client_create. * Returns: * A pointer to the debug info. This info is only updated when requested by * calling cras_client_update_audio_debug_info. */ const struct audio_debug_info *cras_client_get_audio_debug_info( struct cras_client *client); /* Gets the number of streams currently attached to the server. This is the * total number of capture and playback streams. If the ts argument is * not null, then it will be filled with the last time audio was played or * recorded. ts will be set to the current time is streams are currently * active. * Args: * ts - Filled with the timestamp of the last stream. * Returns: * The number of active streams. */ unsigned cras_client_get_num_active_streams(struct cras_client *client, struct timespec *ts); /* Gets the id of the output node currently selected * Args: * client - The client from cras_client_create. * Returns: * The id of the output node currently selected. It is 0 if no output node * is selected. */ cras_node_id_t cras_client_get_selected_output(struct cras_client *client); /* Gets the id of the input node currently selected * Args: * client - The client from cras_client_create. * Returns: * The id of the input node currently selected. It is 0 if no input node * is selected. */ cras_node_id_t cras_client_get_selected_input(struct cras_client *client); /* * Utility functions. */ /* Returns the number of bytes in an audio frame for a stream. * Args: * format - The format of the audio stream. Specifies bits per sample, * number of channels, and sample rate. * Returns: * Positive number of bytes in a frame, or a negative error code if fmt is * NULL. */ int cras_client_format_bytes_per_frame(struct cras_audio_format *fmt); /* For playback streams, calculates the latency of the next sample written. * Only valid when called from the audio callback function for the stream * (aud_cb). * Args: * client - The client the stream is attached to(from cras_client_create). * stream_id - Returned from add_stream to identify which stream. * sample_time - The sample time stamp passed in to aud_cb. * delay - Out parameter will be filled with the latency. * Returns: * 0 on success, -EINVAL if delay is NULL. */ int cras_client_calc_playback_latency(const struct timespec *sample_time, struct timespec *delay); /* For capture returns the latency of the next frame to be read from the buffer * (based on when it was captured). Only valid when called from the audio * callback function for the stream (aud_cb). * Args: * sample_time - The sample time stamp passed in to aud_cb. * delay - Out parameter will be filled with the latency. * Returns: * 0 on success, -EINVAL if delay is NULL. */ int cras_client_calc_capture_latency(const struct timespec *sample_time, struct timespec *delay); /* Set the volume of the given output node. Only for output nodes. * Args: * node_id - ID of the node. * volume - New value for node volume. */ int cras_client_set_node_volume(struct cras_client *client, cras_node_id_t node_id, uint8_t volume); /* Set the volume of the given input node. Only for input nodes. * Args: * node_id - ID of the node. * gain - New capture gain for the node. */ int cras_client_set_node_capture_gain(struct cras_client *client, cras_node_id_t node_id, long gain); #ifdef __cplusplus } #endif #endif /* CRAS_CLIENT_H_ */
{ "content_hash": "f664bad73ebe130523c26a5af66302de", "timestamp": "", "source": "github", "line_count": 591, "max_line_length": 80, "avg_line_length": 36.40270727580372, "alnum_prop": 0.6904806172724738, "repo_name": "drinkcat/adhd", "id": "e7ec93a49af55b01b91fd13d74cb36aa8c98b0be", "size": "21689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cras/src/libcras/cras_client.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1016909" }, { "name": "C++", "bytes": "491643" }, { "name": "CSS", "bytes": "1372" }, { "name": "JavaScript", "bytes": "50671" }, { "name": "Matlab", "bytes": "1324" }, { "name": "Python", "bytes": "29210" }, { "name": "Shell", "bytes": "15363" } ], "symlink_target": "" }
using System.Linq; using Xunit; namespace PreMailer.Net.Tests { public class CssParserTests { [Fact] public void AddStylesheet_ContainsAtCharsetRule_ShouldStripRuleAndParseStylesheet() { var stylesheet = "@charset utf-8; div { width: 100% }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.True(parser.Styles.ContainsKey("div")); } [Fact] public void AddStylesheet_ContainsAtPageSection_ShouldStripRuleAndParseStylesheet() { var stylesheet = "@page :first { margin: 2in 3in; } div { width: 100% }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); } [Fact] public void AddStylesheet_ContainsUnsupportedMediaQuery_ShouldStrip() { var stylesheet = "@media print { div { width: 90%; } }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Empty(parser.Styles); } [Fact] public void AddStylesheet_ContainsUnsupportedMediaQueryAndNormalRules_ShouldStripMediaQueryAndParseRules() { var stylesheet = "div { width: 600px; } @media only screen and (max-width:620px) { div { width: 100% } } p { font-family: serif; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Equal(2, parser.Styles.Count); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); Assert.True(parser.Styles.ContainsKey("p")); Assert.Equal("serif", parser.Styles["p"].Attributes["font-family"].Value); } [Fact] public void AddStylesheet_ContainsSupportedMediaQuery_ShouldParseQueryRules() { var stylesheet = "@media only screen { div { width: 600px; } }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsImportStatement_ShouldStripOutImportStatement() { var stylesheet = "@import url(http://google.com/stylesheet); div { width : 600px; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsImportStatementTest_ShouldStripOutImportStatement() { var stylesheet = "@import 'stylesheet.css'; div { width : 600px; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsMinifiedImportStatement_ShouldStripOutImportStatement() { var stylesheet = "@import url(http://google.com/stylesheet);div{width:600px;}"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsMultipleImportStatement_ShouldStripOutImportStatements() { var stylesheet = "@import url(http://google.com/stylesheet); @import url(http://jquery.com/stylesheet1); @import url(http://amazon.com/stylesheet2); div { width : 600px; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsImportStatementWithMediaQuery_ShouldStripOutImportStatements() { var stylesheet = "@import url(http://google.com/stylesheet) mobile; div { width : 600px; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsMultipleImportStatementWithMediaQueries_ShouldStripOutImportStatements() { var stylesheet = "@import url(http://google.com/stylesheet) mobile; @import url(http://google.com/stylesheet) mobile; @import url(http://google.com/stylesheet) mobile; div { width : 600px; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.Single(parser.Styles); Assert.True(parser.Styles.ContainsKey("div")); Assert.Equal("600px", parser.Styles["div"].Attributes["width"].Value); } [Fact] public void AddStylesheet_ContainsEncodedImage() { var stylesheet = @"#logo { content: url('data:image/jpeg; base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs='); max-width: 200px; height: auto; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); var attributes = parser.Styles["#logo"].Attributes; } [Fact] public void AddStylesheet_ShouldSetStyleClassPositions() { var stylesheet1 = "#id .class1 element { color: #fff; } #id .class2 element { color: #aaa; }"; var stylesheet2 = "#id .class3 element { color: #000; } #id .class2 element { color: #bbb; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet1); parser.AddStyleSheet(stylesheet2); Assert.Equal(1, parser.Styles.Values[0].Position); Assert.Equal(4, parser.Styles.Values[1].Position); Assert.Equal(3, parser.Styles.Values[2].Position); } [Fact] public void AddStylesheet_ShouldKeepTheRightOrderOfCssAttributes() { var stylesheet1 = @" .my-div { background-color: blue; } .my-div { background: red; } .my-div { background-color: green; } "; var parser = new CssParser(); parser.AddStyleSheet(stylesheet1); Assert.Single(parser.Styles); var attributes = parser.Styles.First().Value.Attributes.ToArray(); Assert.True(attributes[0] is {Key: "background", Value: {Value: "red"}}); Assert.True(attributes[1] is {Key: "background-color", Value: {Value: "green"}}); } [Fact] public void AddStylesheet_ContainsSingleQuotes_ShouldParseStylesheet() { var stylesheet = "a { color: #fff; font-family: 'Segoe UI', Verdana, Arial, sans-serif; text-decoration: underline; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.NotNull(parser.Styles["a"]); Assert.NotNull(parser.Styles["a"].Attributes["font-family"]); Assert.Equal(3, parser.Styles["a"].Attributes.Count); } [Fact] public void AddStylesheet_ContainsDoubleQuotes_ShouldParseStylesheet() { var stylesheet = "a { color: #fff; font-family: \"Segoe UI\", Verdana, Arial, sans-serif; text-decoration: underline; }"; var parser = new CssParser(); parser.AddStyleSheet(stylesheet); Assert.NotNull(parser.Styles["a"]); Assert.NotNull(parser.Styles["a"].Attributes["font-family"]); Assert.Equal(3, parser.Styles["a"].Attributes.Count); } } }
{ "content_hash": "1c3d5da182c128e595aed1ab010473b3", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 195, "avg_line_length": 33.959276018099544, "alnum_prop": 0.6695536309127248, "repo_name": "milkshakesoftware/PreMailer.Net", "id": "377afcf9dd9a1c2fcc849bf2c4a4ad43af619761", "size": "7505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "PreMailer.Net/PreMailer.Net.Tests/CssParserTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "221" }, { "name": "C#", "bytes": "107759" } ], "symlink_target": "" }
package com.opengamma.strata.market; import static com.opengamma.strata.collect.TestHelper.assertJodaConvert; import static com.opengamma.strata.collect.TestHelper.assertSerialization; import static com.opengamma.strata.collect.TestHelper.assertThrows; import static com.opengamma.strata.collect.TestHelper.assertThrowsIllegalArg; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; /** * Test {@link ValueType}. */ @Test public class ValueTypeTest { public void test_validation() { assertThrows(() -> ValueType.of(null), IllegalArgumentException.class); assertThrows(() -> ValueType.of(""), IllegalArgumentException.class); assertThrows(() -> ValueType.of("Foo Bar"), IllegalArgumentException.class, ".*must only contain the characters.*"); assertThrows(() -> ValueType.of("Foo_Bar"), IllegalArgumentException.class, ".*must only contain the characters.*"); assertThrows(() -> ValueType.of("FooBar!"), IllegalArgumentException.class, ".*must only contain the characters.*"); // these should execute without throwing an exception ValueType.of("FooBar"); ValueType.of("Foo-Bar"); ValueType.of("123"); ValueType.of("FooBar123"); } //----------------------------------------------------------------------- public void checkEquals() { ValueType test = ValueType.of("Foo"); test.checkEquals(test, "Error"); assertThrowsIllegalArg(() -> test.checkEquals(ValueType.PRICE_INDEX, "Error")); } //----------------------------------------------------------------------- public void coverage() { ValueType test = ValueType.of("Foo"); assertEquals(test.toString(), "Foo"); assertSerialization(test); assertJodaConvert(ValueType.class, test); } }
{ "content_hash": "efae1cd58c0a3dbf0c73fda35ac4f572", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 120, "avg_line_length": 37.38297872340426, "alnum_prop": 0.6647694934547524, "repo_name": "ChinaQuants/Strata", "id": "f301e3a1a5c5e703d1842d9afb36746f8aa6717f", "size": "1894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/market/src/test/java/com/opengamma/strata/market/ValueTypeTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "23559288" } ], "symlink_target": "" }
package co.edu.sena.lesson07.colecciones.map; import java.util.Arrays; import java.util.Objects; public class InformationLocation { private String nombre; private String telefono; private String direccion; private byte[] foto; public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public byte[] getFoto() { return foto; } public void setFoto(byte[] foto) { this.foto = foto; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InformationLocation that = (InformationLocation) o; return Objects.equals(nombre, that.nombre); } @Override public int hashCode() { return Objects.hash(nombre); } @Override public String toString() { return "InformationLocation{" + "nombre='" + nombre + '\'' + ", telefono='" + telefono + '\'' + ", direccion='" + direccion + '\'' + ", foto=" + Arrays.toString(foto) + '}'; } }
{ "content_hash": "1fcfdc9fb260abca8f634840d0ee2eff", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 66, "avg_line_length": 22.507462686567163, "alnum_prop": 0.5656498673740054, "repo_name": "SENA-CEET/1349397-Trimestre-4", "id": "cf22cf59bdd93ba8342eaee48f4507c19448ee47", "size": "1508", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "java/Programming/co.edu.sena.lesson07/src/co/edu/sena/lesson07/colecciones/map/InformationLocation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2596" }, { "name": "HTML", "bytes": "1023171" }, { "name": "Java", "bytes": "3104471" }, { "name": "JavaScript", "bytes": "10414" } ], "symlink_target": "" }
package org.apache.streams.twitter.provider; import com.google.common.base.Strings; import org.apache.streams.core.StreamsDatum; import org.apache.streams.jackson.StreamsJacksonMapper; import org.apache.streams.twitter.api.ThirtyDaySearchRequest; import org.apache.streams.twitter.api.ThirtyDaySearchResponse; import org.apache.streams.twitter.api.Twitter; import org.apache.streams.twitter.converter.TwitterDateTimeFormat; import org.apache.streams.twitter.pojo.Tweet; import org.apache.streams.util.ComponentUtils; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.Callable; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Retrieve recent posts from premium thirty day search. */ public class ThirtyDaySearchProviderTask implements Callable<Iterator<Tweet>>, Runnable { private static final Logger LOGGER = LoggerFactory.getLogger(ThirtyDaySearchProviderTask.class); private static ObjectMapper MAPPER = new StreamsJacksonMapper(Stream.of(TwitterDateTimeFormat.TWITTER_FORMAT).collect(Collectors.toList())); protected ThirtyDaySearchProvider provider; protected Twitter client; protected ThirtyDaySearchRequest request; protected List<Tweet> responseList = new ArrayList<>(); /** * ThirtyDaySearchProviderTask constructor. * @param provider ThirtyDaySearchProvider * @param twitter Twitter * @param request ThirtyDaySearchRequest */ public ThirtyDaySearchProviderTask(ThirtyDaySearchProvider provider, Twitter twitter, ThirtyDaySearchRequest request) { this.provider = provider; this.client = twitter; this.request = request; } int item_count = 0; int last_count = 0; int page_count = 0; String next = null; @Override public Iterator<Tweet> call() throws Exception { LOGGER.info("Thread Starting: {}", request.toString()); do { ThirtyDaySearchResponse response = client.thirtyDaySearch(provider.getConfig().getEnvironment(), request); List<Tweet> statuses = response.getResults(); last_count = statuses.size(); // count items but dont truncate response b/c we already paid for them item_count += statuses.size(); page_count++; responseList.addAll(statuses); next = response.getNext(); request.setNext(next); LOGGER.info("item_count: {} last_count: {} page_count: {} next: {} ", item_count, last_count, page_count, next); } while (shouldContinuePulling(last_count, page_count, item_count, next)); return responseList.iterator(); } public boolean shouldContinuePulling(int count, int page_count, int item_count, String next) { boolean shouldContinuePulling = count > 0; if (Strings.isNullOrEmpty(next)) { shouldContinuePulling = false; } if (item_count >= provider.getConfig().getMaxItems()) { shouldContinuePulling = false; } else if (page_count >= provider.getConfig().getMaxPages()) { shouldContinuePulling = false; } LOGGER.info("shouldContinuePulling: ", shouldContinuePulling); return shouldContinuePulling; } @Override public void run() { try { this.call(); } catch (Exception e) { e.printStackTrace(); } } }
{ "content_hash": "11bc35f9dc5b18ba29d38c892b9dd280", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 142, "avg_line_length": 30.10810810810811, "alnum_prop": 0.7336923997606224, "repo_name": "apache/streams", "id": "7ef0493910f942a46ce3d5e8f451e0b358c0a5b2", "size": "4087", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "streams-contrib/streams-provider-twitter/src/main/java/org/apache/streams/twitter/provider/ThirtyDaySearchProviderTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "38467" }, { "name": "HTML", "bytes": "1278771" }, { "name": "HiveQL", "bytes": "28876" }, { "name": "Java", "bytes": "2576774" }, { "name": "PigLatin", "bytes": "3494" }, { "name": "Scala", "bytes": "105274" }, { "name": "Shell", "bytes": "6016" } ], "symlink_target": "" }
using System.ComponentModel; namespace WIC { [EditorBrowsable(EditorBrowsableState.Advanced)] public static class IWICColorContextExtensions { public static void InitializeFromMemory(this IWICColorContext colorContext, byte[] pbBuffer) { colorContext.InitializeFromMemory(pbBuffer, pbBuffer.Length); } public static byte[] GetProfileBytes(this IWICColorContext colorContext) { FetchIntoBuffer<byte> fetcher = colorContext.GetProfileBytes; return fetcher.FetchArray(); } } }
{ "content_hash": "d90fb39c1cb0528daa4362b9ebc0497d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 100, "avg_line_length": 30.36842105263158, "alnum_prop": 0.6863084922010398, "repo_name": "stakx/stakx.WIC", "id": "1d9b8498ec7c5013de41d3a45a40f859175bb76a", "size": "579", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "WIC/Extensions/IWICColorContextExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "111655" } ], "symlink_target": "" }
package net.jeeshop.core.util; /** * 文件类,需要的时候,可以和数据库进行关联 * * @author MZ * * @Time 2009-11-24下午04:29:31 */ public class UploadFiles { private String uploadFileName;// 上传的文件名称 private String uploadContentType;// 类型 private String uploadRealName;// 保存的文件真实名称,UUID // 如果使用数据库的话,建议这三个字段都进行保存 public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadRealName() { return uploadRealName; } public void setUploadRealName(String uploadRealName) { this.uploadRealName = uploadRealName; } }
{ "content_hash": "a6972fcc04a4c26aa63c3094dd610dcd", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 61, "avg_line_length": 22, "alnum_prop": 0.7249417249417249, "repo_name": "gavin2lee/incubator", "id": "20902ea22a77f0bcc21c2f7082dfea37989881ba", "size": "984", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "jeeshop/src/net/jeeshop/core/util/UploadFiles.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "43520" }, { "name": "Batchfile", "bytes": "26665" }, { "name": "CSS", "bytes": "2876598" }, { "name": "FreeMarker", "bytes": "130" }, { "name": "HTML", "bytes": "1622322" }, { "name": "Java", "bytes": "6718384" }, { "name": "JavaScript", "bytes": "10783743" }, { "name": "Mathematica", "bytes": "28028" }, { "name": "PHP", "bytes": "2352569" }, { "name": "Shell", "bytes": "24983" }, { "name": "Smarty", "bytes": "10759" } ], "symlink_target": "" }
@import LinkedinIOSHelper;
{ "content_hash": "84393f000ef2b1886e03038b355eb8c3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 26, "avg_line_length": 27, "alnum_prop": 0.8518518518518519, "repo_name": "ahmetkgunay/LinkedinIOSHelper", "id": "69eeeed851f4d2f83abf2e2805c1e27bc169dfdd", "size": "132", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SwiftDemo/LinkedInIOSHelperSwiftDemo/LinkedInIOSHelperSwiftDemo-Bridging-Header.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "132" }, { "name": "Objective-C", "bytes": "80763" }, { "name": "Ruby", "bytes": "960" }, { "name": "Swift", "bytes": "6046" } ], "symlink_target": "" }
// Copyright 2022 Google LLC // // 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 // // https://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. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(name) { // [START area120tables_v1alpha1_generated_TablesService_DeleteRow_async] /** * This snippet has been automatically generated and should be regarded as a code template only. * It will require modifications to work. * It may require correct/in-range values for request initialization. * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The name of the row to delete. * Format: tables/{table}/rows/{row} */ // const name = 'abc123' // Imports the Tables library const {TablesServiceClient} = require('@google/area120-tables').v1alpha1; // Instantiates a client const tablesClient = new TablesServiceClient(); async function callDeleteRow() { // Construct request const request = { name, }; // Run request const response = await tablesClient.deleteRow(request); console.log(response); } callDeleteRow(); // [END area120tables_v1alpha1_generated_TablesService_DeleteRow_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
{ "content_hash": "4a599a1a9d50430073aa9d65d952d495", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 98, "avg_line_length": 31.629032258064516, "alnum_prop": 0.7113717491075982, "repo_name": "googleapis/google-cloud-node", "id": "6167e7e77240197ede52cc9aa1c5e68c2bae9b0c", "size": "1961", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "packages/google-area120-tables/samples/generated/v1alpha1/tables_service.delete_row.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2789" }, { "name": "JavaScript", "bytes": "10920867" }, { "name": "Python", "bytes": "19983" }, { "name": "Shell", "bytes": "58046" }, { "name": "TypeScript", "bytes": "77312562" } ], "symlink_target": "" }
#ifndef SkBmpStandardCodec_DEFINED #define SkBmpStandardCodec_DEFINED #include "include/core/SkImageInfo.h" #include "include/core/SkTypes.h" #include "src/codec/SkBmpBaseCodec.h" #include "src/codec/SkColorTable.h" #include "src/codec/SkSwizzler.h" /* * This class implements the decoding for bmp images that use "standard" modes, * which essentially means they do not contain bit masks or RLE codes. */ class SkBmpStandardCodec : public SkBmpBaseCodec { public: /* * Creates an instance of the decoder * * Called only by SkBmpCodec::MakeFromStream * There should be no other callers despite this being public * * @param info contains properties of the encoded data * @param stream the stream of encoded image data * @param bitsPerPixel the number of bits used to store each pixel * @param numColors the number of colors in the color table * @param bytesPerColor the number of bytes in the stream used to represent each color in the color table * @param offset the offset of the image pixel data from the end of the * headers * @param rowOrder indicates whether rows are ordered top-down or bottom-up * @param isOpaque indicates if the bmp itself is opaque (before applying * the icp mask, if there is one) * @param inIco indicates if the bmp is embedded in an ico file */ SkBmpStandardCodec(SkEncodedInfo&& info, std::unique_ptr<SkStream> stream, uint16_t bitsPerPixel, uint32_t numColors, uint32_t bytesPerColor, uint32_t offset, SkCodec::SkScanlineOrder rowOrder, bool isOpaque, bool inIco); protected: Result onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes, const Options&, int*) override; bool onInIco() const override { return fInIco; } SkCodec::Result onPrepareToDecode(const SkImageInfo& dstInfo, const SkCodec::Options& options) override; SkSampler* getSampler(bool createIfNecessary) override { SkASSERT(fSwizzler); return fSwizzler.get(); } private: bool createColorTable(SkColorType colorType, SkAlphaType alphaType); SkEncodedInfo swizzlerInfo() const; void initializeSwizzler(const SkImageInfo& dstInfo, const Options& opts); int decodeRows(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes, const Options& opts) override; /* * @param stream This may be a pointer to the stream owned by the parent SkCodec * or a sub-stream of the stream owned by the parent SkCodec. * Either way, this stream is unowned. */ void decodeIcoMask(SkStream* stream, const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes); sk_sp<SkColorTable> fColorTable; // fNumColors is the number specified in the header, or 0 if not present in the header. const uint32_t fNumColors; const uint32_t fBytesPerColor; const uint32_t fOffset; std::unique_ptr<SkSwizzler> fSwizzler; const bool fIsOpaque; const bool fInIco; const size_t fAndMaskRowBytes; // only used for fInIco decodes typedef SkBmpBaseCodec INHERITED; }; #endif // SkBmpStandardCodec_DEFINED
{ "content_hash": "3cb86aeb5e8340fb3a35901776e2b2ad", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 100, "avg_line_length": 39.50574712643678, "alnum_prop": 0.6587139947628746, "repo_name": "endlessm/chromium-browser", "id": "966330ef4a9fcec17234071f6bdac398c67e103d", "size": "3580", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "third_party/skia/src/codec/SkBmpStandardCodec.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package de.hub.clickwatch.model; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.util.FeatureMap; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Handler</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link de.hub.clickwatch.model.Handler#getName <em>Name</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#isCanRead <em>Can Read</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#isCanWrite <em>Can Write</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#isChanged <em>Changed</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#getMixed <em>Mixed</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#getAny <em>Any</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#getValue <em>Value</em>}</li> * <li>{@link de.hub.clickwatch.model.Handler#getTimestamp <em>Timestamp</em>}</li> * </ul> * </p> * * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler() * @model extendedMetaData="kind='mixed'" * @generated */ public interface Handler extends EObject { /** * Returns the value of the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Name</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Name</em>' attribute. * @see #setName(String) * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_Name() * @model * @generated */ String getName(); /** * Sets the value of the '{@link de.hub.clickwatch.model.Handler#getName <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Name</em>' attribute. * @see #getName() * @generated */ void setName(String value); /** * Returns the value of the '<em><b>Can Read</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Can Read</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Can Read</em>' attribute. * @see #setCanRead(boolean) * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_CanRead() * @model * @generated */ boolean isCanRead(); /** * Sets the value of the '{@link de.hub.clickwatch.model.Handler#isCanRead <em>Can Read</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Can Read</em>' attribute. * @see #isCanRead() * @generated */ void setCanRead(boolean value); /** * Returns the value of the '<em><b>Can Write</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Can Write</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Can Write</em>' attribute. * @see #setCanWrite(boolean) * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_CanWrite() * @model * @generated */ boolean isCanWrite(); /** * Sets the value of the '{@link de.hub.clickwatch.model.Handler#isCanWrite <em>Can Write</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Can Write</em>' attribute. * @see #isCanWrite() * @generated */ void setCanWrite(boolean value); /** * Returns the value of the '<em><b>Changed</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Changed</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Changed</em>' attribute. * @see #setChanged(boolean) * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_Changed() * @model default="false" * @generated */ boolean isChanged(); /** * Sets the value of the '{@link de.hub.clickwatch.model.Handler#isChanged <em>Changed</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Changed</em>' attribute. * @see #isChanged() * @generated */ void setChanged(boolean value); /** * Returns the value of the '<em><b>Mixed</b></em>' attribute list. * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Mixed</em>' attribute list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Mixed</em>' attribute list. * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_Mixed() * @model dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true" * extendedMetaData="kind='elementWildcard' name=':mixed'" * @generated */ FeatureMap getMixed(); /** * Returns the value of the '<em><b>Any</b></em>' attribute list. * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Any</em>' attribute list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Any</em>' attribute list. * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_Any() * @model dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true" * extendedMetaData="kind='elementWildcard' name=':1' processing='lax' wildcards='##any'" * @generated */ FeatureMap getAny(); /** * Returns the value of the '<em><b>Value</b></em>' attribute. * The default value is <code>""</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Value</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Value</em>' attribute. * @see #setValue(String) * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_Value() * @model default="" * @generated */ String getValue(); /** * Sets the value of the '{@link de.hub.clickwatch.model.Handler#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see #getValue() * @generated */ void setValue(String value); /** * Returns the value of the '<em><b>Timestamp</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Timestamp</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Timestamp</em>' attribute. * @see #setTimestamp(long) * @see de.hub.clickwatch.model.ClickWatchModelPackage#getHandler_Timestamp() * @model * @generated */ long getTimestamp(); /** * Sets the value of the '{@link de.hub.clickwatch.model.Handler#getTimestamp <em>Timestamp</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Timestamp</em>' attribute. * @see #getTimestamp() * @generated */ void setTimestamp(long value); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model kind="operation" * @generated */ String getQualifiedName(); } // Handler
{ "content_hash": "326849cb52ca38d55ae08823e85bc59b", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 113, "avg_line_length": 34.04329004329004, "alnum_prop": 0.6063072227873856, "repo_name": "markus1978/clickwatch", "id": "1e8a2863b224fbe23d04913d46eaadb06b231f9b", "size": "7913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/de.hub.clickwatch.core/src/de/hub/clickwatch/model/Handler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10246972" }, { "name": "Matlab", "bytes": "7054" }, { "name": "Shell", "bytes": "256" }, { "name": "XML", "bytes": "14136" } ], "symlink_target": "" }
#if !defined(FUSION_AT_IMPL_07172005_0726) #define FUSION_AT_IMPL_07172005_0726 #include <boost/fusion/support/detail/access.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/bool.hpp> namespace boost { namespace fusion { struct cons_tag; namespace extension { template <typename Tag> struct at_impl; template <> struct at_impl<cons_tag> { template <typename Sequence, typename N> struct apply { typedef typename mpl::eval_if< is_const<Sequence> , add_const<typename Sequence::cdr_type> , mpl::identity<typename Sequence::cdr_type> >::type cdr_type; typedef typename mpl::eval_if< mpl::bool_<N::value == 0> , mpl::identity<typename Sequence::car_type> , apply<cdr_type, mpl::int_<N::value-1> > > element; typedef typename mpl::eval_if< is_const<Sequence> , detail::cref_result<element> , detail::ref_result<element> >::type type; template <typename Cons, int N2> static type call(Cons& s, mpl::int_<N2>) { return call(s.cdr, mpl::int_<N2-1>()); } template <typename Cons> static type call(Cons& s, mpl::int_<0>) { return s.car; } static type call(Sequence& s) { return call(s, mpl::int_<N::value>()); } }; }; } }} #endif
{ "content_hash": "e4c24ead6d9753d170c9eb3a78b414a8", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 66, "avg_line_length": 28.60810810810811, "alnum_prop": 0.41048653755314124, "repo_name": "jaredhoberock/gotham", "id": "593f01eef7a999088b8a39e6a6836ad78b1e2137", "size": "2482", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "windows/include/boost/fusion/container/list/detail/at_impl.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3000328" }, { "name": "C++", "bytes": "43171616" }, { "name": "Perl", "bytes": "6275" }, { "name": "Python", "bytes": "2200222" }, { "name": "Shell", "bytes": "2497" } ], "symlink_target": "" }
'use strict'; var roommates = []; var loggedIn = localStorage.getItem('loggedInID'); var house = JSON.parse(localStorage.getItem(loggedIn)); roommates = house.roommates; // if (localStorage.getItem('roommates')){ // console.log('Fetching LS...'); // roommates = JSON.parse(localStorage.getItem('roommates')); // } else { // //there are no roommates in the list // } function Roommate(firstName, lastName, email){ this.firstName = firstName; this.lastName = lastName; this.userID = ((firstName + lastName).toLowerCase()).replace(/[^a-zA-Z ]/g, ''); this.email = email; this.unpaid = []; this.history = []; roommates.push(this); } var roommateDiv = document.getElementById('roommateDiv'); roommateDiv.addEventListener('click',handleRoommateBillList); function handleRoommateBillList(event){ console.log(event); } var roommateFieldset = document.getElementById('roommateFieldset'); roommateFieldset.addEventListener('click', handleFieldset); function handleFieldset(event){ var toHide = document.getElementById('toHide'); console.log(event); if (event.target.nodeName === 'LEGEND'){ console.log('here'); if(toHide.style.display === 'none'){ toHide.style.display = ''; } else{ toHide.style.display = 'none'; } } } function display(){ roommatesList.innerHTML = ''; for (var i = 0; i < roommates.length; i++){ var ulElement = document.getElementById('roommatesList'); var lineElement = document.createElement('li'); lineElement.textContent = roommates[i].firstName + ' ' + roommates[i].lastName + ' - Email: ' + roommates[i].email + ' '; lineElement.id = roommates[i].userID + 'a'; var buttonElement = document.createElement('button'); buttonElement.setAttribute('id', roommates[i].userID); buttonElement.setAttribute('class', 'removeRoommate'); buttonElement.textContent = 'Remove'; lineElement.appendChild(buttonElement); ulElement.appendChild(lineElement); } if (roommates.length > 0){ ulElement.addEventListener('click', function(event) { // console.log(event); var toRemove = event.target.id; for (var i = 0; i < roommates.length; i++){ if (toRemove === roommates[i].userID){ if (confirm('Are you sure you want to remove ' + roommates[i].firstName + ' from the roommates list?')){ roommates.splice(i, 1); house.roommates = roommates; var toLocalStorage = JSON.stringify(house); localStorage.setItem(loggedIn,toLocalStorage); display(); } else { //do nothing } } } }); } } addRoomateForm.addEventListener('submit', function(event){ // if (localStorage.getItem('roommates')){ // roommates = JSON.parse(localStorage.getItem('roommates')); // } event.preventDefault(); if (!event.target.newFirstName.value || !event.target.newLastName.value || !event.target.newEmail.value){ return alert('Must fill in all values'); } for (var i = 0; i < roommates.length; i++){ if ((event.target.newFirstName.value === roommates[i].firstName) && (event.target.newLastName.value === roommates[i].lastName)){ return alert('Roommate already exists'); } if(event.target.newEmail.value === roommates[i].email){ return alert('Email already exists'); } } var newRoommateFirstName = event.target.newFirstName.value; var newRoommateLastName = event.target.newLastName.value; var newRoommateEmail = event.target.newEmail.value; event.target.newFirstName.value = null; event.target.newLastName.value = null; event.target.newEmail.value = null; var newRoommate = new Roommate(newRoommateFirstName, newRoommateLastName, newRoommateEmail); console.log(newRoommate); house.roommates = roommates; var toLocalStorage = JSON.stringify(house); localStorage.setItem(loggedIn,toLocalStorage); // var arrayToStore = JSON.stringify(roommates); // localStorage.setItem('roommates',arrayToStore); display(); location.reload(); }); display(); //Functions for testing/ not added to final // function resetLS(){ // localStorage.clear(); // } //RLS.addEventListener('click', resetLS)
{ "content_hash": "f54989716668eff389fc705cae5c313c", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 132, "avg_line_length": 35.440677966101696, "alnum_prop": 0.6786226685796269, "repo_name": "midfies/bill-splitter", "id": "23a3a2406e1c9c68da0b40c33abfdb56b69854ef", "size": "4182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "roommate.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12476" }, { "name": "HTML", "bytes": "9448" }, { "name": "JavaScript", "bytes": "41526" } ], "symlink_target": "" }
package com.tkulpa.react.Zendrive; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ZendrivePackage implements ReactPackage { public ZendrivePackage() { } @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new ZendriveModule(reactContext)); return modules; } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
{ "content_hash": "e5735c077a498ac01a78380fbc074ce5", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 89, "avg_line_length": 28.885714285714286, "alnum_prop": 0.7527200791295747, "repo_name": "tkulpa/react-native-zendrive", "id": "ff5f22bae79099fe577f30ef6563c3acf7900262", "size": "1011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/src/main/java/com/tkulpa/react/Zendrive/ZendrivePackage.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7293" }, { "name": "JavaScript", "bytes": "92" } ], "symlink_target": "" }
#pragma once #ifndef GEODE_SERVERLOCATIONRESPONSE_H_ #define GEODE_SERVERLOCATIONRESPONSE_H_ #include <geode/Serializable.hpp> #include "GeodeTypeIdsImpl.hpp" namespace apache { namespace geode { namespace client { class ServerLocationResponse : public Serializable { public: ServerLocationResponse() : Serializable() {} void toData(DataOutput&) const override {} void fromData(DataInput& input) override = 0; int32_t classId() const override { return 0; } int8_t typeId() const override = 0; int8_t DSFID() const override { return static_cast<int8_t>(GeodeTypeIdsImpl::FixedIDByte); } size_t objectSize() const override = 0; ~ServerLocationResponse() override = default; }; } // namespace client } // namespace geode } // namespace apache #endif // GEODE_SERVERLOCATIONRESPONSE_H_
{ "content_hash": "eb9801c754a77f828919c7a54f3e4940", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 62, "avg_line_length": 24.757575757575758, "alnum_prop": 0.7343941248470012, "repo_name": "mmartell/geode-native", "id": "10172189ea9d0fa77dff4834125b0be16da7e46d", "size": "1619", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cppcache/src/ServerLocationResponse.hpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "953" }, { "name": "C#", "bytes": "3332023" }, { "name": "C++", "bytes": "10048743" }, { "name": "CMake", "bytes": "294924" }, { "name": "Dockerfile", "bytes": "1787" }, { "name": "GAP", "bytes": "73860" }, { "name": "Java", "bytes": "408146" }, { "name": "Perl", "bytes": "2704" }, { "name": "PowerShell", "bytes": "20976" }, { "name": "Shell", "bytes": "25767" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <title>React App</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="height=device-height, initial-scale=1"> </head> <body> <div class="container"> <div id="root">Loading...</div> </div> </body> </html>
{ "content_hash": "f13699c128b91927f0ac9caf3faa7cc9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 72, "avg_line_length": 23.428571428571427, "alnum_prop": 0.649390243902439, "repo_name": "sujkh85/react-router-webpack-babel-redux", "id": "ff146e7b28a1280a5de23e0218a95e1a9534224c", "size": "328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/template.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4113" }, { "name": "HTML", "bytes": "328" }, { "name": "JavaScript", "bytes": "14636" } ], "symlink_target": "" }
namespace HaloEzAPI.Abstraction.Enum.Halo5 { public enum CropType { Full, Portrait } }
{ "content_hash": "4dfaa943b6fe7aa89cfbda1d05743f44", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 43, "avg_line_length": 14.375, "alnum_prop": 0.591304347826087, "repo_name": "glitch100/Halo-API", "id": "5bc61bd915ec6abf7b07c5817d62c3e2050a8646", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HaloEzAPI/Abstraction/Enum/Halo5/CropType.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "212959" }, { "name": "PowerShell", "bytes": "6798" } ], "symlink_target": "" }
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ #include "VirtualNetworkPool.h" #include "UserPool.h" #include "NebulaLog.h" #include "Nebula.h" #include "PoolObjectAuth.h" #include "AuthManager.h" #include <sstream> #include <ctype.h> /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ unsigned int VirtualNetworkPool::_mac_prefix; unsigned int VirtualNetworkPool::_default_size; /* -------------------------------------------------------------------------- */ VirtualNetworkPool::VirtualNetworkPool( SqlDB * db, const string& prefix, int __default_size, vector<const Attribute *> hook_mads, const string& remotes_location, const vector<const Attribute *>& _inherit_attrs): PoolSQL(db, VirtualNetwork::table, true, true) { istringstream iss; size_t pos = 0; int count = 0; unsigned int tmp; vector<const Attribute *>::const_iterator it; string mac = prefix; _mac_prefix = 0; _default_size = __default_size; while ( (pos = mac.find(':')) != string::npos ) { mac.replace(pos,1," "); count++; } if (count != 1) { NebulaLog::log("VNM",Log::ERROR, "Wrong MAC prefix format, using default"); _mac_prefix = 1; //"00:01" return; } iss.str(mac); iss >> hex >> _mac_prefix >> ws >> hex >> tmp >> ws; _mac_prefix <<= 8; _mac_prefix += tmp; register_hooks(hook_mads, remotes_location); for (it = _inherit_attrs.begin(); it != _inherit_attrs.end(); it++) { const SingleAttribute* sattr = static_cast<const SingleAttribute *>(*it); inherit_attrs.push_back(sattr->value()); } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualNetworkPool::allocate ( int uid, int gid, const string& uname, const string& gname, int umask, int pvid, VirtualNetworkTemplate * vn_template, int * oid, int cluster_id, const string& cluster_name, string& error_str) { VirtualNetwork * vn; VirtualNetwork * vn_aux = 0; string name; ostringstream oss; vn = new VirtualNetwork(uid, gid, uname, gname, umask, pvid, cluster_id, cluster_name, vn_template); // Check name vn->PoolObjectSQL::get_template_attribute("NAME", name); if ( !PoolObjectSQL::name_is_valid(name, error_str) ) { goto error_name; } // Check for duplicates vn_aux = get(name,uid,false); if( vn_aux != 0 ) { goto error_duplicated; } *oid = PoolSQL::allocate(vn, error_str); return *oid; error_duplicated: oss << "NAME is already taken by NET " << vn_aux->get_oid() << "."; error_str = oss.str(); error_name: delete vn; *oid = -1; return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ VirtualNetwork * VirtualNetworkPool::get_nic_by_name(VectorAttribute * nic, const string& name, int _uid, string& error) { istringstream is; string uid_s ; string uname; int uid; VirtualNetwork * vnet; if (!(uid_s = nic->vector_value("NETWORK_UID")).empty()) { is.str(uid_s); is >> uid; if( is.fail() ) { error = "Cannot get user in NETWORK_UID"; return 0; } } else if (!(uname = nic->vector_value("NETWORK_UNAME")).empty()) { User * user; Nebula& nd = Nebula::instance(); UserPool * upool = nd.get_upool(); user = upool->get(uname,true); if ( user == 0 ) { error = "User set in NETWORK_UNAME does not exist"; return 0; } uid = user->get_oid(); user->unlock(); } else { uid = _uid; } vnet = get(name,uid,true); if (vnet == 0) { ostringstream oss; oss << "User " << uid << " does not own a network with name: " << name << " . Set NETWORK_UNAME or NETWORK_UID of owner in NIC."; error = oss.str(); } return vnet; } /* -------------------------------------------------------------------------- */ VirtualNetwork * VirtualNetworkPool::get_nic_by_id(const string& id_s, string& error) { istringstream is; int id; VirtualNetwork * vnet = 0; is.str(id_s); is >> id; if( !is.fail() ) { vnet = get(id,true); } if (vnet == 0) { ostringstream oss; oss << "Virtual network with ID: " << id_s << " does not exist"; error = oss.str(); } return vnet; } int VirtualNetworkPool::nic_attribute(VectorAttribute * nic, int nic_id, int uid, int vid, string& error) { string network; VirtualNetwork * vnet = 0; if (!(network = nic->vector_value("NETWORK")).empty()) { vnet = get_nic_by_name (nic, network, uid, error); } else if (!(network = nic->vector_value("NETWORK_ID")).empty()) { vnet = get_nic_by_id(network, error); } else //Not using a pre-defined network { return -2; } if (vnet == 0) { return -1; } int rc = vnet->nic_attribute(nic, vid, inherit_attrs); if ( rc == 0 ) { update(vnet); nic->replace("NIC_ID", nic_id); } else { ostringstream oss; oss << "Cannot get IP/MAC lease from virtual network " << vnet->get_oid() << "."; error = oss.str(); } vnet->unlock(); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void VirtualNetworkPool::authorize_nic(VectorAttribute * nic, int uid, AuthRequest * ar) { string network; VirtualNetwork * vnet = 0; PoolObjectAuth perm; string error; if (!(network = nic->vector_value("NETWORK")).empty()) { vnet = get_nic_by_name (nic, network, uid, error); if ( vnet != 0 ) { nic->replace("NETWORK_ID", vnet->get_oid()); } } else if (!(network = nic->vector_value("NETWORK_ID")).empty()) { vnet = get_nic_by_id(network, error); } else //Not using a pre-defined network { return; } if (vnet == 0) { return; } vnet->get_permissions(perm); vnet->unlock(); ar->add_auth(AuthRequest::USE, perm); }
{ "content_hash": "97e7b4e9747f7219fd0da380cb05b916", "timestamp": "", "source": "github", "line_count": 326, "max_line_length": 89, "avg_line_length": 26.5, "alnum_prop": 0.4255122120615812, "repo_name": "dberzano/opennebula-torino", "id": "96cb899d60a9f5937913bfc0e9da98e2ed985db5", "size": "8639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/vnm/VirtualNetworkPool.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "452298" }, { "name": "C++", "bytes": "2406692" }, { "name": "CSS", "bytes": "98599" }, { "name": "Erlang", "bytes": "1741" }, { "name": "Java", "bytes": "354315" }, { "name": "JavaScript", "bytes": "1415927" }, { "name": "Python", "bytes": "118789" }, { "name": "Ruby", "bytes": "1907514" }, { "name": "Shell", "bytes": "598726" } ], "symlink_target": "" }
The JLTest.jl package is licensed under the MIT "Expat" License: > Copyright (c) 2014: Sal Mangano. > > 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.
{ "content_hash": "ab7094ac9b3073e8eef4f8741ca5f748", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 72, "avg_line_length": 52.72727272727273, "alnum_prop": 0.7767241379310345, "repo_name": "smangano/JLTest", "id": "b944c7183604176fb86f6123ef88e3087142a95a", "size": "1160", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LICENSE.md", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "19422" } ], "symlink_target": "" }
[![build status](https://travis-ci.org/exercism/elm.svg?branch=master)](https://travis-ci.org/exercism/elm) Exercism Exercises in Elm ## Track Organization The track is organized with the following main directories and files: ``` bin/ # executables required to manage the track config/ # configuration files for the track docs/ # documentation files for automatically generated web pages on exercism.io exercises/ # contains one directory per exercise template/ # template used when generating a new exercise .travis.yml # Travis automatic build and tests configuration config.json # configuration file for all exercises metadata package.json # Node package configuration required for running builds and tests ``` Each exercise within the `exercises/` directory has the following structure: ``` src/ # directory for elm source files Exercise.elm # template downloaded by students Exercise.example.elm # example solution for this exercise tests/ Tests.elm # test file as downloaded by students README.md # generated readme (do not edit by hand) elm.json # elm json config file ``` ## Contributing We welcome contributions of all sorts and sizes, from reporting issues to submitting patches or implementing missing exercises. Please read first [Exercism contribution guidelines][contributing]. If you are not familiar with git and GitHub, you can also have a look at [GitHub's getting started documentation][github-start]. [contributing]: https://github.com/exercism/problem-specifications/blob/master/CONTRIBUTING.md [github-start]: https://help.github.com/en/github/getting-started-with-github ### Setup In order to contribute code to this track, you need to have already installed [npm][npm-install], [elm][elm-install], [elm-test][elm-test], and [elm-format][elm-format]. The build and tests script for this track lives at `bin/build.sh`. It uses the locally installed versions of elm, elm-test and elm-format, specified in the `package.json` file. Thus you can run `bin/build.sh` without the need of having those installed globally but it will be quite inconvenient when working on single exercises. [npm-install]: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm [elm-install]: https://guide.elm-lang.org/install/elm.html [elm-test]: https://www.npmjs.com/package/elm-test [elm-format]: https://github.com/avh4/elm-format ### Preparing for v3 of Exercism If you are interesting in investing mid-term and long-term energy into this project, have a look at [issue #280][v3-issue]. [v3-issue]: https://github.com/exercism/elm/issues/280 ### Adding Missing Exercise All tracks share a common pool of exercises specified in [exercism/problem-specifications][problem-spec] repository. You can find a list of all missing exercises on [tracks.exercism.io][missing-exercises]. Please read first [Exercism documentation about implementing an exercise][impl-exercise]. [problem-spec]: https://github.com/exercism/problem-specifications [missing-exercises]: https://tracks.exercism.io/elm/master/unimplemented [impl-exercise]: https://github.com/exercism/docs/blob/master/you-can-help/implement-an-exercise-from-specification.md Before you start implementing a missing exercise, make sure your setup is already working. ```sh bin/fetch-configlet # if not already retrieved bin/configlet lint . bin/build.sh ``` Then, the general steps for implementing a missing exercise are the following. 1. Run the command `bin/stub-new-exercise.sh <exercise-slug>` 2. Move into that exercise directory 3. Replace placeholder names in `src/` and `tests/`, rename `src/<exercise>.elm` accordingly 4. Run `elm-test` to verify that everything is setup correctly 5. Complete tests according to the `canonical-data.json` file of the exercise in [exercism/problem-specifications][problem-spec] 6. Complete implementation of the solution in `src/<exercise>.elm` and check it passes all tests. 7. Prepare files such that they are ready for student use: * Rename `<exercise>.elm` into `<exercise>.example.elm` * Prepare a starter file for students named `<exercise>.elm`. That is what `exercise download` will retrieve * Add `skip <|` to all tests except the first one so that students can progress gradually 8. Update `config.json` file with an entry for this exercise. * Explanations regarding this file are provided in [Exercism documentation][exercise-config] * The uuid should be generated with the command `bin/configlet uuid` 9. Check that everything is configured correctly and that builds pass by running `bin/configlet lint .` and `bin/build.sh` from the root of the directory 10. Yeah! you can submit your PR [exercise-config]: https://github.com/exercism/docs/blob/master/language-tracks/configuration/exercises.md ### Make Up New Exercises Follow [instructions on Exercism documentation][new-exercise]. [new-exercise]: https://github.com/exercism/docs/blob/master/you-can-help/make-up-new-exercises.md ## Elm icon We were unable to find copyright information about the Elm logo, nor information about who designed it. Presumably Evan Czaplicki, creator of the Elm language, also made the logo, and holds copyright. It may also fall within the public domain, since it is a geometric shape. We've adapted the official Elm logo by changing the colors, which we believe falls under "fair use".
{ "content_hash": "5d4b9fb30b0b0c884b372ac7c04e31b7", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 128, "avg_line_length": 47.68421052631579, "alnum_prop": 0.7641648270787343, "repo_name": "exercism/xelm", "id": "f8b9eb71005e1f802692ebcd859a49d14326a1b9", "size": "5457", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Elm", "bytes": "85652" }, { "name": "Shell", "bytes": "2930" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112-release) on Tue Nov 29 14:28:11 MST 2016 --> <title>com.thundersquadron.thundercab.fragments.login Class Hierarchy</title> <meta name="date" content="2016-11-29"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.thundersquadron.thundercab.fragments.login Class Hierarchy"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/thundersquadron/thundercab/application/package-tree.html">Prev</a></li> <li><a href="../../../../../com/thundersquadron/thundercab/fragments/register/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/thundersquadron/thundercab/fragments/login/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package com.thundersquadron.thundercab.fragments.login</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.Object <ul> <li type="circle">android.app.Fragment (implements android.content.ComponentCallbacks2, android.view.View.OnCreateContextMenuListener) <ul> <li type="circle">com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginFragment.html" title="class in com.thundersquadron.thundercab.fragments.login"><span class="typeNameLink">LoginFragment</span></a> (implements com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginView.html" title="interface in com.thundersquadron.thundercab.fragments.login">LoginView</a>)</li> </ul> </li> <li type="circle">com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginControllerImp.html" title="class in com.thundersquadron.thundercab.fragments.login"><span class="typeNameLink">LoginControllerImp</span></a> (implements com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginController.html" title="interface in com.thundersquadron.thundercab.fragments.login">LoginController</a>)</li> <li type="circle">com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginFragment_ViewBinding.html" title="class in com.thundersquadron.thundercab.fragments.login"><span class="typeNameLink">LoginFragment_ViewBinding</span></a>&lt;T&gt; (implements butterknife.Unbinder)</li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginController.html" title="interface in com.thundersquadron.thundercab.fragments.login"><span class="typeNameLink">LoginController</span></a></li> <li type="circle">com.thundersquadron.thundercab.fragments.login.<a href="../../../../../com/thundersquadron/thundercab/fragments/login/LoginView.html" title="interface in com.thundersquadron.thundercab.fragments.login"><span class="typeNameLink">LoginView</span></a></li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/thundersquadron/thundercab/application/package-tree.html">Prev</a></li> <li><a href="../../../../../com/thundersquadron/thundercab/fragments/register/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/thundersquadron/thundercab/fragments/login/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "b8fb7f5ebcecd08a0500c2ea6bee891a", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 527, "avg_line_length": 46.73287671232877, "alnum_prop": 0.6680345888905174, "repo_name": "CMPUT301F16T13/ThunderCab", "id": "56cf541d55943606e79f56654664122d1f62734a", "size": "6823", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/javadoc/com/thundersquadron/thundercab/fragments/login/package-tree.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "303012" } ], "symlink_target": "" }
- #174 - Cache not being fully emptied if using localStorage and multiple web pages ##### 4.1.0 30 March 2015 ###### Backwards compatible API changes - #169 - Official support for ngResource ##### 4.0.2 22 March 2015 ###### Backwards compatible bug fixes - #164 - onExpire is still called when cache is empty ##### 4.0.1 20 March 2015 ###### Backwards compatible bug fixes - #163 - Configuring CacheOption storagePrefix results in "true.{key}" ##### 4.0.0 15 March 2015 ###### Breaking API changes - Completely disassociated angular-cache from the deprecated angular-data (angular-data has been replaced by js-data + js-data-angular) - Angular module renamed to _angular-cache_ - _DSCacheFactory_ renamed to _CacheFactory_ - _DSBinaryHeap_ renamed to _BinaryHeap_ - Removed `DSCacheFactoryProvider.setCacheDefaults`. You now do `angular.extend(CacheFactoryProvider.defaults, { ... });` - No longer exposing a `DSCache` constructor function (as it no longer exists) - `storageMode` can now be set dynamically, which will remove all items from current storage and insert them into the new storage ###### Other - Fixes #161 - Converted to ES6 and a webpack build with better umd support - Now exporting the module name _angular-cache_ (when you do `require('angular-cache')` you get `"angular-cache"`) - Deprecating angular-cache < 4.0.0 ##### 3.2.5 02 February 2015 ###### Backwards compatible bug fixes - #152 - Expired items sometimes only expire after double time. - #153 - Missing angular dependency in bower.json ##### 3.2.4 17 December 2014 ###### Backwards compatible bug fixes - #149 - when removing an object from localStorage the key didn't get removed if the passed parameter is of number type. ##### 3.2.3 13 December 2014 ###### Backwards compatible bug fixes - #112 - $resource cache and 3.0.0-beta-x - #122 - Error using DSCacheFactory with $http/ $resource and localStorage - #148 - Illegal operation when using local-/sessionStorage ##### 3.2.2 24 November 2014 ###### Backwards compatible bug fixes - #147 - `storeOnResolve` and `storeOnReject` should default to `false` ##### 3.2.1 10 November 2014 ###### Backwards compatible bug fixes - #142 - Use JSON.stringify instead of angular.toJson ##### 3.2.0 07 November 2014 ###### Backwards compatible API changes - #135 - Closes #135. (Improved handling of promises.) ##### 3.1.1 28 August 2014 ###### Backwards compatible bug fixes - #124 - DSCache.info does not work if the storageMode is localStorage. - #127 - requirejs conflict, require object overwritten ##### 3.1.0 15 July 2014 ###### Backwards compatible API changes - #117 - call to DSCacheFactory(...) produces JSHint warning (Added DSCacheFactory.createCache method) ###### Backwards compatible bug fixes - #118 - dist/angular-cache.js doesn't end with a semicolon (Upgraded dependencies) - #120 - How come the non minified version has minified code? (Upgraded dependencies) ##### 3.0.3 16 June 2014 ###### Backwards compatible bug fixes - Angular 1.2.18 with $http/localStorage #116 ##### 3.0.2 15 June 2014 ###### Backwards compatible bug fixes - $http w/ cache is trying to store a promise, which dies on JSON.stringify #115 ##### 3.0.1 14 June 2014 ###### Backwards compatible bug fixes - Added polyfill for `$$minErr`. ##### 3.0.0 14 June 2014 3.0.0 Release ##### 3.0.0-beta.4 22 April 2014 ###### Backwards compatible API changes - Add feature to 'touch' elements in the cache #103 ###### Backwards compatible bug fixes - `localstorage` and Safari Private Browsing #107 ##### 3.0.0-beta.3 03 March 2014 ###### Backwards compatible bug fixes - Fixed duplicate keys when using localStorage #106 ##### 3.0.0-beta.2 25 February 2014 ###### Backwards compatible bug fixes - Fixed missing reference to DSBinaryHeap #105 ##### 3.0.0-beta.1 24 February 2014 ###### Breaking API changes - `maxAge` and `deleteOnExpire` are no longer overridable for individual items - Renamed angular module to `angular-data.DSCacheFactory`. Angular-cache is now part of the `angular-data` namespace - The `verifyIntegrity` option has been completely removed due to a cache being exclusively in-memory OR in web storage #96 - Supported values for the `storageMode` option are now: `"memory"`, `"localStorage"` or `"sessionStorage"` with the default being `"memory"` - `DSCache#put(key, value)` no longer accepts a third `options` argument - `DSCache#removeExpired()` no longer accepts an `options` argument and thus no longer supports returning removed expired items as an array - `DSCache#remove(key)` no longer accepts an `options` argument - `DSCache#setOptions(options[, strict])` no longer accepts `storageMode` and `storageImpl` as part of the `options` argument - `storageMode` is no longer dynamically configurable - `storageImpl` is no longer dynamically configurable ###### Backwards compatible API changes - Added `DSCache#enable()` - Added `DSCache#disable()` - Added `DSCache#setCapacity(capacity)` - Added `DSCache#setMaxAge(maxAge)` - Added `DSCache#setCacheFlushInterval(cacheFlushInterval)` - Added `DSCache#setRecycleFreq(recycleFreq)` - Added `DSCache#setDeleteOnExpire(deleteOnExpire)` - Added `DSCache#setOnExpire(onExpire)` - Added option `storagePrefix` for customizing the prefix used in `localStorage`, etc. #98 - Refactored to be in-memory OR webStorage, never both #96 ###### Other - I might have missed something... ##### 2.3.3 - 24 February 2014 ###### Backwards compatible bug fixes - *sigh Fixed #102 (regression from #100) ##### 2.3.2 - 23 February 2014 ###### Backwards compatible bug fixes - Fixed #100 (regression from #89) ##### 2.3.1 - 19 February 2014 ###### Backwards compatible bug fixes - Fixed #89 ##### 2.3.0 - 09 January 2014 - Caches can now be disabled #82 - The `options` object (`$angularCacheFactory()`, `AngularCache#setOptions()`, and `$angularCacheFactoryProvider.setCacheDefaults()`) now accepts a `disabled` field, which can be set to `true` and defaults to `false`. - `$angularCacheFactory.enableAll()` will enable any disabled caches. - `$angularCacheFactory.disableAll()` will disable all caches. - A disabled cache will operate as normal, except `AngularCache#get()` and `AngularCache#put()` will both immediately return `undefined` instead of performing their normal functions. ###### Backwards compatible API changes - `removeExpired()` now returns an object (or array) of the removed items. ###### Backwards compatible bug fixes - `removeExpired()` now removes _all_ expired items. ##### 2.2.0 - 15 December 2013 ###### Backwards compatible API changes - `removeExpired()` now returns an object (or array) of the removed items. ###### Backwards compatible bug fixes - `removeExpired()` now removes _all_ expired items. ##### 2.1.1 - 20 November 2013 ###### Backwards compatible bug fixes - Allow number keys, but stringify them #76 - Fix "Uncaught TypeError: Cannot read property 'maxAge' of null" #77 (thanks @evngeny-o) ##### 2.1.0 - 03 November 2013 ###### Backwards compatible API changes - Modify .get(key, options) to accept multiple keys #71 (thanks @roryf) ###### Other - Run tests against multiple versions of Angular.js #72 - Add banner to dist/angular-cache.min.js #68 ##### 2.0.0 - 30 October 2013 - Not all methods of AngularCache and $angularCacheFactory are in README #61 - Fix demo to work with 2.0.0-rc.1 #62 - Using Bower to install this package, the dist filenames change per version? #63 ##### 2.0.0-rc.1 - 14 October 2013 ###### Breaking API changes - Swapped `aggressiveDelete` option for `deleteOnExpire` option. #30, #47 - Changed `$angularCacheFactory.info()` to return an object similar to `AngularCache.info()` #45 - Namespaced angular-cache module under `jmdobry` so it is now "jmdobry.angular-cache". #42 - Substituted `storageImpl` and `sessionStorageImpl` options for just `storageImpl` option. ###### Backwards compatible API changes - Added `recycleFreq` to specify how frequently to check for expired items (no more $timeout). #28, #57 - Added ability to set global cache defaults in $angularCacheFactoryProvider. #55 ###### Backwards compatible bug fixes - cacheFlushInterval doesn't clear web storage when storageMode is used. #52 - AngularCache#info(key) should return 'undefined' if the key isn't in the cache #53 - Fixed timespan issues in README.md. #59 ###### Other - Refactored angular-cache `setOptions()` internals to be less convoluted and to have better validation. #46 - Re-wrote documentation to be clearer and more organized. #56 - Fixed documentation where time spans were incorrectly labeled. #59 ##### 1.2.0 - 20 September 2013 ###### Backwards compatible API changes - Added AngularCache#info(key) #43 ###### Backwards compatible bug fixes - Fixed #39, #44, #49, #50 ##### 1.1.0 - 03 September 2013 ###### Backwards compatible API changes - Added `onExpire` callback hook #27 - Added `$angularCacheFactory.removeAll()` and `$angularCacheFactory.clearAll()` convenience methods #37, #38 ###### Backwards compatible bug fixes - Fixed #36 ##### 1.0.0 - 25 August 2013 - Closed #31 (Improved documentation) - Closed #32 ##### 1.0.0-rc.1 - 21 August 2013 - Added localStorage feature #26, #29 ##### 0.9.1 - 03 August 2013 - Fixed #25 ##### 0.9.0 - 03 August 2013 - Added a changelog #13 - Added documentation for installing with bower - Added ability to set option `aggressiveDelete` when creating cache and when adding items - Cleaned up README.md - Switched the demo to use Bootstrap 3 ##### 0.8.2 - 09 July 2013 - Added CONTRIBUTING.md #22 - Cleaned up meta data in bower.json and package.json ##### 0.8.1 - 09 July 2013 - Added .jshintrc - Cleaned up the docs a bit - `bower.json` now uses `src/angular-cache.js` instead of the versioned output files #21 - From now on the tags for the project will be named using [semver](http://semver.org/) ##### 0.8.0 - 08 July 2013 - Added `AngularCache.setOptions()`, the ability to dynamically change the configuration of a cache #20 - Added `AngularCache.keys()`, which returns an array of the keys in a cache #19 - Added `AngularCache.keySet()`, which returns a hash of the keys in a cache #19 ##### 0.7.2 - June 2013 - Added `angular-cache` to bower registry #7 - Created a working demo #9 #17 - Fixed the size not being reset to 0 when the cache clears itself #14 #16 - Added `$angularCacheFactory.keys()`, which returns an array of the keys (the names of the caches) in $angularCacheFactory #18 - Added `$angularCacheFactory.keySet()`, which returns a hash of the keys (the names of the caches) in $angularCacheFactory #18 ##### 0.6.1 - June 2013 - Got the project building on TravisCI - Renamed the project to `angular-cache` #5 ##### 0.5.0 - June 2013 - Added a roadmap to README.md #4 - Clarify usage documentation #3 - Wrote unit tests #2 ##### 0.4.0 - May 2013 - Added Grunt build tasks #1
{ "content_hash": "3548aa3418e798d27c12337df500bea0", "timestamp": "", "source": "github", "line_count": 293, "max_line_length": 217, "avg_line_length": 37.01023890784983, "alnum_prop": 0.7221504979712283, "repo_name": "Malkiat-Singh/angular-cache", "id": "5688309033edb67a5500f8f1cf08285b649fa206", "size": "10909", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "108108" } ], "symlink_target": "" }
import React from 'react'; import Login from './Login'; import { signIn } from '../firebase' import Link from './Link'; const SignInPage = ({ assign, setUser }) => { return ( <div> <div id='header'> <Link to='/'> <h1 id='main-header'>DigiDex</h1> </Link> </div> <Login id='signIn' text='Sign In With Gmail' authorize={signIn} setUser={setUser} /> </div> ) } export default SignInPage
{ "content_hash": "8da1395ebb38e469b7d71ca06fb7c8cd", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 45, "avg_line_length": 18.653846153846153, "alnum_prop": 0.5216494845360825, "repo_name": "mlimberg/Digidex", "id": "ef9fc7a353ae0b0ded3e5042a4a51f2796cba5b7", "size": "485", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/components/SignInPage.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5063" }, { "name": "HTML", "bytes": "9160" }, { "name": "JavaScript", "bytes": "27151" } ], "symlink_target": "" }
package org.planx.xmlstore.routing; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.math.BigInteger; import java.net.InetAddress; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import org.planx.xmlstore.routing.messaging.Streamable; /** * Represents a node and contains information about the IP address, * UDP port, and ID of the node. **/ public class Node implements Streamable { public static final Comparator LASTSEEN_COMPARATOR = new LastSeenComparator(); public static final Comparator FIRSTSEEN_COMPARATOR = new FirstSeenComparator(); private InetAddress ip; private int port; private Identifier id; private long lastSeen; private long firstSeen; private int failCount = 0; /** * Constructs a node with the specified IP address, UDP port, and identifier. * This constructor should be used for foreign nodes. **/ public Node(InetAddress ip, int port, Identifier id) { this.ip = ip; this.port = port; this.id = id; firstSeen = System.currentTimeMillis(); seenNow(); } /** * Constructs a node by reading the state from a DataInput. **/ public Node(DataInput in) throws IOException { fromStream(in); } public void fromStream(DataInput in) throws IOException { id = new Identifier(in); byte[] a = new byte[4]; in.readFully(a); ip = InetAddress.getByAddress(a); port = ((int) in.readShort()) & 0xFFFF; firstSeen = System.currentTimeMillis(); seenNow(); } public void toStream(DataOutput out) throws IOException { id.toStream(out); byte[] a = ip.getAddress(); if (a.length != 4) { throw new RuntimeException("Expected InetAddress of 4 bytes, got "+a.length); } out.write(a); out.writeShort((short) port); } /** * Update time last seen for this node and reset fail count. **/ public void seenNow() { lastSeen = System.currentTimeMillis(); failCount = 0; } /** * Returns the time this node was first seen. **/ public long firstSeen() { return firstSeen; } /** * Returns the time this node was last seen. **/ public long lastSeen() { return lastSeen; } /** * Returns the IP address of this node. **/ public InetAddress getInetAddress() { return ip; } /** * Returns the UDP port of this node. **/ public int getPort() { return port; } /** * Returns the identifier of this node. **/ public Identifier getId() { return id; } /** * Increments the failure counter and returns the new value. **/ public int incFailCount() { return ++failCount; } /** * Returns <code>true</code> if <code>o</code> is a <code>Node</code> * and has the same identifier as this. Note that IP address and port * are ignored in this comparison. **/ public boolean equals(Object o) { if (o instanceof Node) { return id.equals(((Node) o).id); } return false; } public int hashCode() { return id.hashCode(); } public String toString() { return "Node[ip="+ip.getHostAddress()+",port="+port+",id="+id+"]"; } /** * Sorts the nodes in the specified list in order of increasing distance * to the specified identifier. **/ public static Node[] sort(Collection nodes, Identifier rel) { Node[] sorted = new Node[nodes.size()]; sorted = (Node[]) nodes.toArray(sorted); Arrays.sort(sorted, new Node.DistanceComparator(rel)); return sorted; } /** * A DistanceComparator is capable of comparing Node objects according to * closeness to a predetermined identifier using the XOR metric. **/ public static class DistanceComparator implements Comparator { private BigInteger relval; /** * The identifier relative to which the distance should be measured. **/ public DistanceComparator(Identifier relId) { relval = relId.value(); } /** * Compare two objects which must both be of type <code>Node</code> * and determine which is closest to the identifier specified in the * constructor. **/ public int compare(Object o1, Object o2) { Node n1 = (Node) o1; Node n2 = (Node) o2; BigInteger distance1 = relval.xor(n1.id.value()); BigInteger distance2 = relval.xor(n2.id.value()); return distance1.compareTo(distance2); } } /** * A LastSeenComparator is capable of comparing Node objects according to * time last seen. **/ public static class LastSeenComparator implements Comparator { /** * Compare two objects which must both be of type <code>Node</code> * and determine which is seen last. If <code>o1</code> is seen more * recently than <code>o2</code> a positive integer is returned, etc. **/ public int compare(Object o1, Object o2) { Node n1 = (Node) o1; Node n2 = (Node) o2; return (int) (n1.lastSeen - n2.lastSeen); } } /** * A FirstSeenComparator is capable of comparing Node objects according to * time first seen. **/ public static class FirstSeenComparator implements Comparator { /** * Compare two objects which must both be of type <code>Node</code> * and determine which is seen first. If <code>o1</code> is seen before * <code>o2</code> a negative integer is returned, etc. **/ public int compare(Object o1, Object o2) { Node n1 = (Node) o1; Node n2 = (Node) o2; return (int) (n1.firstSeen - n2.firstSeen); } } }
{ "content_hash": "bc04ebb7c7493af63617d22bf6235810", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 89, "avg_line_length": 28.919047619047618, "alnum_prop": 0.5955870245348263, "repo_name": "lvanni/synapse", "id": "8facc79d5f2a046b3846015e7301722534a1c178", "size": "6073", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jSynapse/trunk/src/org/planx/xmlstore/routing/Node.java", "mode": "33188", "license": "mit", "language": [ { "name": "Emacs Lisp", "bytes": "1021" }, { "name": "Java", "bytes": "563196" }, { "name": "JavaScript", "bytes": "229986" }, { "name": "PHP", "bytes": "4832" }, { "name": "Perl", "bytes": "1476" }, { "name": "Ruby", "bytes": "1016" }, { "name": "Shell", "bytes": "12995" } ], "symlink_target": "" }
""" Telnet protocol implementation. @author: Jean-Paul Calderone """ from __future__ import absolute_import, division import struct from zope.interface import implementer from twisted.internet import protocol, interfaces as iinternet, defer from twisted.python import log from twisted.python.compat import _bytesChr as chr, iterbytes MODE = chr(1) EDIT = 1 TRAPSIG = 2 MODE_ACK = 4 SOFT_TAB = 8 LIT_ECHO = 16 # Characters gleaned from the various (and conflicting) RFCs. Not all of these are correct. NULL = chr(0) # No operation. BEL = chr(7) # Produces an audible or # visible signal (which does # NOT move the print head). BS = chr(8) # Moves the print head one # character position towards # the left margin. HT = chr(9) # Moves the printer to the # next horizontal tab stop. # It remains unspecified how # either party determines or # establishes where such tab # stops are located. LF = chr(10) # Moves the printer to the # next print line, keeping the # same horizontal position. VT = chr(11) # Moves the printer to the # next vertical tab stop. It # remains unspecified how # either party determines or # establishes where such tab # stops are located. FF = chr(12) # Moves the printer to the top # of the next page, keeping # the same horizontal position. CR = chr(13) # Moves the printer to the left # margin of the current line. ECHO = chr(1) # User-to-Server: Asks the server to send # Echos of the transmitted data. SGA = chr(3) # Suppress Go Ahead. Go Ahead is silly # and most modern servers should suppress # it. NAWS = chr(31) # Negotiate About Window Size. Indicate that # information about the size of the terminal # can be communicated. LINEMODE = chr(34) # Allow line buffering to be # negotiated about. SE = chr(240) # End of subnegotiation parameters. NOP = chr(241) # No operation. DM = chr(242) # "Data Mark": The data stream portion # of a Synch. This should always be # accompanied by a TCP Urgent # notification. BRK = chr(243) # NVT character Break. IP = chr(244) # The function Interrupt Process. AO = chr(245) # The function Abort Output AYT = chr(246) # The function Are You There. EC = chr(247) # The function Erase Character. EL = chr(248) # The function Erase Line GA = chr(249) # The Go Ahead signal. SB = chr(250) # Indicates that what follows is # subnegotiation of the indicated # option. WILL = chr(251) # Indicates the desire to begin # performing, or confirmation that # you are now performing, the # indicated option. WONT = chr(252) # Indicates the refusal to perform, # or continue performing, the # indicated option. DO = chr(253) # Indicates the request that the # other party perform, or # confirmation that you are expecting # the other party to perform, the # indicated option. DONT = chr(254) # Indicates the demand that the # other party stop performing, # or confirmation that you are no # longer expecting the other party # to perform, the indicated option. IAC = chr(255) # Data Byte 255. Introduces a # telnet command. LINEMODE_MODE = chr(1) LINEMODE_EDIT = chr(1) LINEMODE_TRAPSIG = chr(2) LINEMODE_MODE_ACK = chr(4) LINEMODE_SOFT_TAB = chr(8) LINEMODE_LIT_ECHO = chr(16) LINEMODE_FORWARDMASK = chr(2) LINEMODE_SLC = chr(3) LINEMODE_SLC_SYNCH = chr(1) LINEMODE_SLC_BRK = chr(2) LINEMODE_SLC_IP = chr(3) LINEMODE_SLC_AO = chr(4) LINEMODE_SLC_AYT = chr(5) LINEMODE_SLC_EOR = chr(6) LINEMODE_SLC_ABORT = chr(7) LINEMODE_SLC_EOF = chr(8) LINEMODE_SLC_SUSP = chr(9) LINEMODE_SLC_EC = chr(10) LINEMODE_SLC_EL = chr(11) LINEMODE_SLC_EW = chr(12) LINEMODE_SLC_RP = chr(13) LINEMODE_SLC_LNEXT = chr(14) LINEMODE_SLC_XON = chr(15) LINEMODE_SLC_XOFF = chr(16) LINEMODE_SLC_FORW1 = chr(17) LINEMODE_SLC_FORW2 = chr(18) LINEMODE_SLC_MCL = chr(19) LINEMODE_SLC_MCR = chr(20) LINEMODE_SLC_MCWL = chr(21) LINEMODE_SLC_MCWR = chr(22) LINEMODE_SLC_MCBOL = chr(23) LINEMODE_SLC_MCEOL = chr(24) LINEMODE_SLC_INSRT = chr(25) LINEMODE_SLC_OVER = chr(26) LINEMODE_SLC_ECR = chr(27) LINEMODE_SLC_EWR = chr(28) LINEMODE_SLC_EBOL = chr(29) LINEMODE_SLC_EEOL = chr(30) LINEMODE_SLC_DEFAULT = chr(3) LINEMODE_SLC_VALUE = chr(2) LINEMODE_SLC_CANTCHANGE = chr(1) LINEMODE_SLC_NOSUPPORT = chr(0) LINEMODE_SLC_LEVELBITS = chr(3) LINEMODE_SLC_ACK = chr(128) LINEMODE_SLC_FLUSHIN = chr(64) LINEMODE_SLC_FLUSHOUT = chr(32) LINEMODE_EOF = chr(236) LINEMODE_SUSP = chr(237) LINEMODE_ABORT = chr(238) class ITelnetProtocol(iinternet.IProtocol): def unhandledCommand(command, argument): """A command was received but not understood. @param command: the command received. @type command: C{str}, a single character. @param argument: the argument to the received command. @type argument: C{str}, a single character, or None if the command that was unhandled does not provide an argument. """ def unhandledSubnegotiation(command, bytes): """A subnegotiation command was received but not understood. @param command: the command being subnegotiated. That is, the first byte after the SB command. @type command: C{str}, a single character. @param bytes: all other bytes of the subneogation. That is, all but the first bytes between SB and SE, with IAC un-escaping applied. @type bytes: C{list} of C{str}, each a single character """ def enableLocal(option): """Enable the given option locally. This should enable the given option on this side of the telnet connection and return True. If False is returned, the option will be treated as still disabled and the peer will be notified. @param option: the option to be enabled. @type option: C{str}, a single character. """ def enableRemote(option): """Indicate whether the peer should be allowed to enable this option. Returns True if the peer should be allowed to enable this option, False otherwise. @param option: the option to be enabled. @type option: C{str}, a single character. """ def disableLocal(option): """Disable the given option locally. Unlike enableLocal, this method cannot fail. The option must be disabled. @param option: the option to be disabled. @type option: C{str}, a single character. """ def disableRemote(option): """Indicate that the peer has disabled this option. @param option: the option to be disabled. @type option: C{str}, a single character. """ class ITelnetTransport(iinternet.ITransport): def do(option): """ Indicate a desire for the peer to begin performing the given option. Returns a Deferred that fires with True when the peer begins performing the option, or fails with L{OptionRefused} when the peer refuses to perform it. If the peer is already performing the given option, the Deferred will fail with L{AlreadyEnabled}. If a negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be enabled. """ def dont(option): """ Indicate a desire for the peer to cease performing the given option. Returns a Deferred that fires with True when the peer ceases performing the option. If the peer is not performing the given option, the Deferred will fail with L{AlreadyDisabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be disabled. """ def will(option): """ Indicate our willingness to begin performing this option locally. Returns a Deferred that fires with True when the peer agrees to allow us to begin performing this option, or fails with L{OptionRefused} if the peer refuses to allow us to begin performing it. If the option is already enabled locally, the Deferred will fail with L{AlreadyEnabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be enabled. """ def wont(option): """ Indicate that we will stop performing the given option. Returns a Deferred that fires with True when the peer acknowledges we have stopped performing this option. If the option is already disabled locally, the Deferred will fail with L{AlreadyDisabled}. If negotiation regarding this option is already in progress, the Deferred will fail with L{AlreadyNegotiating}. Note: It is currently possible that this Deferred will never fire, if the peer never responds, or if the peer believes the option to already be disabled. """ def requestNegotiation(about, bytes): """ Send a subnegotiation request. @param about: A byte indicating the feature being negotiated. @param bytes: Any number of bytes containing specific information about the negotiation being requested. No values in this string need to be escaped, as this function will escape any value which requires it. """ class TelnetError(Exception): pass class NegotiationError(TelnetError): def __str__(self): return self.__class__.__module__ + '.' + self.__class__.__name__ + ':' + repr(self.args[0]) class OptionRefused(NegotiationError): pass class AlreadyEnabled(NegotiationError): pass class AlreadyDisabled(NegotiationError): pass class AlreadyNegotiating(NegotiationError): pass @implementer(ITelnetProtocol) class TelnetProtocol(protocol.Protocol): def unhandledCommand(self, command, argument): pass def unhandledSubnegotiation(self, command, bytes): pass def enableLocal(self, option): pass def enableRemote(self, option): pass def disableLocal(self, option): pass def disableRemote(self, option): pass class Telnet(protocol.Protocol): """ @ivar commandMap: A mapping of bytes to callables. When a telnet command is received, the command byte (the first byte after IAC) is looked up in this dictionary. If a callable is found, it is invoked with the argument of the command, or None if the command takes no argument. Values should be added to this dictionary if commands wish to be handled. By default, only WILL, WONT, DO, and DONT are handled. These should not be overridden, as this class handles them correctly and provides an API for interacting with them. @ivar negotiationMap: A mapping of bytes to callables. When a subnegotiation command is received, the command byte (the first byte after SB) is looked up in this dictionary. If a callable is found, it is invoked with the argument of the subnegotiation. Values should be added to this dictionary if subnegotiations are to be handled. By default, no values are handled. @ivar options: A mapping of option bytes to their current state. This state is likely of little use to user code. Changes should not be made to it. @ivar state: A string indicating the current parse state. It can take on the values "data", "escaped", "command", "newline", "subnegotiation", and "subnegotiation-escaped". Changes should not be made to it. @ivar transport: This protocol's transport object. """ # One of a lot of things state = 'data' def __init__(self): self.options = {} self.negotiationMap = {} self.commandMap = { WILL: self.telnet_WILL, WONT: self.telnet_WONT, DO: self.telnet_DO, DONT: self.telnet_DONT} def _write(self, bytes): self.transport.write(bytes) class _OptionState: """ Represents the state of an option on both sides of a telnet connection. @ivar us: The state of the option on this side of the connection. @ivar him: The state of the option on the other side of the connection. """ class _Perspective: """ Represents the state of an option on side of the telnet connection. Some options can be enabled on a particular side of the connection (RFC 1073 for example: only the client can have NAWS enabled). Other options can be enabled on either or both sides (such as RFC 1372: each side can have its own flow control state). @ivar state: C{'yes'} or C{'no'} indicating whether or not this option is enabled on one side of the connection. @ivar negotiating: A boolean tracking whether negotiation about this option is in progress. @ivar onResult: When negotiation about this option has been initiated by this side of the connection, a L{Deferred} which will fire with the result of the negotiation. C{None} at other times. """ state = 'no' negotiating = False onResult = None def __str__(self): return self.state + ('*' * self.negotiating) def __init__(self): self.us = self._Perspective() self.him = self._Perspective() def __repr__(self): return '<_OptionState us=%s him=%s>' % (self.us, self.him) def getOptionState(self, opt): return self.options.setdefault(opt, self._OptionState()) def _do(self, option): self._write(IAC + DO + option) def _dont(self, option): self._write(IAC + DONT + option) def _will(self, option): self._write(IAC + WILL + option) def _wont(self, option): self._write(IAC + WONT + option) def will(self, option): """Indicate our willingness to enable an option. """ s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.us.state == 'yes': return defer.fail(AlreadyEnabled(option)) else: s.us.negotiating = True s.us.onResult = d = defer.Deferred() self._will(option) return d def wont(self, option): """Indicate we are not willing to enable an option. """ s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.us.state == 'no': return defer.fail(AlreadyDisabled(option)) else: s.us.negotiating = True s.us.onResult = d = defer.Deferred() self._wont(option) return d def do(self, option): s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.him.state == 'yes': return defer.fail(AlreadyEnabled(option)) else: s.him.negotiating = True s.him.onResult = d = defer.Deferred() self._do(option) return d def dont(self, option): s = self.getOptionState(option) if s.us.negotiating or s.him.negotiating: return defer.fail(AlreadyNegotiating(option)) elif s.him.state == 'no': return defer.fail(AlreadyDisabled(option)) else: s.him.negotiating = True s.him.onResult = d = defer.Deferred() self._dont(option) return d def requestNegotiation(self, about, bytes): """ Send a negotiation message for the option C{about} with C{bytes} as the payload. @see: L{ITelnetTransport.requestNegotiation} """ bytes = bytes.replace(IAC, IAC * 2) self._write(IAC + SB + about + bytes + IAC + SE) def dataReceived(self, data): appDataBuffer = [] for b in iterbytes(data): if self.state == 'data': if b == IAC: self.state = 'escaped' elif b == b'\r': self.state = 'newline' else: appDataBuffer.append(b) elif self.state == 'escaped': if b == IAC: appDataBuffer.append(b) self.state = 'data' elif b == SB: self.state = 'subnegotiation' self.commands = [] elif b in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA): self.state = 'data' if appDataBuffer: self.applicationDataReceived(b''.join(appDataBuffer)) del appDataBuffer[:] self.commandReceived(b, None) elif b in (WILL, WONT, DO, DONT): self.state = 'command' self.command = b else: raise ValueError("Stumped", b) elif self.state == 'command': self.state = 'data' command = self.command del self.command if appDataBuffer: self.applicationDataReceived(b''.join(appDataBuffer)) del appDataBuffer[:] self.commandReceived(command, b) elif self.state == 'newline': self.state = 'data' if b == b'\n': appDataBuffer.append(b'\n') elif b == b'\0': appDataBuffer.append(b'\r') elif b == IAC: # IAC isn't really allowed after \r, according to the # RFC, but handling it this way is less surprising than # delivering the IAC to the app as application data. # The purpose of the restriction is to allow terminals # to unambiguously interpret the behavior of the CR # after reading only one more byte. CR LF is supposed # to mean one thing (cursor to next line, first column), # CR NUL another (cursor to first column). Absent the # NUL, it still makes sense to interpret this as CR and # then apply all the usual interpretation to the IAC. appDataBuffer.append(b'\r') self.state = 'escaped' else: appDataBuffer.append(b'\r' + b) elif self.state == 'subnegotiation': if b == IAC: self.state = 'subnegotiation-escaped' else: self.commands.append(b) elif self.state == 'subnegotiation-escaped': if b == SE: self.state = 'data' commands = self.commands del self.commands if appDataBuffer: self.applicationDataReceived(b''.join(appDataBuffer)) del appDataBuffer[:] self.negotiate(commands) else: self.state = 'subnegotiation' self.commands.append(b) else: raise ValueError("How'd you do this?") if appDataBuffer: self.applicationDataReceived(b''.join(appDataBuffer)) def connectionLost(self, reason): for state in self.options.values(): if state.us.onResult is not None: d = state.us.onResult state.us.onResult = None d.errback(reason) if state.him.onResult is not None: d = state.him.onResult state.him.onResult = None d.errback(reason) def applicationDataReceived(self, bytes): """Called with application-level data. """ def unhandledCommand(self, command, argument): """Called for commands for which no handler is installed. """ def commandReceived(self, command, argument): cmdFunc = self.commandMap.get(command) if cmdFunc is None: self.unhandledCommand(command, argument) else: cmdFunc(argument) def unhandledSubnegotiation(self, command, bytes): """Called for subnegotiations for which no handler is installed. """ def negotiate(self, bytes): command, bytes = bytes[0], bytes[1:] cmdFunc = self.negotiationMap.get(command) if cmdFunc is None: self.unhandledSubnegotiation(command, bytes) else: cmdFunc(bytes) def telnet_WILL(self, option): s = self.getOptionState(option) self.willMap[s.him.state, s.him.negotiating](self, s, option) def will_no_false(self, state, option): # He is unilaterally offering to enable an option. if self.enableRemote(option): state.him.state = 'yes' self._do(option) else: self._dont(option) def will_no_true(self, state, option): # Peer agreed to enable an option in response to our request. state.him.state = 'yes' state.him.negotiating = False d = state.him.onResult state.him.onResult = None d.callback(True) assert self.enableRemote(option), "enableRemote must return True in this context (for option %r)" % (option,) def will_yes_false(self, state, option): # He is unilaterally offering to enable an already-enabled option. # Ignore this. pass def will_yes_true(self, state, option): # This is a bogus state. It is here for completeness. It will # never be entered. assert False, "will_yes_true can never be entered, but was called with %r, %r" % (state, option) willMap = {('no', False): will_no_false, ('no', True): will_no_true, ('yes', False): will_yes_false, ('yes', True): will_yes_true} def telnet_WONT(self, option): s = self.getOptionState(option) self.wontMap[s.him.state, s.him.negotiating](self, s, option) def wont_no_false(self, state, option): # He is unilaterally demanding that an already-disabled option be/remain disabled. # Ignore this (although we could record it and refuse subsequent enable attempts # from our side - he can always refuse them again though, so we won't) pass def wont_no_true(self, state, option): # Peer refused to enable an option in response to our request. state.him.negotiating = False d = state.him.onResult state.him.onResult = None d.errback(OptionRefused(option)) def wont_yes_false(self, state, option): # Peer is unilaterally demanding that an option be disabled. state.him.state = 'no' self.disableRemote(option) self._dont(option) def wont_yes_true(self, state, option): # Peer agreed to disable an option at our request. state.him.state = 'no' state.him.negotiating = False d = state.him.onResult state.him.onResult = None d.callback(True) self.disableRemote(option) wontMap = {('no', False): wont_no_false, ('no', True): wont_no_true, ('yes', False): wont_yes_false, ('yes', True): wont_yes_true} def telnet_DO(self, option): s = self.getOptionState(option) self.doMap[s.us.state, s.us.negotiating](self, s, option) def do_no_false(self, state, option): # Peer is unilaterally requesting that we enable an option. if self.enableLocal(option): state.us.state = 'yes' self._will(option) else: self._wont(option) def do_no_true(self, state, option): # Peer agreed to allow us to enable an option at our request. state.us.state = 'yes' state.us.negotiating = False d = state.us.onResult state.us.onResult = None d.callback(True) self.enableLocal(option) def do_yes_false(self, state, option): # Peer is unilaterally requesting us to enable an already-enabled option. # Ignore this. pass def do_yes_true(self, state, option): # This is a bogus state. It is here for completeness. It will never be # entered. assert False, "do_yes_true can never be entered, but was called with %r, %r" % (state, option) doMap = {('no', False): do_no_false, ('no', True): do_no_true, ('yes', False): do_yes_false, ('yes', True): do_yes_true} def telnet_DONT(self, option): s = self.getOptionState(option) self.dontMap[s.us.state, s.us.negotiating](self, s, option) def dont_no_false(self, state, option): # Peer is unilaterally demanding us to disable an already-disabled option. # Ignore this. pass def dont_no_true(self, state, option): # Offered option was refused. Fail the Deferred returned by the # previous will() call. state.us.negotiating = False d = state.us.onResult state.us.onResult = None d.errback(OptionRefused(option)) def dont_yes_false(self, state, option): # Peer is unilaterally demanding we disable an option. state.us.state = 'no' self.disableLocal(option) self._wont(option) def dont_yes_true(self, state, option): # Peer acknowledged our notice that we will disable an option. state.us.state = 'no' state.us.negotiating = False d = state.us.onResult state.us.onResult = None d.callback(True) self.disableLocal(option) dontMap = {('no', False): dont_no_false, ('no', True): dont_no_true, ('yes', False): dont_yes_false, ('yes', True): dont_yes_true} def enableLocal(self, option): """ Reject all attempts to enable options. """ return False def enableRemote(self, option): """ Reject all attempts to enable options. """ return False def disableLocal(self, option): """ Signal a programming error by raising an exception. L{enableLocal} must return true for the given value of C{option} in order for this method to be called. If a subclass of L{Telnet} overrides enableLocal to allow certain options to be enabled, it must also override disableLocal to disable those options. @raise NotImplementedError: Always raised. """ raise NotImplementedError( "Don't know how to disable local telnet option %r" % (option,)) def disableRemote(self, option): """ Signal a programming error by raising an exception. L{enableRemote} must return true for the given value of C{option} in order for this method to be called. If a subclass of L{Telnet} overrides enableRemote to allow certain options to be enabled, it must also override disableRemote tto disable those options. @raise NotImplementedError: Always raised. """ raise NotImplementedError( "Don't know how to disable remote telnet option %r" % (option,)) class ProtocolTransportMixin: def write(self, bytes): self.transport.write(bytes.replace(b'\n', b'\r\n')) def writeSequence(self, seq): self.transport.writeSequence(seq) def loseConnection(self): self.transport.loseConnection() def getHost(self): return self.transport.getHost() def getPeer(self): return self.transport.getPeer() class TelnetTransport(Telnet, ProtocolTransportMixin): """ @ivar protocol: An instance of the protocol to which this transport is connected, or None before the connection is established and after it is lost. @ivar protocolFactory: A callable which returns protocol instances which provide L{ITelnetProtocol}. This will be invoked when a connection is established. It is passed *protocolArgs and **protocolKwArgs. @ivar protocolArgs: A tuple of additional arguments to pass to protocolFactory. @ivar protocolKwArgs: A dictionary of additional arguments to pass to protocolFactory. """ disconnecting = False protocolFactory = None protocol = None def __init__(self, protocolFactory=None, *a, **kw): Telnet.__init__(self) if protocolFactory is not None: self.protocolFactory = protocolFactory self.protocolArgs = a self.protocolKwArgs = kw def connectionMade(self): if self.protocolFactory is not None: self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs) assert ITelnetProtocol.providedBy(self.protocol) try: factory = self.factory except AttributeError: pass else: self.protocol.factory = factory self.protocol.makeConnection(self) def connectionLost(self, reason): Telnet.connectionLost(self, reason) if self.protocol is not None: try: self.protocol.connectionLost(reason) finally: del self.protocol def enableLocal(self, option): return self.protocol.enableLocal(option) def enableRemote(self, option): return self.protocol.enableRemote(option) def disableLocal(self, option): return self.protocol.disableLocal(option) def disableRemote(self, option): return self.protocol.disableRemote(option) def unhandledSubnegotiation(self, command, bytes): self.protocol.unhandledSubnegotiation(command, bytes) def unhandledCommand(self, command, argument): self.protocol.unhandledCommand(command, argument) def applicationDataReceived(self, bytes): self.protocol.dataReceived(bytes) def write(self, data): ProtocolTransportMixin.write(self, data.replace(b'\xff', b'\xff\xff')) class TelnetBootstrapProtocol(TelnetProtocol, ProtocolTransportMixin): protocol = None def __init__(self, protocolFactory, *args, **kw): self.protocolFactory = protocolFactory self.protocolArgs = args self.protocolKwArgs = kw def connectionMade(self): self.transport.negotiationMap[NAWS] = self.telnet_NAWS self.transport.negotiationMap[LINEMODE] = self.telnet_LINEMODE for opt in (LINEMODE, NAWS, SGA): self.transport.do(opt).addErrback(log.err) for opt in (ECHO,): self.transport.will(opt).addErrback(log.err) self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs) try: factory = self.factory except AttributeError: pass else: self.protocol.factory = factory self.protocol.makeConnection(self) def connectionLost(self, reason): if self.protocol is not None: try: self.protocol.connectionLost(reason) finally: del self.protocol def dataReceived(self, data): self.protocol.dataReceived(data) def enableLocal(self, opt): if opt == ECHO: return True elif opt == SGA: return True else: return False def enableRemote(self, opt): if opt == LINEMODE: self.transport.requestNegotiation(LINEMODE, MODE + chr(TRAPSIG)) return True elif opt == NAWS: return True elif opt == SGA: return True else: return False def telnet_NAWS(self, bytes): # NAWS is client -> server *only*. self.protocol will # therefore be an ITerminalTransport, the `.protocol' # attribute of which will be an ITerminalProtocol. Maybe. # You know what, XXX TODO clean this up. if len(bytes) == 4: width, height = struct.unpack('!HH', b''.join(bytes)) self.protocol.terminalProtocol.terminalSize(width, height) else: log.msg("Wrong number of NAWS bytes") linemodeSubcommands = { LINEMODE_SLC: 'SLC'} def telnet_LINEMODE(self, bytes): linemodeSubcommand = bytes[0] if 0: # XXX TODO: This should be enabled to parse linemode subnegotiation. getattr(self, 'linemode_' + self.linemodeSubcommands[linemodeSubcommand])(bytes[1:]) def linemode_SLC(self, bytes): chunks = zip(*[iter(bytes)]*3) for slcFunction, slcValue, slcWhat in chunks: # Later, we should parse stuff. 'SLC', ord(slcFunction), ord(slcValue), ord(slcWhat) from twisted.protocols import basic class StatefulTelnetProtocol(basic.LineReceiver, TelnetProtocol): delimiter = b'\n' state = 'Discard' def connectionLost(self, reason): basic.LineReceiver.connectionLost(self, reason) TelnetProtocol.connectionLost(self, reason) def lineReceived(self, line): oldState = self.state newState = getattr(self, "telnet_" + oldState)(line) if newState is not None: if self.state == oldState: self.state = newState else: log.msg("Warning: state changed and new state returned") def telnet_Discard(self, line): pass from twisted.cred import credentials class AuthenticatingTelnetProtocol(StatefulTelnetProtocol): """A protocol which prompts for credentials and attempts to authenticate them. Username and password prompts are given (the password is obscured). When the information is collected, it is passed to a portal and an avatar implementing L{ITelnetProtocol} is requested. If an avatar is returned, it connected to this protocol's transport, and this protocol's transport is connected to it. Otherwise, the user is re-prompted for credentials. """ state = "User" protocol = None def __init__(self, portal): self.portal = portal def connectionMade(self): self.transport.write(b"Username: ") def connectionLost(self, reason): StatefulTelnetProtocol.connectionLost(self, reason) if self.protocol is not None: try: self.protocol.connectionLost(reason) self.logout() finally: del self.protocol, self.logout def telnet_User(self, line): self.username = line self.transport.will(ECHO) self.transport.write(b"Password: ") return 'Password' def telnet_Password(self, line): username, password = self.username, line del self.username def login(ignored): creds = credentials.UsernamePassword(username, password) d = self.portal.login(creds, None, ITelnetProtocol) d.addCallback(self._cbLogin) d.addErrback(self._ebLogin) self.transport.wont(ECHO).addCallback(login) return 'Discard' def _cbLogin(self, ial): interface, protocol, logout = ial assert interface is ITelnetProtocol self.protocol = protocol self.logout = logout self.state = 'Command' protocol.makeConnection(self.transport) self.transport.protocol = protocol def _ebLogin(self, failure): self.transport.write(b"\nAuthentication failed\n") self.transport.write(b"Username: ") self.state = "User" __all__ = [ # Exceptions 'TelnetError', 'NegotiationError', 'OptionRefused', 'AlreadyNegotiating', 'AlreadyEnabled', 'AlreadyDisabled', # Interfaces 'ITelnetProtocol', 'ITelnetTransport', # Other stuff, protocols, etc. 'Telnet', 'TelnetProtocol', 'TelnetTransport', 'TelnetBootstrapProtocol', ]
{ "content_hash": "f28a47092b9fa1e2f15893d72109ac50", "timestamp": "", "source": "github", "line_count": 1083, "max_line_length": 117, "avg_line_length": 35.256694367497694, "alnum_prop": 0.5971767540528508, "repo_name": "ArcherSys/ArcherSys", "id": "75a2a763f1dd7a4151f5bbbd031f4631cc3e9062", "size": "38313", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Lib/site-packages/twisted/conch/telnet.py", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
git://github.com/simplefocus/FlowType.JS.git
{ "content_hash": "eb317cf0dd561c5984f9c2e6dcb0b7b4", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 44, "avg_line_length": 45, "alnum_prop": 0.8, "repo_name": "silenceper/birdsnest", "id": "9bb06f8410b9e28434903829550469dea037168b", "size": "45", "binary": false, "copies": "3", "ref": "refs/heads/gh-pages", "path": "packages/Flowtype.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<readable><title>2855727603_e917ded363</title><content> a black dog splashes in the water . a brown dog walking in a river with trees in the background A large brown dog plays in the water . A large sleek brown dog is standing in the water . The large brown dog is walking into a shallow lake . </content></readable>
{ "content_hash": "edd5de024f578c488f4a51389e8ef420", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 59, "avg_line_length": 45.142857142857146, "alnum_prop": 0.7721518987341772, "repo_name": "kevint2u/audio-collector", "id": "114c71eaa1c8443953aa9fcfe16fe382098d95b2", "size": "316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "captions/xml/2855727603_e917ded363.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1015" }, { "name": "HTML", "bytes": "18349" }, { "name": "JavaScript", "bytes": "109819" }, { "name": "Python", "bytes": "3260" }, { "name": "Shell", "bytes": "4319" } ], "symlink_target": "" }
package com.magnet.mmx.server.plugin.mmxmgmt.context; import com.magnet.mmx.protocol.Constants; import org.junit.Before; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.TestCase.assertTrue; public class ContextDispatcherFactoryTest { @Before public void setUp() throws Exception { } @Test public void testGetInstance() throws Exception { assertTrue(ContextDispatcherFactory.getInstance() != null); } @Test public void testGetGeoDispatcher() throws Exception { Class.forName(GeoEventDispatcher.class.getName()); // load the class to initialize itself IContextDispatcher dispatcher = ContextDispatcherFactory.getInstance().getDispatcher((GeoEventDispatcher.class.getName())); assertNotNull(dispatcher); assertEquals(dispatcher.getSupportedTypeName(), Constants.MMX_MTYPE_GEOLOC); assertEquals(dispatcher.getSupportedProtocol(), GeoEventDispatcher.PROTOCOL_XMPP); } }
{ "content_hash": "a3d2404bfa4ce88c6bc18dfe4c34a414", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 127, "avg_line_length": 32, "alnum_prop": 0.787109375, "repo_name": "sanyaade-iot/message-server", "id": "849d6e8d4e373ee3bcbe1539e0ef46b490b6ae70", "size": "1639", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/plugins/mmxmgmt/src/test/java/com/magnet/mmx/server/plugin/mmxmgmt/context/ContextDispatcherFactoryTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15" }, { "name": "Java", "bytes": "2078934" }, { "name": "Shell", "bytes": "7282" } ], "symlink_target": "" }
package finder import ( "context" ) // MockFinder is used for testing purposes type MockFinder struct { result [][]byte // from new query string // logged from execute } // NewMockFinder returns new MockFinder object with given result func NewMockFinder(result [][]byte) *MockFinder { return &MockFinder{ result: result, } } // Execute assigns given query to the query field func (m *MockFinder) Execute(ctx context.Context, query string, from int64, until int64) error { m.query = query return nil } // List returns the result func (m *MockFinder) List() [][]byte { return m.result } // Series returns the result func (m *MockFinder) Series() [][]byte { return m.result } // Abs returns the same given v func (m *MockFinder) Abs(v []byte) []byte { return v } // Strings returns the result converted to []string func (m *MockFinder) Strings() (result []string) { result = make([]string, len(m.result)) for i := range m.result { result[i] = string(m.result[i]) } return }
{ "content_hash": "3562dac137dafd8621f78d099a30b4fa", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 96, "avg_line_length": 20.833333333333332, "alnum_prop": 0.693, "repo_name": "lomik/graphite-clickhouse", "id": "131c04503a45bfbd167a91ee87c2aa97f1bd73ed", "size": "1000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "finder/mock.go", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "408" }, { "name": "Go", "bytes": "192873" }, { "name": "Makefile", "bytes": "3035" }, { "name": "Shell", "bytes": "2916" } ], "symlink_target": "" }
require 'test_helper' class VeritransModuleTest < Test::Unit::TestCase include ActiveMerchant::Billing::Integrations def test_notification_method assert_instance_of Veritrans::Notification, Veritrans.notification('name=cody') end end
{ "content_hash": "ee4973cacf21d233b0560ec80f18c31a", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 83, "avg_line_length": 27.333333333333332, "alnum_prop": 0.7886178861788617, "repo_name": "barock19/active_merchant", "id": "ad4d06be497661484b43843ac837b1217d910917", "size": "246", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/integrations/veritrans_module_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3644733" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using JetBrains.Annotations; using Reusable.OmniLog.Abstractions; namespace Reusable.OmniLog { public delegate string MessageFunc(); [PublicAPI] public static class LoggerExtensions { #region LogLevels public static ILogger Trace(this ILogger logger, string message, Func<ILog, ILog> logAction = null) { return logger.Log(LogLevel.Trace, message, null, logAction); } public static ILogger Debug(this ILogger logger, string message, Func<ILog, ILog> logAction = null) { return logger.Log(LogLevel.Debug, message, null, logAction); } public static ILogger Warning(this ILogger logger, string message, Func<ILog, ILog> logAction = null) { return logger.Log(LogLevel.Warning, message, null, logAction); } public static ILogger Information(this ILogger logger, string message, Func<ILog, ILog> logAction = null) { return logger.Log(LogLevel.Information, message, null, logAction); } public static ILogger Error(this ILogger logger, string message, Exception exception = null, Func<ILog, ILog> logAction = null) { return logger.Log(LogLevel.Error, message, exception, logAction); } public static ILogger Fatal(this ILogger logger, string message, Exception exception = null, Func<ILog, ILog> logAction = null) { return logger.Log(LogLevel.Fatal, message, exception, logAction); } private static ILogger Log ( [NotNull] this ILogger logger, [NotNull] LogLevel logLevel, [CanBeNull] string message, [CanBeNull] Exception exception, [CanBeNull] Func<ILog, ILog> logAction ) { if (logger == null) throw new ArgumentNullException(nameof(logger)); if (logLevel == null) throw new ArgumentNullException(nameof(logLevel)); return logger.Log(logLevel, log => { log.Message(message); log.Exception(exception); }); } #endregion #region LogLevels lazy public static ILogger Trace(this ILogger logger, MessageFunc messageFunc, Func<ILog, ILog> logFunc = null) { return logger.Log(LogLevel.Trace, messageFunc, logFunc ?? (_ => _)); } public static ILogger Debug(this ILogger logger, MessageFunc messageFunc, Func<ILog, ILog> logFunc = null) { return logger.Log(LogLevel.Debug, messageFunc, logFunc ?? (_ => _)); } public static ILogger Information(this ILogger logger, MessageFunc messageFunc, Func<ILog, ILog> logFunc = null) { return logger.Log(LogLevel.Information, messageFunc, logFunc ?? (_ => _)); } public static ILogger Warning(this ILogger logger, MessageFunc messageFunc, Func<ILog, ILog> logFunc = null) { return logger.Log(LogLevel.Warning, messageFunc, logFunc ?? (_ => _)); } public static ILogger Error(this ILogger logger, MessageFunc messageFunc, Func<ILog, ILog> logFunc = null) { return logger.Log(LogLevel.Error, messageFunc, logFunc ?? (_ => _)); } public static ILogger Fatal(this ILogger logger, MessageFunc messageFunc, Func<ILog, ILog> logFunc = null) { return logger.Log(LogLevel.Fatal, messageFunc, logFunc ?? (_ => _)); } public static T TraceReturn<T>(this ILogger logger, T obj, Func<T, string> messageFunc, Func<ILog, ILog> logFunc = null) { logger.Log(LogLevel.Trace, () => messageFunc(obj), logFunc ?? (_ => _)); return obj; } public static T DebugReturn<T>(this ILogger logger, T obj, Func<T, string> messageFunc, Func<ILog, ILog> logFunc = null) { logger.Log(LogLevel.Debug, () => messageFunc(obj), logFunc ?? (_ => _)); return obj; } private static ILogger Log ( [NotNull] this ILogger logger, [NotNull] LogLevel logLevel, [NotNull] MessageFunc messageFunc, [NotNull] Func<ILog, ILog> logFunc ) { if (logger == null) throw new ArgumentNullException(nameof(logger)); if (logLevel == null) throw new ArgumentNullException(nameof(logLevel)); if (messageFunc == null) throw new ArgumentNullException(nameof(messageFunc)); if (logFunc == null) throw new ArgumentNullException(nameof(logFunc)); return logger.Log(logLevel, log => log.MessageFunc(messageFunc)); } #endregion #region Other public static T Return<T>(this ILogger logger, T obj) { return obj; } #endregion #region BeginScope public static ILogScope BeginScope(this ILogger logger, out object correlationId) { var scope = LogScope.Push(); scope.WithCorrelationId(out correlationId); return scope; } public static ILogScope BeginScope(this ILogger logger) { return logger.BeginScope(out _); } /// <summary> /// Gets log scopes ordered by depths ascending. /// </summary> [NotNull] [ItemNotNull] public static IEnumerable<ILogScope> Scopes(this ILogger logger) { return LogScope .Current .Flatten(); } #endregion } }
{ "content_hash": "41336686870298b03b52f3c87f91d454", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 135, "avg_line_length": 34.234939759036145, "alnum_prop": 0.5908850959000528, "repo_name": "he-dev/Reusable", "id": "88869c38bf13376828352f241b31254f70de13fa", "size": "5685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Reusable.OmniLog/src/_logger/LoggerExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1047239" }, { "name": "CSS", "bytes": "588" }, { "name": "HTML", "bytes": "1757" } ], "symlink_target": "" }
export class Category { _id: String diaries: Object[] name: String publish_time: Date }
{ "content_hash": "d88329d3912df5744cc792edb6004c17", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 23, "avg_line_length": 16, "alnum_prop": 0.6770833333333334, "repo_name": "ScenK/Dev_Blog3", "id": "de55370f514afd172d08f82bb0f67738bb81994c", "size": "96", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/app/models/category.ts", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "66466" }, { "name": "HTML", "bytes": "3545" }, { "name": "JavaScript", "bytes": "30523" }, { "name": "TypeScript", "bytes": "13544" } ], "symlink_target": "" }
<!doctype html> <!-- Our uiRouterSample module defined here --> <html lang="en" ng-app="uiRouterSample"> <head> <meta charset="utf-8"> <!-- using twitter bootstrap, but of course --> <link rel="stylesheet" type="text/css" href="vendor/bootstrap.min.css"> <!-- styles for ng-animate are located here --> <link rel="stylesheet" type="text/css" href="css/styles.css"> <!-- Include both angular.js and angular-ui-router.js--> <script src="../lib/angular-1.2.14/angular.js"></script> <script src="../lib/angular-1.2.14/angular-animate.js"></script> <script src="../build/angular-ui-router.js"></script> <!-- app.js declares the uiRouterSample module and adds items to $rootScope, and defines the "home" and "about" states --> <script src="app/app.js"></script> <!-- contacts.js declares the uiRouterSample.contacts module, and adds a number of contact related states --> <script src="app/contacts/contacts.js"></script> <!-- contacts-service.js, and utils-service.js define services for use by the contacts module. --> <script src="app/contacts/contacts-service.js"></script> <script src="common/utils/utils-service.js"></script> <!-- could easily use a custom property of the state here instead of 'name' --> <title ng-bind="$state.current.name + ' - ui-router'">ui-router</title> <script src="vendor/jquery-1.11.1.min.js"></script> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"><div class="container"> <!-- ui-sref is a great directive for linking a state location with an anchor link. You should almost always use ui-sref instead of href on your links when you want then to navigate to a state. When this link is clicked it will take the application to the 'home' state. Behind the scenes the directive also adds the correct href attr and url. --> <a class="brand" ui-sref="home">ui-router</a> <ul class="nav"> <!-- Here you can see ui-sref in action again. Also notice the use of $state.includes, which will set the links to 'active' if, for example on the first link, 'contacts' or any of its descendant states are activated. --> <li ng-class="{active: $state.includes('contacts')}"><a ui-sref="contacts.list">Contacts</a></li> <li ui-sref-active="active"><a ui-sref="about">About</a></li> <li ui-sref-active="active"><a ui-sref="block">Block</a></li> <li ui-sref-active="active"><a ui-sref="block2">Block2</a></li> </ul> <!-- Here is a named ui-view. ui-views don't have to be named, but we'll be populate this on from various different child states and we want a name to help us target. --> <p ui-view="hint" class="navbar-text pull-right"></p> </div></div> </div> <!-- Here is the main ui-view (unnamed) and will be populated by its immediate children's templates unless otherwise explicitly named views are targeted. It's also employing ng-animate. --> <div extra-ui-view class="container slide" style="padding-top: 80px;"></div> <hr> <pre> <!-- Here's some values to keep an eye on in the sample in order to understand $state and $stateParams --> $state = {{$state.current.name}} $stateParams = {{$stateParams}} $state full url = {{ $state.$current.url.source }} <!-- $state.$current is not a public api, we are using it to display the full url for learning purposes--> </pre> </body> </html>
{ "content_hash": "5a17cf54db35980e5a29bc7d219409a8", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 112, "avg_line_length": 45.575, "alnum_prop": 0.6291826659352715, "repo_name": "sskyy/ui-router", "id": "8a13e270497070655ad9a8dae3459df2024e451c", "size": "3646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sample/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "741" }, { "name": "JavaScript", "bytes": "297763" } ], "symlink_target": "" }
using boost::algorithm::join; using namespace llvm; using namespace strings; namespace impala { string NullIndicatorOffset::DebugString() const { stringstream out; out << "(offset=" << byte_offset << " mask=" << hex << static_cast<int>(bit_mask) << dec << ")"; return out.str(); } ostream& operator<<(ostream& os, const NullIndicatorOffset& null_indicator) { os << null_indicator.DebugString(); return os; } SlotDescriptor::SlotDescriptor( const TSlotDescriptor& tdesc, const TupleDescriptor* parent, const TupleDescriptor* collection_item_descriptor) : id_(tdesc.id), type_(ColumnType::FromThrift(tdesc.slotType)), parent_(parent), collection_item_descriptor_(collection_item_descriptor), col_path_(tdesc.columnPath), tuple_offset_(tdesc.byteOffset), null_indicator_offset_(tdesc.nullIndicatorByte, tdesc.nullIndicatorBit), slot_idx_(tdesc.slotIdx), slot_size_(type_.GetByteSize()), field_idx_(-1), is_materialized_(tdesc.isMaterialized), is_null_fn_(NULL), set_not_null_fn_(NULL), set_null_fn_(NULL) { DCHECK_NE(type_.type, TYPE_STRUCT); DCHECK(parent_ != NULL) << tdesc.parent; if (type_.IsCollectionType()) { DCHECK(tdesc.__isset.itemTupleId); DCHECK(collection_item_descriptor_ != NULL) << tdesc.itemTupleId; } else { DCHECK(!tdesc.__isset.itemTupleId); DCHECK(collection_item_descriptor == NULL); } } bool SlotDescriptor::ColPathLessThan(const SlotDescriptor* a, const SlotDescriptor* b) { int common_levels = min(a->col_path().size(), b->col_path().size()); for (int i = 0; i < common_levels; ++i) { if (a->col_path()[i] == b->col_path()[i]) continue; return a->col_path()[i] < b->col_path()[i]; } return a->col_path().size() < b->col_path().size(); } string SlotDescriptor::DebugString() const { stringstream out; out << "Slot(id=" << id_ << " type=" << type_.DebugString() << " col_path=["; if (col_path_.size() > 0) out << col_path_[0]; for (int i = 1; i < col_path_.size(); ++i) { out << ","; out << col_path_[i]; } out << "]"; if (collection_item_descriptor_ != NULL) { out << " collection_item_tuple_id=" << collection_item_descriptor_->id(); } out << " offset=" << tuple_offset_ << " null=" << null_indicator_offset_.DebugString() << " slot_idx=" << slot_idx_ << " field_idx=" << field_idx_ << ")"; return out.str(); } ColumnDescriptor::ColumnDescriptor(const TColumnDescriptor& tdesc) : name_(tdesc.name), type_(ColumnType::FromThrift(tdesc.type)) { } string ColumnDescriptor::DebugString() const { return Substitute("$0: $1", name_, type_.DebugString()); } TableDescriptor::TableDescriptor(const TTableDescriptor& tdesc) : name_(tdesc.tableName), database_(tdesc.dbName), id_(tdesc.id), num_clustering_cols_(tdesc.numClusteringCols) { for (int i = 0; i < tdesc.columnDescriptors.size(); ++i) { col_descs_.push_back(ColumnDescriptor(tdesc.columnDescriptors[i])); } } string TableDescriptor::DebugString() const { vector<string> cols; BOOST_FOREACH(const ColumnDescriptor& col_desc, col_descs_) { cols.push_back(col_desc.DebugString()); } stringstream out; out << "#cols=" << num_cols() << " #clustering_cols=" << num_clustering_cols_; out << " cols=["; out << join(cols, ", "); out << "]"; return out.str(); } HdfsPartitionDescriptor::HdfsPartitionDescriptor(const THdfsPartition& thrift_partition, ObjectPool* pool) : line_delim_(thrift_partition.lineDelim), field_delim_(thrift_partition.fieldDelim), collection_delim_(thrift_partition.collectionDelim), escape_char_(thrift_partition.escapeChar), block_size_(thrift_partition.blockSize), location_(thrift_partition.location), id_(thrift_partition.id), exprs_prepared_(false), exprs_opened_(false), exprs_closed_(false), file_format_(thrift_partition.fileFormat), object_pool_(pool) { for (int i = 0; i < thrift_partition.partitionKeyExprs.size(); ++i) { ExprContext* ctx; // TODO: Move to dedicated Init method and treat Status return correctly Status status = Expr::CreateExprTree(object_pool_, thrift_partition.partitionKeyExprs[i], &ctx); DCHECK(status.ok()); partition_key_value_ctxs_.push_back(ctx); } } Status HdfsPartitionDescriptor::PrepareExprs(RuntimeState* state) { if (!exprs_prepared_) { // TODO: RowDescriptor should arguably be optional in Prepare for known literals exprs_prepared_ = true; // Partition exprs are not used in the codegen case. Don't codegen them. RETURN_IF_ERROR(Expr::Prepare(partition_key_value_ctxs_, state, RowDescriptor(), state->instance_mem_tracker())); } return Status::OK(); } Status HdfsPartitionDescriptor::OpenExprs(RuntimeState* state) { if (exprs_opened_) return Status::OK(); exprs_opened_ = true; return Expr::Open(partition_key_value_ctxs_, state); } void HdfsPartitionDescriptor::CloseExprs(RuntimeState* state) { if (exprs_closed_ || !exprs_prepared_) return; exprs_closed_ = true; Expr::Close(partition_key_value_ctxs_, state); } string HdfsPartitionDescriptor::DebugString() const { stringstream out; out << " file_format=" << file_format_ << "'" << " line_delim='" << line_delim_ << "'" << " field_delim='" << field_delim_ << "'" << " coll_delim='" << collection_delim_ << "'" << " escape_char='" << escape_char_ << "')"; return out.str(); } string DataSourceTableDescriptor::DebugString() const { stringstream out; out << "DataSourceTable(" << TableDescriptor::DebugString() << ")"; return out.str(); } HdfsTableDescriptor::HdfsTableDescriptor(const TTableDescriptor& tdesc, ObjectPool* pool) : TableDescriptor(tdesc), hdfs_base_dir_(tdesc.hdfsTable.hdfsBaseDir), null_partition_key_value_(tdesc.hdfsTable.nullPartitionKeyValue), null_column_value_(tdesc.hdfsTable.nullColumnValue), object_pool_(pool) { map<int64_t, THdfsPartition>::const_iterator it; for (it = tdesc.hdfsTable.partitions.begin(); it != tdesc.hdfsTable.partitions.end(); ++it) { HdfsPartitionDescriptor* partition = new HdfsPartitionDescriptor(it->second, pool); object_pool_->Add(partition); partition_descriptors_[it->first] = partition; } avro_schema_ = tdesc.hdfsTable.__isset.avroSchema ? tdesc.hdfsTable.avroSchema : ""; } string HdfsTableDescriptor::DebugString() const { stringstream out; out << "HdfsTable(" << TableDescriptor::DebugString() << " hdfs_base_dir='" << hdfs_base_dir_ << "'"; out << " partitions=["; vector<string> partition_strings; map<int64_t, HdfsPartitionDescriptor*>::const_iterator it; for (it = partition_descriptors_.begin(); it != partition_descriptors_.end(); ++it) { stringstream s; s << " (id: " << it->first << ", partition: " << it->second->DebugString() << ")"; partition_strings.push_back(s.str()); } out << join(partition_strings, ",") << "]"; out << " null_partition_key_value='" << null_partition_key_value_ << "'"; out << " null_column_value='" << null_column_value_ << "'"; return out.str(); } HBaseTableDescriptor::HBaseTableDescriptor(const TTableDescriptor& tdesc) : TableDescriptor(tdesc), table_name_(tdesc.hbaseTable.tableName) { for (int i = 0; i < tdesc.hbaseTable.families.size(); ++i) { bool is_binary_encoded = tdesc.hbaseTable.__isset.binary_encoded && tdesc.hbaseTable.binary_encoded[i]; cols_.push_back(HBaseTableDescriptor::HBaseColumnDescriptor( tdesc.hbaseTable.families[i], tdesc.hbaseTable.qualifiers[i], is_binary_encoded)); } } string HBaseTableDescriptor::DebugString() const { stringstream out; out << "HBaseTable(" << TableDescriptor::DebugString() << " table=" << table_name_; out << " cols=["; for (int i = 0; i < cols_.size(); ++i) { out << (i > 0 ? " " : "") << cols_[i].family << ":" << cols_[i].qualifier << ":" << cols_[i].binary_encoded; } out << "])"; return out.str(); } TupleDescriptor::TupleDescriptor(const TTupleDescriptor& tdesc) : id_(tdesc.id), table_desc_(NULL), byte_size_(tdesc.byteSize), num_null_bytes_(tdesc.numNullBytes), num_materialized_slots_(0), slots_(), tuple_path_(tdesc.tuplePath), llvm_struct_(NULL) { } void TupleDescriptor::AddSlot(SlotDescriptor* slot) { slots_.push_back(slot); if (slot->is_materialized()) { ++num_materialized_slots_; if (slot->type().IsVarLenStringType()) string_slots_.push_back(slot); if (slot->type().IsCollectionType()) collection_slots_.push_back(slot); } } string TupleDescriptor::DebugString() const { stringstream out; out << "Tuple(id=" << id_ << " size=" << byte_size_; if (table_desc_ != NULL) { //out << " " << table_desc_->DebugString(); } out << " slots=["; for (size_t i = 0; i < slots_.size(); ++i) { if (i > 0) out << ", "; out << slots_[i]->DebugString(); } out << "]"; out << " tuple_path=["; for (size_t i = 0; i < tuple_path_.size(); ++i) { if (i > 0) out << ", "; out << tuple_path_[i]; } out << "]"; out << ")"; return out.str(); } RowDescriptor::RowDescriptor(const DescriptorTbl& desc_tbl, const vector<TTupleId>& row_tuples, const vector<bool>& nullable_tuples) : tuple_idx_nullable_map_(nullable_tuples) { DCHECK_EQ(nullable_tuples.size(), row_tuples.size()); for (int i = 0; i < row_tuples.size(); ++i) { tuple_desc_map_.push_back(desc_tbl.GetTupleDescriptor(row_tuples[i])); DCHECK(tuple_desc_map_.back() != NULL); } InitTupleIdxMap(); } RowDescriptor::RowDescriptor(const RowDescriptor& lhs_row_desc, const RowDescriptor& rhs_row_desc) { tuple_desc_map_.insert(tuple_desc_map_.end(), lhs_row_desc.tuple_desc_map_.begin(), lhs_row_desc.tuple_desc_map_.end()); tuple_desc_map_.insert(tuple_desc_map_.end(), rhs_row_desc.tuple_desc_map_.begin(), rhs_row_desc.tuple_desc_map_.end()); tuple_idx_nullable_map_.insert(tuple_idx_nullable_map_.end(), lhs_row_desc.tuple_idx_nullable_map_.begin(), lhs_row_desc.tuple_idx_nullable_map_.end()); tuple_idx_nullable_map_.insert(tuple_idx_nullable_map_.end(), rhs_row_desc.tuple_idx_nullable_map_.begin(), rhs_row_desc.tuple_idx_nullable_map_.end()); InitTupleIdxMap(); } RowDescriptor::RowDescriptor(const vector<TupleDescriptor*>& tuple_descs, const vector<bool>& nullable_tuples) : tuple_desc_map_(tuple_descs), tuple_idx_nullable_map_(nullable_tuples) { DCHECK_EQ(nullable_tuples.size(), tuple_descs.size()); InitTupleIdxMap(); } RowDescriptor::RowDescriptor(TupleDescriptor* tuple_desc, bool is_nullable) : tuple_desc_map_(1, tuple_desc), tuple_idx_nullable_map_(1, is_nullable) { InitTupleIdxMap(); } void RowDescriptor::InitTupleIdxMap() { // find max id TupleId max_id = 0; for (int i = 0; i < tuple_desc_map_.size(); ++i) { max_id = max(tuple_desc_map_[i]->id(), max_id); } tuple_idx_map_.resize(max_id + 1, INVALID_IDX); for (int i = 0; i < tuple_desc_map_.size(); ++i) { tuple_idx_map_[tuple_desc_map_[i]->id()] = i; } } int RowDescriptor::GetRowSize() const { int size = 0; for (int i = 0; i < tuple_desc_map_.size(); ++i) { size += tuple_desc_map_[i]->byte_size(); } return size; } int RowDescriptor::GetTupleIdx(TupleId id) const { DCHECK_LT(id, tuple_idx_map_.size()) << "RowDescriptor: " << DebugString(); return tuple_idx_map_[id]; } bool RowDescriptor::TupleIsNullable(int tuple_idx) const { DCHECK_LT(tuple_idx, tuple_idx_nullable_map_.size()); return tuple_idx_nullable_map_[tuple_idx]; } bool RowDescriptor::IsAnyTupleNullable() const { for (int i = 0; i < tuple_idx_nullable_map_.size(); ++i) { if (tuple_idx_nullable_map_[i]) return true; } return false; } void RowDescriptor::ToThrift(vector<TTupleId>* row_tuple_ids) { row_tuple_ids->clear(); for (int i = 0; i < tuple_desc_map_.size(); ++i) { row_tuple_ids->push_back(tuple_desc_map_[i]->id()); } } bool RowDescriptor::IsPrefixOf(const RowDescriptor& other_desc) const { if (tuple_desc_map_.size() > other_desc.tuple_desc_map_.size()) return false; for (int i = 0; i < tuple_desc_map_.size(); ++i) { // pointer comparison okay, descriptors are unique if (tuple_desc_map_[i] != other_desc.tuple_desc_map_[i]) return false; } return true; } bool RowDescriptor::Equals(const RowDescriptor& other_desc) const { if (tuple_desc_map_.size() != other_desc.tuple_desc_map_.size()) return false; for (int i = 0; i < tuple_desc_map_.size(); ++i) { // pointer comparison okay, descriptors are unique if (tuple_desc_map_[i] != other_desc.tuple_desc_map_[i]) return false; } return true; } string RowDescriptor::DebugString() const { stringstream ss; for (int i = 0; i < tuple_desc_map_.size(); ++i) { ss << tuple_desc_map_[i]->DebugString() << endl; } return ss.str(); } Status DescriptorTbl::Create(ObjectPool* pool, const TDescriptorTable& thrift_tbl, DescriptorTbl** tbl) { *tbl = pool->Add(new DescriptorTbl()); // deserialize table descriptors first, they are being referenced by tuple descriptors for (size_t i = 0; i < thrift_tbl.tableDescriptors.size(); ++i) { const TTableDescriptor& tdesc = thrift_tbl.tableDescriptors[i]; TableDescriptor* desc = NULL; switch (tdesc.tableType) { case TTableType::HDFS_TABLE: desc = pool->Add(new HdfsTableDescriptor(tdesc, pool)); break; case TTableType::HBASE_TABLE: desc = pool->Add(new HBaseTableDescriptor(tdesc)); break; case TTableType::DATA_SOURCE_TABLE: desc = pool->Add(new DataSourceTableDescriptor(tdesc)); break; default: DCHECK(false) << "invalid table type: " << tdesc.tableType; } (*tbl)->tbl_desc_map_[tdesc.id] = desc; } for (size_t i = 0; i < thrift_tbl.tupleDescriptors.size(); ++i) { const TTupleDescriptor& tdesc = thrift_tbl.tupleDescriptors[i]; TupleDescriptor* desc = pool->Add(new TupleDescriptor(tdesc)); // fix up table pointer if (tdesc.__isset.tableId) { desc->table_desc_ = (*tbl)->GetTableDescriptor(tdesc.tableId); DCHECK(desc->table_desc_ != NULL); } (*tbl)->tuple_desc_map_[tdesc.id] = desc; } for (size_t i = 0; i < thrift_tbl.slotDescriptors.size(); ++i) { const TSlotDescriptor& tdesc = thrift_tbl.slotDescriptors[i]; // Tuple descriptors are already populated in tbl TupleDescriptor* parent = (*tbl)->GetTupleDescriptor(tdesc.parent); TupleDescriptor* collection_item_descriptor = tdesc.__isset.itemTupleId ? (*tbl)->GetTupleDescriptor(tdesc.itemTupleId) : NULL; SlotDescriptor* slot_d = pool->Add( new SlotDescriptor(tdesc, parent, collection_item_descriptor)); (*tbl)->slot_desc_map_[tdesc.id] = slot_d; // link to parent TupleDescriptorMap::iterator entry = (*tbl)->tuple_desc_map_.find(tdesc.parent); if (entry == (*tbl)->tuple_desc_map_.end()) { return Status("unknown tid in slot descriptor msg"); } entry->second->AddSlot(slot_d); } return Status::OK(); } TableDescriptor* DescriptorTbl::GetTableDescriptor(TableId id) const { // TODO: is there some boost function to do exactly this? TableDescriptorMap::const_iterator i = tbl_desc_map_.find(id); if (i == tbl_desc_map_.end()) { return NULL; } else { return i->second; } } TupleDescriptor* DescriptorTbl::GetTupleDescriptor(TupleId id) const { // TODO: is there some boost function to do exactly this? TupleDescriptorMap::const_iterator i = tuple_desc_map_.find(id); if (i == tuple_desc_map_.end()) { return NULL; } else { return i->second; } } SlotDescriptor* DescriptorTbl::GetSlotDescriptor(SlotId id) const { // TODO: is there some boost function to do exactly this? SlotDescriptorMap::const_iterator i = slot_desc_map_.find(id); if (i == slot_desc_map_.end()) { return NULL; } else { return i->second; } } // return all registered tuple descriptors void DescriptorTbl::GetTupleDescs(vector<TupleDescriptor*>* descs) const { descs->clear(); for (TupleDescriptorMap::const_iterator i = tuple_desc_map_.begin(); i != tuple_desc_map_.end(); ++i) { descs->push_back(i->second); } } // Generate function to check if a slot is null. The resulting IR looks like: // (in this case the tuple contains only a nullable double) // define i1 @IsNull({ i8, double }* %tuple) { // entry: // %null_byte_ptr = getelementptr inbounds { i8, double }* %tuple, i32 0, i32 0 // %null_byte = load i8* %null_byte_ptr // %null_mask = and i8 %null_byte, 1 // %is_null = icmp ne i8 %null_mask, 0 // ret i1 %is_null // } Function* SlotDescriptor::CodegenIsNull(LlvmCodeGen* codegen, StructType* tuple) { if (is_null_fn_ != NULL) return is_null_fn_; PointerType* tuple_ptr_type = PointerType::get(tuple, 0); LlvmCodeGen::FnPrototype prototype(codegen, "IsNull", codegen->GetType(TYPE_BOOLEAN)); prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple", tuple_ptr_type)); Value* mask = codegen->GetIntConstant(TYPE_TINYINT, null_indicator_offset_.bit_mask); Value* zero = codegen->GetIntConstant(TYPE_TINYINT, 0); int byte_offset = null_indicator_offset_.byte_offset; LlvmCodeGen::LlvmBuilder builder(codegen->context()); Value* tuple_ptr; Function* fn = prototype.GeneratePrototype(&builder, &tuple_ptr); Value* null_byte_ptr = builder.CreateStructGEP(tuple_ptr, byte_offset, "null_byte_ptr"); Value* null_byte = builder.CreateLoad(null_byte_ptr, "null_byte"); Value* null_mask = builder.CreateAnd(null_byte, mask, "null_mask"); Value* is_null = builder.CreateICmpNE(null_mask, zero, "is_null"); builder.CreateRet(is_null); return is_null_fn_ = codegen->FinalizeFunction(fn); } // Generate function to set a slot to be null or not-null. The resulting IR // for SetNotNull looks like: // (in this case the tuple contains only a nullable double) // define void @SetNotNull({ i8, double }* %tuple) { // entry: // %null_byte_ptr = getelementptr inbounds { i8, double }* %tuple, i32 0, i32 0 // %null_byte = load i8* %null_byte_ptr // %0 = and i8 %null_byte, -2 // store i8 %0, i8* %null_byte_ptr // ret void // } Function* SlotDescriptor::CodegenUpdateNull(LlvmCodeGen* codegen, StructType* tuple, bool set_null) { if (set_null && set_null_fn_ != NULL) return set_null_fn_; if (!set_null && set_not_null_fn_ != NULL) return set_not_null_fn_; PointerType* tuple_ptr_type = PointerType::get(tuple, 0); LlvmCodeGen::FnPrototype prototype(codegen, (set_null) ? "SetNull" :"SetNotNull", codegen->void_type()); prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple", tuple_ptr_type)); LlvmCodeGen::LlvmBuilder builder(codegen->context()); Value* tuple_ptr; Function* fn = prototype.GeneratePrototype(&builder, &tuple_ptr); Value* null_byte_ptr = builder.CreateStructGEP( tuple_ptr, null_indicator_offset_.byte_offset, "null_byte_ptr"); Value* null_byte = builder.CreateLoad(null_byte_ptr, "null_byte"); Value* result = NULL; if (set_null) { Value* null_set = codegen->GetIntConstant( TYPE_TINYINT, null_indicator_offset_.bit_mask); result = builder.CreateOr(null_byte, null_set); } else { Value* null_clear_val = codegen->GetIntConstant(TYPE_TINYINT, ~null_indicator_offset_.bit_mask); result = builder.CreateAnd(null_byte, null_clear_val); } builder.CreateStore(result, null_byte_ptr); builder.CreateRetVoid(); fn = codegen->FinalizeFunction(fn); if (set_null) { set_null_fn_ = fn; } else { set_not_null_fn_ = fn; } return fn; } // The default llvm packing is identical to what we do in the FE. Each field is aligned // to begin on the size for that type. // TODO: Understand llvm::SetTargetData which allows you to explicitly define the packing // rules. StructType* TupleDescriptor::GenerateLlvmStruct(LlvmCodeGen* codegen) { // If we already generated the llvm type, just return it. if (llvm_struct_ != NULL) return llvm_struct_; // For each null byte, add a byte to the struct vector<Type*> struct_fields; struct_fields.resize(num_null_bytes_ + num_materialized_slots_); for (int i = 0; i < num_null_bytes_; ++i) { struct_fields[i] = codegen->GetType(TYPE_TINYINT); } // Add the slot types to the struct description. for (int i = 0; i < slots().size(); ++i) { SlotDescriptor* slot_desc = slots()[i]; if (slot_desc->type().type == TYPE_CHAR) return NULL; if (slot_desc->is_materialized()) { slot_desc->field_idx_ = slot_desc->slot_idx_ + num_null_bytes_; DCHECK_LT(slot_desc->field_idx(), struct_fields.size()); struct_fields[slot_desc->field_idx()] = codegen->GetType(slot_desc->type()); } } // Construct the struct type. StructType* tuple_struct = StructType::get(codegen->context(), ArrayRef<Type*>(struct_fields)); // Verify the alignment is correct. It is essential that the layout matches // identically. If the layout does not match, return NULL indicating the // struct could not be codegen'd. This will trigger codegen for anything using // the tuple to be disabled. const DataLayout* data_layout = codegen->execution_engine()->getDataLayout(); const StructLayout* layout = data_layout->getStructLayout(tuple_struct); if (layout->getSizeInBytes() != byte_size()) { DCHECK_EQ(layout->getSizeInBytes(), byte_size()); return NULL; } for (int i = 0; i < slots().size(); ++i) { SlotDescriptor* slot_desc = slots()[i]; if (slot_desc->is_materialized()) { int field_idx = slot_desc->field_idx(); // Verify that the byte offset in the llvm struct matches the tuple offset // computed in the FE if (layout->getElementOffset(field_idx) != slot_desc->tuple_offset()) { DCHECK_EQ(layout->getElementOffset(field_idx), slot_desc->tuple_offset()); return NULL; } } } llvm_struct_ = tuple_struct; return tuple_struct; } string DescriptorTbl::DebugString() const { stringstream out; out << "tuples:\n"; for (TupleDescriptorMap::const_iterator i = tuple_desc_map_.begin(); i != tuple_desc_map_.end(); ++i) { out << i->second->DebugString() << '\n'; } return out.str(); } }
{ "content_hash": "852605f69d8b4cd81928c6dc0b88175b", "timestamp": "", "source": "github", "line_count": 629, "max_line_length": 90, "avg_line_length": 35.58346581875993, "alnum_prop": 0.6540970422661067, "repo_name": "cgvarela/Impala", "id": "21bb82356cf318d8112fa3edc8088b6b72764141", "size": "23431", "binary": false, "copies": "1", "ref": "refs/heads/cdh5-trunk", "path": "be/src/runtime/descriptors.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "203216" }, { "name": "C++", "bytes": "7379006" }, { "name": "CMake", "bytes": "102042" }, { "name": "CSS", "bytes": "89516" }, { "name": "Groff", "bytes": "1633" }, { "name": "HTML", "bytes": "56" }, { "name": "Java", "bytes": "3470785" }, { "name": "JavaScript", "bytes": "484" }, { "name": "Lex", "bytes": "21664" }, { "name": "PLpgSQL", "bytes": "393" }, { "name": "Protocol Buffer", "bytes": "630" }, { "name": "Python", "bytes": "1711422" }, { "name": "SQLPL", "bytes": "3253" }, { "name": "Shell", "bytes": "161203" }, { "name": "Thrift", "bytes": "242308" }, { "name": "Yacc", "bytes": "79535" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>htt: 3 m 20 s 🏆</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.15.0 / htt - 1.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> htt <small> 1.1.0 <span class="label label-success">3 m 20 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-01 08:46:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-01 08:46:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.15.0 Formal proof management system dune 3.4.1 Fast, portable, and opinionated build system ocaml 4.06.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.06.1 Official 4.06.1 release ocaml-config 1 OCaml Switch Configuration ocaml-secondary-compiler 4.08.1-1 OCaml 4.08.1 Secondary Switch Compiler ocamlfind 1.9.1 A library manager for OCaml ocamlfind-secondary 1.9.1 Adds support for ocaml-secondary-compiler to ocamlfind zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;fcsl@software.imdea.org&quot; homepage: &quot;https://github.com/imdea-software/htt&quot; dev-repo: &quot;git+https://github.com/imdea-software/htt.git&quot; bug-reports: &quot;https://github.com/imdea-software/htt/issues&quot; license: &quot;Apache-2.0&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; { (&gt;= &quot;8.14&quot; &amp; &lt; &quot;8.17~&quot;) | (= &quot;dev&quot;) } &quot;coq-mathcomp-ssreflect&quot; { (&gt;= &quot;1.13.0&quot; &amp; &lt; &quot;1.16~&quot;) | (= &quot;dev&quot;) } &quot;coq-fcsl-pcm&quot; { (&gt;= &quot;1.6.0&quot; &amp; &lt; &quot;1.7~&quot;) | (= &quot;dev&quot;) } ] tags: [ &quot;category:Computer Science/Data Types and Data Structures&quot; &quot;keyword:partial commutative monoids&quot; &quot;keyword:separation logic&quot; &quot;logpath:HTT&quot; ] authors: [ &quot;Aleksandar Nanevski&quot; &quot;Germán Andrés Delbianco&quot; &quot;Alexander Gryzlov&quot; ] synopsis: &quot;Hoare Type Theory&quot; description: &quot;&quot;&quot; Hoare Type Theory (HTT) is a verification system for reasoning about sequential heap-manipulating programs based on Separation logic. HTT incorporates Hoare-style specifications via preconditions and postconditions into types. A Hoare type `ST P (fun x : A =&gt; Q)` denotes computations with a precondition `P` and postcondition `Q`, returning a value `x` of type `A`. Hoare types are a dependently typed version of monads, as used in the programming language Haskell. Monads hygienically combine the language features for pure functional programming, with those for imperative programming, such as state or exceptions. In this sense, HTT establishes a formal connection in the style of Curry-Howard isomorphism between monads and (functional programming variant of) Separation logic. Every effectful command in HTT has a type that corresponds to the appropriate non-structural inference rule in Separation logic, and vice versa, every non-structural inference rule corresponds to a command in HTT that has that rule as the type. The type for monadic bind is the Hoare rule for sequential composition, and the type for monadic unit combines the Hoare rules for the idle program (in a small-footprint variant) and for variable assignment (adapted for functional variables). The connection reconciles dependent types with effects of state and exceptions and establishes Separation logic as a type theory for such effects. In implementation terms, it means that HTT implements Separation logic as a shallow embedding in Coq.&quot;&quot;&quot; url { src: &quot;https://github.com/imdea-software/htt/archive/v1.1.0.tar.gz&quot; checksum: &quot;sha256=3d0d29fc04368aadfc96be0246b26619c093aa81d77bf1fcb05465aff4c10396&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-htt.1.1.0 coq.8.15.0</code></dd> <dt>Return code</dt> <dd>0</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>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-htt.1.1.0 coq.8.15.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>4 m 52 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-htt.1.1.0 coq.8.15.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>3 m 20 s</dd> </dl> <h2>Installation size</h2> <p>Total: 5 M</p> <ul> <li>1 M <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/congmath.vo</code></li> <li>454 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/congmath.glob</code></li> <li>300 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/model.vo</code></li> <li>257 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/kvmaps.vo</code></li> <li>219 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/domain.vo</code></li> <li>190 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/llist.vo</code></li> <li>177 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/bintree.vo</code></li> <li>167 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/cyclic.vo</code></li> <li>165 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/domain.glob</code></li> <li>165 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/model.glob</code></li> <li>161 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/hashtab.vo</code></li> <li>151 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/dlist.vo</code></li> <li>121 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/bst.vo</code></li> <li>117 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/queue.vo</code></li> <li>112 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/heapauto.vo</code></li> <li>106 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/kvmaps.glob</code></li> <li>100 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/array.vo</code></li> <li>93 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/heapauto.glob</code></li> <li>69 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/congmath.v</code></li> <li>63 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/llist.glob</code></li> <li>60 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/cyclic.glob</code></li> <li>56 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/stack.vo</code></li> <li>54 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/dlist.glob</code></li> <li>51 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/array.glob</code></li> <li>51 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/hashtab.glob</code></li> <li>44 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/bintree.glob</code></li> <li>44 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/bst.glob</code></li> <li>39 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/gcd.vo</code></li> <li>37 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/domain.v</code></li> <li>37 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/interlude.vo</code></li> <li>36 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/model.v</code></li> <li>33 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/queue.glob</code></li> <li>25 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/heapauto.v</code></li> <li>23 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/kvmaps.v</code></li> <li>19 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/interlude.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/cyclic.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/llist.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/stack.glob</code></li> <li>11 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/gcd.glob</code></li> <li>11 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/hashtab.v</code></li> <li>10 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/bst.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/array.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/dlist.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/bintree.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/queue.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/exploit.vo</code></li> <li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/stack.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/gcd.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/core/interlude.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/exploit.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.06.1/lib/coq/user-contrib/HTT/examples/exploit.v</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-htt.1.1.0</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>
{ "content_hash": "20a0246c6ecd5a78342275943fb7c4c1", "timestamp": "", "source": "github", "line_count": 235, "max_line_length": 159, "avg_line_length": 61.22127659574468, "alnum_prop": 0.5993605338152499, "repo_name": "coq-bench/coq-bench.github.io", "id": "6379b8466f8159d438478d69de71ad4910e9ab68", "size": "14414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.15.0/htt/1.1.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>lin-alg: 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.11.1 / lin-alg - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> lin-alg <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-07 08:18:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-07 08:18:39 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 conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/lin-alg&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/LinAlg&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} &quot;coq-algebra&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: linear algebra&quot; &quot;category: Mathematics/Algebra&quot; &quot;date: 19 spetember 2003&quot; ] authors: [ &quot;Jasper Stein &lt;jasper@cs.kun.nl&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/lin-alg/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/lin-alg.git&quot; synopsis: &quot;Linear Algebra&quot; description: &quot;&quot;&quot; A development of some preliminary linear algebra based on Chapter 1 of &quot;Linear Algebra&quot; by Friedberg, Insel and Spence&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/lin-alg/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=91ad67b59d2e256a95f4a9426a353e32&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-lin-alg.8.9.0 coq.8.11.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.11.1). The following dependencies couldn&#39;t be met: - coq-lin-alg -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints 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-lin-alg.8.9.0</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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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>
{ "content_hash": "d87ef80d47b2ef2eff1c4f2584649f87", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 157, "avg_line_length": 40.41618497109827, "alnum_prop": 0.539616704805492, "repo_name": "coq-bench/coq-bench.github.io", "id": "25fe34474deb051be6697d2ae1851da16de78059", "size": "6994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.6/released/8.11.1/lin-alg/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!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.19: https://docutils.sourceforge.io/" /> <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.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional &#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/_sphinx_javascript_frameworks_compat.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sphinx_highlight.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.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method.html" /> <link rel="prev" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical.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.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional" 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 0.13.3</span> <span class="md-header-nav__topic"> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional </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="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother</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 0.13.3</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> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </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> </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"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional--page-root" class="md-nav__link">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">KalmanSmoother.smooth_conventional</span></code></a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional.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-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional"> <h1 id="generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional--page-root">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional<a class="headerlink" href="#generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-conventional--page-root" title="Permalink to this heading">¶</a></h1> <dl class="py attribute"> <dt class="sig sig-object py" id="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional"> <span class="sig-prename descclassname"><span class="pre">KalmanSmoother.</span></span><span class="sig-name descname"><span class="pre">smooth_conventional</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">False</span></em><a class="headerlink" href="#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional" title="Permalink to this definition">¶</a></dt> <dd><p>(bool) Flag for conventional (Durbin and Koopman, 2012) Kalman smoothing.</p> </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.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical.html" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical" 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.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_classical </span> </div> </a> <a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method.html" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method" 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.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method </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 Nov 01, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.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>
{ "content_hash": "289f5c8f1323c7daad87b89bd1e89366", "timestamp": "", "source": "github", "line_count": 457, "max_line_length": 999, "avg_line_length": 41.90809628008753, "alnum_prop": 0.6147660818713451, "repo_name": "statsmodels/statsmodels.github.io", "id": "d7c3b571f0570f68dcc6f415a726a1e09ce00d5c", "size": "19156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.13.3/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_conventional.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/dark_grey" android:state_pressed="true" /> <item android:color="@color/colorAccent" /> </selector>
{ "content_hash": "d666601bd122b9874804b7501f7bcd21", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 74, "avg_line_length": 48.6, "alnum_prop": 0.6995884773662552, "repo_name": "Yuanhongliang/HLOLI", "id": "fdff96e49ff074916255cddaf6380381145f917a", "size": "243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/drawable/text_color.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "230846" } ], "symlink_target": "" }
package org.tools.hqlbuilder.service; import org.hibernate.Session; import org.hibernate.SessionFactory; public class HibernateUtils { public static Session newSession(SessionFactory sessionFactory) { return sessionFactory.openSession(); } }
{ "content_hash": "d520a3ddeb4f93e1f98f99e91a5cc21a", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 69, "avg_line_length": 26, "alnum_prop": 0.7769230769230769, "repo_name": "jurgendl/hql-builder", "id": "bde06da13bc73f2af8ef8832d8c1fc4bdfe96fe1", "size": "260", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hql-builder/hibernate/hibernate-5.4/src/main/java/org/tools/hqlbuilder/service/HibernateUtils.java", "mode": "33188", "license": "mit", "language": [ { "name": "AspectJ", "bytes": "3016" }, { "name": "Batchfile", "bytes": "8678" }, { "name": "HTML", "bytes": "57926" }, { "name": "Java", "bytes": "696389" }, { "name": "Shell", "bytes": "1179" } ], "symlink_target": "" }