text
stringlengths
2
1.04M
meta
dict
/** * Package housing classes relevant to anything involving * the Lua integration of Undertailor. */ package me.scarlet.undertailor.lua;
{ "content_hash": "088c42758ee51d67b42831ee8ff3d092", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 57, "avg_line_length": 28, "alnum_prop": 0.7714285714285715, "repo_name": "Xemiru/Undertailor", "id": "586a7c6b28f8bdf5a61cf41a860a16779999247b", "size": "140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/me/scarlet/undertailor/lua/package-info.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "810336" } ], "symlink_target": "" }
using System; using System.Runtime.Serialization; namespace Dnn.PersonaBar.Pages.Services.Dto { [DataContract] public class BulkPage { [DataMember(Name = "bulkPages")] public string BulkPages { get; set; } [DataMember(Name = "parentId")] public int ParentId { get; set; } [DataMember(Name = "keywords")] public string Keywords { get; set; } [DataMember(Name = "tags")] public string Tags { get; set; } [DataMember(Name = "includeInMenu")] public bool IncludeInMenu { get; set; } [DataMember(Name = "startDate")] public DateTime? StartDate { get; set; } [DataMember(Name = "endDate")] public DateTime? EndDate { get; set; } } }
{ "content_hash": "a4b31fe0d92a6651d30b0268d1de94a9", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 48, "avg_line_length": 24.612903225806452, "alnum_prop": 0.5897771952817824, "repo_name": "dnnsoftware/Dnn.AdminExperience.Extensions", "id": "a3ddfcc577af4ec9f1d0a90d5903cd2f19b81c79", "size": "765", "binary": false, "copies": "3", "ref": "refs/heads/development", "path": "src/Modules/Content/Dnn.PersonaBar.Pages/Services/Dto/BulkPage.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "362" }, { "name": "C#", "bytes": "1752728" }, { "name": "CSS", "bytes": "495897" }, { "name": "HTML", "bytes": "38779" }, { "name": "JavaScript", "bytes": "3436901" } ], "symlink_target": "" }
/* custom styles can go here */
{ "content_hash": "209a31d81fbed66729e987f35f4efbd0", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 31, "avg_line_length": 32, "alnum_prop": 0.65625, "repo_name": "egoughnour/calamari-tamashii", "id": "b276b3221cacc4e6d5f21b850c7439ac84ed78a6", "size": "32", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "css/custom.css", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4496" }, { "name": "CSS", "bytes": "281498" }, { "name": "HTML", "bytes": "26424" }, { "name": "JavaScript", "bytes": "159455" } ], "symlink_target": "" }
import Notification = require('./Notification') import { NotificationProps } from './Notification' import NotificationActionButton = require('./NotificationActionButton') import { NotificationActionButtonProps } from './NotificationActionButton' import NotificationButton = require('./NotificationButton') import { NotificationButtonProps } from './NotificationButton' import NotificationTextDetails = require('./NotificationTextDetails') import { NotificationTextDetailsProps } from './NotificationTextDetails' import NotificationIcon = require('./NotificationIcon') import { NotificationIconProps } from './NotificationIcon' import ToastNotification = require('./ToastNotification') import { ToastNotificationProps } from './ToastNotification' import InlineNotification = require('./InlineNotification') import { InlineNotificationProps } from './InlineNotification' export { NotificationActionButton, NotificationActionButtonProps, Notification, NotificationProps, NotificationButton, NotificationButtonProps, NotificationTextDetails, NotificationTextDetailsProps, NotificationIcon, NotificationIconProps, ToastNotification, ToastNotificationProps, InlineNotification, InlineNotificationProps }
{ "content_hash": "327883c7ddb536e969fe558a5cfcc7b5", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 74, "avg_line_length": 39.58064516129032, "alnum_prop": 0.8190709046454768, "repo_name": "wfp/ui", "id": "cb150e44e0dfea2d66a9a99fb2a60d81f605a223", "size": "1227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/types/Notification/index.d.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "272839" }, { "name": "HTML", "bytes": "80373" }, { "name": "JavaScript", "bytes": "2864371" }, { "name": "Shell", "bytes": "284" } ], "symlink_target": "" }
angular.module('studentInfoApp').directive('studentsList', function() { return { templateUrl: '/studentDetails.html', replace : true, scope: { students: '=', tableHeading: '@' }, link: function(){ }, controller: 'studentsDetailsController' }; }).controller('studentsDetailsController', ['$scope', function($scope) { $scope.removeSt = function(roll) { $scope.removeStudent(roll); } }]);
{ "content_hash": "c9810d55d41fd220bed4b5480daddbc6", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 72, "avg_line_length": 26.88888888888889, "alnum_prop": 0.5661157024793388, "repo_name": "ranadeepak/angularjsStepbyStep", "id": "31e35cf0d117f8716aa1740e0fc068cf8cbea1e8", "size": "484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "StudentInfoApp/studentDetails.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "183" }, { "name": "HTML", "bytes": "10894" }, { "name": "JavaScript", "bytes": "8690" } ], "symlink_target": "" }
============================= Rule ``no_unset_on_property`` ============================= Properties should be set to ``null`` instead of using ``unset``. Warning ------- Using this rule is risky ~~~~~~~~~~~~~~~~~~~~~~~~ Risky when relying on attributes to be removed using ``unset`` rather than be set to ``null``. Changing variables to ``null`` instead of unsetting means these still show up when looping over class variables and reference properties remain unbroken. With PHP 7.4, this rule might introduce ``null`` assignments to properties whose type declaration does not allow it. Examples -------- Example #1 ~~~~~~~~~~ .. code-block:: diff --- Original +++ New <?php -unset($this->a); +$this->a = null; Rule sets --------- The rule is part of the following rule set: @PhpCsFixer:risky Using the `@PhpCsFixer:risky <./../../ruleSets/PhpCsFixerRisky.rst>`_ rule set will enable the ``no_unset_on_property`` rule.
{ "content_hash": "16f7619dca6befeaa459ea61dda6d20a", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 127, "avg_line_length": 24.307692307692307, "alnum_prop": 0.6244725738396625, "repo_name": "FriendsOfPHP/PHP-CS-Fixer", "id": "8d1ebb6f602c7823f0af04f170688e98cbdbfa6a", "size": "948", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "doc/rules/language_construct/no_unset_on_property.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "3369" }, { "name": "PHP", "bytes": "9499804" }, { "name": "Shell", "bytes": "5393" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2) on Fri Jul 22 13:27:52 PDT 2005 --> <TITLE> ScriptgenTask (Java Card Tools for Ant - API) </TITLE> <META NAME="keywords" CONTENT="com.sun.javacard.ant.tasks.ScriptgenTask class"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="ScriptgenTask (Java Card Tools for Ant - API)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../com/sun/javacard/ant/tasks/MaskgenTask.html" title="class in com.sun.javacard.ant.tasks"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/sun/javacard/ant/tasks/VerifierTask.html" title="class in com.sun.javacard.ant.tasks"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ScriptgenTask.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> com.sun.javacard.ant.tasks</FONT> <BR> Class ScriptgenTask</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by">org.apache.tools.ant.ProjectComponent <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by">org.apache.tools.ant.Task <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by">org.apache.tools.ant.taskdefs.Java <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by"><A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html" title="class in com.sun.javacard.ant.tasks">com.sun.javacard.ant.tasks.JavacardTaskBase</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by"><B>com.sun.javacard.ant.tasks.ScriptgenTask</B> </PRE> <HR> <DL> <DT>public class <B>ScriptgenTask</B><DT>extends <A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html" title="class in com.sun.javacard.ant.tasks">JavacardTaskBase</A></DL> <P> This class is responsible for invoking Scriptgen to generate APDU script files from CAP files. <P> <P> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Field Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#capName">capName</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name of CAP file</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#noBeginEnd">noBeginEnd</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;If this paramter is true, CAP Begin and CAP end are not included in the script file</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#outFileName">outFileName</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;output file name</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#pkgName">pkgName</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name of the package</TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_com.sun.javacard.ant.tasks.JavacardTaskBase"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Fields inherited from class com.sun.javacard.ant.tasks.<A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html" title="class in com.sun.javacard.ant.tasks">JavacardTaskBase</A></B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#bundleName">bundleName</A>, <A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#messages">messages</A>, <A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#noBanner">noBanner</A>, <A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#version">version</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.tools.ant.taskdefs.Java"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Fields inherited from class org.apache.tools.ant.taskdefs.Java</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>redirector, redirectorElement</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.tools.ant.Task"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Fields inherited from class org.apache.tools.ant.Task</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>description, location, target, taskName, taskType, wrapper</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="fields_inherited_from_class_org.apache.tools.ant.ProjectComponent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Fields inherited from class org.apache.tools.ant.ProjectComponent</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>project</CODE></TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#ScriptgenTask()">ScriptgenTask</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Method Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#execute()">execute</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Executes the task</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#setCapFile(java.lang.String)">setCapFile</A></B>(java.lang.String&nbsp;capName)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets cap file name</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#setNoBeginEnd(boolean)">setNoBeginEnd</A></B>(boolean&nbsp;on)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets noBeginEnd value to the requested value</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#setOutFile(java.lang.String)">setOutFile</A></B>(java.lang.String&nbsp;outFileName)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets output file name</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../com/sun/javacard/ant/tasks/ScriptgenTask.html#setPkgName(java.lang.String)">setPkgName</A></B>(java.lang.String&nbsp;pkgName)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the package name for verifier</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_com.sun.javacard.ant.tasks.JavacardTaskBase"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class com.sun.javacard.ant.tasks.<A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html" title="class in com.sun.javacard.ant.tasks">JavacardTaskBase</A></B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#setNoBanner(boolean)">setNoBanner</A>, <A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#setupCommonOptions()">setupCommonOptions</A>, <A HREF="../../../../../com/sun/javacard/ant/tasks/JavacardTaskBase.html#setVersion(boolean)">setVersion</A></CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.tools.ant.taskdefs.Java"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class org.apache.tools.ant.taskdefs.Java</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>addAssertions, addConfiguredRedirector, addEnv, addSysproperty, addSyspropertyset, clearArgs, createArg, createBootclasspath, createClasspath, createJvmarg, createPermissions, createWatchdog, executeJava, handleErrorFlush, handleErrorOutput, handleFlush, handleInput, handleOutput, maybeSetResultPropertyValue, run, setAppend, setArgs, setClassname, setClasspath, setClasspathRef, setDir, setError, setErrorProperty, setFailonerror, setFork, setInput, setInputString, setJar, setJvm, setJvmargs, setJVMVersion, setLogError, setMaxmemory, setNewenvironment, setOutput, setOutputproperty, setResultProperty, setSpawn, setTimeout, setupRedirector</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.tools.ant.Task"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class org.apache.tools.ant.Task</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>getDescription, getLocation, getOwningTarget, getRuntimeConfigurableWrapper, getTaskName, getTaskType, getWrapper, init, isInvalid, log, log, maybeConfigure, perform, reconfigure, setDescription, setLocation, setOwningTarget, setRuntimeConfigurableWrapper, setTaskName, setTaskType</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_org.apache.tools.ant.ProjectComponent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class org.apache.tools.ant.ProjectComponent</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>getProject, setProject</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TD><B>Methods inherited from class java.lang.Object</B></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Field Detail</B></FONT></TD> </TR> </TABLE> <A NAME="outFileName"><!-- --></A><H3> outFileName</H3> <PRE> protected java.lang.String <B>outFileName</B></PRE> <DL> <DD>output file name <P> <DL> </DL> </DL> <HR> <A NAME="noBeginEnd"><!-- --></A><H3> noBeginEnd</H3> <PRE> protected boolean <B>noBeginEnd</B></PRE> <DL> <DD>If this paramter is true, CAP Begin and CAP end are not included in the script file <P> <DL> </DL> </DL> <HR> <A NAME="pkgName"><!-- --></A><H3> pkgName</H3> <PRE> protected java.lang.String <B>pkgName</B></PRE> <DL> <DD>Name of the package <P> <DL> </DL> </DL> <HR> <A NAME="capName"><!-- --></A><H3> capName</H3> <PRE> protected java.lang.String <B>capName</B></PRE> <DL> <DD>Name of CAP file <P> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TD> </TR> </TABLE> <A NAME="ScriptgenTask()"><!-- --></A><H3> ScriptgenTask</H3> <PRE> public <B>ScriptgenTask</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=1><FONT SIZE="+2"> <B>Method Detail</B></FONT></TD> </TR> </TABLE> <A NAME="setPkgName(java.lang.String)"><!-- --></A><H3> setPkgName</H3> <PRE> public void <B>setPkgName</B>(java.lang.String&nbsp;pkgName)</PRE> <DL> <DD>Sets the package name for verifier <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>pkgName</CODE> - is package name</DL> </DD> </DL> <HR> <A NAME="setNoBeginEnd(boolean)"><!-- --></A><H3> setNoBeginEnd</H3> <PRE> public void <B>setNoBeginEnd</B>(boolean&nbsp;on)</PRE> <DL> <DD>Sets noBeginEnd value to the requested value <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>on</CODE> - is boolean value to be set for noBeginEnd flag</DL> </DD> </DL> <HR> <A NAME="setOutFile(java.lang.String)"><!-- --></A><H3> setOutFile</H3> <PRE> public void <B>setOutFile</B>(java.lang.String&nbsp;outFileName)</PRE> <DL> <DD>Sets output file name <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>outFileName</CODE> - is the ouput file name</DL> </DD> </DL> <HR> <A NAME="setCapFile(java.lang.String)"><!-- --></A><H3> setCapFile</H3> <PRE> public void <B>setCapFile</B>(java.lang.String&nbsp;capName)</PRE> <DL> <DD>Sets cap file name <P> <DD><DL> <DT><B>Parameters:</B><DD><CODE>capName</CODE> - is the cap file name</DL> </DD> </DL> <HR> <A NAME="execute()"><!-- --></A><H3> execute</H3> <PRE> public void <B>execute</B>() throws org.apache.tools.ant.BuildException</PRE> <DL> <DD>Executes the task <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>org.apache.tools.ant.BuildException</CODE></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../com/sun/javacard/ant/tasks/MaskgenTask.html" title="class in com.sun.javacard.ant.tasks"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../com/sun/javacard/ant/tasks/VerifierTask.html" title="class in com.sun.javacard.ant.tasks"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ScriptgenTask.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &#169; 2005 Sun Microsystems, Inc. 4150 Network Circle,<br>Santa Clara, CA-95054, U.S.A. All Rights Reserved.</i> </BODY> </HTML>
{ "content_hash": "3bfe2794b43801772a1275763d179423", "timestamp": "", "source": "github", "line_count": 514, "max_line_length": 665, "avg_line_length": 41.62256809338521, "alnum_prop": 0.6497148733289707, "repo_name": "nversbra/SIC", "id": "2de9f6b2fbf45c75703a1e52ef243dcc3a11df64", "size": "21394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workspace/java_card_kit-2_2_2/ant-tasks/docs/html/javadocs/api/com/sun/javacard/ant/tasks/ScriptgenTask.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "31752" }, { "name": "C", "bytes": "633148" }, { "name": "C++", "bytes": "1707" }, { "name": "CSS", "bytes": "114435" }, { "name": "HTML", "bytes": "10208145" }, { "name": "Java", "bytes": "1417742" }, { "name": "Makefile", "bytes": "237083" }, { "name": "Objective-C", "bytes": "69190" }, { "name": "PHP", "bytes": "730" }, { "name": "Roff", "bytes": "8181" }, { "name": "Shell", "bytes": "742809" }, { "name": "XSLT", "bytes": "4615" } ], "symlink_target": "" }
package lila.tournament import org.joda.time.DateTime import reactivemongo.bson.{ BSONDocument, BSONArray } import BSONHandlers._ import lila.db.BSON.BSONJodaDateTimeHandler import lila.db.Implicits._ object TournamentRepo { private lazy val coll = Env.current.tournamentColl private def selectId(id: String) = BSONDocument("_id" -> id) private val enterableSelect = BSONDocument( "status" -> BSONDocument("$in" -> List(Status.Created.id, Status.Started.id))) private val createdSelect = BSONDocument("status" -> Status.Created.id) private val startedSelect = BSONDocument("status" -> Status.Started.id) private val finishedSelect = BSONDocument("status" -> Status.Finished.id) private val startedOrFinishedSelect = BSONDocument("status" -> BSONDocument("$gte" -> Status.Started.id)) private val unfinishedSelect = BSONDocument("status" -> BSONDocument("$ne" -> Status.Finished.id)) private val scheduledSelect = BSONDocument("schedule" -> BSONDocument("$exists" -> true)) private def sinceSelect(date: DateTime) = BSONDocument("startsAt" -> BSONDocument("$gt" -> date)) def byId(id: String): Fu[Option[Tournament]] = coll.find(selectId(id)).one[Tournament] def recentStartedOrFinished: Fu[List[Tournament]] = coll.find(sinceSelect(DateTime.now minusDays 2) ++ startedOrFinishedSelect) .cursor[Tournament]().collect[List]() def byIdAndPlayerId(id: String, userId: String): Fu[Option[Tournament]] = coll.find( selectId(id) ++ BSONDocument("players.id" -> userId) ).one[Tournament] def createdById(id: String): Fu[Option[Tournament]] = coll.find(selectId(id) ++ createdSelect).one[Tournament] def enterableById(id: String): Fu[Option[Tournament]] = coll.find(selectId(id) ++ enterableSelect).one[Tournament] def startedById(id: String): Fu[Option[Tournament]] = coll.find(selectId(id) ++ startedSelect).one[Tournament] def finishedById(id: String): Fu[Option[Tournament]] = coll.find(selectId(id) ++ finishedSelect).one[Tournament] def startedOrFinishedById(id: String): Fu[Option[Tournament]] = byId(id) map { _ filterNot (_.isCreated) } def createdByIdAndCreator(id: String, userId: String): Fu[Option[Tournament]] = createdById(id) map (_ filter (_.createdBy == userId)) def allEnterable: Fu[List[Tournament]] = coll.find(enterableSelect).cursor[Tournament]().collect[List]() def createdIncludingScheduled: Fu[List[Tournament]] = coll.find(createdSelect).toList[Tournament](None) def started: Fu[List[Tournament]] = coll.find(startedSelect).sort(BSONDocument("createdAt" -> -1)).toList[Tournament](None) def publicStarted: Fu[List[Tournament]] = coll.find(startedSelect ++ BSONDocument("private" -> BSONDocument("$exists" -> false))) .sort(BSONDocument("createdAt" -> -1)) .cursor[Tournament]().collect[List]() def finished(limit: Int): Fu[List[Tournament]] = coll.find(finishedSelect) .sort(BSONDocument("startsAt" -> -1)) .cursor[Tournament]().collect[List](limit) def finishedNotable(limit: Int): Fu[List[Tournament]] = coll.find(finishedSelect ++ BSONDocument( "$or" -> BSONArray( BSONDocument("nbPlayers" -> BSONDocument("$gte" -> 15)), scheduledSelect ))) .sort(BSONDocument("startsAt" -> -1)) .cursor[Tournament]().collect[List](limit) def setStatus(tourId: String, status: Status) = coll.update( selectId(tourId), BSONDocument("$set" -> BSONDocument("status" -> status.id)) ).void def setNbPlayers(tourId: String, nb: Int) = coll.update( selectId(tourId), BSONDocument("$set" -> BSONDocument("nbPlayers" -> nb)) ).void def setWinnerId(tourId: String, userId: String) = coll.update( selectId(tourId), BSONDocument("$set" -> BSONDocument("winner" -> userId)) ).void private def allCreatedSelect(aheadMinutes: Int) = createdSelect ++ BSONDocument( "$or" -> BSONArray( BSONDocument("schedule" -> BSONDocument("$exists" -> false)), BSONDocument("startsAt" -> BSONDocument("$lt" -> (DateTime.now plusMinutes aheadMinutes))) ) ) def publicCreatedSorted(aheadMinutes: Int): Fu[List[Tournament]] = coll.find( allCreatedSelect(aheadMinutes) ++ BSONDocument("private" -> BSONDocument("$exists" -> false)) ).sort(BSONDocument("startsAt" -> 1)).cursor[Tournament]().collect[List]() def allCreated(aheadMinutes: Int): Fu[List[Tournament]] = coll.find(allCreatedSelect(aheadMinutes)).cursor[Tournament]().collect[List]() private def stillWorthEntering: Fu[List[Tournament]] = coll.find(startedSelect ++ BSONDocument( "private" -> BSONDocument("$exists" -> false) )).sort(BSONDocument("startsAt" -> 1)).toList[Tournament](none) map { _.filter(_.isStillWorthEntering) } private def isPromotable(tour: Tournament) = tour.startsAt isBefore DateTime.now.plusMinutes { tour.schedule.map(_.freq) map { case Schedule.Freq.Marathon => 24 * 60 case Schedule.Freq.Monthly => 6 * 60 case Schedule.Freq.Weekly => 3 * 60 case Schedule.Freq.Daily => 1 * 60 case _ => 30 } getOrElse 30 } def promotable: Fu[List[Tournament]] = stillWorthEntering zip publicCreatedSorted(24 * 60) map { case (started, created) => (started ::: created).foldLeft(List.empty[Tournament]) { case (acc, tour) if !isPromotable(tour) => acc case (acc, tour) if acc.exists(_ similarTo tour) => acc case (acc, tour) => tour :: acc }.reverse } def scheduledUnfinished: Fu[List[Tournament]] = coll.find(scheduledSelect ++ unfinishedSelect) .sort(BSONDocument("startsAt" -> 1)).cursor[Tournament]().collect[List]() def scheduledCreated: Fu[List[Tournament]] = coll.find(createdSelect ++ scheduledSelect) .sort(BSONDocument("startsAt" -> 1)).cursor[Tournament]().collect[List]() def scheduledDedup: Fu[List[Tournament]] = scheduledCreated map { import Schedule.Freq _.flatMap { tour => tour.schedule map (tour -> _) }.foldLeft(List[Tournament]() -> none[Freq]) { case ((tours, skip), (_, sched)) if skip.contains(sched.freq) => (tours, skip) case ((tours, skip), (tour, sched)) => (tour :: tours, sched.freq match { case Freq.Daily => Freq.Eastern.some case Freq.Eastern => Freq.Daily.some case _ => skip }) }._1.reverse } def lastFinishedScheduledByFreq(freq: Schedule.Freq, since: DateTime, nb: Int): Fu[List[Tournament]] = coll.find( finishedSelect ++ sinceSelect(since) ++ BSONDocument( "schedule.freq" -> freq.name, "schedule.speed" -> BSONDocument("$in" -> Schedule.Speed.mostPopular.map(_.name)) ) ).sort(BSONDocument("startsAt" -> -1)).toList[Tournament](nb.some) def update(tour: Tournament) = coll.update(BSONDocument("_id" -> tour.id), tour) def insert(tour: Tournament) = coll.insert(tour) def remove(tour: Tournament) = coll.remove(BSONDocument("_id" -> tour.id)) def exists(id: String) = coll.count(BSONDocument("_id" -> id).some) map (0 !=) def isFinished(id: String): Fu[Boolean] = coll.count(BSONDocument("_id" -> id, "status" -> Status.Finished.id).some) map (0 !=) def toursToWithdrawWhenEntering(tourId: String): Fu[List[Tournament]] = coll.find(enterableSelect ++ BSONDocument( "_id" -> BSONDocument("$ne" -> tourId), "schedule.freq" -> BSONDocument("$ne" -> Schedule.Freq.Marathon.name), "nbPlayers" -> BSONDocument("$ne" -> 0) )).cursor[Tournament]().collect[List]() }
{ "content_hash": "72457b5dccaa27cd810fb0072941bfd4", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 115, "avg_line_length": 41.266304347826086, "alnum_prop": 0.6704859739233504, "repo_name": "terokinnunen/lila", "id": "f70c4eb650b088fe381c6563e1d387c0956f1c07", "size": "7593", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/tournament/src/main/TournamentRepo.scala", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "849" }, { "name": "CSS", "bytes": "230494" }, { "name": "Cycript", "bytes": "19945" }, { "name": "Emacs Lisp", "bytes": "32256" }, { "name": "Erlang", "bytes": "20393" }, { "name": "Fancy", "bytes": "119" }, { "name": "GAP", "bytes": "13291" }, { "name": "GLSL", "bytes": "2434" }, { "name": "HTML", "bytes": "343978" }, { "name": "Hy", "bytes": "20547" }, { "name": "Io", "bytes": "4943" }, { "name": "Java", "bytes": "21088" }, { "name": "JavaScript", "bytes": "456791" }, { "name": "Makefile", "bytes": "16380" }, { "name": "Mathematica", "bytes": "18993" }, { "name": "NewLisp", "bytes": "19702" }, { "name": "OCaml", "bytes": "2098" }, { "name": "Perl6", "bytes": "20507" }, { "name": "PostScript", "bytes": "2604" }, { "name": "Python", "bytes": "1959" }, { "name": "Ruby", "bytes": "31968" }, { "name": "Scala", "bytes": "1679618" }, { "name": "Shell", "bytes": "10263" }, { "name": "Slash", "bytes": "18594" }, { "name": "Smalltalk", "bytes": "19650" }, { "name": "SystemVerilog", "bytes": "19318" }, { "name": "UrWeb", "bytes": "17437" } ], "symlink_target": "" }
package encrypted import ( "encoding/json" "testing" . "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } type EncryptedSuite struct{} var _ = Suite(&EncryptedSuite{}) var plaintext = []byte("reallyimportant") func (EncryptedSuite) TestRoundtrip(c *C) { passphrase := []byte("supersecret") enc, err := Encrypt(plaintext, passphrase) c.Assert(err, IsNil) // successful decrypt dec, err := Decrypt(enc, passphrase) c.Assert(err, IsNil) c.Assert(dec, DeepEquals, plaintext) // wrong passphrase passphrase[0] = 0 dec, err = Decrypt(enc, passphrase) c.Assert(err, NotNil) c.Assert(dec, IsNil) } func (EncryptedSuite) TestTamperedRoundtrip(c *C) { passphrase := []byte("supersecret") enc, err := Encrypt(plaintext, passphrase) c.Assert(err, IsNil) data := &data{} err = json.Unmarshal(enc, data) c.Assert(err, IsNil) data.Ciphertext[0] = 0 data.Ciphertext[1] = 0 enc, _ = json.Marshal(data) dec, err := Decrypt(enc, passphrase) c.Assert(err, NotNil) c.Assert(dec, IsNil) } func (EncryptedSuite) TestDecrypt(c *C) { enc := []byte(`{"kdf":{"name":"scrypt","params":{"N":32768,"r":8,"p":1},"salt":"N9a7x5JFGbrtB2uBR81jPwp0eiLR4A7FV3mjVAQrg1g="},"cipher":{"name":"nacl/secretbox","nonce":"2h8HxMmgRfuYdpswZBQaU3xJ1nkA/5Ik"},"ciphertext":"SEW6sUh0jf2wfdjJGPNS9+bkk2uB+Cxamf32zR8XkQ=="}`) passphrase := []byte("supersecret") dec, err := Decrypt(enc, passphrase) c.Assert(err, IsNil) c.Assert(dec, DeepEquals, plaintext) }
{ "content_hash": "38bca7fd523e72deca3f03476b0c8f89", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 268, "avg_line_length": 23.703125, "alnum_prop": 0.6921555702043507, "repo_name": "dmcgowan/gotuf", "id": "31b058252fbd1495e0f4ba1ed777a231e8079c03", "size": "1517", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "encrypted/encrypted_test.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "135685" }, { "name": "Makefile", "bytes": "748" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>euclidean-geometry: 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.15.0 / euclidean-geometry - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> euclidean-geometry <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-02 08:22:03 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-02 08:22:03 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.5.0 Fast, portable, and opinionated build system 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 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;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/euclidean-geometry&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/EuclideanGeometry&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: plane geometry&quot; &quot;keyword: Euclid&quot; &quot;keyword: ruler and compass&quot; &quot;category: Mathematics/Geometry/General&quot; ] authors: [ &quot;Jean Duprat &lt;Jean.Duprat@ens-lyon.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/euclidean-geometry/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/euclidean-geometry.git&quot; synopsis: &quot;Basis of the Euclid&#39;s plane geometry&quot; description: &quot;&quot;&quot; This is a more recent version of the basis of Euclid&#39;s plane geometry, the previous version was the contribution intitled RulerCompassGeometry. The plane geometry is defined as a set of points, with two predicates : Clokwise for the orientation and Equidistant for the metric and three constructors, Ruler for the lines, Compass for the circles and Intersection for the points. For using it, we suggest to compile the files the name of which begin by a capital letter and a number from A1 to N7 in the lexicographic order and to keep modifiable the files of tacics (from Tactic1 to Tactic4) and the files of examples (Hilbert and Bolyai).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/euclidean-geometry/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=d1341193f9fd7a8aa5c1d87ceda9ed61&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-euclidean-geometry.8.8.0 coq.8.15.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.15.0). The following dependencies couldn&#39;t be met: - coq-euclidean-geometry -&gt; coq &lt; 8.9~ -&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-euclidean-geometry.8.8.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"> 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": "4f7edfca183b72e4e5cf37765999d5ca", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 278, "avg_line_length": 46.305882352941175, "alnum_prop": 0.5664380081300813, "repo_name": "coq-bench/coq-bench.github.io", "id": "e6b6725de749071e4cd608646da3b480d1f927a0", "size": "7897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.15.0/euclidean-geometry/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System.Web.Mvc; namespace BackOffice.Areas.Users { public class UsersAreaRegistration : AreaRegistration { public override string AreaName { get { return "Users"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Users_default", "Users/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
{ "content_hash": "2a9bf21cabba97fa2b60a1143304de72", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 75, "avg_line_length": 23.541666666666668, "alnum_prop": 0.49911504424778763, "repo_name": "LykkeCity/MarketPlace", "id": "d12644faa0e9b333c928977b227aeecb3ef84929", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BackOffice/Areas/Users/UsersAreaRegistration.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "414" }, { "name": "C#", "bytes": "956368" }, { "name": "CSS", "bytes": "2472773" }, { "name": "HTML", "bytes": "18959" }, { "name": "JavaScript", "bytes": "276245" }, { "name": "TypeScript", "bytes": "66276" } ], "symlink_target": "" }
package dnsimple import ( "fmt" ) // Collaborator represents a Collaborator in DNSimple. type Collaborator struct { ID int `json:"id,omitempty"` DomainID int `json:"domain_id,omitempty"` DomainName string `json:"domain_name,omitempty"` UserID int `json:"user_id,omitempty"` UserEmail string `json:"user_email,omitempty"` Invitation bool `json:"invitation,omitempty"` CreatedAt string `json:"created_at,omitempty"` UpdatedAt string `json:"updated_at,omitempty"` AcceptedAt string `json:"accepted_at,omitempty"` } // CollaboratorAttributes represents Collaborator attributes for AddCollaborator operation. type CollaboratorAttributes struct { Email string `json:"email,omitempty"` } func collaboratorPath(accountID, domainIdentifier, collaboratorID string) (path string) { path = fmt.Sprintf("%v/collaborators", domainPath(accountID, domainIdentifier)) if collaboratorID != "" { path += fmt.Sprintf("/%v", collaboratorID) } return } // CollaboratorResponse represents a response from an API method that returns a Collaborator struct. type CollaboratorResponse struct { Response Data *Collaborator `json:"data"` } // CollaboratorsResponse represents a response from an API method that returns a collection of Collaborator struct. type CollaboratorsResponse struct { Response Data []Collaborator `json:"data"` } // ListCollaborators list the collaborators for a domain. // // See https://developer.dnsimple.com/v2/domains/collaborators#list func (s *DomainsService) ListCollaborators(accountID, domainIdentifier string, options *ListOptions) (*CollaboratorsResponse, error) { path := versioned(collaboratorPath(accountID, domainIdentifier, "")) collaboratorsResponse := &CollaboratorsResponse{} path, err := addURLQueryOptions(path, options) if err != nil { return nil, err } resp, err := s.client.get(path, collaboratorsResponse) if err != nil { return collaboratorsResponse, err } collaboratorsResponse.HttpResponse = resp return collaboratorsResponse, nil } // AddCollaborator adds a new collaborator to the domain in the account. // // See https://developer.dnsimple.com/v2/domains/collaborators#add func (s *DomainsService) AddCollaborator(accountID string, domainIdentifier string, attributes CollaboratorAttributes) (*CollaboratorResponse, error) { path := versioned(collaboratorPath(accountID, domainIdentifier, "")) collaboratorResponse := &CollaboratorResponse{} resp, err := s.client.post(path, attributes, collaboratorResponse) if err != nil { return nil, err } collaboratorResponse.HttpResponse = resp return collaboratorResponse, nil } // RemoveCollaborator PERMANENTLY deletes a domain from the account. // // See https://developer.dnsimple.com/v2/domains/collaborators#add func (s *DomainsService) RemoveCollaborator(accountID string, domainIdentifier string, collaboratorID string) (*CollaboratorResponse, error) { path := versioned(collaboratorPath(accountID, domainIdentifier, collaboratorID)) collaboratorResponse := &CollaboratorResponse{} resp, err := s.client.delete(path, nil, nil) if err != nil { return nil, err } collaboratorResponse.HttpResponse = resp return collaboratorResponse, nil }
{ "content_hash": "9869ec54cac5a2266ef9091da2fc29d8", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 151, "avg_line_length": 33.427083333333336, "alnum_prop": 0.7687753194141477, "repo_name": "stardog-union/stardog-graviton", "id": "b25f8fba4fa4010b39e807e545db6d5d04a62e3b", "size": "3209", "binary": false, "copies": "71", "ref": "refs/heads/develop", "path": "vendor/github.com/hashicorp/terraform/vendor/github.com/dnsimple/dnsimple-go/dnsimple/collaborators.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "BitBake", "bytes": "50002" }, { "name": "Dockerfile", "bytes": "1212" }, { "name": "Go", "bytes": "195457" }, { "name": "HCL", "bytes": "26587" }, { "name": "Makefile", "bytes": "602" }, { "name": "Python", "bytes": "43992" }, { "name": "Shell", "bytes": "11173" }, { "name": "Smarty", "bytes": "2192" } ], "symlink_target": "" }
using System; namespace UniRx.Operators { internal class ReturnObservable<T> : OperatorObservableBase<T> { readonly T value; readonly IScheduler scheduler; public ReturnObservable(T value, IScheduler scheduler) : base(scheduler == Scheduler.CurrentThread) { this.value = value; this.scheduler = scheduler; } protected override IDisposable SubscribeCore(IObserver<T> observer, IDisposable cancel) { observer = new Return(observer, cancel); if (scheduler == Scheduler.Immediate) { observer.OnNext(value); observer.OnCompleted(); return Disposable.Empty; } else { return scheduler.Schedule(() => { observer.OnNext(value); observer.OnCompleted(); }); } } class Return : OperatorObserverBase<T, T> { public Return(IObserver<T> observer, IDisposable cancel) : base(observer, cancel) { } public override void OnNext(T value) { try { base.observer.OnNext(value); } catch { Dispose(); throw; } } public override void OnError(Exception error) { try { observer.OnError(error); } finally { Dispose(); } } public override void OnCompleted() { try { observer.OnCompleted(); } finally { Dispose(); } } } } }
{ "content_hash": "7931e831e43aaebbc3f3ded5719a402f", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 95, "avg_line_length": 26.271428571428572, "alnum_prop": 0.44480696030451333, "repo_name": "Deepscorn/DeepLabs", "id": "9ffde07344be0e02c39360e4da9084b8587e0790", "size": "1841", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Core/Dependencies/UniRx/Scripts/Operators/Return.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1378718" } ], "symlink_target": "" }
// Copyright (c) 2014-2019 The Innova Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "darksend.h" #include "governance-classes.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "netfulfilledman.h" #include "spork.h" #include "util.h" #include <boost/lexical_cast.hpp> /** Object for who's going to get paid on which blocks */ CMasternodePayments mnpayments; CCriticalSection cs_vecPayees; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePaymentVotes; /** * IsBlockValueValid * * Determine if coinbase outgoing created money is the correct value * * Why is this needed? * - In Innova some blocks are superblocks, which output much higher amounts of coins * - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created * - When non-superblocks are detected, the normal schedule should be maintained */ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet) { strErrorRet = ""; bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward); if(fDebug) LogPrintf("block.vtx[0].GetValueOut() %lld <= blockReward %lld\n", block.vtx[0].GetValueOut(), blockReward); // we are still using budgets, but we have no data about them anymore, // all we know is predefined budget cycle and window const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { // NOTE: make sure SPORK_13_OLD_SUPERBLOCK_FLAG is disabled when 12.1 starts to go live if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, budgets are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n"); // TODO: reprocess blocks to make sure they are legit? return true; } // LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in budget cycle window", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } // superblocks started CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue); LogPrint("gobject", "block.vtx[0].GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0].GetValueOut(), nSuperblockMaxValue); if(!masternodeSync.IsSynced()) { // not enough data but at least it must NOT exceed superblock max value if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n"); if(!isSuperblockMaxValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", nBlockHeight, block.vtx[0].GetValueOut(), nSuperblockMaxValue); } return isSuperblockMaxValueMet; } if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } // it MUST be a regular block otherwise return isBlockRewardValueMet; } // we are synced, let's try to check as much data as we can if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(block.vtx[0], nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // all checks are done in CSuperblock::IsValid, nothing to do here return true; } // triggered but invalid? that's weird LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // should NOT allow invalid superblocks, when superblocks are enabled strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight); return false; } LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } // it MUST be a regular block return isBlockRewardValueMet; } bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { if(!masternodeSync.IsSynced()) { //there is no budget data to use to check anything, let's just accept the longest chain if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n"); return true; } // we are still using budgets, but we have no data about them anymore, // we can only check masternode payments const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { if(!sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and masternode payment is invalid\n"); return false; } // NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n"); // TODO: reprocess blocks to make sure they are legit? return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } // superblocks started // SEE IF THIS IS A VALID SUPERBLOCK if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString()); return true; } LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString()); // should NOT allow such superblocks, when superblocks are enabled return false; } // continue validation, should pay MN LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight); } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n"); } // IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet) { // only create superblocks if spork is enabled AND if superblock is actually triggered // (height should be validated inside) if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight); CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet); return; } // FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet); LogPrint("mnpayments", "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString()); } std::string GetRequiredPaymentsString(int nBlockHeight) { // IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight); } // OTHERWISE, PAY MASTERNODE return mnpayments.GetRequiredPaymentsString(nBlockHeight); } void CMasternodePayments::Clear() { LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodeBlocks.clear(); mapMasternodePaymentVotes.clear(); } bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight) { LOCK(cs_mapMasternodePaymentVotes); if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) { return false; } //record this masternode voted mapMasternodesLastVote[outMasternode] = nBlockHeight; return true; } /** * FillBlockPayee * * Fill Masternode ONLY payment block */ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) { // make sure it's not filled yet txoutMasternodeRet = CTxOut(); CScript payee; if(!mnpayments.GetBlockPayee(nBlockHeight, payee)) { // no masternode detected... int nCount = 0; CMasternode *winningNode = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount); if(!winningNode) { // ...and we can't calculate it on our own LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n"); return; } // fill payee with locally calculated winner and hope for the best payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID()); } // GET MASTERNODE PAYMENT VARIABLES SETUP CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward); // split reward between miner ... txNew.vout[0].nValue -= masternodePayment; // ... and masternode txoutMasternodeRet = CTxOut(masternodePayment, payee); txNew.vout.push_back(txoutMasternodeRet); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", masternodePayment, address2.ToString()); } int CMasternodePayments::GetMinMasternodePaymentsProto() { return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES) ? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2 : MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } void CMasternodePayments::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // Ignore any payments messages until masternode list is synced if(!masternodeSync.IsMasternodeListSynced()) return; if(fLiteMode) return; // disable all Innova specific functionality if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync // Ignore such requests until we are fully synced. // We could start processing this after masternode list is synced // but this is a heavy one so it's better to finish sync first. if (!masternodeSync.IsSynced()) return; int nCountNeeded; vRecv >> nCountNeeded; if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) { // Asking for the payments list multiple times in a short period of time is no good LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id); Misbehaving(pfrom->GetId(), 20); return; } netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC); Sync(pfrom); LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->id); } else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner CMasternodePaymentVote vote; vRecv >> vote; if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return; if(!pCurrentBlockIndex) return; uint256 nHash = vote.GetHash(); pfrom->setAskFor.erase(nHash); { LOCK(cs_mapMasternodePaymentVotes); if(mapMasternodePaymentVotes.count(nHash)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), pCurrentBlockIndex->nHeight); return; } // Avoid processing same vote multiple times mapMasternodePaymentVotes[nHash] = vote; // but first mark vote as non-verified, // AddPaymentVote() below should take care of it if vote is actually ok mapMasternodePaymentVotes[nHash].MarkAsNotVerified(); } int nFirstBlock = pCurrentBlockIndex->nHeight - GetStorageLimit(); if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > pCurrentBlockIndex->nHeight+20) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, pCurrentBlockIndex->nHeight); return; } std::string strError = ""; if(!vote.IsValid(pfrom, pCurrentBlockIndex->nHeight, strError)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError); return; } if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) { LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.vinMasternode.prevout.ToStringShort()); return; } masternode_info_t mnInfo = mnodeman.GetMasternodeInfo(vote.vinMasternode); if(!mnInfo.fInfoValid) { // mn was not found, so we can't check vote, some info is probably missing LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.vinMasternode.prevout.ToStringShort()); mnodeman.AskForMN(pfrom, vote.vinMasternode); return; } int nDos = 0; if(!vote.CheckSignature(mnInfo.pubKeyMasternode, pCurrentBlockIndex->nHeight, nDos)) { if(nDos) { LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), nDos); } else { // only warn about anything non-critical (i.e. nDos == 0) in debug mode LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n"); } // Either our info or vote info could be outdated. // In case our info is outdated, ask for an update, mnodeman.AskForMN(pfrom, vote.vinMasternode); // but there is nothing we can do if vote info itself is outdated // (i.e. it was signed by a mn which changed its key), // so just quit here. return; } CTxDestination address1; ExtractDestination(vote.payee, address1); CBitcoinAddress address2(address1); LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s\n", address2.ToString(), vote.nBlockHeight, pCurrentBlockIndex->nHeight, vote.vinMasternode.prevout.ToStringShort()); if(AddPaymentVote(vote)){ vote.Relay(); masternodeSync.AddedPaymentVote(); } } } bool CMasternodePaymentVote::Sign() { std::string strError; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); if(!darkSendSigner.SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n"); return false; } if(!darkSendSigner.VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee); } return false; } // Is this masternode scheduled to get paid soon? // -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(!pCurrentBlockIndex) return false; CScript mnpayee; mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); CScript payee; for(int64_t h = pCurrentBlockIndex->nHeight; h <= pCurrentBlockIndex->nHeight + 8; h++){ if(h == nNotBlockHeight) continue; if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks[h].GetBestPayee(payee) && mnpayee == payee) { return true; } } return false; } bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote) { uint256 blockHash = uint256(); if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false; if(HasVerifiedPaymentVote(vote.GetHash())) return false; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodePaymentVotes[vote.GetHash()] = vote; if(!mapMasternodeBlocks.count(vote.nBlockHeight)) { CMasternodeBlockPayees blockPayees(vote.nBlockHeight); mapMasternodeBlocks[vote.nBlockHeight] = blockPayees; } mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote); return true; } bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn) { LOCK(cs_mapMasternodePaymentVotes); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn); return it != mapMasternodePaymentVotes.end() && it->second.IsVerified(); } void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetPayee() == vote.payee) { payee.AddVoteHash(vote.GetHash()); return; } } CMasternodePayee payeeNew(vote.payee, vote.GetHash()); vecPayees.push_back(payeeNew); } bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) { LOCK(cs_vecPayees); if(!vecPayees.size()) { LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n"); return false; } int nVotes = -1; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() > nVotes) { payeeRet = payee.GetPayee(); nVotes = payee.GetVoteCount(); } } return (nVotes > -1); } bool CMasternodeBlockPayees::HasPayeeWithVotes(CScript payeeIn, int nVotesReq) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) { return true; } } LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq); return false; } bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) { LOCK(cs_vecPayees); int nMaxSignatures = 0; std::string strPayeesPossible = ""; CAmount nMasternodePayment = GetMasternodePayment(nBlockHeight, txNew.GetValueOut()); //require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nMaxSignatures) { nMaxSignatures = payee.GetVoteCount(); } } // if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { BOOST_FOREACH(CTxOut txout, txNew.vout) { if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) { LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n"); return true; } } CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); if(strPayeesPossible == "") { strPayeesPossible = address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); } } } LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f INNOVA\n", strPayeesPossible, (float)nMasternodePayment/COIN); return false; } std::string CMasternodeBlockPayees::GetRequiredPaymentsString() { LOCK(cs_vecPayees); std::string strRequiredPayments = "Unknown"; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); if (strRequiredPayments != "Unknown") { strRequiredPayments += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } else { strRequiredPayments = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } } return strRequiredPayments; } std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString(); } return "Unknown"; } bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew); } return true; } void CMasternodePayments::CheckAndRemove() { if(!pCurrentBlockIndex) return; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); int nLimit = GetStorageLimit(); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin(); while(it != mapMasternodePaymentVotes.end()) { CMasternodePaymentVote vote = (*it).second; if(pCurrentBlockIndex->nHeight - vote.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight); mapMasternodePaymentVotes.erase(it++); mapMasternodeBlocks.erase(vote.nBlockHeight); } else { ++it; } } LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString()); } bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError) { CMasternode* pmn = mnodeman.Find(vinMasternode); if(!pmn) { strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToStringShort()); // Only ask if we are already synced and still have no idea about that Masternode if(masternodeSync.IsMasternodeListSynced()) { mnodeman.AskForMN(pnode, vinMasternode); } return false; } int nMinRequiredProtocol; if(nBlockHeight >= nValidationHeight) { // new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto(); } else { // allow non-updated masternodes for old blocks nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } if(pmn->nProtocolVersion < nMinRequiredProtocol) { strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", pmn->nProtocolVersion, nMinRequiredProtocol); return false; } // Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks. // Regular clients (miners included) need to verify masternode rank for future block votes only. if(!fMasterNode && nBlockHeight < nValidationHeight) return true; int nRank = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 101, nMinRequiredProtocol, false); if(nRank == -1) { LogPrint("mnpayments", "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n", vinMasternode.prevout.ToStringShort()); return false; } if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) { // It's common to have masternodes mistakenly think they are in the top 10 // We don't want to print all of these messages in normal mode, debug mode should print though strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank); // Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) { strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank); LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError); Misbehaving(pnode->GetId(), 20); } // Still invalid however return false; } return true; } bool CMasternodePayments::ProcessBlock(int nBlockHeight) { // DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE if(fLiteMode || !fMasterNode) return false; // We have little chances to pick the right winner if winners list is out of sync // but we have no choice, so we'll try. However it doesn't make sense to even try to do so // if we have not enough data about masternodes. if(!masternodeSync.IsMasternodeListSynced()) return false; int nRank = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 101, GetMinMasternodePaymentsProto(), false); if (nRank == -1) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n"); return false; } if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank); return false; } // LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.vin.prevout.ToStringShort()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; CMasternode *pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount); if (pmn == NULL) { LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n"); return false; } LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", pmn->vin.prevout.ToStringShort()); CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID()); CMasternodePaymentVote voteNew(activeMasternode.vin, nBlockHeight, payee); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); // SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n"); if (voteNew.Sign()) { LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n"); if (AddPaymentVote(voteNew)) { voteNew.Relay(); return true; } } return false; } void CMasternodePaymentVote::Relay() { // do not relay until synced if (!masternodeSync.IsWinnersListSynced()) return; CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash()); RelayInv(inv); } bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos) { // do not ban by default nDos = 0; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); std::string strError = ""; if (!darkSendSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { nDos = 20; } return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", vinMasternode.prevout.ToStringShort().c_str(), strError); } return true; } std::string CMasternodePaymentVote::ToString() const { std::ostringstream info; info << vinMasternode.prevout.ToStringShort() << ", " << nBlockHeight << ", " << ScriptToAsmStr(payee) << ", " << (int)vchSig.size(); return info.str(); } // Send only votes for future blocks, node should request every other missing payment block individually void CMasternodePayments::Sync(CNode* pnode) { LOCK(cs_mapMasternodeBlocks); if(!pCurrentBlockIndex) return; int nInvCount = 0; for(int h = pCurrentBlockIndex->nHeight; h < pCurrentBlockIndex->nHeight + 20; h++) { if(mapMasternodeBlocks.count(h)) { BOOST_FOREACH(CMasternodePayee& payee, mapMasternodeBlocks[h].vecPayees) { std::vector<uint256> vecVoteHashes = payee.GetVoteHashes(); BOOST_FOREACH(uint256& hash, vecVoteHashes) { if(!HasVerifiedPaymentVote(hash)) continue; pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash)); nInvCount++; } } } } LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer %d\n", nInvCount, pnode->id); pnode->PushMessage(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount); } // Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync. void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode) { if(!pCurrentBlockIndex) return; LOCK2(cs_main, cs_mapMasternodeBlocks); std::vector<CInv> vToFetch; int nLimit = GetStorageLimit(); const CBlockIndex *pindex = pCurrentBlockIndex; while(pCurrentBlockIndex->nHeight - pindex->nHeight < nLimit) { if(!mapMasternodeBlocks.count(pindex->nHeight)) { // We have no idea about this block height, let's ask vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash())); // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d blocks\n", pnode->id, MAX_INV_SZ); pnode->PushMessage(NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } } if(!pindex->pprev) break; pindex = pindex->pprev; } std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while(it != mapMasternodeBlocks.end()) { int nTotalVotes = 0; bool fFound = false; BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { fFound = true; break; } nTotalVotes += payee.GetVoteCount(); } // A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found // or no clear winner was found but there are at least avg number of votes if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) { // so just move to the next block ++it; continue; } // DEBUG DBG ( // Let's see why this failed BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount()); } printf("block %d votes total %d\n", it->first, nTotalVotes); ) // END DEBUG // Low data block found, let's try to sync it uint256 hash; if(GetBlockHash(hash, it->first)) { vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash)); } // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, MAX_INV_SZ); pnode->PushMessage(NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } ++it; } // Ask for the rest of it if(!vToFetch.empty()) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, vToFetch.size()); pnode->PushMessage(NetMsgType::GETDATA, vToFetch); } } std::string CMasternodePayments::ToString() const { std::ostringstream info; info << "Votes: " << (int)mapMasternodePaymentVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } bool CMasternodePayments::IsEnoughData() { float nAverageVotes = (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2; int nStorageLimit = GetStorageLimit(); return GetBlockCount() > nStorageLimit && GetVoteCount() > nStorageLimit * nAverageVotes; } int CMasternodePayments::GetStorageLimit() { return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore); } void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex) { pCurrentBlockIndex = pindex; LogPrint("mnpayments", "CMasternodePayments::UpdatedBlockTip -- pCurrentBlockIndex->nHeight=%d\n", pCurrentBlockIndex->nHeight); ProcessBlock(pindex->nHeight + 10); }
{ "content_hash": "e4e411ae07c2cd756bf52baf90517a5f", "timestamp": "", "source": "github", "line_count": 955, "max_line_length": 232, "avg_line_length": 40.809424083769635, "alnum_prop": 0.6704641675005774, "repo_name": "innovacoin/innova", "id": "ddbcc2d4b7ec368218f859c4bc87764e4262ce92", "size": "38973", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/masternode-payments.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "419693" }, { "name": "C", "bytes": "1388240" }, { "name": "C++", "bytes": "5310604" }, { "name": "CSS", "bytes": "124335" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "M4", "bytes": "147911" }, { "name": "Makefile", "bytes": "97247" }, { "name": "Objective-C", "bytes": "4273" }, { "name": "Objective-C++", "bytes": "7228" }, { "name": "Python", "bytes": "706936" }, { "name": "QMake", "bytes": "2057" }, { "name": "Roff", "bytes": "3766" }, { "name": "Shell", "bytes": "418957" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.I2c; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace CommunicateI2CWithArduino { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private const string I2C_CONTROLLER_NAME = "I2C1"; //specific to RPI2 private const byte I2C_ARDUINO = 18; public MainPage() { this.InitializeComponent(); initI2C(); } private async void initI2C() { try { var i2cSettings = new I2cConnectionSettings(I2C_ARDUINO); i2cSettings.BusSpeed = I2cBusSpeed.FastMode; string deviceSelector = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME); var i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector); var i2cdev = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, i2cSettings); byte[] wbuffer = new byte[] { 1, 2 }; byte[] rbuffer = new byte[8]; //var resutl = i2cdev.WriteReadPartial(wbuffer, rbuffer); //Debug.WriteLine(resutl.Status); //i2cdev.WriteRead(wbuffer, rbuffer); i2cdev.Write(wbuffer); await Task.Delay(10000); var resutl = i2cdev.ReadPartial(rbuffer); Debug.WriteLine(rbuffer[0]); } catch (Exception ex) { throw; } } } }
{ "content_hash": "d9c14979efbbd0865dd39101a31c61d0", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 106, "avg_line_length": 34.36923076923077, "alnum_prop": 0.6092211280214861, "repo_name": "tkopacz/iot-kabelki-azure-iot-hub", "id": "5cf91086cf4cd4487fc40fc1f1780ad2b6b3489c", "size": "2236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TK_CommunicateI2CWithArduino/CommunicateI2CWithArduino/MainPage.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "17473" }, { "name": "Batchfile", "bytes": "145" }, { "name": "C", "bytes": "8988" }, { "name": "C#", "bytes": "91301" }, { "name": "C++", "bytes": "35572" }, { "name": "Processing", "bytes": "3030" } ], "symlink_target": "" }
Flask-Pbj provides support for [Google Protocol Buffers](https://developers.google.com/protocol-buffers/docs/overview) and json formatted request and response data. The api decorator serializes and deserializes json or protobuf formatted messages to and from a python dictionary. ## Why Flask-Pbj Flask Peanut Butter and Jelly to simplifies the creation of REST APIs for C++ clients. Flask-pbj decorated app.routes accept and return protobuf messages or JSON. The JSON is useful for debugging and public API's while Google Protobuf is a well-documented compact and efficient format, particularly useful for C++/Python communication. ## Examples *example_messages.proto* ``` message Person { required int32 id = 1; required string name = 2; optional string email = 3; } message Team { required int32 id = 1; required string name = 2; required Person leader = 3 repeated Person members = 4; } ``` *app.py* ```python # The route function can access the added request.data_dict data member for # input and return a dictionary for output. The client's accept and # content-type headers determine the format of the messages. # Similar to flask, routes can avoid pbjs response serialization by directly # returning a flask.Response object. @app.route('/teams', methods=['POST']) @api(json, protobuf(receives=Person, sends=Team, errors=Error)) def create_team(): leader = request.data_dict if len(leader['name']) < 3: # Optionally, return a tuple of the form dict, status_code, headers # A 4xx HTTP error will use the 'errors' protobuf message type return {"errorMessage": "Name too short"}, 400 # For a 200 response, just return a dict return { 'id': get_url(2), 'name': "{0}'s Team".format(leader['name']), 'leader': get_url(person[id]), 'members': [], } ``` *Create a team with JSON:* ``` curl -X POST -H "Accept: application/json" \ -H "Content-type: application/json" \ http://127.0.0.1:5000/teams --data {'id': 1, 'name': 'Red Leader'} { "id": 2, "name": "Red Leader's Team", "leader": "/people/1" "members": [] } ``` *Create a new team with google protobuf:* ```python # Create and save a Person structure in python from example_messages_pb2 import Person leader = Person() leader.id = 1 leader.name = 'Red Leader' with open('person.pb', 'wb') as f: f.write(leader.SerializeToString()) ``` ``` curl -X POST -H "Accept: application/x-protobuf" \ -H "Content-type: application/x-protobuf" \ http://127.0.0.1:5000/teams --data-binary @person.pb > team.pb ``` ## Adding new mimetypes Codecs are classes see JsonCodec and ProtobufCodec for examples
{ "content_hash": "d24f160b2d93dabb1b306edbd4facec4", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 118, "avg_line_length": 32.46987951807229, "alnum_prop": 0.6912801484230056, "repo_name": "keenbrowne/flask-pbj", "id": "1098c909c1583db614e0f2e03ed8da7a58f3a211", "size": "2725", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "21285" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Login Page - Photon Admin Panel Theme</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0"> <link rel="shortcut icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/favicon.ico"/> <link rel="apple-touch-icon" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/iosicon.png"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/css/css_compiled/photon-min.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/css/css_compiled/photon-min-part2.css?v1.1" media="all"/> <link rel="stylesheet" href="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/css/css_compiled/photon-responsive-min.css?v1.1" media="all"/> <!--[if IE]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie-only-min.css?v1.1" /> <![endif]--> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="css/css_compiled/ie8-only-min.css?v1.1" /> <script type="text/javascript" src="js/plugins/excanvas.js"></script> <script type="text/javascript" src="js/plugins/html5shiv.js"></script> <script type="text/javascript" src="js/plugins/respond.min.js"></script> <script type="text/javascript" src="js/plugins/fixFontIcons.js"></script> <![endif]--> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/bootstrap/bootstrap.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/modernizr.custom.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.pnotify.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/less-1.3.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/xbreadcrumbs.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.maskedinput-1.3.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.autotab-1.1b.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/charCount.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.textareaCounter.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/elrte.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/elrte.en.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/select2.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery-picklist.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.validate.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/additional-methods.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.form.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.metadata.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.mockjax.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.uniform.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.tagsinput.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.rating.pack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/farbtastic.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.timeentry.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.dataTables.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.jstree.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/dataTables.bootstrap.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.mousewheel.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.mCustomScrollbar.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.flot.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.flot.stack.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.flot.pie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.flot.resize.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/raphael.2.1.0.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/justgage.1.0.1.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.qrcode.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.clock.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.countdown.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.jqtweet.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/jquery.cookie.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/bootstrap-fileupload.min.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/prettify/prettify.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/bootstrapSwitch.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/plugins/mfupload.js"></script> <script type="text/javascript" src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/js/common.js"></script> </head> <body class="body-login"> <div class="nav-fixed-topright" style="visibility: hidden"> <ul class="nav nav-user-menu"> <li class="user-sub-menu-container"> <a href="javascript:;"> <i class="user-icon"></i><span class="nav-user-selection">Theme Options</span><i class="icon-menu-arrow"></i> </a> <ul class="nav user-sub-menu"> <li class="light"> <a href="javascript:;"> <i class='icon-photon stop'></i>Light Version </a> </li> <li class="dark"> <a href="javascript:;"> <i class='icon-photon stop'></i>Dark Version </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-photon mail"></i> </a> </li> <li> <a href="javascript:;"> <i class="icon-photon comment_alt2_stroke"></i> <div class="notification-count">12</div> </a> </li> </ul> </div> <script> $(function(){ setTimeout(function(){ $('.nav-fixed-topright').removeAttr('style'); }, 300); $(window).scroll(function(){ if($('.breadcrumb-container').length){ var scrollState = $(window).scrollTop(); if (scrollState > 0) $('.nav-fixed-topright').addClass('nav-released'); else $('.nav-fixed-topright').removeClass('nav-released') } }); $('.user-sub-menu-container').on('click', function(){ $(this).toggleClass('active-user-menu'); }); $('.user-sub-menu .light').on('click', function(){ if ($('body').is('.light-version')) return; $('body').addClass('light-version'); setTimeout(function() { $.cookie('themeColor', 'light', { expires: 7, path: '/' }); }, 500); }); $('.user-sub-menu .dark').on('click', function(){ if ($('body').is('.light-version')) { $('body').removeClass('light-version'); $.cookie('themeColor', 'dark', { expires: 7, path: '/' }); } }); }); </script> <div class="container-login"> <div class="form-centering-wrapper"> <div class="form-window-login"> <div class="form-window-login-logo"> <div class="login-logo"> <img src="http://photonui.orangehilldev.com/css/css_compiled/@%7BphotonImagePath%7Dplugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/images/photon/login-logo@2x.png" alt="Photon UI"/> </div> <h2 class="login-title">Welcome to Photon UI!</h2> <div class="login-member">Not a Member?&nbsp;<a href="jquery.flot.resize.js.html#">Sign Up &#187;</a> <a href="jquery.flot.resize.js.html#" class="btn btn-facebook"><i class="icon-fb"></i>Login with Facebook<i class="icon-fb-arrow"></i></a> </div> <div class="login-or">Or</div> <div class="login-input-area"> <form method="POST" action="dashboard.php"> <span class="help-block">Login With Your Photon Account</span> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button type="submit" class="btn btn-large btn-success btn-login">Login</button> </form> <a href="jquery.flot.resize.js.html#" class="forgot-pass">Forgot Your Password?</a> </div> </div> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-1936460-27']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
{ "content_hash": "f264cb85f78b3e664aca739b4799589e", "timestamp": "", "source": "github", "line_count": 182, "max_line_length": 243, "avg_line_length": 87.92857142857143, "alnum_prop": 0.7448603386864963, "repo_name": "user-tony/photon-rails", "id": "a42b40f83261b69496471c7de7ca655bf2131284", "size": "16003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/assets/css/css_compiled/@{photonImagePath}plugins/elrte/css/css_compiled/js/plugins/prettify/css/css_compiled/js/plugins/jquery.flot.resize.js.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "291750913" }, { "name": "JavaScript", "bytes": "59305" }, { "name": "Ruby", "bytes": "203" }, { "name": "Shell", "bytes": "99" } ], "symlink_target": "" }
package bq.jpa.demo.inherit.pertable.domain; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Entity; /** * <b> </b> * * <p> override parent entity attributes </p> * * @author Jonathan Q. Bo (jonathan.q.bo@gmail.com) * * Created at Feb 10, 2014 9:18:29 PM * */ @Entity(name="jpa_inherit_pertable_contract") @AttributeOverrides({ @AttributeOverride(name="name", column=@Column(name="fullname")), @AttributeOverride(name="startDate", column=@Column(name="sdate")) }) public class ContractEmployee extends Employee{ private int dailyRate; private int term; public int getDailyRate() { return dailyRate; } public void setDailyRate(int dailyRate) { this.dailyRate = dailyRate; } public int getTerm() { return term; } public void setTerm(int term) { this.term = term; } }
{ "content_hash": "63a57858b7dafa73edb0018c701a3b3c", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 68, "avg_line_length": 19.340425531914892, "alnum_prop": 0.7150715071507151, "repo_name": "jonathanqbo/jpa", "id": "c9aec87cd303fd4ccc1a551077f4e92842f4e630", "size": "2023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/bq/jpa/demo/inherit/pertable/domain/ContractEmployee.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "303108" } ], "symlink_target": "" }
package org.spongycastle.pqc.crypto.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import junit.framework.TestCase; import org.spongycastle.pqc.crypto.ntru.NTRUSigningKeyGenerationParameters; public class NTRUSigningParametersTest extends TestCase { public void testLoadSave() throws IOException { for (NTRUSigningKeyGenerationParameters params : new NTRUSigningKeyGenerationParameters[]{NTRUSigningKeyGenerationParameters.TEST157, NTRUSigningKeyGenerationParameters.TEST157_PROD}) { testLoadSave(params); } } private void testLoadSave(NTRUSigningKeyGenerationParameters params) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); params.writeTo(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); assertEquals(params, new NTRUSigningKeyGenerationParameters(is)); } public void testEqualsHashCode() throws IOException { for (NTRUSigningKeyGenerationParameters params : new NTRUSigningKeyGenerationParameters[]{NTRUSigningKeyGenerationParameters.TEST157, NTRUSigningKeyGenerationParameters.TEST157_PROD}) { testEqualsHashCode(params); } } private void testEqualsHashCode(NTRUSigningKeyGenerationParameters params) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); params.writeTo(os); ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); NTRUSigningKeyGenerationParameters params2 = new NTRUSigningKeyGenerationParameters(is); assertEquals(params, params2); assertEquals(params.hashCode(), params2.hashCode()); params.N += 1; assertFalse(params.equals(params2)); assertFalse(params.equals(params2)); assertFalse(params.hashCode() == params2.hashCode()); } public void testClone() { for (NTRUSigningKeyGenerationParameters params : new NTRUSigningKeyGenerationParameters[]{NTRUSigningKeyGenerationParameters.TEST157, NTRUSigningKeyGenerationParameters.TEST157_PROD}) { assertEquals(params, params.clone()); } } }
{ "content_hash": "d9abeb27f4f4e42abb49afebc1f6a7f6", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 191, "avg_line_length": 35.215384615384615, "alnum_prop": 0.7247706422018348, "repo_name": "FAU-Inf2/spongycastle", "id": "b9129f003f6a65cc9f4d56650e6982fd39073c91", "size": "2289", "binary": false, "copies": "7", "ref": "refs/heads/spongy-master", "path": "core/src/test/java/org/spongycastle/pqc/crypto/test/NTRUSigningParametersTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "54207" }, { "name": "Java", "bytes": "22605732" }, { "name": "Shell", "bytes": "74632" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe RecipeReviewPolicy do let(:user) { User.new } subject { described_class } permissions '.scope' do pending "add some examples to (or delete) #{__FILE__}" end permissions :show? do pending "add some examples to (or delete) #{__FILE__}" end permissions :create? do pending "add some examples to (or delete) #{__FILE__}" end permissions :update? do pending "add some examples to (or delete) #{__FILE__}" end permissions :destroy? do pending "add some examples to (or delete) #{__FILE__}" end end
{ "content_hash": "b5270697ac873b9d4af9b5f9776a76d7", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 58, "avg_line_length": 22.307692307692307, "alnum_prop": 0.65, "repo_name": "jcpny1/recipe-cat", "id": "44c6ccc4475bae1028c7e298a90aa0fc139e93b7", "size": "580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/policies/recipe_review_policy_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "1055" }, { "name": "HTML", "bytes": "35993" }, { "name": "JavaScript", "bytes": "185477" }, { "name": "Ruby", "bytes": "124463" }, { "name": "SCSS", "bytes": "2390" }, { "name": "Shell", "bytes": "192" } ], "symlink_target": "" }
/* globals describe, beforeEach, afterEach, it, expect, jasmine, localStorage */ var LocalStorage = require('./local-storage'); var randomStrings = []; function randomString() { 'use strict'; function randomChar() { return String.fromCharCode(32 + Math.floor(Math.random() * 95)); } function randomChars(length) { var result = ''; for (var i = length; i > 0; i--) { result += randomChar(); } return result; } var result; do { result = randomChars(1 + Math.floor(Math.random() * 10)); } while (randomStrings.indexOf(result) >= 0); randomStrings.push(result); return result; } describe('local-storage', function () { 'use strict'; var TESTS = [ ['null', null], ['text', 'a'], ['zero', 0], ['int', 10], ['float', 12.2], ['array', ['a', 0, {}]], ['object', {'a': 'a', 'b': 0, 'c': {}}] ]; // create a description for each value function describeTest(title, value, index) { describe('.. and for ' + title, function () { if (index === 0) { it('should be initially undefined', function () { expect(this.instance.get()).toBeUndefined(); }); } it('should be set without a return value', function () { expect(this.instance.put(value)).toBeUndefined(); }); it('should have the value when required', function () { this.instance.put(value); expect(this.instance.get()).toEqual(value); }); }); } // create a description for each key function describeForKey(storageKey) { describe('for key "' + storageKey + '"', function () { beforeEach(function () { this.instance = new LocalStorage(storageKey); }); it('should be an instance', function () { expect(this.instance).toEqual(jasmine.any(LocalStorage)); }); TESTS.forEach(function (args, i) { describeTest.apply(this, args.concat(i)); }); afterEach(function () { localStorage.clear(); }); }); } // attempt 3 random keys for (var i = 0; i < 3; i++) { describeForKey(randomString()); } });
{ "content_hash": "b20c95c63b86584c6ccea6530ab1d443", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 80, "avg_line_length": 28.352941176470587, "alnum_prop": 0.4995850622406639, "repo_name": "tosh001/demo", "id": "6dc2d4df2be2dfa2d8c468a81fcf57d5aef29802", "size": "2410", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "storage/local-storage.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "113" }, { "name": "HTML", "bytes": "843" }, { "name": "JavaScript", "bytes": "12253" }, { "name": "Ruby", "bytes": "2503" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_02) on Thu Sep 01 16:38:10 CEST 2005 --> <TITLE> net.sf.j2ep.requesthandlers Class Hierarchy </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="net.sf.j2ep.requesthandlers Class Hierarchy"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../net/sf/j2ep/model/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../net/sf/j2ep/responsehandlers/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/sf/j2ep/requesthandlers/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package net.sf.j2ep.requesthandlers </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">net.sf.j2ep.requesthandlers.<A HREF="../../../../net/sf/j2ep/requesthandlers/RequestHandlerBase.html" title="class in net.sf.j2ep.requesthandlers"><B>RequestHandlerBase</B></A> (implements net.sf.j2ep.model.<A HREF="../../../../net/sf/j2ep/model/RequestHandler.html" title="interface in net.sf.j2ep.model">RequestHandler</A>) <UL> <LI TYPE="circle">net.sf.j2ep.requesthandlers.<A HREF="../../../../net/sf/j2ep/requesthandlers/BasicRequestHandler.html" title="class in net.sf.j2ep.requesthandlers"><B>BasicRequestHandler</B></A><LI TYPE="circle">net.sf.j2ep.requesthandlers.<A HREF="../../../../net/sf/j2ep/requesthandlers/EntityEnclosingRequestHandler.html" title="class in net.sf.j2ep.requesthandlers"><B>EntityEnclosingRequestHandler</B></A><LI TYPE="circle">net.sf.j2ep.requesthandlers.<A HREF="../../../../net/sf/j2ep/requesthandlers/MaxForwardRequestHandler.html" title="class in net.sf.j2ep.requesthandlers"><B>MaxForwardRequestHandler</B></A></UL> </UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../net/sf/j2ep/model/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../net/sf/j2ep/responsehandlers/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?net/sf/j2ep/requesthandlers/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "0d78cff07008fb7cb421ff15df50d9cc", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 623, "avg_line_length": 43.86, "alnum_prop": 0.6317069463444293, "repo_name": "kidneyball/J2EP", "id": "186920518832bea37fe69ba1982ddf8effaf0702", "size": "6579", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/net/sf/j2ep/requesthandlers/package-tree.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "204990" } ], "symlink_target": "" }
/** * This class is generated by jOOQ */ package org.carbon.sample.ext.jooq; import javax.annotation.Generated; import org.carbon.sample.ext.jooq.tables.Asset; import org.carbon.sample.ext.jooq.tables.Lecturer; import org.carbon.sample.ext.jooq.tables.LecturerApplyHistory; import org.carbon.sample.ext.jooq.tables.LecturerRoom; import org.carbon.sample.ext.jooq.tables.LecturerSchedule; import org.carbon.sample.ext.jooq.tables.Product; import org.carbon.sample.ext.jooq.tables.Role; import org.carbon.sample.ext.jooq.tables.SchemaVersion; import org.carbon.sample.ext.jooq.tables.Student; import org.carbon.sample.ext.jooq.tables.User; /** * Convenience access to all tables in carbondb */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.6" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({"all", "unchecked", "rawtypes"}) public class Tables { /** * The table <code>carbondb.asset</code>. */ public static final Asset ASSET = org.carbon.sample.ext.jooq.tables.Asset.ASSET; /** * The table <code>carbondb.lecturer</code>. */ public static final Lecturer LECTURER = org.carbon.sample.ext.jooq.tables.Lecturer.LECTURER; /** * The table <code>carbondb.lecturer_apply_history</code>. */ public static final LecturerApplyHistory LECTURER_APPLY_HISTORY = org.carbon.sample.ext.jooq.tables.LecturerApplyHistory.LECTURER_APPLY_HISTORY; /** * The table <code>carbondb.lecturer_room</code>. */ public static final LecturerRoom LECTURER_ROOM = org.carbon.sample.ext.jooq.tables.LecturerRoom.LECTURER_ROOM; /** * The table <code>carbondb.lecturer_schedule</code>. */ public static final LecturerSchedule LECTURER_SCHEDULE = org.carbon.sample.ext.jooq.tables.LecturerSchedule.LECTURER_SCHEDULE; /** * The table <code>carbondb.product</code>. */ public static final Product PRODUCT = org.carbon.sample.ext.jooq.tables.Product.PRODUCT; /** * The table <code>carbondb.role</code>. */ public static final Role ROLE = org.carbon.sample.ext.jooq.tables.Role.ROLE; /** * The table <code>carbondb.schema_version</code>. */ public static final SchemaVersion SCHEMA_VERSION = org.carbon.sample.ext.jooq.tables.SchemaVersion.SCHEMA_VERSION; /** * The table <code>carbondb.student</code>. */ public static final Student STUDENT = org.carbon.sample.ext.jooq.tables.Student.STUDENT; /** * The table <code>carbondb.user</code>. */ public static final User USER = org.carbon.sample.ext.jooq.tables.User.USER; }
{ "content_hash": "6145de57ca56777ab10540ac7bd9283a", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 148, "avg_line_length": 32.21686746987952, "alnum_prop": 0.6948391922213911, "repo_name": "ShotaOd/dabunt", "id": "74ba116d700bed501e0c98f43621bed56873f2c5", "size": "2674", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "carbon-sample/src/main/java/org/carbon/sample/ext/jooq/Tables.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "449616" }, { "name": "Groovy", "bytes": "5623" }, { "name": "HTML", "bytes": "34461" }, { "name": "Java", "bytes": "217962" }, { "name": "JavaScript", "bytes": "309036" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace jarwin.State { public class StateFailedSyncing : StateAbstract { public StateFailedSyncing(bool isRefreshRequiredIn) { description = "Failed to sync..."; isRefreshRequired = isRefreshRequiredIn; } } }
{ "content_hash": "001ec911d8d730750ab96c2532d7757c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 59, "avg_line_length": 23.88235294117647, "alnum_prop": 0.6477832512315271, "repo_name": "jamescorbould/jarwin", "id": "a4e55b24be6818886749f285da23f6054042e06d", "size": "408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jarwin.State/StateFailedSyncing.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "78986" } ], "symlink_target": "" }
[Unconditional Loan Income](http://www.naturalfinance.net/2016/02/unconditional-loan-income-ubi-pilot.html) is a private or public (social) program that uses "soft loans" whose only repayment obligation is a royalty on future income. Special considerations for core/simple test are: 1. An automatic clawback (to repay previous loans) of new social loans takes place when the total outstanding balance exceeds a threshold cap. 2. A higher royalty rate applies when recipient's age is 65 or higher, and applies for both income and new ULI loans. When repayments are made, the first loan in queue (first loan taken out) is repaid with the payment. Special considerations **for bonus** are: 1. once repayments for a loan exceed (or equal) the principal amount, interest stops accruing, 2. there is a total repayment cap of 2x the principal for any loan (once cap is reached, 3. there may be a social guarantor for the loans, which will repay up to the loan principal upon the borrower's death. #sample test Given an interest rate, annual loan amount, starting age, royalty rate under age 65, clawback balance trigger, royalty rate over 65 and an annual (assumed) income stream, calculate total repayments and profit or loss: #sample input interest rate: 2% annual loan amount: $15000 start age: 18 clawback balance trigger: $100000 royalty rate (under 65): 20% royalty rate (over 65): 40% income stream: (in thousands) 0 0 20 20 20 20 20 20 20 20 20 20 30 30 30 30 30 30 30 30 30 30 40 40 40 40 40 40 40 40 40 40 50 50 50 50 50 50 50 50 50 50 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 #sample output (in thousands) Overall loans taken: $1080 Repayments from income: $280 Repayments from benefit clawbacks: $270 Ending balance with interest: $1169.09 #input #2 interest rate: 2% annual loan amount: $15000 start age: 18 clawback balance trigger: $100000 royalty rate (under 65): 20% royalty rate (over 65): 40% income stream: (in thousands) 0 0 30 30 30 30 30 30 30 30 30 30 40 40 40 40 40 40 40 40 40 40 50 50 50 50 50 50 50 50 50 50 60 60 60 60 60 60 60 60 60 60 100 120 140 160 200 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 # output #2 (in thousands) Overall loans taken: $1005 Repayments from income: $584 Repayments from benefit clawbacks: $237 Ending balance with interest: $509.487 #bonus Previous format allows calculations with a single running total. Adding the bonus special considerations means tracking each $15000 loan individually.
{ "content_hash": "3d176cf0453a67a0655d884efbb9e70f", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 233, "avg_line_length": 49.88461538461539, "alnum_prop": 0.7297609868928296, "repo_name": "FreddieV4/DailyProgrammerChallenges", "id": "e19a234c431496b52c85a1ef26abc4327f922745", "size": "2594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Easy Challenges/Challenge 0253 Easy - Unconditional Loan Income/challenge_text.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "184826" }, { "name": "C++", "bytes": "20049" }, { "name": "Common Lisp", "bytes": "567" }, { "name": "Crystal", "bytes": "81" }, { "name": "D", "bytes": "2372" }, { "name": "Elixir", "bytes": "621" }, { "name": "Go", "bytes": "1799" }, { "name": "Java", "bytes": "49443" }, { "name": "JavaScript", "bytes": "20193" }, { "name": "Matlab", "bytes": "2612" }, { "name": "Perl", "bytes": "6698" }, { "name": "Python", "bytes": "76412" }, { "name": "R", "bytes": "1011" }, { "name": "Ruby", "bytes": "7239" }, { "name": "Rust", "bytes": "3580" }, { "name": "Tcl", "bytes": "977" } ], "symlink_target": "" }
using namespace llvm; namespace { class MCAsmStreamer : public MCStreamer { protected: formatted_raw_ostream &OS; const MCAsmInfo *MAI; private: std::unique_ptr<MCInstPrinter> InstPrinter; std::unique_ptr<MCCodeEmitter> Emitter; std::unique_ptr<MCAsmBackend> AsmBackend; SmallString<128> CommentToEmit; raw_svector_ostream CommentStream; unsigned IsVerboseAsm : 1; unsigned ShowInst : 1; unsigned UseDwarfDirectory : 1; void EmitRegisterName(int64_t Register); void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override; void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override; public: MCAsmStreamer(MCContext &Context, formatted_raw_ostream &os, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *printer, MCCodeEmitter *emitter, MCAsmBackend *asmbackend, bool showInst) : MCStreamer(Context), OS(os), MAI(Context.getAsmInfo()), InstPrinter(printer), Emitter(emitter), AsmBackend(asmbackend), CommentStream(CommentToEmit), IsVerboseAsm(isVerboseAsm), ShowInst(showInst), UseDwarfDirectory(useDwarfDirectory) { if (InstPrinter && IsVerboseAsm) InstPrinter->setCommentStream(CommentStream); } inline void EmitEOL() { // If we don't have any comments, just emit a \n. if (!IsVerboseAsm) { OS << '\n'; return; } EmitCommentsAndEOL(); } void EmitCommentsAndEOL(); /// isVerboseAsm - Return true if this streamer supports verbose assembly at /// all. bool isVerboseAsm() const override { return IsVerboseAsm; } /// hasRawTextSupport - We support EmitRawText. bool hasRawTextSupport() const override { return true; } /// AddComment - Add a comment that can be emitted to the generated .s /// file if applicable as a QoI issue to make the output of the compiler /// more readable. This only affects the MCAsmStreamer, and only when /// verbose assembly output is enabled. void AddComment(const Twine &T) override; /// AddEncodingComment - Add a comment showing the encoding of an instruction. void AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &); /// GetCommentOS - Return a raw_ostream that comments can be written to. /// Unlike AddComment, you are required to terminate comments with \n if you /// use this method. raw_ostream &GetCommentOS() override { if (!IsVerboseAsm) return nulls(); // Discard comments unless in verbose asm mode. return CommentStream; } void emitRawComment(const Twine &T, bool TabPrefix = true) override; /// AddBlankLine - Emit a blank line to a .s file to pretty it up. void AddBlankLine() override { EmitEOL(); } /// @name MCStreamer Interface /// @{ void ChangeSection(const MCSection *Section, const MCExpr *Subsection) override; void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) override; void EmitLabel(MCSymbol *Symbol) override; void EmitAssemblerFlag(MCAssemblerFlag Flag) override; void EmitLinkerOptions(ArrayRef<std::string> Options) override; void EmitDataRegion(MCDataRegionType Kind) override; void EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor, unsigned Update) override; void EmitThumbFunc(MCSymbol *Func) override; void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override; void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override; bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override; void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override; void BeginCOFFSymbolDef(const MCSymbol *Symbol) override; void EmitCOFFSymbolStorageClass(int StorageClass) override; void EmitCOFFSymbolType(int Type) override; void EndCOFFSymbolDef() override; void EmitCOFFSectionIndex(MCSymbol const *Symbol) override; void EmitCOFFSecRel32(MCSymbol const *Symbol) override; void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) override; void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override; /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol. /// /// @param Symbol - The common symbol to emit. /// @param Size - The size of the common symbol. /// @param ByteAlignment - The alignment of the common symbol in bytes. void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) override; void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = nullptr, uint64_t Size = 0, unsigned ByteAlignment = 0) override; void EmitTBSSSymbol (const MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment = 0) override; void EmitBytes(StringRef Data) override; void EmitValueImpl(const MCExpr *Value, unsigned Size, const SMLoc &Loc = SMLoc()) override; void EmitIntValue(uint64_t Value, unsigned Size) override; void EmitULEB128Value(const MCExpr *Value) override; void EmitSLEB128Value(const MCExpr *Value) override; void EmitGPRel64Value(const MCExpr *Value) override; void EmitGPRel32Value(const MCExpr *Value) override; void EmitFill(uint64_t NumBytes, uint8_t FillValue) override; void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0, unsigned ValueSize = 1, unsigned MaxBytesToEmit = 0) override; void EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit = 0) override; bool EmitValueToOffset(const MCExpr *Offset, unsigned char Value = 0) override; void EmitFileDirective(StringRef Filename) override; unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, unsigned CUID = 0) override; void EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) override; MCSymbol *getDwarfLineTableSymbol(unsigned CUID) override; void EmitIdent(StringRef IdentString) override; void EmitCFISections(bool EH, bool Debug) override; void EmitCFIDefCfa(int64_t Register, int64_t Offset) override; void EmitCFIDefCfaOffset(int64_t Offset) override; void EmitCFIDefCfaRegister(int64_t Register) override; void EmitCFIOffset(int64_t Register, int64_t Offset) override; void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) override; void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) override; void EmitCFIRememberState() override; void EmitCFIRestoreState() override; void EmitCFISameValue(int64_t Register) override; void EmitCFIRelOffset(int64_t Register, int64_t Offset) override; void EmitCFIAdjustCfaOffset(int64_t Adjustment) override; void EmitCFISignalFrame() override; void EmitCFIUndefined(int64_t Register) override; void EmitCFIRegister(int64_t Register1, int64_t Register2) override; void EmitCFIWindowSave() override; void EmitWinCFIStartProc(const MCSymbol *Symbol) override; void EmitWinCFIEndProc() override; void EmitWinCFIStartChained() override; void EmitWinCFIEndChained() override; void EmitWinCFIPushReg(unsigned Register) override; void EmitWinCFISetFrame(unsigned Register, unsigned Offset) override; void EmitWinCFIAllocStack(unsigned Size) override; void EmitWinCFISaveReg(unsigned Register, unsigned Offset) override; void EmitWinCFISaveXMM(unsigned Register, unsigned Offset) override; void EmitWinCFIPushFrame(bool Code) override; void EmitWinCFIEndProlog() override; void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) override; void EmitWinEHHandlerData() override; void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) override; void EmitBundleAlignMode(unsigned AlignPow2) override; void EmitBundleLock(bool AlignToEnd) override; void EmitBundleUnlock() override; /// EmitRawText - If this file is backed by an assembly streamer, this dumps /// the specified string in the output .s file. This capability is /// indicated by the hasRawTextSupport() predicate. void EmitRawTextImpl(StringRef String) override; void FinishImpl() override; }; } // end anonymous namespace. /// AddComment - Add a comment that can be emitted to the generated .s /// file if applicable as a QoI issue to make the output of the compiler /// more readable. This only affects the MCAsmStreamer, and only when /// verbose assembly output is enabled. void MCAsmStreamer::AddComment(const Twine &T) { if (!IsVerboseAsm) return; // Make sure that CommentStream is flushed. CommentStream.flush(); T.toVector(CommentToEmit); // Each comment goes on its own line. CommentToEmit.push_back('\n'); // Tell the comment stream that the vector changed underneath it. CommentStream.resync(); } void MCAsmStreamer::EmitCommentsAndEOL() { if (CommentToEmit.empty() && CommentStream.GetNumBytesInBuffer() == 0) { OS << '\n'; return; } CommentStream.flush(); StringRef Comments = CommentToEmit.str(); assert(Comments.back() == '\n' && "Comment array not newline terminated"); do { // Emit a line of comments. OS.PadToColumn(MAI->getCommentColumn()); size_t Position = Comments.find('\n'); OS << MAI->getCommentString() << ' ' << Comments.substr(0, Position) <<'\n'; Comments = Comments.substr(Position+1); } while (!Comments.empty()); CommentToEmit.clear(); // Tell the comment stream that the vector changed underneath it. CommentStream.resync(); } static inline int64_t truncateToSize(int64_t Value, unsigned Bytes) { assert(Bytes && "Invalid size!"); return Value & ((uint64_t) (int64_t) -1 >> (64 - Bytes * 8)); } void MCAsmStreamer::emitRawComment(const Twine &T, bool TabPrefix) { if (TabPrefix) OS << '\t'; OS << MAI->getCommentString() << T; EmitEOL(); } void MCAsmStreamer::ChangeSection(const MCSection *Section, const MCExpr *Subsection) { assert(Section && "Cannot switch to a null section!"); Section->PrintSwitchToSection(*MAI, OS, Subsection); } void MCAsmStreamer::EmitLabel(MCSymbol *Symbol) { assert(Symbol->isUndefined() && "Cannot define a symbol twice!"); MCStreamer::EmitLabel(Symbol); OS << *Symbol << MAI->getLabelSuffix(); EmitEOL(); } void MCAsmStreamer::EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) { StringRef str = MCLOHIdToName(Kind); #ifndef NDEBUG int NbArgs = MCLOHIdToNbArgs(Kind); assert(NbArgs != -1 && ((size_t)NbArgs) == Args.size() && "Malformed LOH!"); assert(str != "" && "Invalid LOH name"); #endif OS << "\t" << MCLOHDirectiveName() << " " << str << "\t"; bool IsFirst = true; for (MCLOHArgs::const_iterator It = Args.begin(), EndIt = Args.end(); It != EndIt; ++It) { if (!IsFirst) OS << ", "; IsFirst = false; OS << **It; } EmitEOL(); } void MCAsmStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) { switch (Flag) { case MCAF_SyntaxUnified: OS << "\t.syntax unified"; break; case MCAF_SubsectionsViaSymbols: OS << ".subsections_via_symbols"; break; case MCAF_Code16: OS << '\t'<< MAI->getCode16Directive();break; case MCAF_Code32: OS << '\t'<< MAI->getCode32Directive();break; case MCAF_Code64: OS << '\t'<< MAI->getCode64Directive();break; } EmitEOL(); } void MCAsmStreamer::EmitLinkerOptions(ArrayRef<std::string> Options) { assert(!Options.empty() && "At least one option is required!"); OS << "\t.linker_option \"" << Options[0] << '"'; for (ArrayRef<std::string>::iterator it = Options.begin() + 1, ie = Options.end(); it != ie; ++it) { OS << ", " << '"' << *it << '"'; } OS << "\n"; } void MCAsmStreamer::EmitDataRegion(MCDataRegionType Kind) { if (!MAI->doesSupportDataRegionDirectives()) return; switch (Kind) { case MCDR_DataRegion: OS << "\t.data_region"; break; case MCDR_DataRegionJT8: OS << "\t.data_region jt8"; break; case MCDR_DataRegionJT16: OS << "\t.data_region jt16"; break; case MCDR_DataRegionJT32: OS << "\t.data_region jt32"; break; case MCDR_DataRegionEnd: OS << "\t.end_data_region"; break; } EmitEOL(); } void MCAsmStreamer::EmitVersionMin(MCVersionMinType Kind, unsigned Major, unsigned Minor, unsigned Update) { switch (Kind) { case MCVM_IOSVersionMin: OS << "\t.ios_version_min"; break; case MCVM_OSXVersionMin: OS << "\t.macosx_version_min"; break; } OS << " " << Major << ", " << Minor; if (Update) OS << ", " << Update; EmitEOL(); } void MCAsmStreamer::EmitThumbFunc(MCSymbol *Func) { // This needs to emit to a temporary string to get properly quoted // MCSymbols when they have spaces in them. OS << "\t.thumb_func"; // Only Mach-O hasSubsectionsViaSymbols() if (MAI->hasSubsectionsViaSymbols()) OS << '\t' << *Func; EmitEOL(); } void MCAsmStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) { OS << *Symbol << " = " << *Value; EmitEOL(); MCStreamer::EmitAssignment(Symbol, Value); } void MCAsmStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) { OS << ".weakref " << *Alias << ", " << *Symbol; EmitEOL(); } bool MCAsmStreamer::EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) { switch (Attribute) { case MCSA_Invalid: llvm_unreachable("Invalid symbol attribute"); case MCSA_ELF_TypeFunction: /// .type _foo, STT_FUNC # aka @function case MCSA_ELF_TypeIndFunction: /// .type _foo, STT_GNU_IFUNC case MCSA_ELF_TypeObject: /// .type _foo, STT_OBJECT # aka @object case MCSA_ELF_TypeTLS: /// .type _foo, STT_TLS # aka @tls_object case MCSA_ELF_TypeCommon: /// .type _foo, STT_COMMON # aka @common case MCSA_ELF_TypeNoType: /// .type _foo, STT_NOTYPE # aka @notype case MCSA_ELF_TypeGnuUniqueObject: /// .type _foo, @gnu_unique_object if (!MAI->hasDotTypeDotSizeDirective()) return false; // Symbol attribute not supported OS << "\t.type\t" << *Symbol << ',' << ((MAI->getCommentString()[0] != '@') ? '@' : '%'); switch (Attribute) { default: return false; case MCSA_ELF_TypeFunction: OS << "function"; break; case MCSA_ELF_TypeIndFunction: OS << "gnu_indirect_function"; break; case MCSA_ELF_TypeObject: OS << "object"; break; case MCSA_ELF_TypeTLS: OS << "tls_object"; break; case MCSA_ELF_TypeCommon: OS << "common"; break; case MCSA_ELF_TypeNoType: OS << "no_type"; break; case MCSA_ELF_TypeGnuUniqueObject: OS << "gnu_unique_object"; break; } EmitEOL(); return true; case MCSA_Global: // .globl/.global OS << MAI->getGlobalDirective(); break; case MCSA_Hidden: OS << "\t.hidden\t"; break; case MCSA_IndirectSymbol: OS << "\t.indirect_symbol\t"; break; case MCSA_Internal: OS << "\t.internal\t"; break; case MCSA_LazyReference: OS << "\t.lazy_reference\t"; break; case MCSA_Local: OS << "\t.local\t"; break; case MCSA_NoDeadStrip: OS << "\t.no_dead_strip\t"; break; case MCSA_SymbolResolver: OS << "\t.symbol_resolver\t"; break; case MCSA_PrivateExtern: OS << "\t.private_extern\t"; break; case MCSA_Protected: OS << "\t.protected\t"; break; case MCSA_Reference: OS << "\t.reference\t"; break; case MCSA_Weak: OS << "\t.weak\t"; break; case MCSA_WeakDefinition: OS << "\t.weak_definition\t"; break; // .weak_reference case MCSA_WeakReference: OS << MAI->getWeakRefDirective(); break; case MCSA_WeakDefAutoPrivate: OS << "\t.weak_def_can_be_hidden\t"; break; } OS << *Symbol; EmitEOL(); return true; } void MCAsmStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) { OS << ".desc" << ' ' << *Symbol << ',' << DescValue; EmitEOL(); } void MCAsmStreamer::BeginCOFFSymbolDef(const MCSymbol *Symbol) { OS << "\t.def\t " << *Symbol << ';'; EmitEOL(); } void MCAsmStreamer::EmitCOFFSymbolStorageClass (int StorageClass) { OS << "\t.scl\t" << StorageClass << ';'; EmitEOL(); } void MCAsmStreamer::EmitCOFFSymbolType (int Type) { OS << "\t.type\t" << Type << ';'; EmitEOL(); } void MCAsmStreamer::EndCOFFSymbolDef() { OS << "\t.endef"; EmitEOL(); } void MCAsmStreamer::EmitCOFFSectionIndex(MCSymbol const *Symbol) { OS << "\t.secidx\t" << *Symbol; EmitEOL(); } void MCAsmStreamer::EmitCOFFSecRel32(MCSymbol const *Symbol) { OS << "\t.secrel32\t" << *Symbol; EmitEOL(); } void MCAsmStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) { assert(MAI->hasDotTypeDotSizeDirective()); OS << "\t.size\t" << *Symbol << ", " << *Value << '\n'; } void MCAsmStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { // Common symbols do not belong to any actual section. AssignSection(Symbol, nullptr); OS << "\t.comm\t" << *Symbol << ',' << Size; if (ByteAlignment != 0) { if (MAI->getCOMMDirectiveAlignmentIsInBytes()) OS << ',' << ByteAlignment; else OS << ',' << Log2_32(ByteAlignment); } EmitEOL(); } /// EmitLocalCommonSymbol - Emit a local common (.lcomm) symbol. /// /// @param Symbol - The common symbol to emit. /// @param Size - The size of the common symbol. void MCAsmStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size, unsigned ByteAlign) { // Common symbols do not belong to any actual section. AssignSection(Symbol, nullptr); OS << "\t.lcomm\t" << *Symbol << ',' << Size; if (ByteAlign > 1) { switch (MAI->getLCOMMDirectiveAlignmentType()) { case LCOMM::NoAlignment: llvm_unreachable("alignment not supported on .lcomm!"); case LCOMM::ByteAlignment: OS << ',' << ByteAlign; break; case LCOMM::Log2Alignment: assert(isPowerOf2_32(ByteAlign) && "alignment must be a power of 2"); OS << ',' << Log2_32(ByteAlign); break; } } EmitEOL(); } void MCAsmStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { if (Symbol) AssignSection(Symbol, Section); // Note: a .zerofill directive does not switch sections. OS << ".zerofill "; // This is a mach-o specific directive. const MCSectionMachO *MOSection = ((const MCSectionMachO*)Section); OS << MOSection->getSegmentName() << "," << MOSection->getSectionName(); if (Symbol) { OS << ',' << *Symbol << ',' << Size; if (ByteAlignment != 0) OS << ',' << Log2_32(ByteAlignment); } EmitEOL(); } // .tbss sym, size, align // This depends that the symbol has already been mangled from the original, // e.g. _a. void MCAsmStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol, uint64_t Size, unsigned ByteAlignment) { AssignSection(Symbol, Section); assert(Symbol && "Symbol shouldn't be NULL!"); // Instead of using the Section we'll just use the shortcut. // This is a mach-o specific directive and section. OS << ".tbss " << *Symbol << ", " << Size; // Output align if we have it. We default to 1 so don't bother printing // that. if (ByteAlignment > 1) OS << ", " << Log2_32(ByteAlignment); EmitEOL(); } static inline char toOctal(int X) { return (X&7)+'0'; } static void PrintQuotedString(StringRef Data, raw_ostream &OS) { OS << '"'; for (unsigned i = 0, e = Data.size(); i != e; ++i) { unsigned char C = Data[i]; if (C == '"' || C == '\\') { OS << '\\' << (char)C; continue; } if (isprint((unsigned char)C)) { OS << (char)C; continue; } switch (C) { case '\b': OS << "\\b"; break; case '\f': OS << "\\f"; break; case '\n': OS << "\\n"; break; case '\r': OS << "\\r"; break; case '\t': OS << "\\t"; break; default: OS << '\\'; OS << toOctal(C >> 6); OS << toOctal(C >> 3); OS << toOctal(C >> 0); break; } } OS << '"'; } void MCAsmStreamer::EmitBytes(StringRef Data) { assert(getCurrentSection().first && "Cannot emit contents before setting section!"); if (Data.empty()) return; if (Data.size() == 1) { OS << MAI->getData8bitsDirective(); OS << (unsigned)(unsigned char)Data[0]; EmitEOL(); return; } // If the data ends with 0 and the target supports .asciz, use it, otherwise // use .ascii if (MAI->getAscizDirective() && Data.back() == 0) { OS << MAI->getAscizDirective(); Data = Data.substr(0, Data.size()-1); } else { OS << MAI->getAsciiDirective(); } PrintQuotedString(Data, OS); EmitEOL(); } void MCAsmStreamer::EmitIntValue(uint64_t Value, unsigned Size) { EmitValue(MCConstantExpr::Create(Value, getContext()), Size); } void MCAsmStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size, const SMLoc &Loc) { assert(Size <= 8 && "Invalid size"); assert(getCurrentSection().first && "Cannot emit contents before setting section!"); const char *Directive = nullptr; switch (Size) { default: break; case 1: Directive = MAI->getData8bitsDirective(); break; case 2: Directive = MAI->getData16bitsDirective(); break; case 4: Directive = MAI->getData32bitsDirective(); break; case 8: Directive = MAI->getData64bitsDirective(); break; } if (!Directive) { int64_t IntValue; if (!Value->EvaluateAsAbsolute(IntValue)) report_fatal_error("Don't know how to emit this value."); // We couldn't handle the requested integer size so we fallback by breaking // the request down into several, smaller, integers. Since sizes greater // than eight are invalid and size equivalent to eight should have been // handled earlier, we use four bytes as our largest piece of granularity. bool IsLittleEndian = MAI->isLittleEndian(); for (unsigned Emitted = 0; Emitted != Size;) { unsigned Remaining = Size - Emitted; // The size of our partial emission must be a power of two less than // eight. unsigned EmissionSize = PowerOf2Floor(Remaining); if (EmissionSize > 4) EmissionSize = 4; // Calculate the byte offset of our partial emission taking into account // the endianness of the target. unsigned ByteOffset = IsLittleEndian ? Emitted : (Remaining - EmissionSize); uint64_t ValueToEmit = IntValue >> (ByteOffset * 8); // We truncate our partial emission to fit within the bounds of the // emission domain. This produces nicer output and silences potential // truncation warnings when round tripping through another assembler. ValueToEmit &= ~0ULL >> (64 - EmissionSize * 8); EmitIntValue(ValueToEmit, EmissionSize); Emitted += EmissionSize; } return; } assert(Directive && "Invalid size for machine code value!"); OS << Directive << *Value; EmitEOL(); } void MCAsmStreamer::EmitULEB128Value(const MCExpr *Value) { int64_t IntValue; if (Value->EvaluateAsAbsolute(IntValue)) { EmitULEB128IntValue(IntValue); return; } assert(MAI->hasLEB128() && "Cannot print a .uleb"); OS << ".uleb128 " << *Value; EmitEOL(); } void MCAsmStreamer::EmitSLEB128Value(const MCExpr *Value) { int64_t IntValue; if (Value->EvaluateAsAbsolute(IntValue)) { EmitSLEB128IntValue(IntValue); return; } assert(MAI->hasLEB128() && "Cannot print a .sleb"); OS << ".sleb128 " << *Value; EmitEOL(); } void MCAsmStreamer::EmitGPRel64Value(const MCExpr *Value) { assert(MAI->getGPRel64Directive() != nullptr); OS << MAI->getGPRel64Directive() << *Value; EmitEOL(); } void MCAsmStreamer::EmitGPRel32Value(const MCExpr *Value) { assert(MAI->getGPRel32Directive() != nullptr); OS << MAI->getGPRel32Directive() << *Value; EmitEOL(); } /// EmitFill - Emit NumBytes bytes worth of the value specified by /// FillValue. This implements directives such as '.space'. void MCAsmStreamer::EmitFill(uint64_t NumBytes, uint8_t FillValue) { if (NumBytes == 0) return; if (const char *ZeroDirective = MAI->getZeroDirective()) { OS << ZeroDirective << NumBytes; if (FillValue != 0) OS << ',' << (int)FillValue; EmitEOL(); return; } // Emit a byte at a time. MCStreamer::EmitFill(NumBytes, FillValue); } void MCAsmStreamer::EmitValueToAlignment(unsigned ByteAlignment, int64_t Value, unsigned ValueSize, unsigned MaxBytesToEmit) { // Some assemblers don't support non-power of two alignments, so we always // emit alignments as a power of two if possible. if (isPowerOf2_32(ByteAlignment)) { switch (ValueSize) { default: llvm_unreachable("Invalid size for machine code value!"); case 1: OS << "\t.align\t"; break; case 2: OS << ".p2alignw "; break; case 4: OS << ".p2alignl "; break; case 8: llvm_unreachable("Unsupported alignment size!"); } if (MAI->getAlignmentIsInBytes()) OS << ByteAlignment; else OS << Log2_32(ByteAlignment); if (Value || MaxBytesToEmit) { OS << ", 0x"; OS.write_hex(truncateToSize(Value, ValueSize)); if (MaxBytesToEmit) OS << ", " << MaxBytesToEmit; } EmitEOL(); return; } // Non-power of two alignment. This is not widely supported by assemblers. // FIXME: Parameterize this based on MAI. switch (ValueSize) { default: llvm_unreachable("Invalid size for machine code value!"); case 1: OS << ".balign"; break; case 2: OS << ".balignw"; break; case 4: OS << ".balignl"; break; case 8: llvm_unreachable("Unsupported alignment size!"); } OS << ' ' << ByteAlignment; OS << ", " << truncateToSize(Value, ValueSize); if (MaxBytesToEmit) OS << ", " << MaxBytesToEmit; EmitEOL(); } void MCAsmStreamer::EmitCodeAlignment(unsigned ByteAlignment, unsigned MaxBytesToEmit) { // Emit with a text fill value. EmitValueToAlignment(ByteAlignment, MAI->getTextAlignFillValue(), 1, MaxBytesToEmit); } bool MCAsmStreamer::EmitValueToOffset(const MCExpr *Offset, unsigned char Value) { // FIXME: Verify that Offset is associated with the current section. OS << ".org " << *Offset << ", " << (unsigned) Value; EmitEOL(); return false; } void MCAsmStreamer::EmitFileDirective(StringRef Filename) { assert(MAI->hasSingleParameterDotFile()); OS << "\t.file\t"; PrintQuotedString(Filename, OS); EmitEOL(); } unsigned MCAsmStreamer::EmitDwarfFileDirective(unsigned FileNo, StringRef Directory, StringRef Filename, unsigned CUID) { assert(CUID == 0); MCDwarfLineTable &Table = getContext().getMCDwarfLineTable(CUID); unsigned NumFiles = Table.getMCDwarfFiles().size(); FileNo = Table.getFile(Directory, Filename, FileNo); if (FileNo == 0) return 0; if (NumFiles == Table.getMCDwarfFiles().size()) return FileNo; SmallString<128> FullPathName; if (!UseDwarfDirectory && !Directory.empty()) { if (sys::path::is_absolute(Filename)) Directory = ""; else { FullPathName = Directory; sys::path::append(FullPathName, Filename); Directory = ""; Filename = FullPathName; } } OS << "\t.file\t" << FileNo << ' '; if (!Directory.empty()) { PrintQuotedString(Directory, OS); OS << ' '; } PrintQuotedString(Filename, OS); EmitEOL(); return FileNo; } void MCAsmStreamer::EmitDwarfLocDirective(unsigned FileNo, unsigned Line, unsigned Column, unsigned Flags, unsigned Isa, unsigned Discriminator, StringRef FileName) { this->MCStreamer::EmitDwarfLocDirective(FileNo, Line, Column, Flags, Isa, Discriminator, FileName); OS << "\t.loc\t" << FileNo << " " << Line << " " << Column; if (Flags & DWARF2_FLAG_BASIC_BLOCK) OS << " basic_block"; if (Flags & DWARF2_FLAG_PROLOGUE_END) OS << " prologue_end"; if (Flags & DWARF2_FLAG_EPILOGUE_BEGIN) OS << " epilogue_begin"; unsigned OldFlags = getContext().getCurrentDwarfLoc().getFlags(); if ((Flags & DWARF2_FLAG_IS_STMT) != (OldFlags & DWARF2_FLAG_IS_STMT)) { OS << " is_stmt "; if (Flags & DWARF2_FLAG_IS_STMT) OS << "1"; else OS << "0"; } if (Isa) OS << " isa " << Isa; if (Discriminator) OS << " discriminator " << Discriminator; if (IsVerboseAsm) { OS.PadToColumn(MAI->getCommentColumn()); OS << MAI->getCommentString() << ' ' << FileName << ':' << Line << ':' << Column; } EmitEOL(); } MCSymbol *MCAsmStreamer::getDwarfLineTableSymbol(unsigned CUID) { // Always use the zeroth line table, since asm syntax only supports one line // table for now. return MCStreamer::getDwarfLineTableSymbol(0); } void MCAsmStreamer::EmitIdent(StringRef IdentString) { assert(MAI->hasIdentDirective() && ".ident directive not supported"); OS << "\t.ident\t"; PrintQuotedString(IdentString, OS); EmitEOL(); } void MCAsmStreamer::EmitCFISections(bool EH, bool Debug) { MCStreamer::EmitCFISections(EH, Debug); OS << "\t.cfi_sections "; if (EH) { OS << ".eh_frame"; if (Debug) OS << ", .debug_frame"; } else if (Debug) { OS << ".debug_frame"; } EmitEOL(); } void MCAsmStreamer::EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) { OS << "\t.cfi_startproc"; if (Frame.IsSimple) OS << " simple"; EmitEOL(); } void MCAsmStreamer::EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) { MCStreamer::EmitCFIEndProcImpl(Frame); OS << "\t.cfi_endproc"; EmitEOL(); } void MCAsmStreamer::EmitRegisterName(int64_t Register) { if (InstPrinter && !MAI->useDwarfRegNumForCFI()) { const MCRegisterInfo *MRI = getContext().getRegisterInfo(); unsigned LLVMRegister = MRI->getLLVMRegNum(Register, true); InstPrinter->printRegName(OS, LLVMRegister); } else { OS << Register; } } void MCAsmStreamer::EmitCFIDefCfa(int64_t Register, int64_t Offset) { MCStreamer::EmitCFIDefCfa(Register, Offset); OS << "\t.cfi_def_cfa "; EmitRegisterName(Register); OS << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIDefCfaOffset(int64_t Offset) { MCStreamer::EmitCFIDefCfaOffset(Offset); OS << "\t.cfi_def_cfa_offset " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIDefCfaRegister(int64_t Register) { MCStreamer::EmitCFIDefCfaRegister(Register); OS << "\t.cfi_def_cfa_register "; EmitRegisterName(Register); EmitEOL(); } void MCAsmStreamer::EmitCFIOffset(int64_t Register, int64_t Offset) { this->MCStreamer::EmitCFIOffset(Register, Offset); OS << "\t.cfi_offset "; EmitRegisterName(Register); OS << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding) { MCStreamer::EmitCFIPersonality(Sym, Encoding); OS << "\t.cfi_personality " << Encoding << ", " << *Sym; EmitEOL(); } void MCAsmStreamer::EmitCFILsda(const MCSymbol *Sym, unsigned Encoding) { MCStreamer::EmitCFILsda(Sym, Encoding); OS << "\t.cfi_lsda " << Encoding << ", " << *Sym; EmitEOL(); } void MCAsmStreamer::EmitCFIRememberState() { MCStreamer::EmitCFIRememberState(); OS << "\t.cfi_remember_state"; EmitEOL(); } void MCAsmStreamer::EmitCFIRestoreState() { MCStreamer::EmitCFIRestoreState(); OS << "\t.cfi_restore_state"; EmitEOL(); } void MCAsmStreamer::EmitCFISameValue(int64_t Register) { MCStreamer::EmitCFISameValue(Register); OS << "\t.cfi_same_value "; EmitRegisterName(Register); EmitEOL(); } void MCAsmStreamer::EmitCFIRelOffset(int64_t Register, int64_t Offset) { MCStreamer::EmitCFIRelOffset(Register, Offset); OS << "\t.cfi_rel_offset "; EmitRegisterName(Register); OS << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitCFIAdjustCfaOffset(int64_t Adjustment) { MCStreamer::EmitCFIAdjustCfaOffset(Adjustment); OS << "\t.cfi_adjust_cfa_offset " << Adjustment; EmitEOL(); } void MCAsmStreamer::EmitCFISignalFrame() { MCStreamer::EmitCFISignalFrame(); OS << "\t.cfi_signal_frame"; EmitEOL(); } void MCAsmStreamer::EmitCFIUndefined(int64_t Register) { MCStreamer::EmitCFIUndefined(Register); OS << "\t.cfi_undefined " << Register; EmitEOL(); } void MCAsmStreamer::EmitCFIRegister(int64_t Register1, int64_t Register2) { MCStreamer::EmitCFIRegister(Register1, Register2); OS << "\t.cfi_register " << Register1 << ", " << Register2; EmitEOL(); } void MCAsmStreamer::EmitCFIWindowSave() { MCStreamer::EmitCFIWindowSave(); OS << "\t.cfi_window_save"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIStartProc(const MCSymbol *Symbol) { MCStreamer::EmitWinCFIStartProc(Symbol); OS << ".seh_proc " << *Symbol; EmitEOL(); } void MCAsmStreamer::EmitWinCFIEndProc() { MCStreamer::EmitWinCFIEndProc(); OS << "\t.seh_endproc"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIStartChained() { MCStreamer::EmitWinCFIStartChained(); OS << "\t.seh_startchained"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIEndChained() { MCStreamer::EmitWinCFIEndChained(); OS << "\t.seh_endchained"; EmitEOL(); } void MCAsmStreamer::EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except) { MCStreamer::EmitWinEHHandler(Sym, Unwind, Except); OS << "\t.seh_handler " << *Sym; if (Unwind) OS << ", @unwind"; if (Except) OS << ", @except"; EmitEOL(); } static const MCSection *getWin64EHTableSection(StringRef suffix, MCContext &context) { // FIXME: This doesn't belong in MCObjectFileInfo. However, /// this duplicate code in MCWin64EH.cpp. if (suffix == "") return context.getObjectFileInfo()->getXDataSection(); return context.getCOFFSection((".xdata"+suffix).str(), COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, SectionKind::getDataRel()); } void MCAsmStreamer::EmitWinEHHandlerData() { MCStreamer::EmitWinEHHandlerData(); // Switch sections. Don't call SwitchSection directly, because that will // cause the section switch to be visible in the emitted assembly. // We only do this so the section switch that terminates the handler // data block is visible. MCWinFrameInfo *CurFrame = getCurrentWinFrameInfo(); StringRef suffix=MCWin64EHUnwindEmitter::GetSectionSuffix(CurFrame->Function); const MCSection *xdataSect = getWin64EHTableSection(suffix, getContext()); if (xdataSect) SwitchSectionNoChange(xdataSect); OS << "\t.seh_handlerdata"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIPushReg(unsigned Register) { MCStreamer::EmitWinCFIPushReg(Register); OS << "\t.seh_pushreg " << Register; EmitEOL(); } void MCAsmStreamer::EmitWinCFISetFrame(unsigned Register, unsigned Offset) { MCStreamer::EmitWinCFISetFrame(Register, Offset); OS << "\t.seh_setframe " << Register << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitWinCFIAllocStack(unsigned Size) { MCStreamer::EmitWinCFIAllocStack(Size); OS << "\t.seh_stackalloc " << Size; EmitEOL(); } void MCAsmStreamer::EmitWinCFISaveReg(unsigned Register, unsigned Offset) { MCStreamer::EmitWinCFISaveReg(Register, Offset); OS << "\t.seh_savereg " << Register << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitWinCFISaveXMM(unsigned Register, unsigned Offset) { MCStreamer::EmitWinCFISaveXMM(Register, Offset); OS << "\t.seh_savexmm " << Register << ", " << Offset; EmitEOL(); } void MCAsmStreamer::EmitWinCFIPushFrame(bool Code) { MCStreamer::EmitWinCFIPushFrame(Code); OS << "\t.seh_pushframe"; if (Code) OS << " @code"; EmitEOL(); } void MCAsmStreamer::EmitWinCFIEndProlog(void) { MCStreamer::EmitWinCFIEndProlog(); OS << "\t.seh_endprologue"; EmitEOL(); } void MCAsmStreamer::AddEncodingComment(const MCInst &Inst, const MCSubtargetInfo &STI) { raw_ostream &OS = GetCommentOS(); SmallString<256> Code; SmallVector<MCFixup, 4> Fixups; raw_svector_ostream VecOS(Code); Emitter->EncodeInstruction(Inst, VecOS, Fixups, STI); VecOS.flush(); // If we are showing fixups, create symbolic markers in the encoded // representation. We do this by making a per-bit map to the fixup item index, // then trying to display it as nicely as possible. SmallVector<uint8_t, 64> FixupMap; FixupMap.resize(Code.size() * 8); for (unsigned i = 0, e = Code.size() * 8; i != e; ++i) FixupMap[i] = 0; for (unsigned i = 0, e = Fixups.size(); i != e; ++i) { MCFixup &F = Fixups[i]; const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind()); for (unsigned j = 0; j != Info.TargetSize; ++j) { unsigned Index = F.getOffset() * 8 + Info.TargetOffset + j; assert(Index < Code.size() * 8 && "Invalid offset in fixup!"); FixupMap[Index] = 1 + i; } } // FIXME: Note the fixup comments for Thumb2 are completely bogus since the // high order halfword of a 32-bit Thumb2 instruction is emitted first. OS << "encoding: ["; for (unsigned i = 0, e = Code.size(); i != e; ++i) { if (i) OS << ','; // See if all bits are the same map entry. uint8_t MapEntry = FixupMap[i * 8 + 0]; for (unsigned j = 1; j != 8; ++j) { if (FixupMap[i * 8 + j] == MapEntry) continue; MapEntry = uint8_t(~0U); break; } if (MapEntry != uint8_t(~0U)) { if (MapEntry == 0) { OS << format("0x%02x", uint8_t(Code[i])); } else { if (Code[i]) { // FIXME: Some of the 8 bits require fix up. OS << format("0x%02x", uint8_t(Code[i])) << '\'' << char('A' + MapEntry - 1) << '\''; } else OS << char('A' + MapEntry - 1); } } else { // Otherwise, write out in binary. OS << "0b"; for (unsigned j = 8; j--;) { unsigned Bit = (Code[i] >> j) & 1; unsigned FixupBit; if (MAI->isLittleEndian()) FixupBit = i * 8 + j; else FixupBit = i * 8 + (7-j); if (uint8_t MapEntry = FixupMap[FixupBit]) { assert(Bit == 0 && "Encoder wrote into fixed up bit!"); OS << char('A' + MapEntry - 1); } else OS << Bit; } } } OS << "]\n"; for (unsigned i = 0, e = Fixups.size(); i != e; ++i) { MCFixup &F = Fixups[i]; const MCFixupKindInfo &Info = AsmBackend->getFixupKindInfo(F.getKind()); OS << " fixup " << char('A' + i) << " - " << "offset: " << F.getOffset() << ", value: " << *F.getValue() << ", kind: " << Info.Name << "\n"; } } void MCAsmStreamer::EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI) { assert(getCurrentSection().first && "Cannot emit contents before setting section!"); // Show the encoding in a comment if we have a code emitter. if (Emitter) AddEncodingComment(Inst, STI); // Show the MCInst if enabled. if (ShowInst) { Inst.dump_pretty(GetCommentOS(), MAI, InstPrinter.get(), "\n "); GetCommentOS() << "\n"; } // If we have an AsmPrinter, use that to print, otherwise print the MCInst. if (InstPrinter) InstPrinter->printInst(&Inst, OS, ""); else Inst.print(OS, MAI); EmitEOL(); } void MCAsmStreamer::EmitBundleAlignMode(unsigned AlignPow2) { OS << "\t.bundle_align_mode " << AlignPow2; EmitEOL(); } void MCAsmStreamer::EmitBundleLock(bool AlignToEnd) { OS << "\t.bundle_lock"; if (AlignToEnd) OS << " align_to_end"; EmitEOL(); } void MCAsmStreamer::EmitBundleUnlock() { OS << "\t.bundle_unlock"; EmitEOL(); } /// EmitRawText - If this file is backed by an assembly streamer, this dumps /// the specified string in the output .s file. This capability is /// indicated by the hasRawTextSupport() predicate. void MCAsmStreamer::EmitRawTextImpl(StringRef String) { if (!String.empty() && String.back() == '\n') String = String.substr(0, String.size()-1); OS << String; EmitEOL(); } void MCAsmStreamer::FinishImpl() { // If we are generating dwarf for assembly source files dump out the sections. if (getContext().getGenDwarfForAssembly()) MCGenDwarfInfo::Emit(this); // Emit the label for the line table, if requested - since the rest of the // line table will be defined by .loc/.file directives, and not emitted // directly, the label is the only work required here. auto &Tables = getContext().getMCDwarfLineTables(); if (!Tables.empty()) { assert(Tables.size() == 1 && "asm output only supports one line table"); if (auto *Label = Tables.begin()->second.getLabel()) { SwitchSection(getContext().getObjectFileInfo()->getDwarfLineSection()); EmitLabel(Label); } } } MCStreamer *llvm::createAsmStreamer(MCContext &Context, formatted_raw_ostream &OS, bool isVerboseAsm, bool useDwarfDirectory, MCInstPrinter *IP, MCCodeEmitter *CE, MCAsmBackend *MAB, bool ShowInst) { return new MCAsmStreamer(Context, OS, isVerboseAsm, useDwarfDirectory, IP, CE, MAB, ShowInst); }
{ "content_hash": "1e90039bfb6204fea628d11de99adbd8", "timestamp": "", "source": "github", "line_count": 1297, "max_line_length": 85, "avg_line_length": 32.48573631457209, "alnum_prop": 0.6417857312384297, "repo_name": "zakki/openhsp", "id": "14f0f05edd1f6fd12ab568733b5fcfb378eaa4ea", "size": "43335", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "hsp3ll/llvm/lib/MC/MCAsmStreamer.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "150345" }, { "name": "AngelScript", "bytes": "415842" }, { "name": "Assembly", "bytes": "6835762" }, { "name": "Awk", "bytes": "8286" }, { "name": "Batchfile", "bytes": "17416" }, { "name": "C", "bytes": "44323065" }, { "name": "C++", "bytes": "77401621" }, { "name": "CMake", "bytes": "327385" }, { "name": "CSS", "bytes": "65110" }, { "name": "DIGITAL Command Language", "bytes": "74194" }, { "name": "Emacs Lisp", "bytes": "11716" }, { "name": "GLSL", "bytes": "243100" }, { "name": "HTML", "bytes": "15891798" }, { "name": "Haskell", "bytes": "2139250" }, { "name": "Java", "bytes": "101998" }, { "name": "JavaScript", "bytes": "218752" }, { "name": "LLVM", "bytes": "26468545" }, { "name": "Lua", "bytes": "1143" }, { "name": "M4", "bytes": "184884" }, { "name": "Makefile", "bytes": "676117" }, { "name": "Mathematica", "bytes": "20070" }, { "name": "Monkey C", "bytes": "274" }, { "name": "NASL", "bytes": "9831" }, { "name": "OCaml", "bytes": "378127" }, { "name": "Objective-C", "bytes": "18168" }, { "name": "Objective-C++", "bytes": "663471" }, { "name": "Perl", "bytes": "55068" }, { "name": "Python", "bytes": "845989" }, { "name": "Roff", "bytes": "23681" }, { "name": "Shell", "bytes": "842849" }, { "name": "Vim Script", "bytes": "13176" }, { "name": "sed", "bytes": "482" } ], "symlink_target": "" }
// Generated Source interface ParsePhoneNumberRequest { /** * Phone numbers passed in a string. The maximum value of phone numbers is limited to 64. The maximum number of symbols in each phone number in a string is 64 */ originalStrings?: string; } export default ParsePhoneNumberRequest;
{ "content_hash": "9640ec02fc99943bf375f2d7179c9f92", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 162, "avg_line_length": 28.181818181818183, "alnum_prop": 0.7354838709677419, "repo_name": "ringcentral/ringcentral-js-client", "id": "6bb105974a4b1fa546da2f20478b9670aab93768", "size": "310", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/definitions/ParsePhoneNumberRequest.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2462" }, { "name": "JavaScript", "bytes": "4782" }, { "name": "Shell", "bytes": "953" }, { "name": "TypeScript", "bytes": "572774" } ], "symlink_target": "" }
<?php namespace ZpgRtf\Objects; /** * The description is expressed as an array of description objects, each of which represent a paragraph or section. */ class DescriptionObject implements \JsonSerializable { /** @var null|string */ private $heading; /** @var null|DimensionsObject */ private $dimensions; /** @var null|string */ private $text; /** * @return null|string */ public function getHeading() { return $this->heading; } /** * @param string $heading * * @return DescriptionObject */ public function setHeading(string $heading): self { $this->heading = $heading; return $this; } /** * @return null|DimensionsObject */ public function getDimensions() { return $this->dimensions; } /** * @param DimensionsObject $dimensions * * @return DescriptionObject */ public function setDimensions(DimensionsObject $dimensions): self { $this->dimensions = $dimensions; return $this; } /** * @return null|string */ public function getText() { return $this->text; } /** * @param string $text * * @return DescriptionObject */ public function setText(string $text): self { $this->text = $text; return $this; } /** {@inheritDoc} */ public function jsonSerialize(): array { return array_filter([ 'heading' => $this->getHeading(), 'dimensions' => $this->getDimensions(), 'text' => $this->getText(), ]); } }
{ "content_hash": "944fb22fd4a3cd95b7d680613945f1a2", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 115, "avg_line_length": 18.875, "alnum_prop": 0.5478627332931969, "repo_name": "lukeoliff/zpg-rtf-php", "id": "eca24c88be9b4718d4d8dfbd76ce93df212e199e", "size": "1661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Objects/DescriptionObject.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "150151" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LiveDocs.Diagrams.Examples.Console")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LiveDocs.Diagrams.Examples.Console")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("627ce748-403d-4ec8-b0a3-c09ee6f147c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "fce6cfc75a51af8a6975956524a5d29c", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 40.02777777777778, "alnum_prop": 0.7487855655794587, "repo_name": "devdigital/LiveDocs", "id": "57f67862c1eb9c40c458646398770a4bd401a9f0", "size": "1444", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Examples/LiveDocs.Diagrams.Examples.Console/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "167166" } ], "symlink_target": "" }
 #include <aws/license-manager/model/RenewType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace LicenseManager { namespace Model { namespace RenewTypeMapper { static const int None_HASH = HashingUtils::HashString("None"); static const int Weekly_HASH = HashingUtils::HashString("Weekly"); static const int Monthly_HASH = HashingUtils::HashString("Monthly"); RenewType GetRenewTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == None_HASH) { return RenewType::None; } else if (hashCode == Weekly_HASH) { return RenewType::Weekly; } else if (hashCode == Monthly_HASH) { return RenewType::Monthly; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<RenewType>(hashCode); } return RenewType::NOT_SET; } Aws::String GetNameForRenewType(RenewType enumValue) { switch(enumValue) { case RenewType::None: return "None"; case RenewType::Weekly: return "Weekly"; case RenewType::Monthly: return "Monthly"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace RenewTypeMapper } // namespace Model } // namespace LicenseManager } // namespace Aws
{ "content_hash": "aab091dc3b756225f8a4532fea3d609a", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 92, "avg_line_length": 27.39189189189189, "alnum_prop": 0.5806610754810064, "repo_name": "cedral/aws-sdk-cpp", "id": "29074a6d687a22a2d82cffdecfc2d3693e02a260", "size": "2146", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "aws-cpp-sdk-license-manager/source/model/RenewType.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
import subprocess import os from glim.core import Facade from glim import Log from glim import paths OPTION_MAP = { 'nojs': '--no-js', 'lint': '--lint', 'verbose': '--verbose', 'units': '-sm=on', 'compress': '--compress' } DEFAULT_CONFIG = { 'source': os.path.join(paths.APP_PATH, 'assets/less/main.less'), 'destination': os.path.join(paths.APP_PATH, 'assets/css/main.css'), 'options': [ 'lint', 'units', 'verbose' ] } class Less(object): def __init__(self, config): self.config = DEFAULT_CONFIG for key, value in config.items(): self.config[key] = value # Log.info("config") # Log.info(self.config) def compile(self): source = self.config['source'] destination = self.config['destination'] options = self.config['options'] try: options_string = '' for option in options: options_string += '%s ' % OPTION_MAP[option] options_string = options_string.rstrip() command = 'lessc' arguments = '%s %s > %s' % (options_string, source, destination) # Log.debug("command: %s" % command) # Log.debug("arguments: %s" % arguments) cmd = '%s %s' % (command, arguments) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() Log.info("Compiling LESS source..") except Exception as e: Log.error(e) class LessFacade(Facade): accessor = Less
{ "content_hash": "3dcf9bb4a74e8278c054daf01cd00568", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 68, "avg_line_length": 21.890625, "alnum_prop": 0.635260528194147, "repo_name": "aacanakin/glim-extensions", "id": "9b5dcf78f4b4bb31bdbede42b67cc66f64aac0f6", "size": "1401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "glim_extensions/less/less.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "26739" } ], "symlink_target": "" }
require 'faraday' require 'faraday_middleware' require 'spyke/config' require 'spyke/path' require 'spyke/result' module Spyke module Http extend ActiveSupport::Concern METHODS = %i{ get post put patch delete } included do class_attribute :connection, instance_accessor: false end module ClassMethods METHODS.each do |method| define_method(method) do new_instance_or_collection_from_result scoped_request(method) end end def request(method, path, params = {}) ActiveSupport::Notifications.instrument('request.spyke', method: method) do |payload| response = connection.send(method) do |request| if method == :get request.url path.to_s, params else request.url path.to_s request.body = params end end payload[:url], payload[:status] = response.env.url, response.status Result.new_from_response(response) end end def new_instance_from_result(result) new_or_return result.data if result.data end def new_collection_from_result(result) Collection.new Array(result.data).map { |record| new_or_return(record) }, result.metadata end def uri(uri_template = nil) @uri ||= uri_template || default_uri end private def scoped_request(method) uri = new.uri params = current_scope.params.except(*uri.variables) request(method, uri, params) end def new_instance_or_collection_from_result(result) if result.data.is_a?(Array) new_collection_from_result(result) else new_instance_from_result(result) end end def new_or_return(attributes_or_object) if attributes_or_object.is_a?(Spyke::Base) attributes_or_object else new attributes_or_object end end def default_uri "#{model_name.element.pluralize}/(:id)" end end METHODS.each do |method| define_method(method) do |action = nil, params = {}| params = action if action.is_a?(Hash) path = resolve_path_from_action(action) result = self.class.request(method, path, params) add_errors_to_model(result.errors) self.attributes = result.data end end def uri Path.new(@uri_template, attributes) if @uri_template end private def add_errors_to_model(errors_hash) errors_hash.each do |field, field_errors| field_errors.each do |attributes| error_name = attributes.delete(:error).to_sym errors.add(field.to_sym, error_name, attributes.symbolize_keys) end end end def resolve_path_from_action(action) case action when Symbol then uri.join(action) when String then Path.new(action, attributes) else uri end end end end
{ "content_hash": "91d1ca2af385e02ecd10ffe025f797c4", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 97, "avg_line_length": 26.780701754385966, "alnum_prop": 0.5941696691778579, "repo_name": "Pamplemousse/spyke", "id": "ea9b2ebe7f29d223dd3fa84cc593791baa1d5728", "size": "3053", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/spyke/http.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "64691" } ], "symlink_target": "" }
namespace Idecom.Bus.Utility { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; [DebuggerStepThrough] public static class InterfaceImplementor { static readonly Dictionary<Type, Type> ImplementationCache = new Dictionary<Type, Type>(); static readonly object SyncRoot = new object(); static readonly ModuleBuilder ModuleBuilder; static InterfaceImplementor() { lock (SyncRoot) { if (ModuleBuilder != null) return; var assemblyName = new AssemblyName(String.Format("GeneratedInterfaceImplementation_{0}", Guid.NewGuid().ToString("N"))); var appDomain = AppDomain.CurrentDomain; var assemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); } } public static Type ImplementInterface(Type @interface) { if (!@interface.IsInterface) throw new Exception(string.Format("Could not implement {0} as it is not an interface", @interface.Name)); if (ImplementationCache.ContainsKey(@interface)) { return ImplementationCache[@interface]; } var typeBuilder = ModuleBuilder.DefineType(string.Format("{0}_{1}", @interface.Name, Guid.NewGuid().ToString("N")), TypeAttributes.Serializable | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed); typeBuilder.AddInterfaceImplementation(@interface); var props = GetAllProperties(@interface); foreach (var prop in props) DefineProperty(typeBuilder, prop); var newType = typeBuilder.CreateType(); lock (SyncRoot) if (!ImplementationCache.ContainsKey(@interface)) ImplementationCache.Add(@interface, newType); return newType; } static IEnumerable<PropertyInfo> GetAllProperties(Type type) { var allPropertiesWithInheritance = new List<PropertyInfo>(type.GetProperties()); foreach (var interfaceType in type.GetInterfaces()) allPropertiesWithInheritance.AddRange(GetAllProperties(interfaceType)); var result = allPropertiesWithInheritance.Select(x => x.Name).Distinct().Select(x => allPropertiesWithInheritance.First(y => y.Name.Equals(x))); return result; } static void DefineProperty(TypeBuilder typeBuilder, PropertyInfo propertyInfo) { var propertyName = propertyInfo.Name; var propertyType = propertyInfo.GetMethod.ReturnType; var field = typeBuilder.DefineField(String.Format("_{0}", propertyName), propertyType, FieldAttributes.Private); var prop = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null); const MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual; //Getter var get = typeBuilder.DefineMethod(String.Format("get_{0}", propertyName), methodAttributes, propertyType, Type.EmptyTypes); var getGen = get.GetILGenerator(); getGen.Emit(OpCodes.Ldarg_0); getGen.Emit(OpCodes.Ldfld, field); getGen.Emit(OpCodes.Ret); //Setter var getterName = String.Format("set_{0}", propertyName); var set = typeBuilder.DefineMethod(getterName, methodAttributes, null, new[] {propertyType}); var setGen = set.GetILGenerator(); setGen.Emit(OpCodes.Ldarg_0); setGen.Emit(OpCodes.Ldarg_1); setGen.Emit(OpCodes.Stfld, field); setGen.Emit(OpCodes.Ret); prop.SetGetMethod(get); prop.SetSetMethod(set); } } }
{ "content_hash": "4ece6a0d5a28dbe4f3de25d1c3d8d5e5", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 190, "avg_line_length": 42.371134020618555, "alnum_prop": 0.6462287104622871, "repo_name": "evgenyk/Idecom.Bus", "id": "eb9bb1e6b41b4a33a16a05218529621994c3b9b7", "size": "4110", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Idecom.Bus/Utility/InterfaceImplementor.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1515" }, { "name": "C#", "bytes": "272541" } ], "symlink_target": "" }
Server ============= You can find server documentation files in this folder.
{ "content_hash": "4c26bb75592c2d5a7d946e15acf54090", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 55, "avg_line_length": 25.333333333333332, "alnum_prop": 0.6842105263157895, "repo_name": "EverywhereHouseControl/Documentation", "id": "826e4573be3a0f61aa5a691977425479876366af", "size": "76", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Servidor/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "TeX", "bytes": "193674" } ], "symlink_target": "" }
package com.pyamsoft.dontsuckmp.queue; import android.support.annotation.CheckResult; import android.support.annotation.NonNull; import com.google.auto.value.AutoValue; import com.pyamsoft.dontsuckmp.model.Album; public final class QueueEvents { private QueueEvents() { throw new RuntimeException("No instances"); } @AutoValue public static abstract class Add { @CheckResult @NonNull public static Add add(@NonNull Album album, int track) { return new AutoValue_QueueEvents_Add(album, track); } @CheckResult public abstract Album album(); @CheckResult public abstract int track(); } }
{ "content_hash": "440d58f92766cb12697b648c3fa5ad99", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 82, "avg_line_length": 24.153846153846153, "alnum_prop": 0.7468152866242038, "repo_name": "pyamsoft/dontsuck-mp", "id": "2b1e1eacfcd0a9eaf1eb12b093b2ae0ce0cbb252", "size": "1231", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dontsuckmp-queue/src/main/java/com/pyamsoft/dontsuckmp/queue/QueueEvents.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "157361" } ], "symlink_target": "" }
FROM balenalib/jetson-tx1-ubuntu:bionic-run ENV NODE_VERSION 10.24.0 ENV YARN_VERSION 1.22.4 RUN buildDeps='curl libatomic1' \ && set -x \ && for key in \ 6A010C5166006599AA17F08146C2130DFD2497F5 \ ; do \ gpg --keyserver pgp.mit.edu --recv-keys "$key" || \ gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \ gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \ done \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends \ && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \ && echo "65e6255c6f95b6dcf87f13c21994bc80205b4bd7c7d9a3fe1f8f2a18daec576d node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \ && tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \ && curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \ && gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && mkdir -p /opt/yarn \ && tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \ && ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \ && rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \ && npm config set unsafe-perm true -g --unsafe-perm \ && rm -rf /tmp/* CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \ && echo "Running test-stack@node" \ && chmod +x test-stack@node.sh \ && bash test-stack@node.sh \ && rm -rf test-stack@node.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v10.24.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "2dd6fbfa08ea805ba2e30f3a033de8de", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 692, "avg_line_length": 64.28888888888889, "alnum_prop": 0.7044590390597996, "repo_name": "nghiant2710/base-images", "id": "80528e5eef63ae420303faaaa146691148d1abc3", "size": "2914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/node/jetson-tx1/ubuntu/bionic/10.24.0/run/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "144558581" }, { "name": "JavaScript", "bytes": "16316" }, { "name": "Shell", "bytes": "368690" } ], "symlink_target": "" }
package com.amazonaws.services.medialive.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.medialive.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateInputRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateInputRequestMarshaller { private static final MarshallingInfo<List> DESTINATIONS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("destinations").build(); private static final MarshallingInfo<List> INPUTDEVICES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("inputDevices").build(); private static final MarshallingInfo<String> INPUTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("inputId").build(); private static final MarshallingInfo<List> INPUTSECURITYGROUPS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("inputSecurityGroups").build(); private static final MarshallingInfo<List> MEDIACONNECTFLOWS_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("mediaConnectFlows").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("name").build(); private static final MarshallingInfo<String> ROLEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("roleArn").build(); private static final MarshallingInfo<List> SOURCES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("sources").build(); private static final UpdateInputRequestMarshaller instance = new UpdateInputRequestMarshaller(); public static UpdateInputRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateInputRequest updateInputRequest, ProtocolMarshaller protocolMarshaller) { if (updateInputRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateInputRequest.getDestinations(), DESTINATIONS_BINDING); protocolMarshaller.marshall(updateInputRequest.getInputDevices(), INPUTDEVICES_BINDING); protocolMarshaller.marshall(updateInputRequest.getInputId(), INPUTID_BINDING); protocolMarshaller.marshall(updateInputRequest.getInputSecurityGroups(), INPUTSECURITYGROUPS_BINDING); protocolMarshaller.marshall(updateInputRequest.getMediaConnectFlows(), MEDIACONNECTFLOWS_BINDING); protocolMarshaller.marshall(updateInputRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(updateInputRequest.getRoleArn(), ROLEARN_BINDING); protocolMarshaller.marshall(updateInputRequest.getSources(), SOURCES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "0b4f971e31258bcd2b3d3ac1439a1c5c", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 158, "avg_line_length": 55.09090909090909, "alnum_prop": 0.7637513751375138, "repo_name": "aws/aws-sdk-java", "id": "ccfbd345562c4ed383a85438222b12a1453b6e47", "size": "4216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/UpdateInputRequestMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package cgeo.geocaching.unifiedmap.tileproviders; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.storage.ContentStorage; import cgeo.geocaching.unifiedmap.LayerHelper; import static cgeo.geocaching.unifiedmap.tileproviders.TileProviderFactory.MAP_MAPSFORGE; import android.net.Uri; import java.io.FileInputStream; import org.apache.commons.lang3.StringUtils; import org.oscim.layers.tile.buildings.BuildingLayer; import org.oscim.layers.tile.vector.VectorTileLayer; import org.oscim.layers.tile.vector.labeling.LabelLayer; import org.oscim.map.Map; import org.oscim.tiling.source.mapfile.MapFileTileSource; import org.oscim.tiling.source.mapfile.MapInfo; class AbstractMapsforgeOfflineTileProvider extends AbstractMapsforgeTileProvider { MapFileTileSource tileSource; AbstractMapsforgeOfflineTileProvider(final String name, final Uri uri, final int zoomMin, final int zoomMax) { super(name, uri, zoomMin, zoomMax); supportsThemes = true; supportsThemeOptions = true; // rule of thumb, not all themes support options } @Override public void addTileLayer(final Map map) { tileSource = new MapFileTileSource(); tileSource.setPreferredLanguage(Settings.getMapLanguage()); tileSource.setMapFileInputStream((FileInputStream) ContentStorage.get().openForRead(mapUri)); final VectorTileLayer tileLayer = (VectorTileLayer) MAP_MAPSFORGE.setBaseMap(tileSource); MAP_MAPSFORGE.addLayer(LayerHelper.ZINDEX_BUILDINGS, new BuildingLayer(map, tileLayer)); MAP_MAPSFORGE.addLayer(LayerHelper.ZINDEX_LABELS, new LabelLayer(map, tileLayer)); MAP_MAPSFORGE.applyTheme(); final MapInfo info = tileSource.getMapInfo(); if (info != null) { supportsLanguages = StringUtils.isNotBlank(info.languagesPreference); if (supportsLanguages) { TileProviderFactory.setLanguages(info.languagesPreference.split(",")); } parseZoomLevel(info.zoomLevel); if (!info.boundingBox.contains(map.getMapPosition().getGeoPoint())) { MAP_MAPSFORGE.zoomToBounds(info.boundingBox); } } } @Override public void setPreferredLanguage(final String language) { tileSource.setPreferredLanguage(language); } }
{ "content_hash": "3433e0c6ec4fb1c3655009dfce66f1af", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 114, "avg_line_length": 40.96491228070175, "alnum_prop": 0.7357601713062099, "repo_name": "cgeo/cgeo", "id": "b8184ea6ae51a225857b0a976aa2d0de557b6187", "size": "2335", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/src/cgeo/geocaching/unifiedmap/tileproviders/AbstractMapsforgeOfflineTileProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "2756" }, { "name": "HTML", "bytes": "3106894" }, { "name": "Java", "bytes": "6683227" }, { "name": "Python", "bytes": "1215" }, { "name": "Shell", "bytes": "8308" } ], "symlink_target": "" }
<?php namespace Rails\ActionView\Template\Exception; class LayoutMissingException extends \Rails\Exception\RuntimeException implements ExceptionInterface { protected $title = "Layout missing"; }
{ "content_hash": "6bf1d972902b63afd065b54afc662874", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 100, "avg_line_length": 28.428571428571427, "alnum_prop": 0.8190954773869347, "repo_name": "railsphp/railsphp", "id": "6f5d0f29f868cada7728135a8a897fdbe1892cb7", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Rails/ActionView/Template/Exception/LayoutMissingException.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "596132" } ], "symlink_target": "" }
using System; using System.Runtime.InteropServices; namespace EarTrumpet.Interop.MMDeviceAPI { // W10_TH1: CA286FC3-91FD-42C3-8E9B-CAAFA66242E3 // W10_TH2: 6BE54BE8-A068-4875-A49D-0C2966473B11 // Win7-Win8, W10_RS1-Present: [Guid("F8679F50-850A-41CF-9C72-430F290290C8")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPolicyConfigWin7 { void Unused1(); void Unused2(); void Unused3(); void Unused4(); void Unused5(); void Unused6(); void Unused7(); void Unused8(); void GetPropertyValue([MarshalAs(UnmanagedType.LPWStr)]string wszDeviceId, ref PROPERTYKEY pkey, ref PropVariant pv); void SetPropertyValue([MarshalAs(UnmanagedType.LPWStr)]string wszDeviceId, ref PROPERTYKEY pkey, ref PropVariant pv); void SetDefaultEndpoint([MarshalAs(UnmanagedType.LPWStr)]string wszDeviceId, ERole eRole); void SetEndpointVisibility([MarshalAs(UnmanagedType.LPWStr)]string wszDeviceId, [MarshalAs(UnmanagedType.I2)]short isVisible); } }
{ "content_hash": "1b027a48626ba3a6ce600bbfb4327907", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 134, "avg_line_length": 41.46153846153846, "alnum_prop": 0.7096474953617811, "repo_name": "File-New-Project/EarTrumpet", "id": "0d2c0f912da2d44d3bbc373677c2c90b46e7a6aa", "size": "1080", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EarTrumpet/Interop/MMDeviceAPI/IPolicyConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "584565" }, { "name": "PowerShell", "bytes": "1412" } ], "symlink_target": "" }
<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@android:integer/config_shortAnimTime" android:fromXDelta="30%p" android:toXDelta="0" /> <alpha android:duration="@android:integer/config_shortAnimTime" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set>
{ "content_hash": "fcacd744633f8917de96069ae69baf07", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 65, "avg_line_length": 27.846153846153847, "alnum_prop": 0.6408839779005525, "repo_name": "cfmobile/arca-android-samples", "id": "01265fc31c688d3696721fc756c63d75684d033f", "size": "362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RottenTomatoes/app/src/main/res/anim/slide_in_right.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "100361" } ], "symlink_target": "" }
<?php /* Template Name: Custom Page Template */ ?> <?php get_header(); ?> <?php get_sidebar(); ?> <?php get_footer(); ?>
{ "content_hash": "725d37d4b80f7f06ca66e2f0de24c3dd", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 50, "avg_line_length": 21.166666666666668, "alnum_prop": 0.5511811023622047, "repo_name": "Mattyvac/Templates", "id": "20321d99ae32253fd21b612847c3a3eb959f15d6", "size": "127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WordPress Theme/custom-page.php", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
skyscheduler-to-csv =================== Script to convert SkyScheduler Flight log entries to CSV.
{ "content_hash": "769259951daec424488345a2130bbc78", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 57, "avg_line_length": 24.75, "alnum_prop": 0.6565656565656566, "repo_name": "ablyler/skyscheduler-to-csv", "id": "5fedf4104510d15ba1dcc7bb65307221b789663b", "size": "99", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "3518" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo { internal interface INavigateToSearchResultProvider { /// <summary> /// Compute navigate to search results for the given search pattern in the given project. /// </summary> Task<IEnumerable<INavigateToSearchResult>> SearchProjectAsync(Project project, string searchPattern, CancellationToken cancellationToken); } }
{ "content_hash": "9962c6cfa76b720805225b2b160f7c33", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 146, "avg_line_length": 36.857142857142854, "alnum_prop": 0.7558139534883721, "repo_name": "jaredpar/roslyn", "id": "4e08f8a73ccadaddee33d0cf41b813da67c29f60", "size": "678", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "src/EditorFeatures/Core/Implementation/NavigateTo/INavigateToSearchResultProvider.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15099" }, { "name": "C#", "bytes": "80732271" }, { "name": "C++", "bytes": "6311" }, { "name": "F#", "bytes": "421" }, { "name": "Groovy", "bytes": "7036" }, { "name": "Makefile", "bytes": "3606" }, { "name": "PowerShell", "bytes": "25894" }, { "name": "Shell", "bytes": "7453" }, { "name": "Visual Basic", "bytes": "61232818" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace mko.Asp.Mvc.Test.Controllers { public class LispUiController : Controller { // // GET: /LispUi/ public ActionResult Index() { return View(); } } }
{ "content_hash": "648dcc0224fe74542080f1ae9455a6e2", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 46, "avg_line_length": 16.6, "alnum_prop": 0.5963855421686747, "repo_name": "mk-prg-net/mk-prg-net.lib", "id": "d46fe9c45d51c62624885b15c2a724da7466b95f", "size": "334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mko.Asp.Mvc.Test/Controllers/LispUiController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "5659" }, { "name": "C#", "bytes": "2986260" }, { "name": "CSS", "bytes": "18121" }, { "name": "HTML", "bytes": "65797" }, { "name": "JavaScript", "bytes": "40258" }, { "name": "PowerShell", "bytes": "10570" }, { "name": "TSQL", "bytes": "13826" }, { "name": "Visual Basic .NET", "bytes": "6093" } ], "symlink_target": "" }
/*! UIkit 3.6.12 | https://www.getuikit.com | (c) 2014 - 2021 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitlightbox', ['uikit-util'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitLightbox = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Animations = { slide: { show: function(dir) { return [ {transform: translate(dir * -100)}, {transform: translate()} ]; }, percent: function(current) { return translated(current); }, translate: function(percent, dir) { return [ {transform: translate(dir * -100 * percent)}, {transform: translate(dir * 100 * (1 - percent))} ]; } } }; function translated(el) { return Math.abs(uikitUtil.css(el, 'transform').split(',')[4] / el.offsetWidth) || 0; } function translate(value, unit) { if ( value === void 0 ) value = 0; if ( unit === void 0 ) unit = '%'; value += value ? unit : ''; return uikitUtil.isIE ? ("translateX(" + value + ")") : ("translate3d(" + value + ", 0, 0)"); // currently not translate3d in IE, translate3d within translate3d does not work while transitioning } function scale3d(value) { return ("scale3d(" + value + ", " + value + ", 1)"); } var Animations$1 = uikitUtil.assign({}, Animations, { fade: { show: function() { return [ {opacity: 0}, {opacity: 1} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent}, {opacity: percent} ]; } }, scale: { show: function() { return [ {opacity: 0, transform: scale3d(1 - .2)}, {opacity: 1, transform: scale3d(1)} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent, transform: scale3d(1 - .2 * percent)}, {opacity: percent, transform: scale3d(1 - .2 + .2 * percent)} ]; } } }); var Container = { props: { container: Boolean }, data: { container: true }, computed: { container: function(ref) { var container = ref.container; return container === true && this.$container || container && uikitUtil.$(container); } } }; var Class = { connected: function() { !uikitUtil.hasClass(this.$el, this.$name) && uikitUtil.addClass(this.$el, this.$name); } }; var Togglable = { props: { cls: Boolean, animation: 'list', duration: Number, origin: String, transition: String }, data: { cls: false, animation: [false], duration: 200, origin: false, transition: 'linear', clsEnter: 'uk-togglabe-enter', clsLeave: 'uk-togglabe-leave', initProps: { overflow: '', height: '', paddingTop: '', paddingBottom: '', marginTop: '', marginBottom: '' }, hideProps: { overflow: 'hidden', height: 0, paddingTop: 0, paddingBottom: 0, marginTop: 0, marginBottom: 0 } }, computed: { hasAnimation: function(ref) { var animation = ref.animation; return !!animation[0]; }, hasTransition: function(ref) { var animation = ref.animation; return this.hasAnimation && animation[0] === true; } }, methods: { toggleElement: function(targets, toggle, animate) { var this$1 = this; return new uikitUtil.Promise(function (resolve) { return uikitUtil.Promise.all(uikitUtil.toNodes(targets).map(function (el) { var show = uikitUtil.isBoolean(toggle) ? toggle : !this$1.isToggled(el); if (!uikitUtil.trigger(el, ("before" + (show ? 'show' : 'hide')), [this$1])) { return uikitUtil.Promise.reject(); } var promise = ( uikitUtil.isFunction(animate) ? animate : animate === false || !this$1.hasAnimation ? this$1._toggle : this$1.hasTransition ? toggleHeight(this$1) : toggleAnimation(this$1) )(el, show) || uikitUtil.Promise.resolve(); uikitUtil.addClass(el, show ? this$1.clsEnter : this$1.clsLeave); uikitUtil.trigger(el, show ? 'show' : 'hide', [this$1]); promise .catch(uikitUtil.noop) .then(function () { return uikitUtil.removeClass(el, show ? this$1.clsEnter : this$1.clsLeave); }); return promise.then(function () { uikitUtil.removeClass(el, show ? this$1.clsEnter : this$1.clsLeave); uikitUtil.trigger(el, show ? 'shown' : 'hidden', [this$1]); this$1.$update(el); }); })).then(resolve, uikitUtil.noop); } ); }, isToggled: function(el) { if ( el === void 0 ) el = this.$el; return uikitUtil.hasClass(el, this.clsEnter) ? true : uikitUtil.hasClass(el, this.clsLeave) ? false : this.cls ? uikitUtil.hasClass(el, this.cls.split(' ')[0]) : !uikitUtil.hasAttr(el, 'hidden'); }, _toggle: function(el, toggled) { if (!el) { return; } toggled = Boolean(toggled); var changed; if (this.cls) { changed = uikitUtil.includes(this.cls, ' ') || toggled !== uikitUtil.hasClass(el, this.cls); changed && uikitUtil.toggleClass(el, this.cls, uikitUtil.includes(this.cls, ' ') ? undefined : toggled); } else { changed = toggled === el.hidden; changed && (el.hidden = !toggled); } uikitUtil.$$('[autofocus]', el).some(function (el) { return uikitUtil.isVisible(el) ? el.focus() || true : el.blur(); }); if (changed) { uikitUtil.trigger(el, 'toggled', [toggled, this]); this.$update(el); } } } }; function toggleHeight(ref) { var isToggled = ref.isToggled; var duration = ref.duration; var initProps = ref.initProps; var hideProps = ref.hideProps; var transition = ref.transition; var _toggle = ref._toggle; return function (el, show) { var inProgress = uikitUtil.Transition.inProgress(el); var inner = el.hasChildNodes ? uikitUtil.toFloat(uikitUtil.css(el.firstElementChild, 'marginTop')) + uikitUtil.toFloat(uikitUtil.css(el.lastElementChild, 'marginBottom')) : 0; var currentHeight = uikitUtil.isVisible(el) ? uikitUtil.height(el) + (inProgress ? 0 : inner) : 0; uikitUtil.Transition.cancel(el); if (!isToggled(el)) { _toggle(el, true); } uikitUtil.height(el, ''); // Update child components first uikitUtil.fastdom.flush(); var endHeight = uikitUtil.height(el) + (inProgress ? 0 : inner); uikitUtil.height(el, currentHeight); return (show ? uikitUtil.Transition.start(el, uikitUtil.assign({}, initProps, {overflow: 'hidden', height: endHeight}), Math.round(duration * (1 - currentHeight / endHeight)), transition) : uikitUtil.Transition.start(el, hideProps, Math.round(duration * (currentHeight / endHeight)), transition).then(function () { return _toggle(el, false); }) ).then(function () { return uikitUtil.css(el, initProps); }); }; } function toggleAnimation(cmp) { return function (el, show) { uikitUtil.Animation.cancel(el); var animation = cmp.animation; var duration = cmp.duration; var _toggle = cmp._toggle; if (show) { _toggle(el, true); return uikitUtil.Animation.in(el, animation[0], duration, cmp.origin); } return uikitUtil.Animation.out(el, animation[1] || animation[0], duration, cmp.origin).then(function () { return _toggle(el, false); }); }; } var active = []; var Modal = { mixins: [Class, Container, Togglable], props: { selPanel: String, selClose: String, escClose: Boolean, bgClose: Boolean, stack: Boolean }, data: { cls: 'uk-open', escClose: true, bgClose: true, overlay: true, stack: false }, computed: { panel: function(ref, $el) { var selPanel = ref.selPanel; return uikitUtil.$(selPanel, $el); }, transitionElement: function() { return this.panel; }, bgClose: function(ref) { var bgClose = ref.bgClose; return bgClose && this.panel; } }, beforeDisconnect: function() { if (this.isToggled()) { this.toggleElement(this.$el, false, false); } }, events: [ { name: 'click', delegate: function() { return this.selClose; }, handler: function(e) { e.preventDefault(); this.hide(); } }, { name: 'toggle', self: true, handler: function(e) { if (e.defaultPrevented) { return; } e.preventDefault(); if (this.isToggled() === uikitUtil.includes(active, this)) { this.toggle(); } } }, { name: 'beforeshow', self: true, handler: function(e) { if (uikitUtil.includes(active, this)) { return false; } if (!this.stack && active.length) { uikitUtil.Promise.all(active.map(function (modal) { return modal.hide(); })).then(this.show); e.preventDefault(); } else { active.push(this); } } }, { name: 'show', self: true, handler: function() { var this$1 = this; if (uikitUtil.width(window) - uikitUtil.width(document) && this.overlay) { uikitUtil.css(document.body, 'overflowY', 'scroll'); } if (this.stack) { uikitUtil.css(this.$el, 'zIndex', uikitUtil.toFloat(uikitUtil.css(this.$el, 'zIndex')) + active.length); } uikitUtil.addClass(document.documentElement, this.clsPage); if (this.bgClose) { uikitUtil.once(this.$el, 'hide', uikitUtil.on(document, uikitUtil.pointerDown, function (ref) { var target = ref.target; if (uikitUtil.last(active) !== this$1 || this$1.overlay && !uikitUtil.within(target, this$1.$el) || uikitUtil.within(target, this$1.panel)) { return; } uikitUtil.once(document, (uikitUtil.pointerUp + " " + uikitUtil.pointerCancel + " scroll"), function (ref) { var defaultPrevented = ref.defaultPrevented; var type = ref.type; var newTarget = ref.target; if (!defaultPrevented && type === uikitUtil.pointerUp && target === newTarget) { this$1.hide(); } }, true); }), {self: true}); } if (this.escClose) { uikitUtil.once(this.$el, 'hide', uikitUtil.on(document, 'keydown', function (e) { if (e.keyCode === 27 && uikitUtil.last(active) === this$1) { this$1.hide(); } }), {self: true}); } } }, { name: 'hidden', self: true, handler: function() { var this$1 = this; active.splice(active.indexOf(this), 1); if (!active.length) { uikitUtil.css(document.body, 'overflowY', ''); } uikitUtil.css(this.$el, 'zIndex', ''); if (!active.some(function (modal) { return modal.clsPage === this$1.clsPage; })) { uikitUtil.removeClass(document.documentElement, this.clsPage); } } } ], methods: { toggle: function() { return this.isToggled() ? this.hide() : this.show(); }, show: function() { var this$1 = this; if (this.isToggled()) { return uikitUtil.Promise.resolve(); } if (this.container && uikitUtil.parent(this.$el) !== this.container) { uikitUtil.append(this.container, this.$el); return new uikitUtil.Promise(function (resolve) { return requestAnimationFrame(function () { return this$1.show().then(resolve); } ); } ); } return this.toggleElement(this.$el, true, animate(this)); }, hide: function() { if (!this.isToggled()) { return uikitUtil.Promise.resolve(); } return this.toggleElement(this.$el, false, animate(this)); } } }; function animate(ref) { var transitionElement = ref.transitionElement; var _toggle = ref._toggle; return function (el, show) { return new uikitUtil.Promise(function (resolve, reject) { return uikitUtil.once(el, 'show hide', function () { el._reject && el._reject(); el._reject = reject; _toggle(el, show); var off = uikitUtil.once(transitionElement, 'transitionstart', function () { uikitUtil.once(transitionElement, 'transitionend transitioncancel', resolve, {self: true}); clearTimeout(timer); }, {self: true}); var timer = setTimeout(function () { off(); resolve(); }, uikitUtil.toMs(uikitUtil.css(transitionElement, 'transitionDuration'))); }); } ).then(function () { return delete el._reject; }); }; } function Transitioner(prev, next, dir, ref) { var animation = ref.animation; var easing = ref.easing; var percent = animation.percent; var translate = animation.translate; var show = animation.show; if ( show === void 0 ) show = uikitUtil.noop; var props = show(dir); var deferred = new uikitUtil.Deferred(); return { dir: dir, show: function(duration, percent, linear) { var this$1 = this; if ( percent === void 0 ) percent = 0; var timing = linear ? 'linear' : easing; duration -= Math.round(duration * uikitUtil.clamp(percent, -1, 1)); this.translate(percent); triggerUpdate(next, 'itemin', {percent: percent, duration: duration, timing: timing, dir: dir}); triggerUpdate(prev, 'itemout', {percent: 1 - percent, duration: duration, timing: timing, dir: dir}); uikitUtil.Promise.all([ uikitUtil.Transition.start(next, props[1], duration, timing), uikitUtil.Transition.start(prev, props[0], duration, timing) ]).then(function () { this$1.reset(); deferred.resolve(); }, uikitUtil.noop); return deferred.promise; }, cancel: function() { uikitUtil.Transition.cancel([next, prev]); }, reset: function() { for (var prop in props[0]) { uikitUtil.css([next, prev], prop, ''); } }, forward: function(duration, percent) { if ( percent === void 0 ) percent = this.percent(); uikitUtil.Transition.cancel([next, prev]); return this.show(duration, percent, true); }, translate: function(percent) { this.reset(); var props = translate(percent, dir); uikitUtil.css(next, props[1]); uikitUtil.css(prev, props[0]); triggerUpdate(next, 'itemtranslatein', {percent: percent, dir: dir}); triggerUpdate(prev, 'itemtranslateout', {percent: 1 - percent, dir: dir}); }, percent: function() { return percent(prev || next, next, dir); }, getDistance: function() { return prev && prev.offsetWidth; } }; } function triggerUpdate(el, type, data) { uikitUtil.trigger(el, uikitUtil.createEvent(type, false, false, data)); } var SliderAutoplay = { props: { autoplay: Boolean, autoplayInterval: Number, pauseOnHover: Boolean }, data: { autoplay: false, autoplayInterval: 7000, pauseOnHover: true }, connected: function() { this.autoplay && this.startAutoplay(); }, disconnected: function() { this.stopAutoplay(); }, update: function() { uikitUtil.attr(this.slides, 'tabindex', '-1'); }, events: [ { name: 'visibilitychange', el: uikitUtil.inBrowser && document, filter: function() { return this.autoplay; }, handler: function() { if (document.hidden) { this.stopAutoplay(); } else { this.startAutoplay(); } } } ], methods: { startAutoplay: function() { var this$1 = this; this.stopAutoplay(); this.interval = setInterval( function () { return (!this$1.draggable || !uikitUtil.$(':focus', this$1.$el)) && (!this$1.pauseOnHover || !uikitUtil.matches(this$1.$el, ':hover')) && !this$1.stack.length && this$1.show('next'); }, this.autoplayInterval ); }, stopAutoplay: function() { this.interval && clearInterval(this.interval); } } }; var SliderDrag = { props: { draggable: Boolean }, data: { draggable: true, threshold: 10 }, created: function() { var this$1 = this; ['start', 'move', 'end'].forEach(function (key) { var fn = this$1[key]; this$1[key] = function (e) { var pos = uikitUtil.getEventPos(e).x * (uikitUtil.isRtl ? -1 : 1); this$1.prevPos = pos !== this$1.pos ? this$1.pos : this$1.prevPos; this$1.pos = pos; fn(e); }; }); }, events: [ { name: uikitUtil.pointerDown, delegate: function() { return this.selSlides; }, handler: function(e) { if (!this.draggable || !uikitUtil.isTouch(e) && hasTextNodesOnly(e.target) || uikitUtil.closest(e.target, uikitUtil.selInput) || e.button > 0 || this.length < 2 ) { return; } this.start(e); } }, { name: 'dragstart', handler: function(e) { e.preventDefault(); } } ], methods: { start: function() { this.drag = this.pos; if (this._transitioner) { this.percent = this._transitioner.percent(); this.drag += this._transitioner.getDistance() * this.percent * this.dir; this._transitioner.cancel(); this._transitioner.translate(this.percent); this.dragging = true; this.stack = []; } else { this.prevIndex = this.index; } // Workaround for iOS's inert scrolling preventing pointerdown event // https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action uikitUtil.on(this.list, 'touchmove', this.move, {passive: false}); uikitUtil.on(document, uikitUtil.pointerMove, this.move, {passive: false}); uikitUtil.on(document, (uikitUtil.pointerUp + " " + uikitUtil.pointerCancel), this.end, true); uikitUtil.css(this.list, 'userSelect', 'none'); }, move: function(e) { var this$1 = this; var distance = this.pos - this.drag; if (distance === 0 || this.prevPos === this.pos || !this.dragging && Math.abs(distance) < this.threshold) { return; } e.cancelable && e.preventDefault(); this.dragging = true; this.dir = (distance < 0 ? 1 : -1); var ref = this; var slides = ref.slides; var ref$1 = this; var prevIndex = ref$1.prevIndex; var dis = Math.abs(distance); var nextIndex = this.getIndex(prevIndex + this.dir, prevIndex); var width = this._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; while (nextIndex !== prevIndex && dis > width) { this.drag -= width * this.dir; prevIndex = nextIndex; dis -= width; nextIndex = this.getIndex(prevIndex + this.dir, prevIndex); width = this._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; } this.percent = dis / width; var prev = slides[prevIndex]; var next = slides[nextIndex]; var changed = this.index !== nextIndex; var edge = prevIndex === nextIndex; var itemShown; [this.index, this.prevIndex].filter(function (i) { return !uikitUtil.includes([nextIndex, prevIndex], i); }).forEach(function (i) { uikitUtil.trigger(slides[i], 'itemhidden', [this$1]); if (edge) { itemShown = true; this$1.prevIndex = prevIndex; } }); if (this.index === prevIndex && this.prevIndex !== prevIndex || itemShown) { uikitUtil.trigger(slides[this.index], 'itemshown', [this]); } if (changed) { this.prevIndex = prevIndex; this.index = nextIndex; !edge && uikitUtil.trigger(prev, 'beforeitemhide', [this]); uikitUtil.trigger(next, 'beforeitemshow', [this]); } this._transitioner = this._translate(Math.abs(this.percent), prev, !edge && next); if (changed) { !edge && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); } }, end: function() { uikitUtil.off(this.list, 'touchmove', this.move, {passive: false}); uikitUtil.off(document, uikitUtil.pointerMove, this.move, {passive: false}); uikitUtil.off(document, (uikitUtil.pointerUp + " " + uikitUtil.pointerCancel), this.end, true); if (this.dragging) { this.dragging = null; if (this.index === this.prevIndex) { this.percent = 1 - this.percent; this.dir *= -1; this._show(false, this.index, true); this._transitioner = null; } else { var dirChange = (uikitUtil.isRtl ? this.dir * (uikitUtil.isRtl ? 1 : -1) : this.dir) < 0 === this.prevPos > this.pos; this.index = dirChange ? this.index : this.prevIndex; if (dirChange) { this.percent = 1 - this.percent; } this.show(this.dir > 0 && !dirChange || this.dir < 0 && dirChange ? 'next' : 'previous', true); } } uikitUtil.css(this.list, {userSelect: '', pointerEvents: ''}); this.drag = this.percent = null; } } }; function hasTextNodesOnly(el) { return !el.children.length && el.childNodes.length; } var SliderNav = { data: { selNav: false }, computed: { nav: function(ref, $el) { var selNav = ref.selNav; return uikitUtil.$(selNav, $el); }, selNavItem: function(ref) { var attrItem = ref.attrItem; return ("[" + attrItem + "],[data-" + attrItem + "]"); }, navItems: function(_, $el) { return uikitUtil.$$(this.selNavItem, $el); } }, update: { write: function() { var this$1 = this; if (this.nav && this.length !== this.nav.children.length) { uikitUtil.html(this.nav, this.slides.map(function (_, i) { return ("<li " + (this$1.attrItem) + "=\"" + i + "\"><a href></a></li>"); }).join('')); } this.navItems.concat(this.nav).forEach(function (el) { return el && (el.hidden = !this$1.maxIndex); }); this.updateNav(); }, events: ['resize'] }, events: [ { name: 'click', delegate: function() { return this.selNavItem; }, handler: function(e) { e.preventDefault(); this.show(uikitUtil.data(e.current, this.attrItem)); } }, { name: 'itemshow', handler: 'updateNav' } ], methods: { updateNav: function() { var this$1 = this; var i = this.getValidIndex(); this.navItems.forEach(function (el) { var cmd = uikitUtil.data(el, this$1.attrItem); uikitUtil.toggleClass(el, this$1.clsActive, uikitUtil.toNumber(cmd) === i); uikitUtil.toggleClass(el, 'uk-invisible', this$1.finite && (cmd === 'previous' && i === 0 || cmd === 'next' && i >= this$1.maxIndex)); }); } } }; var Slider = { mixins: [SliderAutoplay, SliderDrag, SliderNav], props: { clsActivated: Boolean, easing: String, index: Number, finite: Boolean, velocity: Number, selSlides: String }, data: function () { return ({ easing: 'ease', finite: false, velocity: 1, index: 0, prevIndex: -1, stack: [], percent: 0, clsActive: 'uk-active', clsActivated: false, Transitioner: false, transitionOptions: {} }); }, connected: function() { this.prevIndex = -1; this.index = this.getValidIndex(this.$props.index); this.stack = []; }, disconnected: function() { uikitUtil.removeClass(this.slides, this.clsActive); }, computed: { duration: function(ref, $el) { var velocity = ref.velocity; return speedUp($el.offsetWidth / velocity); }, list: function(ref, $el) { var selList = ref.selList; return uikitUtil.$(selList, $el); }, maxIndex: function() { return this.length - 1; }, selSlides: function(ref) { var selList = ref.selList; var selSlides = ref.selSlides; return (selList + " " + (selSlides || '> *')); }, slides: { get: function() { return uikitUtil.$$(this.selSlides, this.$el); }, watch: function() { this.$reset(); } }, length: function() { return this.slides.length; } }, events: { itemshown: function() { this.$update(this.list); } }, methods: { show: function(index, force) { var this$1 = this; if ( force === void 0 ) force = false; if (this.dragging || !this.length) { return; } var ref = this; var stack = ref.stack; var queueIndex = force ? 0 : stack.length; var reset = function () { stack.splice(queueIndex, 1); if (stack.length) { this$1.show(stack.shift(), true); } }; stack[force ? 'unshift' : 'push'](index); if (!force && stack.length > 1) { if (stack.length === 2) { this._transitioner.forward(Math.min(this.duration, 200)); } return; } var prevIndex = this.getIndex(this.index); var prev = uikitUtil.hasClass(this.slides, this.clsActive) && this.slides[prevIndex]; var nextIndex = this.getIndex(index, this.index); var next = this.slides[nextIndex]; if (prev === next) { reset(); return; } this.dir = getDirection(index, prevIndex); this.prevIndex = prevIndex; this.index = nextIndex; if (prev && !uikitUtil.trigger(prev, 'beforeitemhide', [this]) || !uikitUtil.trigger(next, 'beforeitemshow', [this, prev]) ) { this.index = this.prevIndex; reset(); return; } var promise = this._show(prev, next, force).then(function () { prev && uikitUtil.trigger(prev, 'itemhidden', [this$1]); uikitUtil.trigger(next, 'itemshown', [this$1]); return new uikitUtil.Promise(function (resolve) { uikitUtil.fastdom.write(function () { stack.shift(); if (stack.length) { this$1.show(stack.shift(), true); } else { this$1._transitioner = null; } resolve(); }); }); }); prev && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); return promise; }, getIndex: function(index, prev) { if ( index === void 0 ) index = this.index; if ( prev === void 0 ) prev = this.index; return uikitUtil.clamp(uikitUtil.getIndex(index, this.slides, prev, this.finite), 0, this.maxIndex); }, getValidIndex: function(index, prevIndex) { if ( index === void 0 ) index = this.index; if ( prevIndex === void 0 ) prevIndex = this.prevIndex; return this.getIndex(index, prevIndex); }, _show: function(prev, next, force) { this._transitioner = this._getTransitioner( prev, next, this.dir, uikitUtil.assign({ easing: force ? next.offsetWidth < 600 ? 'cubic-bezier(0.25, 0.46, 0.45, 0.94)' /* easeOutQuad */ : 'cubic-bezier(0.165, 0.84, 0.44, 1)' /* easeOutQuart */ : this.easing }, this.transitionOptions) ); if (!force && !prev) { this._translate(1); return uikitUtil.Promise.resolve(); } var ref = this.stack; var length = ref.length; return this._transitioner[length > 1 ? 'forward' : 'show'](length > 1 ? Math.min(this.duration, 75 + 75 / (length - 1)) : this.duration, this.percent); }, _getDistance: function(prev, next) { return this._getTransitioner(prev, prev !== next && next).getDistance(); }, _translate: function(percent, prev, next) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; var transitioner = this._getTransitioner(prev !== next ? prev : false, next); transitioner.translate(percent); return transitioner; }, _getTransitioner: function(prev, next, dir, options) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; if ( dir === void 0 ) dir = this.dir || 1; if ( options === void 0 ) options = this.transitionOptions; return new this.Transitioner( uikitUtil.isNumber(prev) ? this.slides[prev] : prev, uikitUtil.isNumber(next) ? this.slides[next] : next, dir * (uikitUtil.isRtl ? -1 : 1), options ); } } }; function getDirection(index, prevIndex) { return index === 'next' ? 1 : index === 'previous' ? -1 : index < prevIndex ? -1 : 1; } function speedUp(x) { return .5 * x + 300; // parabola through (400,500; 600,600; 1800,1200) } var Slideshow = { mixins: [Slider], props: { animation: String }, data: { animation: 'slide', clsActivated: 'uk-transition-active', Animations: Animations, Transitioner: Transitioner }, computed: { animation: function(ref) { var animation = ref.animation; var Animations = ref.Animations; return uikitUtil.assign(Animations[animation] || Animations.slide, {name: animation}); }, transitionOptions: function() { return {animation: this.animation}; } }, events: { 'itemshow itemhide itemshown itemhidden': function(ref) { var target = ref.target; this.$update(target); }, beforeitemshow: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActive); }, itemshown: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActivated); }, itemhidden: function(ref) { var target = ref.target; uikitUtil.removeClass(target, this.clsActive, this.clsActivated); } } }; var LightboxPanel = { mixins: [Container, Modal, Togglable, Slideshow], functional: true, props: { delayControls: Number, preload: Number, videoAutoplay: Boolean, template: String }, data: function () { return ({ preload: 1, videoAutoplay: false, delayControls: 3000, items: [], cls: 'uk-open', clsPage: 'uk-lightbox-page', selList: '.uk-lightbox-items', attrItem: 'uk-lightbox-item', selClose: '.uk-close-large', selCaption: '.uk-lightbox-caption', pauseOnHover: false, velocity: 2, Animations: Animations$1, template: "<div class=\"uk-lightbox uk-overflow-hidden\"> <ul class=\"uk-lightbox-items\"></ul> <div class=\"uk-lightbox-toolbar uk-position-top uk-text-right uk-transition-slide-top uk-transition-opaque\"> <button class=\"uk-lightbox-toolbar-icon uk-close-large\" type=\"button\" uk-close></button> </div> <a class=\"uk-lightbox-button uk-position-center-left uk-position-medium uk-transition-fade\" href uk-slidenav-previous uk-lightbox-item=\"previous\"></a> <a class=\"uk-lightbox-button uk-position-center-right uk-position-medium uk-transition-fade\" href uk-slidenav-next uk-lightbox-item=\"next\"></a> <div class=\"uk-lightbox-toolbar uk-lightbox-caption uk-position-bottom uk-text-center uk-transition-slide-bottom uk-transition-opaque\"></div> </div>" }); }, created: function() { var $el = uikitUtil.$(this.template); var list = uikitUtil.$(this.selList, $el); this.items.forEach(function () { return uikitUtil.append(list, '<li>'); }); this.$mount(uikitUtil.append(this.container, $el)); }, computed: { caption: function(ref, $el) { var selCaption = ref.selCaption; return uikitUtil.$('.uk-lightbox-caption', $el); } }, events: [ { name: (uikitUtil.pointerMove + " " + uikitUtil.pointerDown + " keydown"), handler: 'showControls' }, { name: 'click', self: true, delegate: function() { return this.selSlides; }, handler: function(e) { if (e.defaultPrevented) { return; } this.hide(); } }, { name: 'shown', self: true, handler: function() { this.showControls(); } }, { name: 'hide', self: true, handler: function() { this.hideControls(); uikitUtil.removeClass(this.slides, this.clsActive); uikitUtil.Transition.stop(this.slides); } }, { name: 'hidden', self: true, handler: function() { this.$destroy(true); } }, { name: 'keyup', el: uikitUtil.inBrowser && document, handler: function(e) { if (!this.isToggled(this.$el) || !this.draggable) { return; } switch (e.keyCode) { case 37: this.show('previous'); break; case 39: this.show('next'); break; } } }, { name: 'beforeitemshow', handler: function(e) { if (this.isToggled()) { return; } this.draggable = false; e.preventDefault(); this.toggleElement(this.$el, true, false); this.animation = Animations$1['scale']; uikitUtil.removeClass(e.target, this.clsActive); this.stack.splice(1, 0, this.index); } }, { name: 'itemshow', handler: function() { uikitUtil.html(this.caption, this.getItem().caption || ''); for (var j = -this.preload; j <= this.preload; j++) { this.loadItem(this.index + j); } } }, { name: 'itemshown', handler: function() { this.draggable = this.$props.draggable; } }, { name: 'itemload', handler: function(_, item) { var this$1 = this; var src = item.source; var type = item.type; var alt = item.alt; if ( alt === void 0 ) alt = ''; var poster = item.poster; var attrs = item.attrs; if ( attrs === void 0 ) attrs = {}; this.setItem(item, '<span uk-spinner></span>'); if (!src) { return; } var matches; var iframeAttrs = { frameborder: '0', allow: 'autoplay', allowfullscreen: '', style: 'max-width: 100%; box-sizing: border-box;', 'uk-responsive': '', 'uk-video': ("" + (this.videoAutoplay)) }; // Image if (type === 'image' || src.match(/\.(jpe?g|png|gif|svg|webp)($|\?)/i)) { uikitUtil.getImage(src, attrs.srcset, attrs.size).then( function (ref) { var width = ref.width; var height = ref.height; return this$1.setItem(item, createEl('img', uikitUtil.assign({src: src, width: width, height: height, alt: alt}, attrs))); }, function () { return this$1.setError(item); } ); // Video } else if (type === 'video' || src.match(/\.(mp4|webm|ogv)($|\?)/i)) { var video = createEl('video', uikitUtil.assign({ src: src, poster: poster, controls: '', playsinline: '', 'uk-video': ("" + (this.videoAutoplay)) }, attrs)); uikitUtil.on(video, 'loadedmetadata', function () { uikitUtil.attr(video, {width: video.videoWidth, height: video.videoHeight}); this$1.setItem(item, video); }); uikitUtil.on(video, 'error', function () { return this$1.setError(item); }); // Iframe } else if (type === 'iframe' || src.match(/\.(html|php)($|\?)/i)) { this.setItem(item, createEl('iframe', uikitUtil.assign({ src: src, frameborder: '0', allowfullscreen: '', class: 'uk-lightbox-iframe' }, attrs))); // YouTube } else if ((matches = src.match(/\/\/(?:.*?youtube(-nocookie)?\..*?[?&]v=|youtu\.be\/)([\w-]{11})[&?]?(.*)?/))) { this.setItem(item, createEl('iframe', uikitUtil.assign({ src: ("https://www.youtube" + (matches[1] || '') + ".com/embed/" + (matches[2]) + (matches[3] ? ("?" + (matches[3])) : '')), width: 1920, height: 1080 }, iframeAttrs, attrs))); // Vimeo } else if ((matches = src.match(/\/\/.*?vimeo\.[a-z]+\/(\d+)[&?]?(.*)?/))) { uikitUtil.ajax(("https://vimeo.com/api/oembed.json?maxwidth=1920&url=" + (encodeURI(src))), { responseType: 'json', withCredentials: false }).then( function (ref) { var ref_response = ref.response; var height = ref_response.height; var width = ref_response.width; return this$1.setItem(item, createEl('iframe', uikitUtil.assign({ src: ("https://player.vimeo.com/video/" + (matches[1]) + (matches[2] ? ("?" + (matches[2])) : '')), width: width, height: height }, iframeAttrs, attrs))); }, function () { return this$1.setError(item); } ); } } } ], methods: { loadItem: function(index) { if ( index === void 0 ) index = this.index; var item = this.getItem(index); if (!this.getSlide(item).childElementCount) { uikitUtil.trigger(this.$el, 'itemload', [item]); } }, getItem: function(index) { if ( index === void 0 ) index = this.index; return this.items[uikitUtil.getIndex(index, this.slides)]; }, setItem: function(item, content) { uikitUtil.trigger(this.$el, 'itemloaded', [this, uikitUtil.html(this.getSlide(item), content) ]); }, getSlide: function(item) { return this.slides[this.items.indexOf(item)]; }, setError: function(item) { this.setItem(item, '<span uk-icon="icon: bolt; ratio: 2"></span>'); }, showControls: function() { clearTimeout(this.controlsTimer); this.controlsTimer = setTimeout(this.hideControls, this.delayControls); uikitUtil.addClass(this.$el, 'uk-active', 'uk-transition-active'); }, hideControls: function() { uikitUtil.removeClass(this.$el, 'uk-active', 'uk-transition-active'); } } }; function createEl(tag, attrs) { var el = uikitUtil.fragment(("<" + tag + ">")); uikitUtil.attr(el, attrs); return el; } var Component = { install: install, props: {toggle: String}, data: {toggle: 'a'}, computed: { toggles: { get: function(ref, $el) { var toggle = ref.toggle; return uikitUtil.$$(toggle, $el); }, watch: function() { this.hide(); } } }, disconnected: function() { this.hide(); }, events: [ { name: 'click', delegate: function() { return ((this.toggle) + ":not(.uk-disabled)"); }, handler: function(e) { e.preventDefault(); this.show(e.current); } } ], methods: { show: function(index) { var this$1 = this; var items = uikitUtil.uniqueBy(this.toggles.map(toItem), 'source'); if (uikitUtil.isElement(index)) { var ref = toItem(index); var source = ref.source; index = uikitUtil.findIndex(items, function (ref) { var src = ref.source; return source === src; }); } this.panel = this.panel || this.$create('lightboxPanel', uikitUtil.assign({}, this.$props, {items: items})); uikitUtil.on(this.panel.$el, 'hidden', function () { return this$1.panel = false; }); return this.panel.show(index); }, hide: function() { return this.panel && this.panel.hide(); } } }; function install(UIkit, Lightbox) { if (!UIkit.lightboxPanel) { UIkit.component('lightboxPanel', LightboxPanel); } uikitUtil.assign( Lightbox.props, UIkit.component('lightboxPanel').options.props ); } function toItem(el) { var item = {}; ['href', 'caption', 'type', 'poster', 'alt', 'attrs'].forEach(function (attr) { item[attr === 'href' ? 'source' : attr] = uikitUtil.data(el, attr); }); item.attrs = uikitUtil.parseOptions(item.attrs); return item; } if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('lightbox', Component); } return Component; })));
{ "content_hash": "f3a695a2ddcf212efffdf702803e6233", "timestamp": "", "source": "github", "line_count": 1828, "max_line_length": 773, "avg_line_length": 29.38074398249453, "alnum_prop": 0.42745959633574143, "repo_name": "cdnjs/cdnjs", "id": "b60341e7bbf3bfef918f7c4b249499b335a77d34", "size": "53708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ajax/libs/uikit/3.6.12/js/components/lightbox.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "4c9955ae4c7ecc63792821c47b187349", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "f93cef8e105d1fee2597e81bc363453eb3e5731c", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Hymenophyllales/Hymenophyllaceae/Trichomanes/Trichomanes boryanum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '..', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai'], // list of files / patterns to load in the browser files: [ 'dist/bundle/testing/*.js', 'test/bindings/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome', 'Firefox'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }
{ "content_hash": "c848c0f3ac1b13cab6df21967d2a1477", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 120, "avg_line_length": 24.686567164179106, "alnum_prop": 0.6559854897218863, "repo_name": "stasm/l20n.js", "id": "304f44e23949082716d69c2f321c40cedc218aba", "size": "1735", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/karma.conf.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "173283" }, { "name": "Makefile", "bytes": "1839" } ], "symlink_target": "" }
package org.nd4j.linalg.api.ops.impl.layers.recurrent.outputs; import java.util.Arrays; import java.util.List; import lombok.Getter; import org.nd4j.autodiff.samediff.SDVariable; import org.nd4j.base.Preconditions; import org.nd4j.linalg.api.ops.impl.layers.recurrent.GRUCell; /** * The outputs of a GRU cell ({@link GRUCell}. */ @Getter public class GRUCellOutputs { /** * Reset gate output [batchSize, numUnits]. */ private SDVariable r; /** * Update gate output [batchSize, numUnits]. */ private SDVariable u; /** * Cell gate output [batchSize, numUnits]. */ private SDVariable c; /** * Current cell output [batchSize, numUnits]. */ private SDVariable h; public GRUCellOutputs(SDVariable[] outputs){ Preconditions.checkArgument(outputs.length == 4, "Must have 4 GRU cell outputs, got %s", outputs.length); r = outputs[0]; u = outputs[1]; c = outputs[2]; h = outputs[3]; } /** * Get all outputs returned by the cell. */ public List<SDVariable> getAllOutputs(){ return Arrays.asList(r, u, c, h); } /** * Get h, the output of the cell. * * Has shape [batchSize, numUnits]. */ public SDVariable getOutput(){ return h; } }
{ "content_hash": "a7b07fee8c5c3e3f4844695461d3fa8a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 72, "avg_line_length": 21.612903225806452, "alnum_prop": 0.6037313432835821, "repo_name": "RobAltena/deeplearning4j", "id": "a39a5bcc76cb878fb9be3b2eef4b6e108dbd681c", "size": "1340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/layers/recurrent/outputs/GRUCellOutputs.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2469" }, { "name": "C", "bytes": "144275" }, { "name": "C#", "bytes": "138404" }, { "name": "C++", "bytes": "16954560" }, { "name": "CMake", "bytes": "77377" }, { "name": "CSS", "bytes": "10363" }, { "name": "Cuda", "bytes": "2324886" }, { "name": "Dockerfile", "bytes": "1329" }, { "name": "FreeMarker", "bytes": "77045" }, { "name": "HTML", "bytes": "38914" }, { "name": "Java", "bytes": "36293636" }, { "name": "JavaScript", "bytes": "436278" }, { "name": "PureBasic", "bytes": "12256" }, { "name": "Python", "bytes": "325018" }, { "name": "Ruby", "bytes": "4558" }, { "name": "Scala", "bytes": "355054" }, { "name": "Shell", "bytes": "80490" }, { "name": "Smarty", "bytes": "900" }, { "name": "Starlark", "bytes": "931" }, { "name": "TypeScript", "bytes": "80252" } ], "symlink_target": "" }
<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="chrome=1"> <title>maxent_toolbox: getFactors()</title> <link rel="stylesheet" href="stylesheets/styles.css"> <link rel="stylesheet" href="stylesheets/github-light.css"> <meta name="viewport" content="width=device-width"> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="wrapper"> <header> <h1><a href="index.html" style="color:black">maxent_toolbox</a></h1> <p>Maximum Entropy toolbox for MATLAB</p> <p class="view"><a href="https://github.com/orimaoz/maxent_toolbox">View the Project on GitHub <small>orimaoz/maxent_toolbox</small></a></p> <ul> <li><a href="https://github.com/orimaoz/maxent_toolbox/releases/latest">Download <strong>Latest version</strong></a></li> <li><a href="https://github.com/orimaoz/maxent_toolbox">View On <strong>GitHub</strong></a></li> </ul> <ul> <li><a href="function_reference.html">Function <strong>Reference</strong></a></li> <li><a href="quickstart.html">Guide for <strong>Quick Start</strong></a></li> </ul> </header> <section> <h2>maxent.getExplicitDistribution</h2> <article> <h2>Description</h2> <p>Returns an explicit representation of a probability distribution as a vector of probabilities. This function will return an error for large (default &ge; 30) distributions since they typically cannot fit in memory. </p> </article> <article> <h2>Usage</h2> <pre>probabilities = maxent.getExplicitDistribution(model)</pre> </article> <article> <h2>Arguments</h2> <article> <h3>Mandatory arguments</h3> <ul> <li><b>model</b> - Probabilistic model as returned by the <a href="trainModel.html">trainModel</a> function. </li> </ul> </article> <article> <h2>Output</h2> <li><b>probabilities</b> - vector of probabilities for all system states starting from 00000, 00001.... up to 11111. </li> </article> </section> <footer> <p>This project is maintained by <a href="https://github.com/orimaoz">orimaoz</a></p> <p><small>Theme by <a href="https://github.com/orderedlist">orderedlist</a></small></p> </footer> </div> <script src="javascripts/scale.fix.js"></script> </body> </html>
{ "content_hash": "e2f481af1f797d041c1010bd165de254", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 148, "avg_line_length": 31.506493506493506, "alnum_prop": 0.6438582028029678, "repo_name": "orimaoz/maxent_toolbox", "id": "99d63a20ec24f3a9c814cc8bb4e17e46041bfad3", "size": "2426", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/getExplicitDistribution.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5810" }, { "name": "C++", "bytes": "150193" }, { "name": "MATLAB", "bytes": "94942" }, { "name": "Shell", "bytes": "1478" } ], "symlink_target": "" }
package org.apache.hadoop.hdfs.server.namenode; import static org.apache.hadoop.fs.permission.AclEntryScope.*; import static org.apache.hadoop.fs.permission.AclEntryType.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclEntryScope; import org.apache.hadoop.fs.permission.AclEntryType; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.fs.permission.ScopedAclEntries; import org.apache.hadoop.hdfs.protocol.AclException; import org.apache.hadoop.util.Lists; import org.apache.hadoop.thirdparty.com.google.common.collect.ComparisonChain; import org.apache.hadoop.thirdparty.com.google.common.collect.Maps; import org.apache.hadoop.thirdparty.com.google.common.collect.Ordering; /** * AclTransformation defines the operations that can modify an ACL. All ACL * modifications take as input an existing ACL and apply logic to add new * entries, modify existing entries or remove old entries. Some operations also * accept an ACL spec: a list of entries that further describes the requested * change. Different operations interpret the ACL spec differently. In the * case of adding an ACL to an inode that previously did not have one, the * existing ACL can be a "minimal ACL" containing exactly 3 entries for owner, * group and other, all derived from the {@link FsPermission} bits. * * The algorithms implemented here require sorted lists of ACL entries. For any * existing ACL, it is assumed that the entries are sorted. This is because all * ACL creation and modification is intended to go through these methods, and * they all guarantee correct sort order in their outputs. However, an ACL spec * is considered untrusted user input, so all operations pre-sort the ACL spec as * the first step. */ @InterfaceAudience.Private final class AclTransformation { private static final int MAX_ENTRIES = 32; /** * Filters (discards) any existing ACL entries that have the same scope, type * and name of any entry in the ACL spec. If necessary, recalculates the mask * entries. If necessary, default entries may be inferred by copying the * permissions of the corresponding access entries. It is invalid to request * removal of the mask entry from an ACL that would otherwise require a mask * entry, due to existing named entries or an unnamed group entry. * * @param existingAcl List<AclEntry> existing ACL * @param inAclSpec List<AclEntry> ACL spec describing entries to filter * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> filterAclEntriesByAclSpec( List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { if (aclSpec.containsKey(existingEntry)) { scopeDirty.add(existingEntry.getScope()); if (existingEntry.getType() == MASK) { maskDirty.add(existingEntry.getScope()); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); } /** * Filters (discards) any existing default ACL entries. The new ACL retains * only the access ACL entries. * * @param existingAcl List<AclEntry> existing ACL * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> filterDefaultAclEntries( List<AclEntry> existingAcl) throws AclException { ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); for (AclEntry existingEntry: existingAcl) { if (existingEntry.getScope() == DEFAULT) { // Default entries sort after access entries, so we can exit early. break; } aclBuilder.add(existingEntry); } return buildAndValidateAcl(aclBuilder); } /** * Merges the entries of the ACL spec into the existing ACL. If necessary, * recalculates the mask entries. If necessary, default entries may be * inferred by copying the permissions of the corresponding access entries. * * @param existingAcl List<AclEntry> existing ACL * @param inAclSpec List<AclEntry> ACL spec containing entries to merge * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> mergeAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); List<AclEntry> foundAclSpecEntries = Lists.newArrayListWithCapacity(MAX_ENTRIES); EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry existingEntry: existingAcl) { AclEntry aclSpecEntry = aclSpec.findByKey(existingEntry); if (aclSpecEntry != null) { foundAclSpecEntries.add(aclSpecEntry); scopeDirty.add(aclSpecEntry.getScope()); if (aclSpecEntry.getType() == MASK) { providedMask.put(aclSpecEntry.getScope(), aclSpecEntry); maskDirty.add(aclSpecEntry.getScope()); } else { aclBuilder.add(aclSpecEntry); } } else { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } // ACL spec entries that were not replacements are new additions. for (AclEntry newEntry: aclSpec) { if (Collections.binarySearch(foundAclSpecEntries, newEntry, ACL_ENTRY_COMPARATOR) < 0) { scopeDirty.add(newEntry.getScope()); if (newEntry.getType() == MASK) { providedMask.put(newEntry.getScope(), newEntry); maskDirty.add(newEntry.getScope()); } else { aclBuilder.add(newEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); } /** * Completely replaces the ACL with the entries of the ACL spec. If * necessary, recalculates the mask entries. If necessary, default entries * are inferred by copying the permissions of the corresponding access * entries. Replacement occurs separately for each of the access ACL and the * default ACL. If the ACL spec contains only access entries, then the * existing default entries are retained. If the ACL spec contains only * default entries, then the existing access entries are retained. If the ACL * spec contains both access and default entries, then both are replaced. * * @param existingAcl List<AclEntry> existing ACL * @param inAclSpec List<AclEntry> ACL spec containing replacement entries * @return List<AclEntry> new ACL * @throws AclException if validation fails */ public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException { ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec); ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES); // Replacement is done separately for each scope: access and default. EnumMap<AclEntryScope, AclEntry> providedMask = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class); EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class); for (AclEntry aclSpecEntry: aclSpec) { scopeDirty.add(aclSpecEntry.getScope()); if (aclSpecEntry.getType() == MASK) { providedMask.put(aclSpecEntry.getScope(), aclSpecEntry); maskDirty.add(aclSpecEntry.getScope()); } else { aclBuilder.add(aclSpecEntry); } } // Copy existing entries if the scope was not replaced. for (AclEntry existingEntry: existingAcl) { if (!scopeDirty.contains(existingEntry.getScope())) { if (existingEntry.getType() == MASK) { providedMask.put(existingEntry.getScope(), existingEntry); } else { aclBuilder.add(existingEntry); } } } copyDefaultsIfNeeded(aclBuilder); calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty); return buildAndValidateAcl(aclBuilder); } /** * There is no reason to instantiate this class. */ private AclTransformation() { } /** * Comparator that enforces required ordering for entries within an ACL: * -owner entry (unnamed user) * -all named user entries (internal ordering undefined) * -owning group entry (unnamed group) * -all named group entries (internal ordering undefined) * -mask entry * -other entry * All access ACL entries sort ahead of all default ACL entries. */ static final Comparator<AclEntry> ACL_ENTRY_COMPARATOR = new Comparator<AclEntry>() { @Override public int compare(AclEntry entry1, AclEntry entry2) { return ComparisonChain.start() .compare(entry1.getScope(), entry2.getScope(), Ordering.explicit(ACCESS, DEFAULT)) .compare(entry1.getType(), entry2.getType(), Ordering.explicit(USER, GROUP, MASK, OTHER)) .compare(entry1.getName(), entry2.getName(), Ordering.natural().nullsFirst()) .result(); } }; /** * Builds the final list of ACL entries to return by trimming, sorting and * validating the ACL entries that have been added. * * @param aclBuilder ArrayList<AclEntry> containing entries to build * @return List<AclEntry> unmodifiable, sorted list of ACL entries * @throws AclException if validation fails */ private static List<AclEntry> buildAndValidateAcl( ArrayList<AclEntry> aclBuilder) throws AclException { aclBuilder.trimToSize(); Collections.sort(aclBuilder, ACL_ENTRY_COMPARATOR); // Full iteration to check for duplicates and invalid named entries. AclEntry prevEntry = null; for (AclEntry entry: aclBuilder) { if (prevEntry != null && ACL_ENTRY_COMPARATOR.compare(prevEntry, entry) == 0) { throw new AclException( "Invalid ACL: multiple entries with same scope, type and name."); } if (entry.getName() != null && (entry.getType() == MASK || entry.getType() == OTHER)) { throw new AclException( "Invalid ACL: this entry type must not have a name: " + entry + "."); } prevEntry = entry; } ScopedAclEntries scopedEntries = new ScopedAclEntries(aclBuilder); checkMaxEntries(scopedEntries); // Search for the required base access entries. If there is a default ACL, // then do the same check on the default entries. for (AclEntryType type: EnumSet.of(USER, GROUP, OTHER)) { AclEntry accessEntryKey = new AclEntry.Builder().setScope(ACCESS) .setType(type).build(); if (Collections.binarySearch(scopedEntries.getAccessEntries(), accessEntryKey, ACL_ENTRY_COMPARATOR) < 0) { throw new AclException( "Invalid ACL: the user, group and other entries are required."); } if (!scopedEntries.getDefaultEntries().isEmpty()) { AclEntry defaultEntryKey = new AclEntry.Builder().setScope(DEFAULT) .setType(type).build(); if (Collections.binarySearch(scopedEntries.getDefaultEntries(), defaultEntryKey, ACL_ENTRY_COMPARATOR) < 0) { throw new AclException( "Invalid default ACL: the user, group and other entries are required."); } } } return Collections.unmodifiableList(aclBuilder); } // Check the max entries separately on access and default entries // HDFS-7582 private static void checkMaxEntries(ScopedAclEntries scopedEntries) throws AclException { List<AclEntry> accessEntries = scopedEntries.getAccessEntries(); List<AclEntry> defaultEntries = scopedEntries.getDefaultEntries(); if (accessEntries.size() > MAX_ENTRIES) { throw new AclException("Invalid ACL: ACL has " + accessEntries.size() + " access entries, which exceeds maximum of " + MAX_ENTRIES + "."); } if (defaultEntries.size() > MAX_ENTRIES) { throw new AclException("Invalid ACL: ACL has " + defaultEntries.size() + " default entries, which exceeds maximum of " + MAX_ENTRIES + "."); } } /** * Calculates mask entries required for the ACL. Mask calculation is performed * separately for each scope: access and default. This method is responsible * for handling the following cases of mask calculation: * 1. Throws an exception if the caller attempts to remove the mask entry of an * existing ACL that requires it. If the ACL has any named entries, then a * mask entry is required. * 2. If the caller supplied a mask in the ACL spec, use it. * 3. If the caller did not supply a mask, but there are ACL entry changes in * this scope, then automatically calculate a new mask. The permissions of * the new mask are the union of the permissions on the group entry and all * named entries. * * @param aclBuilder ArrayList<AclEntry> containing entries to build * @param providedMask EnumMap<AclEntryScope, AclEntry> mapping each scope to * the mask entry that was provided for that scope (if provided) * @param maskDirty EnumSet<AclEntryScope> which contains a scope if the mask * entry is dirty (added or deleted) in that scope * @param scopeDirty EnumSet<AclEntryScope> which contains a scope if any entry * is dirty (added or deleted) in that scope * @throws AclException if validation fails */ private static void calculateMasks(List<AclEntry> aclBuilder, EnumMap<AclEntryScope, AclEntry> providedMask, EnumSet<AclEntryScope> maskDirty, EnumSet<AclEntryScope> scopeDirty) throws AclException { EnumSet<AclEntryScope> scopeFound = EnumSet.noneOf(AclEntryScope.class); EnumMap<AclEntryScope, FsAction> unionPerms = Maps.newEnumMap(AclEntryScope.class); EnumSet<AclEntryScope> maskNeeded = EnumSet.noneOf(AclEntryScope.class); // Determine which scopes are present, which scopes need a mask, and the // union of group class permissions in each scope. for (AclEntry entry: aclBuilder) { scopeFound.add(entry.getScope()); if (entry.getType() == GROUP || entry.getName() != null) { FsAction scopeUnionPerms = unionPerms.get(entry.getScope()); if (scopeUnionPerms == null) { scopeUnionPerms = FsAction.NONE; } unionPerms.put(entry.getScope(), scopeUnionPerms.or(entry.getPermission())); } if (entry.getName() != null) { maskNeeded.add(entry.getScope()); } } // Add mask entry if needed in each scope. for (AclEntryScope scope: scopeFound) { if (!providedMask.containsKey(scope) && maskNeeded.contains(scope) && maskDirty.contains(scope)) { // Caller explicitly removed mask entry, but it's required. throw new AclException( "Invalid ACL: mask is required and cannot be deleted."); } else if (providedMask.containsKey(scope) && (!scopeDirty.contains(scope) || maskDirty.contains(scope))) { // Caller explicitly provided new mask, or we are preserving the existing // mask in an unchanged scope. aclBuilder.add(providedMask.get(scope)); } else if (maskNeeded.contains(scope) || providedMask.containsKey(scope)) { // Otherwise, if there are maskable entries present, or the ACL // previously had a mask, then recalculate a mask automatically. aclBuilder.add(new AclEntry.Builder() .setScope(scope) .setType(MASK) .setPermission(unionPerms.get(scope)) .build()); } } } /** * Adds unspecified default entries by copying permissions from the * corresponding access entries. * * @param aclBuilder ArrayList<AclEntry> containing entries to build */ private static void copyDefaultsIfNeeded(List<AclEntry> aclBuilder) { Collections.sort(aclBuilder, ACL_ENTRY_COMPARATOR); ScopedAclEntries scopedEntries = new ScopedAclEntries(aclBuilder); if (!scopedEntries.getDefaultEntries().isEmpty()) { List<AclEntry> accessEntries = scopedEntries.getAccessEntries(); List<AclEntry> defaultEntries = scopedEntries.getDefaultEntries(); List<AclEntry> copiedEntries = Lists.newArrayListWithCapacity(3); for (AclEntryType type: EnumSet.of(USER, GROUP, OTHER)) { AclEntry defaultEntryKey = new AclEntry.Builder().setScope(DEFAULT) .setType(type).build(); int defaultEntryIndex = Collections.binarySearch(defaultEntries, defaultEntryKey, ACL_ENTRY_COMPARATOR); if (defaultEntryIndex < 0) { AclEntry accessEntryKey = new AclEntry.Builder().setScope(ACCESS) .setType(type).build(); int accessEntryIndex = Collections.binarySearch(accessEntries, accessEntryKey, ACL_ENTRY_COMPARATOR); if (accessEntryIndex >= 0) { copiedEntries.add(new AclEntry.Builder() .setScope(DEFAULT) .setType(type) .setPermission(accessEntries.get(accessEntryIndex).getPermission()) .build()); } } } // Add all copied entries when done to prevent potential issues with binary // search on a modified aclBulider during the main loop. aclBuilder.addAll(copiedEntries); } } /** * An ACL spec that has been pre-validated and sorted. */ private static final class ValidatedAclSpec implements Iterable<AclEntry> { private final List<AclEntry> aclSpec; /** * Creates a ValidatedAclSpec by pre-validating and sorting the given ACL * entries. Pre-validation checks that it does not exceed the maximum * entries. This check is performed before modifying the ACL, and it's * actually insufficient for enforcing the maximum number of entries. * Transformation logic can create additional entries automatically,such as * the mask and some of the default entries, so we also need additional * checks during transformation. The up-front check is still valuable here * so that we don't run a lot of expensive transformation logic while * holding the namesystem lock for an attacker who intentionally sent a huge * ACL spec. * * @param aclSpec List<AclEntry> containing unvalidated input ACL spec * @throws AclException if validation fails */ public ValidatedAclSpec(List<AclEntry> aclSpec) throws AclException { Collections.sort(aclSpec, ACL_ENTRY_COMPARATOR); checkMaxEntries(new ScopedAclEntries(aclSpec)); this.aclSpec = aclSpec; } /** * Returns true if this contains an entry matching the given key. An ACL * entry's key consists of scope, type and name (but not permission). * * @param key AclEntry search key * @return boolean true if found */ public boolean containsKey(AclEntry key) { return Collections.binarySearch(aclSpec, key, ACL_ENTRY_COMPARATOR) >= 0; } /** * Returns the entry matching the given key or null if not found. An ACL * entry's key consists of scope, type and name (but not permission). * * @param key AclEntry search key * @return AclEntry entry matching the given key or null if not found */ public AclEntry findByKey(AclEntry key) { int index = Collections.binarySearch(aclSpec, key, ACL_ENTRY_COMPARATOR); if (index >= 0) { return aclSpec.get(index); } return null; } @Override public Iterator<AclEntry> iterator() { return aclSpec.iterator(); } } }
{ "content_hash": "7b7b2db9fab85e3f0a53cb369b435726", "timestamp": "", "source": "github", "line_count": 483, "max_line_length": 84, "avg_line_length": 43.4472049689441, "alnum_prop": 0.6956873957588754, "repo_name": "mapr/hadoop-common", "id": "83ca54e0bb21c246092bb879f86b237939cef4af", "size": "21791", "binary": false, "copies": "7", "ref": "refs/heads/trunk", "path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/AclTransformation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78534" }, { "name": "C", "bytes": "2056401" }, { "name": "C++", "bytes": "3158543" }, { "name": "CMake", "bytes": "155815" }, { "name": "CSS", "bytes": "94990" }, { "name": "Dockerfile", "bytes": "4613" }, { "name": "HTML", "bytes": "222622" }, { "name": "Handlebars", "bytes": "207062" }, { "name": "Java", "bytes": "99637080" }, { "name": "JavaScript", "bytes": "1275309" }, { "name": "Python", "bytes": "21600" }, { "name": "SCSS", "bytes": "23607" }, { "name": "Shell", "bytes": "534276" }, { "name": "TLA", "bytes": "14997" }, { "name": "TSQL", "bytes": "17801" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "18026" } ], "symlink_target": "" }
Imports System.Drawing Imports System.Drawing.Drawing2D Imports Owl.Core.Structures Imports Owl.Core.Tensors Namespace Visualization Public Module PlotFactory ''' <summary> ''' Shape = {Rows, Columns, Channel} ''' </summary> ''' <param name="Tensor3D"></param> ''' <returns></returns> Public Function Tensor3DImage(Tensor3D As Tensor, R As Range) As Bitmap 'there is not much code here, but leaving it as it is for --questionable-- clarity. Tensor3D = Tensor3D.Duplicate Tensor3D.TrimFloor(R.Minimum) Tensor3D.TrimCeiling(R.Maximum) Tensor3D.Remap(R, New Range(0, 255)) Return Images.ToBitmap(Tensor3D) End Function Public Function Tensor3DImage(Tensor3D As Tensor) As Bitmap Return Images.ToBitmap(Tensor3D) End Function Public Function Tensor2DImage(Tensor2D As Tensor) As Bitmap Return Owl.Core.Images.ImageConverters.ToGrayscale(Tensor2D, Tensor2D.GetRange) End Function Public Function Tensor2DImage(Tensor2D As Tensor, R As Range) As Bitmap Return Owl.Core.Images.ImageConverters.ToGrayscale(Tensor2D, R) End Function Public Function TensorSetPlot(TSet As TensorSet, YAxisRange As Range, PlotSize As Size, PenThickness As Single, HighlightTensors As List(Of Integer)) As Bitmap Dim ts As TensorSet = TSet.Duplicate() Dim vsr As Range = ts.GetRange ts.Remap(YAxisRange, New Range(PlotSize.Height, 0)) Dim Image = New Bitmap(PlotSize.Width, PlotSize.Height) Using g As Graphics = Graphics.FromImage(Image) g.SmoothingMode = SmoothingMode.HighQuality For i As Integer = 0 To ts.Count - 1 Step 1 Dim tens As Tensor = ts(i) If tens.Length = 0 Then ElseIf tens.Length = 1 Then Dim thisgp As New GraphicsPath Dim pts(1) As Drawing.Point For j As Integer = 0 To 1 Step 1 pts(j) = New Drawing.Point(j * PlotSize.Width, tens(0)) Next thisgp.AddLines(pts) Dim rndhsl As New ColorHSL(120, ((i) / (ts.Count - 1)) * 360, 1, 0.5) Using p As Pen = New Pen(Color.FromArgb(100, ColorConversion.HSLToRGB(rndhsl)), PenThickness) p.DashPattern = {4, 4} p.LineJoin = LineJoin.Round p.SetLineCap(LineCap.Round, LineCap.Round, DashCap.Round) g.DrawPath(p, thisgp) End Using thisgp.Dispose() Else Dim thisgp As New GraphicsPath Dim pts(tens.Length - 1) As Drawing.Point For j As Integer = 0 To tens.Length - 1 Step 1 pts(j) = New Drawing.Point(CInt((j / (tens.Length - 1)) * PlotSize.Width), CInt(tens(j))) Next thisgp.AddLines(pts) Dim rndhsl As New ColorHSL(120, ((i) / (ts.Count)) * 360, 1, 0.5) Using p As Pen = New Pen(Color.FromArgb(100, ColorConversion.HSLToRGB(rndhsl)), PenThickness) p.LineJoin = LineJoin.Round p.SetLineCap(LineCap.Round, LineCap.Round, DashCap.Round) g.DrawPath(p, thisgp) End Using thisgp.Dispose() End If Next If HighlightTensors IsNot Nothing Then For i As Integer = 0 To HighlightTensors.Count - 1 Step 1 Dim v As Tensor = ts(HighlightTensors(i)) Dim thisi As Integer = HighlightTensors(i) Dim thisgp As New GraphicsPath Dim pts(v.Count - 1) As Drawing.Point For j As Integer = 0 To v.Count - 1 Step 1 pts(j) = New Drawing.Point((j / (v.Count - 1)) * PlotSize.Width, v(j)) Next thisgp.AddLines(pts) Using p As Pen = New Pen(Color.FromArgb(120, Color.Black), PenThickness * 5) p.LineJoin = LineJoin.Round p.SetLineCap(LineCap.Round, LineCap.Round, DashCap.Round) g.DrawPath(p, thisgp) End Using Dim rndhsl As New ColorHSL(120, (thisi) / (ts.Count - 1), 1, 0.5) Using p As Pen = New Pen(Color.FromArgb(100, ColorConversion.HSLToRGB(rndhsl)), PenThickness) g.DrawPath(p, thisgp) End Using thisgp.Dispose() Next End If End Using Return Image End Function Public Function DrawGridBackground(ImageW As Integer, ImageH As Integer, Optional GridW As Integer = 10, Optional GridH As Integer = 10) As Bitmap Dim filler As New Bitmap(GridW, GridH) Dim background As New Bitmap(ImageW, ImageH) Using g As Graphics = Graphics.FromImage(filler) g.SmoothingMode = SmoothingMode.None g.InterpolationMode = InterpolationMode.NearestNeighbor g.PixelOffsetMode = PixelOffsetMode.None g.Clear(Color.White) g.DrawRectangle(Pens.LightGray, 0, 0, GridW, GridH) End Using Using g As Graphics = Graphics.FromImage(background) g.SmoothingMode = SmoothingMode.None g.InterpolationMode = InterpolationMode.NearestNeighbor g.PixelOffsetMode = PixelOffsetMode.None Using tx As Brush = New TextureBrush(filler) g.FillRectangle(tx, 0, 0, ImageW, ImageH) End Using End Using filler.Dispose() Return background End Function Public Function ImageStitcher(Tensors2D As IEnumerable(Of Tensor), Width As Integer, Heigth As Integer) As Bitmap If Tensors2D.Count < 1 Then Return Nothing Dim ts As IEnumerable(Of Tensor) = Tensors2D If ts.Count <> Width * Heigth Then Return Nothing Dim tset As New TensorSet(Tensors2D) If Not tset.IsHomogeneous Then Return Nothing Dim sz As New Size(ts(0).Width, ts(0).Height) Dim bmp As New Bitmap(sz.Width * Width, sz.Height * Heigth) Using g As Graphics = Graphics.FromImage(bmp) g.SmoothingMode = SmoothingMode.None g.InterpolationMode = InterpolationMode.NearestNeighbor Dim cnt As Integer = 0 For i As Integer = 0 To Heigth - 1 Step 1 For j As Integer = 0 To Width - 1 Step 1 Dim crop As Bitmap = Tensor2DImage(ts(cnt)) g.DrawImage(crop, j * sz.Width, i * sz.Height) crop.Dispose() cnt += 1 Next Next End Using Return bmp End Function End Module End Namespace
{ "content_hash": "ecb2a7c3240bf2e005d9a26141659599", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 167, "avg_line_length": 37.288557213930346, "alnum_prop": 0.5316877918612408, "repo_name": "mateuszzwierzycki/Owl", "id": "794f220f341977454061b5be4dabde8bc46b784b", "size": "7497", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Owl.Core/Visualization/Plots.vb", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "17477" }, { "name": "Visual Basic .NET", "bytes": "550306" } ], "symlink_target": "" }
"use strict"; var screenWidth; var screenHeight; var context; var fps; var camera; var gameObjects = []; var seek = new Seek(); $(document).ready(function() { var canvas = $("#gameCanvas")[0]; screenWidth = canvas.width; screenHeight = canvas.height; context = canvas.getContext("2d"); context.font = "bold 14px sans-serif"; fps = $("#fps")[0]; setSubmitEvent(); setKeyEvents(); camera = new Camera(); gameObjects[0] = new Trapezoid(); requestAnimationFrame(gameLoop); }); function setSubmitEvent() { $('form').submit(function(e) { var x = $('#x').val(); var z = $('#z').val(); if(isNumber(x) && isNumber(z)) { gameObjects[1] = new Circle([parseFloat(x), 0, parseFloat(z)]); } else { gameObjects.splice(1, 1); } e.preventDefault(); }); } function setKeyEvents() { $(document).keydown(function(e) { var target = gameObjects[1]; if(target) { if(e.which == 37 && target.moveDirection[0] >= 0) { target.moveDirection[0] = -1; } else if(e.which == 39 && target.moveDirection[0] <= 0) { target.moveDirection[0] = 1; } else if(e.which == 38 && target.moveDirection[2] >= 0) { target.moveDirection[2] = -1; } else if(e.which == 40 && target.moveDirection[2] <= 0) { target.moveDirection[2] = 1; } } }); $(document).keyup(function(e) { var target = gameObjects[1]; if(target) { if(e.which == 37 && target.moveDirection[0] < 0) { target.moveDirection[0] = 0; } else if(e.which == 39 && target.moveDirection[0] > 0) { target.moveDirection[0] = 0; } else if(e.which == 38 && target.moveDirection[2] < 0) { target.moveDirection[2] = 0; } else if(e.which == 40 && target.moveDirection[2] > 0) { target.moveDirection[2] = 0; } } }); } var lastFrame = 0; function gameLoop(timestamp) { updateFPS(timestamp); var dt = (timestamp - lastFrame) / 1000; dt = (dt > 1/15) ? 1/15 : dt; lastFrame = timestamp; stepGame(dt, timestamp); drawGame(); requestAnimationFrame(gameLoop); }; function stepGame(dt) { if(gameObjects[1]) { var steering = seek.getSteering(gameObjects[0], gameObjects[1]); gameObjects[0].update(dt, steering); gameObjects[1].update(dt); } } function drawGame() { context.clearRect(0, 0, screenWidth, screenHeight); context.save(); camera.applyTransforms(); drawCoordinateGrid(); for(var i = 0; i < gameObjects.length; i++) { gameObjects[i].draw(); } context.restore(); }
{ "content_hash": "ecc1d9b9af123623f636e0b6ef7c5ea3", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 66, "avg_line_length": 19.816, "alnum_prop": 0.6128381106176827, "repo_name": "antonpantev/game-ai", "id": "87143afddf5c5f502d534e6fc347d132abc9afa5", "size": "2477", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "steering-behaviors/seek/js/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "72950" }, { "name": "GLSL", "bytes": "289" }, { "name": "HTML", "bytes": "31515" }, { "name": "JavaScript", "bytes": "781779" } ], "symlink_target": "" }
/* * Thanks to Dmitry Baranovsky and his Raphael library for inspiration! */ /* * @class SVG * * Although SVG is not available on IE7 and IE8, these browsers support [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language), and the SVG renderer will fall back to VML in this case. * * VML was deprecated in 2012, which means VML functionality exists only for backwards compatibility * with old versions of Internet Explorer. */ // @namespace Browser; @property vml: Boolean // `true` if the browser supports [VML](https://en.wikipedia.org/wiki/Vector_Markup_Language). L.Browser.vml = !L.Browser.svg && (function () { try { var div = document.createElement('div'); div.innerHTML = '<v:shape adj="1"/>'; var shape = div.firstChild; shape.style.behavior = 'url(#default#VML)'; return shape && (typeof shape.adj === 'object'); } catch (e) { return false; } }()); // redefine some SVG methods to handle VML syntax which is similar but with some differences L.SVG.include(!L.Browser.vml ? {} : { _initContainer: function () { this._container = L.DomUtil.create('div', 'leaflet-vml-container'); }, _update: function () { if (this._map._animatingZoom) { return; } L.Renderer.prototype._update.call(this); }, _initPath: function (layer) { var container = layer._container = L.SVG.create('shape'); L.DomUtil.addClass(container, 'leaflet-vml-shape ' + (this.options.className || '')); container.coordsize = '1 1'; layer._path = L.SVG.create('path'); container.appendChild(layer._path); this._updateStyle(layer); }, _addPath: function (layer) { var container = layer._container; this._container.appendChild(container); if (layer.options.interactive) { layer.addInteractiveTarget(container); } }, _removePath: function (layer) { var container = layer._container; L.DomUtil.remove(container); layer.removeInteractiveTarget(container); }, _updateStyle: function (layer) { var stroke = layer._stroke, fill = layer._fill, options = layer.options, container = layer._container; container.stroked = !!options.stroke; container.filled = !!options.fill; if (options.stroke) { if (!stroke) { stroke = layer._stroke = L.SVG.create('stroke'); } container.appendChild(stroke); stroke.weight = options.weight + 'px'; stroke.color = options.color; stroke.opacity = options.opacity; if (options.dashArray) { stroke.dashStyle = L.Util.isArray(options.dashArray) ? options.dashArray.join(' ') : options.dashArray.replace(/( *, *)/g, ' '); } else { stroke.dashStyle = ''; } stroke.endcap = options.lineCap.replace('butt', 'flat'); stroke.joinstyle = options.lineJoin; } else if (stroke) { container.removeChild(stroke); layer._stroke = null; } if (options.fill) { if (!fill) { fill = layer._fill = L.SVG.create('fill'); } container.appendChild(fill); fill.color = options.fillColor || options.color; fill.opacity = options.fillOpacity; } else if (fill) { container.removeChild(fill); layer._fill = null; } }, _updateCircle: function (layer) { var p = layer._point.round(), r = Math.round(layer._radius), r2 = Math.round(layer._radiusY || r); this._setPath(layer, layer._empty() ? 'M0 0' : 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r2 + ' 0,' + (65535 * 360)); }, _setPath: function (layer, path) { layer._path.v = path; }, _bringToFront: function (layer) { L.DomUtil.toFront(layer._container); }, _bringToBack: function (layer) { L.DomUtil.toBack(layer._container); } }); if (L.Browser.vml) { L.SVG.create = (function () { try { document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml'); return function (name) { return document.createElement('<lvml:' + name + ' class="lvml">'); }; } catch (e) { return function (name) { return document.createElement('<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">'); }; } })(); }
{ "content_hash": "eb4389a9b83ab628ac10476257ca59cd", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 189, "avg_line_length": 26.19607843137255, "alnum_prop": 0.6444610778443114, "repo_name": "hyperknot/Leaflet", "id": "127ade901efd0da25a9a3887ac7ccfe9bfd86ced", "size": "4008", "binary": false, "copies": "9", "ref": "refs/heads/rotate-rc1", "path": "src/layer/vector/SVG.VML.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "150" }, { "name": "HTML", "bytes": "160883" }, { "name": "JavaScript", "bytes": "766263" }, { "name": "Shell", "bytes": "360" } ], "symlink_target": "" }
//! //! @file ComponentSystem.h //! @author FluMeS //! @date 2009-12-20 //! //! @brief Contains the subsystem component class and connection assistant help class //! //$Id$ #ifndef COMPONENTSYSTEM_H #define COMPONENTSYSTEM_H #if __cplusplus >= 201103L #include <mutex> #include <chrono> #include <ctime> #endif #include "Component.h" #include "CoreUtilities/SimulationHandler.h" #include "CoreUtilities/AliasHandler.h" namespace hopsan { class NumHopHelper; class ComponentSystemMultiThreadPrivates; class HOPSANCORE_DLLAPI ComponentSystem :public Component { friend class ConnectionAssistant; friend class AliasHandler; public: enum UniqeNameEnumT {UniqueComponentNameType, UniqueSysportNameTyp, UniqueSysparamNameType, UniqueAliasNameType, UniqueReservedNameType}; typedef std::map<HString, std::pair<std::vector<HString>, std::vector<HString> > > SetParametersMapT; //==========Public functions========== virtual ~ComponentSystem(); static Component* Creator(){ return new ComponentSystem(); } virtual void configure(); // Subsystem CQS type methods bool isComponentSystem() const {return true;} CQSEnumT getTypeCQS() const; void setTypeCQS(CQSEnumT cqs_type, bool doOnlyLocalSet=false); bool changeSubComponentSystemTypeCQS(const HString &rName, const CQSEnumT newType); void determineCQSType(); bool isTopLevelSystem() const; bool isExternalSystem() const; void setExternalModelFilePath(const HString &rPath); HString getExternalModelFilePath() const; // Adding removing and renaming components void addComponents(std::vector<Component*> &rComponents); void addComponent(Component *pComponent); void renameSubComponent(const HString &rOldName, const HString &rNewName); void removeSubComponent(const HString &rName, bool doDelete=false); void removeSubComponent(Component *pComponent, bool doDelete=false); HString reserveUniqueName(const HString &rDesiredName, const UniqeNameEnumT type=UniqueReservedNameType); void unReserveUniqueName(const HString &rName); // System Parameter functions bool renameParameter(const HString &rOldName, const HString &rNewName); virtual std::list<HString> getModelAssets() const; // Handle system ports Port* addSystemPort(HString portName, const HString &rDescription=""); HString renameSystemPort(const HString &rOldname, const HString &rNewname); void deleteSystemPort(const HString &rName); // Getting added components and component names Component* getSubComponentOrThisIfSysPort(const HString &rName); Component* getSubComponent(const HString &rName) const; const std::vector<Component*> getSubComponents() const; ComponentSystem* getSubComponentSystem(const HString &rName) const; std::vector<HString> getSubComponentNames() const; bool haveSubComponent(const HString &rName) const; bool isEmpty() const; // Alias handler AliasHandler &getAliasHandler(); // Connecting and disconnecting components bool connect(Port *pPort1, Port *pPort2); bool connect(const HString &compname1, const HString &portname1, const HString &compname2, const HString &portname2); bool disconnect(const HString &compname1, const HString &portname1, const HString &compname2, const HString &portname2); bool disconnect(Port *pPort1, Port *pPort2); // Start value loading bool keepsValuesAsStartValues(); void setKeepValuesAsStartValues(bool load); void loadStartValues(); void loadStartValuesFromSimulation(); void evaluateParametersRecursively(); // Parameter value loading size_t loadParameterValues(const HString &rFilePath); // NumHop script bool evaluateNumHopScriptRecursively(); bool runNumHopScript(const HString &rScript, bool printOutput, HString &rOutput); void setNumHopScript(const HString &rScript); HString getNumHopScript() const; // Initialize and simulate bool checkModelBeforeSimulation(); virtual bool preInitialize(); bool initialize(const double startT, const double stopT); void simulate(const double stopT); bool startRealtimeSimulation(double realTimeFactor=1); virtual void simulateMultiThreaded(const double startT, const double stopT, const size_t nDesiredThreads = 0, const bool noChanges=false, ParallelAlgorithmT algorithm=OfflineSchedulingAlgorithm); void finalize(); bool simulateAndMeasureTime(const size_t nSteps); double getTotalMeasuredTime(); void sortComponentVectorsByMeasuredTime(); void distributeCcomponents(std::vector< std::vector<Component*> > &rSplitCVector, size_t nThreads); void distributeQcomponents(std::vector< std::vector<Component*> > &rSplitQVector, size_t nThreads); void distributeSignalcomponents(std::vector< std::vector<Component*> > &rSplitSignalVector, size_t nThreads); void distributeNodePointers(std::vector< std::vector<Node*> > &rSplitNodeVector, size_t nThreads); void reschedule(size_t nThreads); // Set and get desired timestep void setDesiredTimestep(const double timestep); void setInheritTimestep(const bool inherit=true); bool doesInheritTimestep() const; double getDesiredTimeStep() const; // Log functions void logTimeAndNodes(const size_t simStep); void enableLog(); void disableLog(); std::vector<double>* getLogTimeVector(); void setNumLogSamples(const size_t nLogSamples); double getLogStartTime() const; void setLogStartTime(const double logStartTime); size_t getNumLogSamples() const; size_t getNumActuallyLoggedSamples() const; // Stop a running initialization or simulation void stopSimulation(const HString &rReason); void stopSimulation(); bool wasSimulationAborted() const; // System parameters bool setOrAddSystemParameter(const HString &rName, const HString &rValue, const HString &rType, const HString &rDescription="", const HString &rUnitOrQuantity="", const bool force=false); bool setSystemParameter(const HString &rName, const HString &rValue, const HString &rType, const HString &rDescription="", const HString &rUnitOrQuantity="", const bool force=false); void unRegisterParameter(const HString &name); void addSearchPath(HString searchPath); // Add and Remove sub-nodes void addSubNode(Node* pNode); void removeSubNode(Node* pNode); protected: // Constructor - Destructor- Creator ComponentSystem(); // Internal Flags //! @brief This bool can be toggled off in programmed subsystems to avoid annoying warnings //! @ingroup ComponentPowerAuthorFunctions bool mWarnIfUnusedSystemParameters; // Log and timestep std::vector<size_t> mLogTheseTimeSteps; size_t mTotalTakenSimulationSteps; typedef std::map<HString, Component*> SubComponentMapT; SubComponentMapT mSubComponentMap; NumHopHelper *mpNumHopHelper; HString mNumHopScript; private: //==========Private functions========== // Time specific functions void setTimestep(const double timestep); void adjustTimestep(std::vector<Component*> componentPtrs); // log specific functions //! @todo restore these in some way // void setLogSettingsSampleTime(double log_dt, double start, double stop, double sampletime); // void setLogSettingsSkipFactor(double factor, double start, double stop, double sampletime); void setupLogSlotsAndTs(const double simStartT, const double simStopT, const double simTs); void preAllocateLogSpace(); // Add and Remove subcomponent ptrs from storage vectors void addSubComponentPtrToStorage(Component* pComponent); void removeSubComponentPtrFromStorage(Component* pComponent); // Clear all contents of the system (use in destructor) void clear(); bool sortComponentVector(std::vector<Component*> &rOldSignalVector); // UniqueName specific functions HString determineUniquePortName(const HString &rPortname); HString determineUniqueComponentName(const HString &rName) const; bool hasReservedUniqueName(const HString &rName) const; //==========Private member variables========== CQSEnumT mTypeCQS; HString mExternalModelFilePath; std::vector<Component*> mComponentSignalptrs; std::vector<Component*> mComponentQptrs; std::vector<Component*> mComponentCptrs; std::vector<Component*> mComponentUndefinedptrs; std::vector<Node*> mSubNodePtrs; std::vector<Component*> mDisabledSptrs; std::vector<Component*> mDisabledQptrs; std::vector<Component*> mDisabledCptrs; typedef std::map<HString, UniqeNameEnumT> TakenNamesMapT; TakenNamesMapT mTakenNames; bool volatile mStopSimulation; // This block of variables are only used with multi-threading but they must be included always else // components inheriting ComponentSystem will not know that they exist resulting in overwriting memory //! @todo we could hide them in a private struct and put a forward declared pointer here instead //#if __cplusplus >= 201103L //std::mutex *mpStopMutex; //#endif //std::vector<double *> mvTimePtrs; //std::vector< std::vector<Component*> > mSplitCVector; //std::vector< std::vector<Component*> > mSplitQVector; //std::vector< std::vector<Component*> > mSplitSignalVector; //std::vector< std::vector<Node*> > mSplitNodeVector; ComponentSystemMultiThreadPrivates *mpMultiThreadPrivates; //------------------------------------------------------------------ bool mKeepValuesAsStartValues; AliasHandler mAliasHandler; // Log related variables size_t mRequestedNumLogSamples, mnLogSlots, mLogCtr; double mRequestedLogStartTime, mLogTimeDt; bool mEnableLogData; std::vector<double> mTimeStorage; }; class ConditionalComponentSystem : public ComponentSystem { public: static Component* Creator(){ return new ConditionalComponentSystem(); } void configure(); void simulate(const double stopT); void simulateMultiThreaded(const double startT, const double stopT, const size_t nDesiredThreads, const bool noChanges, ParallelAlgorithmT algorithm); private: double *mpCondition; bool mAsleep; }; } #if __cplusplus >= 201103L #ifdef _WIN32 //! @todo Move to utilities? struct HighResClock { typedef long long rep; typedef std::nano period; typedef std::chrono::duration<rep, period> duration; typedef std::chrono::time_point<HighResClock> time_point; static const bool is_steady = true; static time_point now(); }; #endif //_WIN32 #endif //C++11 #endif // COMPONENTSYSTEM_H
{ "content_hash": "8f0737f43dc812d4ef001eba896f2736", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 203, "avg_line_length": 40.70106761565836, "alnum_prop": 0.6846200926816473, "repo_name": "Hopsan/hopsan", "id": "6a1eec50f4a0c6866bd4fce387ff1b4fae70228c", "size": "12425", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HopsanCore/include/ComponentSystem.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6842" }, { "name": "C", "bytes": "211307" }, { "name": "C++", "bytes": "8125248" }, { "name": "CMake", "bytes": "35439" }, { "name": "HTML", "bytes": "113099" }, { "name": "Inno Setup", "bytes": "4034" }, { "name": "MATLAB", "bytes": "11965" }, { "name": "Makefile", "bytes": "6066" }, { "name": "Mathematica", "bytes": "15604656" }, { "name": "Modelica", "bytes": "5652" }, { "name": "Python", "bytes": "92629" }, { "name": "QMake", "bytes": "88819" }, { "name": "Shell", "bytes": "47273" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Vapor Store")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Vapor Store")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("26e2e9f7-578a-4eb3-80b3-54ea7803ab8b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "9b75a73f60564581ae6c7c7989326a76", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 38.611111111111114, "alnum_prop": 0.746043165467626, "repo_name": "preslavc/SoftUni", "id": "b1ee9c5464d96760807658eecf28892d5e431cad", "size": "1393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming Fundamentals/More Exercises/C# Basics/Vapor Store/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "623455" }, { "name": "Java", "bytes": "49221" } ], "symlink_target": "" }
using System.CommandLine; using System.CommandLine.Parsing; using DistributedTests.Client.Commands; using DistributedTests.Client.LoadGeneratorScenario; using Microsoft.Extensions.Logging; var loggerFactory = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Information) .AddSimpleConsole(options => options.SingleLine = true)); var root = new RootCommand(); root.Add(Scenario.CreateCommand(new PingScenario(), loggerFactory)); root.Add(new CounterCaptureCommand(loggerFactory.CreateLogger<CounterCaptureCommand>())); root.Add(new ChaosAgentCommand(loggerFactory.CreateLogger<ChaosAgentCommand>())); await root.InvokeAsync(args);
{ "content_hash": "191fc7a658fef749aa9726a0d6338547", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 116, "avg_line_length": 44.3125, "alnum_prop": 0.7602256699576869, "repo_name": "ElanHasson/orleans", "id": "0d7086d79229632ba6c526c6a644a6a370abda14", "size": "709", "binary": false, "copies": "8", "ref": "refs/heads/main", "path": "test/DistributedTests/DistributedTests.Client/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2529" }, { "name": "C#", "bytes": "10023471" }, { "name": "Dockerfile", "bytes": "780" }, { "name": "F#", "bytes": "2546" }, { "name": "PLSQL", "bytes": "21319" }, { "name": "PLpgSQL", "bytes": "33702" }, { "name": "PowerShell", "bytes": "6069" }, { "name": "Shell", "bytes": "2686" }, { "name": "Smalltalk", "bytes": "1436" }, { "name": "TSQL", "bytes": "24557" } ], "symlink_target": "" }
""" Pagination: select how many results to display. """ # Maybe refactor later the same way as variant_filter, # but maybe not necessary as long as they are so simple. def pagination_from_request(request): lim = request.GET.get('limit') off = request.GET.get('offset', '0') assert off.isdigit(), "Argument to 'offset' must be an integer" off = int(off) if lim is not None: assert lim.isdigit(), "Argument to 'limit' must be an integer" lim = int(lim) return Pagination(lim, off) class Pagination: def __init__(self, limit=None, offset=0): """ :param limit: (int) keep only that many. :param offset: (int) skip that many. """ self.lim = limit self.off = offset def limit(self, variants): """Keep only the first *lim* variants. Corresponds to the 'LIMIT' and 'OFFSET' SQL statements. :param variants: QuerySet. """ return variants[:self.lim] def offset(self, variants): """Skip the first *off* variants. Corresponds to the 'OFFSET' SQL statement. :param variants: QuerySet. """ return variants[self.off:] def paginate(self, variants): var = self.offset(variants) if self.lim: var = self.limit(var) return var
{ "content_hash": "1b34a2c1849a7b1100bef7135ac80648", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 70, "avg_line_length": 29, "alnum_prop": 0.5982008995502249, "repo_name": "444thLiao/VarappX-flask", "id": "23a47459be9689c0586a52bec877165ddc996c48", "size": "1334", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "varappx/filters/pagination.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "506164" }, { "name": "HTML", "bytes": "267707" }, { "name": "JavaScript", "bytes": "4184850" }, { "name": "Mako", "bytes": "494" }, { "name": "PHP", "bytes": "10512" }, { "name": "Python", "bytes": "280703" }, { "name": "Shell", "bytes": "158" } ], "symlink_target": "" }
require 'devise/strategies/base' module Devise module Strategies # This strategy should be used as basis for authentication strategies. It retrieves # parameters both from params or from http authorization headers. See database_authenticatable # for an example. class Authenticatable < Base attr_accessor :authentication_hash, :authentication_type, :password def store? super && !mapping.to.skip_session_storage.include?(authentication_type) end def valid? valid_for_params_auth? || valid_for_http_auth? end private # Receives a resource and check if it is valid by calling valid_for_authentication? # An optional block that will be triggered while validating can be optionally # given as parameter. Check Devise::Models::Authenticable.valid_for_authentication? # for more information. # # In case the resource can't be validated, it will fail with the given # unauthenticated_message. def validate(resource, &block) unless resource ActiveSupport::Deprecation.warn "an empty resource was given to #{self.class.name}#validate. " \ "Please ensure the resource is not nil", caller end result = resource && resource.valid_for_authentication?(&block) case result when Symbol, String ActiveSupport::Deprecation.warn "valid_for_authentication? should return a boolean value" fail!(result) return false end if result decorate(resource) true else if resource fail!(resource.unauthenticated_message) end false end end # Get values from params and set in the resource. def decorate(resource) resource.remember_me = remember_me? if resource.respond_to?(:remember_me=) end # Should this resource be marked to be remembered? def remember_me? valid_params? && Devise::TRUE_VALUES.include?(params_auth_hash[:remember_me]) end # Check if this is strategy is valid for http authentication by: # # * Validating if the model allows params authentication; # * If any of the authorization headers were sent; # * If all authentication keys are present; # def valid_for_http_auth? http_authenticatable? && request.authorization && with_authentication_hash(:http_auth, http_auth_hash) end # Check if this is strategy is valid for params authentication by: # # * Validating if the model allows params authentication; # * If the request hits the sessions controller through POST; # * If the params[scope] returns a hash with credentials; # * If all authentication keys are present; # def valid_for_params_auth? params_authenticatable? && valid_params_request? && valid_params? && with_authentication_hash(:params_auth, params_auth_hash) end # Check if the model accepts this strategy as http authenticatable. def http_authenticatable? mapping.to.http_authenticatable?(authenticatable_name) end # Check if the model accepts this strategy as params authenticatable. def params_authenticatable? mapping.to.params_authenticatable?(authenticatable_name) end # Extract the appropriate subhash for authentication from params. def params_auth_hash params[scope] end # Extract a hash with attributes:values from the http params. def http_auth_hash keys = [http_authentication_key, :password] Hash[*keys.zip(decode_credentials).flatten] end # By default, a request is valid if the controller set the proper env variable. def valid_params_request? !!env["devise.allow_params_authentication"] end # If the request is valid, finally check if params_auth_hash returns a hash. def valid_params? params_auth_hash.is_a?(Hash) end # Check if password is present and is not equal to "X" (default value for token). def valid_password? password.present? && password != "X" end # Helper to decode credentials from HTTP. def decode_credentials return [] unless request.authorization && request.authorization =~ /^Basic (.*)/m Base64.decode64($1).split(/:/, 2) end # Sets the authentication hash and the password from params_auth_hash or http_auth_hash. def with_authentication_hash(auth_type, auth_values) self.authentication_hash, self.authentication_type = {}, auth_type self.password = auth_values[:password] parse_authentication_key_values(auth_values, authentication_keys) && parse_authentication_key_values(request_values, request_keys) end def authentication_keys @authentication_keys ||= mapping.to.authentication_keys end def http_authentication_key @http_authentication_key ||= mapping.to.http_authentication_key || case authentication_keys when Array then authentication_keys.first when Hash then authentication_keys.keys.first end end def request_keys @request_keys ||= mapping.to.request_keys end def request_values keys = request_keys.respond_to?(:keys) ? request_keys.keys : request_keys values = keys.map { |k| self.request.send(k) } Hash[keys.zip(values)] end def parse_authentication_key_values(hash, keys) keys.each do |key, enforce| value = hash[key].presence if value self.authentication_hash[key] = value else return false unless enforce == false end end true end # Holds the authenticatable name for this class. Devise::Strategies::DatabaseAuthenticatable # becomes simply :database. def authenticatable_name @authenticatable_name ||= ActiveSupport::Inflector.underscore(self.class.name.split("::").last). sub("_authenticatable", "").to_sym end end end end
{ "content_hash": "6b6a03ea04c4fcb01a2d8c4782ae1334", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 110, "avg_line_length": 34.737430167597765, "alnum_prop": 0.6463493084593117, "repo_name": "xiuxian123/loyal_device", "id": "28f12cdacb5312c8990ffcb967cc1de6f635a8d0", "size": "6218", "binary": false, "copies": "11", "ref": "refs/heads/rails4", "path": "lib/devise/strategies/authenticatable.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Logos", "bytes": "572" }, { "name": "Ruby", "bytes": "469823" } ], "symlink_target": "" }
#ifndef Vps_VPublication_Interface #define Vps_VPublication_Interface /************************ ***** Components ***** ************************/ #include "Vca_VRolePlayer.h" #include "Vps_IPublication.h" #include "Vps_IMessage.h" #include "Vps_IMessageSink.h" #include "Vps_ISubscription.h" #include "Vps_IWatermarkedDataSink.h" #include "Vps_IWatermarkablePublication.h" /************************** ***** Declarations ***** **************************/ /************************* ***** Definitions ***** *************************/ namespace Vca { namespace Vps { class Vps_API VPublication : public VRolePlayer { DECLARE_ABSTRACT_RTT (VPublication, VRolePlayer); // Aliases public: typedef Reference PublicationReference; // enum public: enum State { State_Started, State_Stopped }; // Watermark public: class Watermark : public VReferenceable { DECLARE_CONCRETE_RTTLITE (Watermark, VReferenceable); // Construction public: Watermark (VString const &rWatermarkData); private: static VString WatermarkPreamble (VString const &rWatermarkData); // Destruction private: ~Watermark () { } // Access public: VString const &watermarkPreamble () const { return m_iWatermarkPreamble; } VString watermark () const; // State private: VString const m_iWatermarkPreamble; }; // Message public: class Message : public VRolePlayer { DECLARE_CONCRETE_RTT (Message, VRolePlayer); // Contruction public: Message(const VPublication *pPublication); // Destruction private: ~Message (); // Roles public: using BaseClass::getRole; public: VRole<ThisClass,IMessage> m_pIMessage; void getRole (IMessage::Reference &rpRole) { m_pIMessage.getRole (rpRole); } // Access public: void SetWanted(IMessage*, bool wanted) { m_bWanted = wanted; } bool Wanted() { return m_bWanted; } private: PublicationReference const m_pPublication; bool m_bWanted; }; // Subscription public: class Vps_API Subscription : public VRolePlayer { DECLARE_CONCRETE_RTT (Subscription, VRolePlayer); // Aliases public: typedef IVReceiver<VString const &> IRecipient; // enum public: enum State { State_Active, State_Suspended, State_Canceled }; // Construction public: Subscription ( VPublication *pPublication, ISubscriber *pSubscriber, IRecipient *pRecipient, Watermark *pWatermark, bool bSuspended ); // Destruction private: ~Subscription (); // Roles public: using BaseClass::getRole; //---> ISubscription Role private: VRole<ThisClass,ISubscription> m_pISubscription; public: void getRole (ISubscription::Reference &rpRole) { m_pISubscription.getRole (rpRole); } // Role Callbacks //---> ISubscription public: void Suspend (ISubscription *pRole); void Resume (ISubscription *pRole); void Cancel (ISubscription *pRole); // Publication public: ThisClass *publish (VString const &rMessage); ThisClass *publish (Message *pMessage, VString const &rMessage); ThisClass *publishError (IError *pError, VString const &rMessage); // Maintenance private: void unlink (); // State private: PublicationReference const m_pPublication; IRecipient::Reference const m_pRecipient; IWatermarkedDataSink::Reference const m_pWatermarkableRecipient; Watermark::Reference const m_pWatermark; IMessageSink::Reference m_pMessageSink; Pointer m_pSuccessor; Pointer m_pPredecessor; State m_xState; }; friend class Subscription; // Construction protected: VPublication (VString const &rSubject); // Destruction protected: ~VPublication (); // IWatermarkablePublication Role private: VRole<ThisClass,IWatermarkablePublication> m_pIPublication; public: void getRole (IWatermarkablePublication::Reference &rpRole) { m_pIPublication.getRole (rpRole); }; // IWatermarkablePublication Methods public: void SubscribeWithWatermark ( IWatermarkablePublication *pRole, ISubscriber *pSubscriber, IWatermarkedDataSink *pRecipient, VString const &rWatermark, bool bSuspended ); // IPublication Role private: // VRole<ThisClass,IPublication> m_pIPublication; public: void getRole (IPublication::Reference &rpRole) { // m_pIPublication.getRole (rpRole); IWatermarkablePublication::Reference pWatermarkablePublicationRole; getRole (pWatermarkablePublicationRole); rpRole.setTo (pWatermarkablePublicationRole); }; // IPublication Methods public: void Subscribe (IPublication *pRole, ISubscriber *pSubscriber, IRecipient *pRecipient, bool bSuspended); // Overrides private: virtual void OnError_(IError *pInterface, VString const &rMessage) OVERRIDE; // Access protected: State state () const { return m_xState; } VString const &subject () const { return m_iSubject; } counter_t::value_t subscriptionCount () const { return m_cSubscriptions; } Subscription *subscriptionListHead () const { return m_pSubscriptions; } // Query public: bool started () const { return m_xState == State_Started; } bool stopped () const { return m_xState == State_Stopped; } // Control protected: virtual bool start ()=0; virtual bool stop ()=0; // Update private: void addSubscriber (ISubscriber *pSubscriber, IRecipient *pRecipient, Watermark *pWatermark, bool bSuspended); void incrementSubscriptions (); void decrementSubscriptions (); // Use protected: void publish (VString const &rMessage) const; void publish (Message *pMessage, VString const &rMessage) const; // State private: VString const m_iSubject; State m_xState; counter_t m_cSubscriptions; Subscription::Pointer m_pSubscriptions; }; } } #endif
{ "content_hash": "5d588dd4d7c00d7c61649b881950340f", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 142, "avg_line_length": 23.909774436090224, "alnum_prop": 0.6272012578616353, "repo_name": "MichaelJCaruso/vision", "id": "e84899fb6082ba80a51cb56790935b51b5f43749", "size": "6360", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "software/src/master/src/kernel/Vps_VPublication.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1984863" }, { "name": "Batchfile", "bytes": "19723" }, { "name": "Brainfuck", "bytes": "1650" }, { "name": "C", "bytes": "1865301" }, { "name": "C++", "bytes": "34310227" }, { "name": "Clojure", "bytes": "29068" }, { "name": "D", "bytes": "485429" }, { "name": "DTrace", "bytes": "317515" }, { "name": "E", "bytes": "3968" }, { "name": "Eiffel", "bytes": "172" }, { "name": "Forth", "bytes": "674" }, { "name": "Fortran", "bytes": "4330" }, { "name": "G-code", "bytes": "1801" }, { "name": "GAP", "bytes": "792822" }, { "name": "HTML", "bytes": "6391732" }, { "name": "Jasmin", "bytes": "31" }, { "name": "Lex", "bytes": "41231" }, { "name": "Limbo", "bytes": "1787" }, { "name": "M", "bytes": "47" }, { "name": "Makefile", "bytes": "1170" }, { "name": "Objective-C", "bytes": "327" }, { "name": "Objective-J", "bytes": "6964" }, { "name": "PHP", "bytes": "3212" }, { "name": "Python", "bytes": "4346" }, { "name": "Roff", "bytes": "8747" }, { "name": "Shell", "bytes": "244725" }, { "name": "Visual Basic .NET", "bytes": "151824" }, { "name": "Yacc", "bytes": "65808" } ], "symlink_target": "" }
/* door de scrollbar ruimte te reserveren springt het scherm en de menu's niet zo.' */ html { overflow-y: scroll; }
{ "content_hash": "54dde25c6925c34cfc2a45346ae04bed", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 86, "avg_line_length": 30, "alnum_prop": 0.6916666666666667, "repo_name": "joris520/broodjesalami", "id": "364c09d1de2a44dd48c78cd22f2eabc227e63b78", "size": "120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pam-public/css/scrollbar.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7642" }, { "name": "C", "bytes": "139881" }, { "name": "C++", "bytes": "37560" }, { "name": "CSS", "bytes": "97009" }, { "name": "Groff", "bytes": "560" }, { "name": "HTML", "bytes": "3252168" }, { "name": "Java", "bytes": "26557" }, { "name": "JavaScript", "bytes": "171666" }, { "name": "PHP", "bytes": "6250140" }, { "name": "Perl", "bytes": "3810713" }, { "name": "Perl6", "bytes": "12908" }, { "name": "Prolog", "bytes": "36099" }, { "name": "Shell", "bytes": "251398" }, { "name": "Smarty", "bytes": "527143" }, { "name": "Tcl", "bytes": "2138370" }, { "name": "VimL", "bytes": "590417" }, { "name": "Visual Basic", "bytes": "416" }, { "name": "XSLT", "bytes": "50637" } ], "symlink_target": "" }
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <QClipboard> #include <string> #include <vector> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a Vsync address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a Vsync address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter Vsync signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(QString address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(QString address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { if (!model) return; /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(pubkey.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
{ "content_hash": "f8e0dc24ad326aac95abc4e966066408", "timestamp": "", "source": "github", "line_count": 277, "max_line_length": 156, "avg_line_length": 31.772563176895307, "alnum_prop": 0.6418588796727644, "repo_name": "VsyncCrypto/Vsync", "id": "e14eaf0a754844f9d8236de97897b0a3a09bbf54", "size": "8801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/signverifymessagedialog.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "31702" }, { "name": "C++", "bytes": "2507641" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "12596" }, { "name": "NSIS", "bytes": "6077" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3517" }, { "name": "Python", "bytes": "54355" }, { "name": "QMake", "bytes": "13699" }, { "name": "Roff", "bytes": "12538" }, { "name": "Shell", "bytes": "9056" } ], "symlink_target": "" }
/** * Tree * * @version 0.7.0, 2018-01-25 * @author Gregor Kofler * * @param {Object} config object * container: {Object} DOM element tree will be appended to * tree: {Object} (nested) UL element(s) which will be turned into tree * branches: {Array} initial branches * checkBoxes: {Boolean¦"last"} show and handle checkboxes, "last" displays checkboxes only on lowest level * leafNodeDefault: {Boolean} use leafnodes when subtree is undefined * checkBoxIndependence: {Boolean} prevents checkbox states to propagate up or down the tree * expandTo: {Number|"all"} number of levels shown upon default * * events served: * branchClick * labelClick * beforeNodeClick * afterNodeClick * beforeCheckBoxClick * afterCheckBoxClick * expandTree * collapseTree * * @todo handling of "disabled" property * @todo alternatively add "hashes" to speed up tree traversal */ vxJS.widget.tree = function(config) { "use strict"; if(!config) { config = {}; } var tree, that = {}, checkBoxes = config.checkBoxes || false, cbDependence = !config.checkBoxIndependence, activeBranch; /** * Tree object */ var Tree = function(level, ul) { this.element = ul || document.createElement("ul"); vxJS.dom.addClassName(this.element, "vx-tree"); this.level = level || 0; this.branches = []; }; Tree.prototype = { findBranchByElem: function(e) { var l = 0, b; while((b = this.branches[l++])) { if(b.element === e || (b.subtree && (b = b.subtree.findBranchByElem(e)))) { return b; } } }, findBranchByPropertyValue: function(p, v) { var l = 0, b; while((b = this.branches[l++])) { if(b[p] === v || (b.subtree && (b = b.subtree.findBranchByPropertyValue(p, v)))) { return b; } } }, appendBranch: function(data) { var b = new Branch(this, data); b.element.className = "last-branch"; if(this.last) { this.last.element.className = ""; } this.branches.push(b); this.last = b; b.pos = this.branches.length - 1; this.element.appendChild(b.element); }, removeBranch: function(ndx) { var branches = this.branches, l = branches.length, e; if(ndx instanceof Branch) { while(l--) { if(branches[l] === ndx) { ndx = l; break; } } } if(typeof ndx === "number") { e = branches[ndx].element; if(e && e.parentNode) { e.parentNode.removeChild(e); } branches.splice(ndx, 1); if((l = branches.length)) { while(ndx < l) { branches[ndx++].pos--; } this.last = branches[l - 1]; this.last.className = "last-branch"; } else { this.last = null; } } }, truncate: function() { var c; while((c = this.element.firstChild)) { this.element.removeChild(c); } this.branches = []; }, insertBranch: function(data, ndx) { var branches = this.branches, l = branches.length - 1, b, e; if(ndx > l) { return; } if(ndx === l) { this.appendBranch(data); } e = branches[ndx].element; b = new Branch(this, data); branches.splice(ndx, 0, b); while(ndx <= l) { branches[ndx].pos = ndx++; } this.element.insertBefore(b.element, e); }, addBranches: function(branches) { var i = 0, l = branches.length; while(i < l) { this.appendBranch(branches[i++]); } }, setParentCheckBox: function() { var i, b, disabled = 0, ticked = 0, semi, p = this.parent; if(!p || checkBoxes === "last") { return; } for(i = this.branches.length; i--;) { b = this.branches[i]; if (b.disabled) { ++disabled; } ticked += b.cbState === 1 ? 1 : 0; semi = semi || b.cbState === 2; } p.setCheckBox( semi ? 2 : ( !ticked ? 0 : (ticked === this.branches.length ? 1 : 2)), p.disabled || disabled === this.branches.length ); if(this.parent.tree && cbDependence) { this.parent.tree.setParentCheckBox(); } }, expand: function() { this.element.style.display = ""; }, collapse: function() { this.element.style.display = "none"; }, expandToLevel: function(lvl) { var i = this.branches.length, t; if(!lvl) { lvl = 0; } if(this.parent) { this.parent[lvl !== "all" && this.level > lvl ? "hideSubTree" : "showSubTree"](); } while(i--) { t = this.branches[i].subtree; if(t) { t.expandToLevel(lvl); } } }, render: function() { var i, l = this.branches.length, p = this.parent, b, c, n; if(checkBoxes === "last" && l && p) { if((c = p.cbElem) && (n = c.parentNode)) { n.removeChild(c); } } this.onlyLeaves = true; for(i = 0; i < l; ++i) { b = this.branches[i]; if(b.subtree) { b.subtree.render(); this.onlyLeaves = false; } this.element.appendChild(b.element); } if(p) { if(this.element && (n = this.element.parentNode)) { n.removeChild(this.element); } p.element.appendChild(this.element); } if(this.onlyLeaves && cbDependence) { this.setParentCheckBox(); } } }; /** * Branch object */ var Branch = function(tree, data) { var p, hasSubtree; this.element = document.createElement("li"); this.tree = tree; for(p in data) { if(p === "branches" && data.branches.length) { hasSubtree = true; } else if(data.hasOwnProperty(p)) { this[p] = data[p]; } } if(this.terminates === undefined && config.leafNodeDefault && !hasSubtree) { this.terminates = true; } if(this.hasCheckBox === undefined) { this.hasCheckBox = checkBoxes === true || (checkBoxes === "last" && this.terminates); } this.render(); if(hasSubtree) { this.appendSubTree(data.branches); } this.renderNode(); }; Branch.prototype = { insertBefore: function(data) { this.tree.insertBranch(data, this.pos - 1); }, insertAfter: function(data) { this.tree.insertBranch(data, this.pos + 1); }, appendSubTree: function(b) { this.subtree = new Tree(this.tree.level + 1, null); this.subtree.parent = this; if(b) { this.subtree.addBranches(b); } this.element.appendChild(this.subtree.element); }, removeSubTree: function() { var e; if(!this.subtree) { return; } this.hideSubTree(); e = this.subtree.element; e.parentNode.removeChild(e); delete this.subtree; this.renderNode(); }, toggleSubTree: function() { var s = this.subtree; !s || s.element.style.display === "none" ? this.showSubTree() : this.hideSubTree(); }, hideSubTree: function() { var s = this.subtree; vxJS.event.serve(that, "collapseTree", { branch: this }); if(s && s.element.style.display !== "none") { s.collapse(); } this.renderNode(); }, showSubTree: function() { var s = this.subtree; vxJS.event.serve(that, "expandTree", { branch: this }); if(s && s.element.style.display === "none") { s.expand(); } this.renderNode(); }, propagateCheckBox: function() { if(!this.subtree || !this.subtree.branches.length) { return; } var b = this.subtree.branches, i = b.length, s = this.cbState; while(i--) { b[i].setCheckBox(s, b[i].disabled); b[i].propagateCheckBox(); } }, setCheckBox: function(state, disabled) { this.cbState = state; this.disabled = !!disabled; this.renderCheckBox(); }, toggleCheckBox: function() { this.cbState = !this.cbState ? 1 : 0; this.renderCheckBox(); }, renderCheckBox: function() { if(!this.hasCheckBox) { return; } if(!this.cbElem) { this.cbElem = document.createElement("span"); } this.cbElem.className = ["unchecked", "checked", "part-checked"][+this.cbState] + " __check__" + (this.disabled ? " disabled" : ""); }, renderNode: function() { var cn, s = this.subtree; if(this.terminates || s === undefined && config.leafNodeDefault) { cn = "leaf-node"; } else if(s === undefined) { cn = "subtree-collapsed __node__"; } else if(s.branches.length > 0) { if(s.element.style.display === "none") { cn = "subtree-collapsed __node__"; } else { cn = "subtree-expanded __node__"; } } else { cn = "leaf-node"; } this.nodeElem.className = cn; }, render: function() { var li = this.element; li.className = this.tree.last === this ? "last-branch" : ""; // was not rendered before if(!this.labelElem) { this.nodeElem = document.createElement("span"); li.appendChild(this.nodeElem); if(this.hasCheckBox) { // if(checkBoxes == "last" && this.nodeElem.className.indexOf("leafNode") != -1 || checkBoxes == true) { if(this.cbState === undefined) { if(cbDependence && this.tree.parent && this.tree.parent.cbState && this.tree.parent.cbState !== 2) { this.cbState = this.tree.parent.cbState; } else { this.cbState = 0; } } this.renderCheckBox(); li.appendChild(this.cbElem); } this.labelElem = document.createElement("div"); this.labelElem.className = "__label__"; this.labelElem.appendChild(vxJS.dom.parse(this.elements)); li.appendChild(this.labelElem); } } }; var importUl = function(ul) { var li, c, frag, b, prop, rex = /(?:^|\s)__([a-z][a-z0-9]*)__([a-z0-9]+)/ig, branches = []; while((li = ul.childNodes[0])) { if(li.nodeType === 1 && li.nodeName.toLowerCase() === "li") { b = { id: li.id || null }; if(li.className) { while((prop = rex.exec(li.className))) { if(prop[2] === 'false') { b[prop[1]] = false; continue; } if(prop[2] === 'true') { b[prop[1]] = true; continue; } b[prop[1]] = prop[2]; } } frag = document.createDocumentFragment(); while((c = li.childNodes[0])) { if(c.nodeType === 1 && c.nodeName.toLowerCase() === "ul") { b.branches = importUl(c); c.parentNode.removeChild(c); } else { frag.appendChild(c); } } b.elements = [ { fragment: frag } ]; branches.push(b); } ul.removeChild(li); } return branches; }; var handleClick = function(e) { var c, b; // @todo filter or speed up search if(!(b = tree.findBranchByElem(vxJS.dom.getParentElement(this, "li"))) || b.disabled) { return; } activeBranch = b; vxJS.event.serve(that, "branchClick", { branch: b, event: e }); if(b.nodeElem && this === b.nodeElem) { vxJS.event.serve(that, "beforeNodeClick", { branch: b, event: e }); b.toggleSubTree(); vxJS.event.serve(that, "afterNodeClick", { branch: b, event: e }); } else if(b.cbElem && this === b.cbElem) { vxJS.event.serve(that, "beforeCheckBoxClick", { branch: b, event: e }); b.toggleCheckBox(); if(cbDependence) { b.propagateCheckBox(); b.tree.setParentCheckBox(); } vxJS.event.serve(that, "afterCheckBoxClick", { branch: b, event: e }); } else { c = this; while(c !== b.element) { if(c === b.labelElem) { vxJS.event.serve(that, "labelClick", { branch: b, event: e }); break; } c = c.parentNode; } } }; if(config.tree && config.tree.nodeName && config.tree.nodeName.toLowerCase() === "ul") { tree = new Tree(null, config.tree); tree.addBranches(importUl(config.tree)); } else { tree = new Tree(); tree.addBranches(config.branches || []); } tree.expandToLevel(config.expandTo); // tree.render(); if(config.container) { config.container.appendChild(tree.element); } vxJS.event.addListener(tree.element, "click", handleClick); that.element = tree.element; that.getCheckedLeaves = (function() { var branches; var cbRecursion = function(t) { var l = t.branches.length, b; while(l--) { b = t.branches[l]; if(b.subtree) { cbRecursion(b.subtree); } if(b.cbElem && b.cbState === 1) { branches.push(b); } } }; return function(subTree) { branches = []; cbRecursion(subTree || tree); return branches; }; })(); that.getBranch = function(p, v) { return tree.findBranchByPropertyValue(p, v); }; that.customExpandTo = function(cb) { var traces = [], track = [], trace, i, l; var scan = function(t) { var b = t.branches, l = b.length, alreadyExpanding; while(l--) { if(!alreadyExpanding && cb.apply(b[l])) { traces.push(track.concat([])); alreadyExpanding = true; } if(b[l].subtree) { track.push(b[l]); scan(b[l].subtree); } } track.pop(); }; scan(tree); while((trace = traces.pop())) { for(i = 0, l = trace.length; i < l; ++i) { trace[i].showSubTree(); } } }; that.expandToLevel = function(lvl) { tree.expandToLevel(lvl); }; that.getActiveBranch = function() { return activeBranch; }; that.getRootTree = function() { return tree; }; return that; };
{ "content_hash": "0dd3581f1e0cc11d093e0a75f739b96b", "timestamp": "", "source": "github", "line_count": 592, "max_line_length": 135, "avg_line_length": 21.618243243243242, "alnum_prop": 0.5837630879824973, "repo_name": "Vectrex/vxJS", "id": "39498813355dcf9fee4728d1233082ac8f4ee8f8", "size": "12799", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/widgets/tree.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "202958" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>class RubyXL::Font - 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">OOXMLObject </div> <!-- Method Quickref --> <div id="method-list-section" class="nav-section"> <h3>Methods</h3> <ul class="link-list" role="directory"> <li ><a href="#method-c-default">::default</a> <li ><a href="#method-i-get_name">#get_name</a> <li ><a href="#method-i-get_rgb_color">#get_rgb_color</a> <li ><a href="#method-i-get_size">#get_size</a> <li ><a href="#method-i-is_bold">#is_bold</a> <li ><a href="#method-i-is_italic">#is_italic</a> <li ><a href="#method-i-is_strikethrough">#is_strikethrough</a> <li ><a href="#method-i-is_underlined">#is_underlined</a> <li ><a href="#method-i-set_bold">#set_bold</a> <li ><a href="#method-i-set_italic">#set_italic</a> <li ><a href="#method-i-set_name">#set_name</a> <li ><a href="#method-i-set_rgb_color">#set_rgb_color</a> <li ><a href="#method-i-set_size">#set_size</a> <li ><a href="#method-i-set_strikethrough">#set_strikethrough</a> <li ><a href="#method-i-set_underline">#set_underline</a> </ul> </div> </div> </nav> <main role="main" aria-labelledby="class-RubyXL::Font"> <h1 id="class-RubyXL::Font" class="class"> class RubyXL::Font </h1> <section class="description"> <p><a href="http://www.schemacentral.com/sc/ooxml/e-ssml_font-1.html">www.schemacentral.com/sc/ooxml/e-ssml_font-1.html</a></p> </section> <section id="5Buntitled-5D" class="documentation-section"> <section class="constants-list"> <header> <h3>Constants</h3> </header> <dl> <dt id="MAX_DIGIT_WIDTH">MAX_DIGIT_WIDTH <dd><p>Since we have no capability to load the actual fonts, we’ll have to live with the default.</p> </dl> </section> <section id="public-class-5Buntitled-5D-method-details" class="method-section"> <header> <h3>Public Class Methods</h3> </header> <div id="method-c-default" class="method-detail "> <div class="method-heading"> <span class="method-name">default</span><span class="method-args">(size = 10)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="default-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 86</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword">self</span>.<span class="ruby-identifier">default</span>(<span class="ruby-identifier">size</span> = <span class="ruby-value">10</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:name</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">StringValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-string">'Verdana'</span>), <span class="ruby-value">:sz</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">FloatValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">size</span>) ) <span class="ruby-keyword">end</span></pre> </div> </div> </div> </section> <section id="public-instance-5Buntitled-5D-method-details" class="method-section"> <header> <h3>Public Instance Methods</h3> </header> <div id="method-i-get_name" class="method-detail "> <div class="method-heading"> <span class="method-name">get_name</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="get_name-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 61</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">get_name</span> <span class="ruby-identifier">name</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">name</span>.<span class="ruby-identifier">val</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-get_rgb_color" class="method-detail "> <div class="method-heading"> <span class="method-name">get_rgb_color</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="get_rgb_color-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 77</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">get_rgb_color</span> <span class="ruby-identifier">color</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">color</span>.<span class="ruby-identifier">rgb</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-get_size" class="method-detail "> <div class="method-heading"> <span class="method-name">get_size</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="get_size-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 69</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">get_size</span> <span class="ruby-identifier">sz</span> <span class="ruby-operator">&amp;&amp;</span> <span class="ruby-identifier">sz</span>.<span class="ruby-identifier">val</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-is_bold" class="method-detail "> <div class="method-heading"> <span class="method-name">is_bold</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="is_bold-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 37</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">is_bold</span> <span class="ruby-identifier">b</span> <span class="ruby-operator">&amp;&amp;</span> (<span class="ruby-identifier">b</span>.<span class="ruby-identifier">val</span> <span class="ruby-operator">||</span> <span class="ruby-keyword">true</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-is_italic" class="method-detail "> <div class="method-heading"> <span class="method-name">is_italic</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="is_italic-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 29</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">is_italic</span> <span class="ruby-identifier">i</span> <span class="ruby-operator">&amp;&amp;</span> (<span class="ruby-identifier">i</span>.<span class="ruby-identifier">val</span> <span class="ruby-operator">||</span> <span class="ruby-keyword">true</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-is_strikethrough" class="method-detail "> <div class="method-heading"> <span class="method-name">is_strikethrough</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="is_strikethrough-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 53</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">is_strikethrough</span> <span class="ruby-identifier">strike</span> <span class="ruby-operator">&amp;&amp;</span> (<span class="ruby-identifier">strike</span>.<span class="ruby-identifier">val</span> <span class="ruby-operator">||</span> <span class="ruby-keyword">true</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-is_underlined" class="method-detail "> <div class="method-heading"> <span class="method-name">is_underlined</span><span class="method-args">()</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="is_underlined-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 45</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">is_underlined</span> <span class="ruby-identifier">u</span> <span class="ruby-operator">&amp;&amp;</span> (<span class="ruby-identifier">u</span>.<span class="ruby-identifier">val</span> <span class="ruby-operator">||</span> <span class="ruby-keyword">true</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_bold" class="method-detail "> <div class="method-heading"> <span class="method-name">set_bold</span><span class="method-args">(val)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="set_bold-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 41</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_bold</span>(<span class="ruby-identifier">val</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">b</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">BooleanValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">val</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_italic" class="method-detail "> <div class="method-heading"> <span class="method-name">set_italic</span><span class="method-args">(val)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="set_italic-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 33</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_italic</span>(<span class="ruby-identifier">val</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">i</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">BooleanValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">val</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_name" class="method-detail "> <div class="method-heading"> <span class="method-name">set_name</span><span class="method-args">(val)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="set_name-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 65</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_name</span>(<span class="ruby-identifier">val</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">name</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">StringValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">val</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_rgb_color" class="method-detail "> <div class="method-heading"> <span class="method-name">set_rgb_color</span><span class="method-args">(font_color)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <p>Helper method to modify the font color</p> <div class="method-source-code" id="set_rgb_color-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 82</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_rgb_color</span>(<span class="ruby-identifier">font_color</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">color</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">Color</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:rgb</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">font_color</span>.<span class="ruby-identifier">to_s</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_size" class="method-detail "> <div class="method-heading"> <span class="method-name">set_size</span><span class="method-args">(val)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="set_size-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 73</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_size</span>(<span class="ruby-identifier">val</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">sz</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">FloatValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">val</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_strikethrough" class="method-detail "> <div class="method-heading"> <span class="method-name">set_strikethrough</span><span class="method-args">(val)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="set_strikethrough-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 57</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_strikethrough</span>(<span class="ruby-identifier">val</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">strike</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">BooleanValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">val</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div id="method-i-set_underline" class="method-detail "> <div class="method-heading"> <span class="method-name">set_underline</span><span class="method-args">(val)</span> <span class="method-click-advice">click to toggle source</span> </div> <div class="method-description"> <div class="method-source-code" id="set_underline-source"> <pre><span class="ruby-comment"># File lib/rubyXL/objects/font.rb, line 49</span> <span class="ruby-keyword">def</span> <span class="ruby-identifier">set_underline</span>(<span class="ruby-identifier">val</span>) <span class="ruby-keyword">self</span>.<span class="ruby-identifier">u</span> = <span class="ruby-constant">RubyXL</span><span class="ruby-operator">::</span><span class="ruby-constant">BooleanValue</span>.<span class="ruby-identifier">new</span>(<span class="ruby-value">:val</span> =<span class="ruby-operator">&gt;</span> <span class="ruby-identifier">val</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> </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": "e5eefd78c4eda4a900b74d431f254311", "timestamp": "", "source": "github", "line_count": 670, "max_line_length": 449, "avg_line_length": 32.43582089552239, "alnum_prop": 0.5672280508006626, "repo_name": "parallel588/rubyXL", "id": "a3aabcb7b24495ef44914010e407986d681f1ccf", "size": "21734", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rdoc/RubyXL/Font.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15702" }, { "name": "HTML", "bytes": "1703684" }, { "name": "JavaScript", "bytes": "17924" }, { "name": "Ruby", "bytes": "383515" } ], "symlink_target": "" }
<!DOCTYPE html> <!--html5--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <!-- Mirrored from arduino.cc/en/Reference/RobotCompassRead by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 06 Feb 2015 20:16:13 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack --> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="utf-8" /> <title>Arduino - RobotCompassRead </title> <link rel="shortcut icon" type="image/x-icon" href="../favicon.png" /> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <link rel="stylesheet" href="../../fonts/fonts.css" type="text/css" /> <link rel="stylesheet" href="../../css/arduino-icons.css"> <link rel="stylesheet" href="../../css/animation.css"><!--[if IE 7]> <link rel="stylesheet" href="http://arduino.cc/css/arduino-icons-ie7.css"><![endif]--> <!--[if gte IE 9]><!--> <link rel='stylesheet' href='../../css/foundation2.css' type='text/css' /> <!--<![endif]--> <!--[if IE 8]> <link rel='stylesheet' href='http://arduino.cc/css/foundation_ie8.css' type='text/css' /> <![endif]--> <link rel='stylesheet' href='../../css/arduino_code_highlight.css' type='text/css' /> <link rel="stylesheet" type="text/css" media="screen" href="../../css/typeplate.css"> <link rel='stylesheet' href='../pub/skins/arduinoWide_SSO/css/arduinoWide_SSO.css' type='text/css' /> <link rel='stylesheet' href='../../css/common.css' type='text/css' /> <link rel="stylesheet" href="../../css/download_page.css" /> <link href="https://plus.google.com/114839908922424087554" rel="publisher" /> <!-- embedded JS and CSS from PmWiki plugins --> <!--HeaderText--><style type='text/css'><!-- ul, ol, pre, dl, p { margin-top:0px; margin-bottom:0px; } code { white-space: nowrap; } .vspace { margin-top:1.33em; } .indent { margin-left:40px; } .outdent { margin-left:40px; text-indent:-40px; } a.createlinktext { text-decoration:none; border-bottom:1px dotted gray; } a.createlink { text-decoration:none; position:relative; top:-0.5em; font-weight:bold; font-size:smaller; border-bottom:none; } img { border:0px; } span.anchor { float: left; font-size: 10px; margin-left: -10px; width: 10px; position:relative; top:-0.1em; text-align: center; } span.anchor a { text-decoration: none; } span.anchor a:hover { text-decoration: underline; } ol.toc { text-indent:-20px; list-style: none; } ol.toc ol.toc { text-indent:-40px; } div.tocfloat { font-size: smaller; margin-bottom: 10px; border-top: 1px dotted #555555; border-bottom: 1px dotted #555555; padding-top: 5px; padding-bottom: 5px; width: 38%; float: right; margin-left: 10px; clear: right; margin-right:-13px; padding-right: 13px; padding-left: 13px; background-color: #eeeeee; } div.toc { font-size: smaller; padding: 5px; border: 1px dotted #cccccc; background: #f7f7f7; margin-bottom: 10px; } div.toc p { background-color: #f9f6d6; margin-top:-5px; padding-top: 5px; margin-left:-5px; padding-left: 5px; margin-right:-5px; padding-right: 5px; padding-bottom: 3px; border-bottom: 1px dotted #cccccc; }.editconflict { color:green; font-style:italic; margin-top:1.33em; margin-bottom:1.33em; } table.markup { border: 2px dotted #ccf; width:90%; } td.markup1, td.markup2 { padding-left:10px; padding-right:10px; } td.markup1 { border-bottom: 1px solid #ccf; } div.faq { margin-left:2em; } div.faq p.question { margin: 1em 0 0.75em -2em; font-weight:bold; } div.faq hr { margin-left: -2em; } .frame { border:1px solid #cccccc; padding:4px; background-color:#f9f9f9; } .lfloat { float:left; margin-right:0.5em; } .rfloat { float:right; margin-left:0.5em; } a.varlink { text-decoration:none; } /** * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann * (http://qbnz.com/highlighter/ and http://geshi.org/) */ .arduino {font-family:monospace;} .arduino .imp {font-weight: bold; color: red;} .arduino .kw1 {color: #CC6600;} .arduino .kw2 {color: #006699;} .arduino .kw3 {color: #CC6600; font-weight: bold;} .arduino .co1 {color: #7E7E7E; font-style: italic;} .arduino .co2 {color: #7E7E7E;} .arduino .coMULTI {color: #7E7E7E; font-style: italic;} .arduino .es0 {color: #000099; font-weight: bold;} .arduino .es1 {color: #000099; font-weight: bold;} .arduino .es2 {color: #660099; font-weight: bold;} .arduino .es3 {color: #660099; font-weight: bold;} .arduino .es4 {color: #660099; font-weight: bold;} .arduino .es5 {color: #006699; font-weight: bold;} .arduino .br0 {color: #000000;} .arduino .sy0 {color: #000000;} .arduino .st0 {color: #0066CC;} .arduino .nu0 {color: #000000;} .arduino .nu6 {color: #208080;} .arduino .nu8 {color: #208080;} .arduino .nu12 {color: #208080;} .arduino .nu16 {color:#800080;} .arduino .nu17 {color:#800080;} .arduino .nu18 {color:#800080;} .arduino .nu19 {color:#800080;} .arduino .me1 {color: #ff1493;} .arduino .me2 {color: #ff1493;} .arduino span.xtra { display:block; } .sourceblocklink { text-align: right; font-size: smaller; } .sourceblocktext { padding: 0.5em; color: #000000; background-color: #ffffff; } .sourceblocktext div { font-family: monospace; font-size: small; line-height: 1; height: 1%; } .sourceblocktext div.head, .sourceblocktext div.foot { font: italic medium serif; padding: 0.5em; } --></style><script type="text/javascript"> function toggle(obj) { var elstyle = document.getElementById(obj).style; var text = document.getElementById(obj + "tog"); if (elstyle.display == 'none') { elstyle.display = 'block'; text.innerHTML = "hide"; } else { elstyle.display = 'none'; text.innerHTML = "show"; } } </script> <meta name='robots' content='index,follow' /> <script src="http://arduino.cc/js/vendor/custom.modernizr.js"></script> <!-- do not remove none of those lines, comments embedding in pages will break! --> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script> <script src="http://arduino.cc/en/pub/js/newsletter_subscribe_popup.js" type="text/javascript"></script> <script src="https://checkout.stripe.com/checkout.js" type="text/javascript"></script> <script src="https://arduino.cc/en/pub/js/software_download.js" type="text/javascript"></script><!-- keep https! --> <link rel='stylesheet' href='../../../code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.min.css' type='text/css' /> <script src="http://arduino.cc/tools/comments/extern/?s=wiki" type="text/javascript"></script> </head> <body> <div id="menuWings" class="fixed"></div> <div id="page"> <script> var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase(); if(userAgent.indexOf('mac')>0){ $("head").append('<style type="text/css">@-moz-document url-prefix() {h1 a, h2 a, h3 a, h4 a, h5 a, h1 a:hover, h2 a:hover, th a, th a:hover, h3 a:hover, h4 a:hover, h5 a:hover, #wikitext h2 a:hover, #wikitext h3 a:hover, #wikitext h4 a:hover {padding-bottom: 0.5em!important;} #pageheader .search input{font-family: "TyponineSans Regular 18";} #pagefooter .monospace{margin-top: -4px;} #navWrapper ul.left &gt; li{margin-top: -2px; padding-bottom: 2px;}#navWrapper ul.right &gt; li{margin-top: -5px; padding-bottom: 5px;}#navWrapper ul.right &gt; li ul{margin-top: 4px;} .slider-container .fixed-caption p{padding:8px 0 14px 0}}</style>'); } </script> <!--[if IE]> <link rel='stylesheet' href='https://id.arduino.cc//css/ie-monospace.css' type='text/css' /> <![endif]--> <div id="menuWings" class="fixed"></div> <!--[if IE 8]> <div class="alert-box panel ie8alert"> <p><strong>Arduino.cc offers limited compatibility for Internet Explorer 8. Get a modern browser as Chrome, Firefox or Safari.</strong></p> <a href="" class="close">&times;</a> </div> <![endif]--> <div id="pageheader"> <div class="row" class="contain-to-grid"> <div class="small-6 large-8 eight columns"> <div class="title"><a href="http://arduino.cc/">Arduino</a></div> </div> <div class="small-6 large-4 four columns search"> <div class="row collapse"> <form method="GET" action="http://www.google.com/search"> <div class="small-12 twelve columns"> <i class="icon-search-2"></i> <input type="hidden" name="ie" value="UTF-8"> <input type="hidden" name="oe" value="UTF-8"> <input type="text" name="q" size="25" maxlength="255" value="" placeholder="Search the Arduino Website"> <input type="submit" name="btnG" VALUE="search"> <input type="hidden" name="domains" value="http://arduino.cc"> <input type="hidden" name="sitesearch" value="http://arduino.cc"> </div> </form> </div> </div> </div> <!--[if gte IE 9]><!--> <div id="navWrapper" class="sticky"> <!--<![endif]--> <!--[if IE 8]> <div id="navWrapper"> <![endif]--> <nav class="top-bar" data-options="is_hover:true" > <ul class="title-area"> <li class="name"></li> </ul> <section class="top-bar-section"> <ul class="left"> <li id="navLogo"> <a href="http://arduino.cc/"> <img src="../../img/logo_46.png" alt="userpicture" /> </a> </li> <li id="navHome"><a href="http://arduino.cc/">Home</a></li> <li><a href="http://store.arduino.cc/">Buy</a></li> <li><a href="http://arduino.cc/en/Main/Software">Download</a></li> <li class="has-dropdown"><a href="#">Products</a> <ul class="dropdown"> <li><a href="http://arduino.cc/en/Main/Products">Arduino</a></li> <li><a href="http://arduino.cc/en/ArduinoAtHeart/Products">AtHeart</a></li> <li><a href="http://arduino.cc/en/ArduinoCertified/Products">Certified</a></li> </ul> </li> <li class="has-dropdown active"><a href="#">Learning</a> <ul class="dropdown"> <li><a href="../Guide/HomePage.html">Getting started</a></li> <li><a href="http://arduino.cc/en/Tutorial/HomePage">Examples</a></li> <li><a href="HomePage.html">Reference</a></li> <li><a href="http://playground.arduino.cc/">Playground</a></li> </ul> </li> <li><a href="http://forum.arduino.cc/">Forum</a></li> <li class="has-dropdown"><a href="#">Support</a> <ul class="dropdown"> <li><a href="../Main/FAQ.html">FAQ</a></li> <li><a href="http://arduino.cc/en/ContactUs">Contact Us</a></li> </ul> </li> <li><a href="http://blog.arduino.cc/">Blog</a></li> </ul> <ul class="right"> <li><a href="https://id.arduino.cc/auth/login/?returnurl=http%3A%2F%2Farduino.cc%2Fen%2FReference%2FRobotCompassRead" class="cart">LOG IN</a></li> <li><a href="https://id.arduino.cc/auth/signup" class="cart">SIGN UP</a></li> </ul> </section> </nav> </div> </div> <br class="clear"/> <div id="pagetext"> <!--PageText--> <div id='wikitext'> <p><strong>Reference</strong> &nbsp; <a class='wikilink' href='HomePage.html'>Language</a> | <a class='wikilink' href='Libraries.html'>Libraries</a> | <a class='wikilink' href='Comparison.html'>Comparison</a> | <a class='wikilink' href='Changes.html'>Changes</a> </p> <p class='vspace'></p><p><a class='wikilink' href='RobotLibrary.html'>Robot</a> </p> <p class='vspace'></p><h2>compassRead()</h2> <h4>Description</h4> <p>Get the current direction from on-board compass. The values are degrees of rotation from north (in a clockwise direction), so that east is 90, south is 180, and west is 270. </p> <p class='vspace'></p><h4>Syntax</h4> <p>Robot.compassRead() </p> <p class='vspace'></p><h4>Parameters</h4> <p>none </p> <p class='vspace'></p><h4>Returns</h4> <p>int: 0 to 359, representing the number of degrees of rotation from north. </p> <p class='vspace'></p><h3>Note</h3> <p>The compass module may be disrupted by magnetic fields in surrounding areas. </p> <p class='vspace'></p><h4>Examples</h4> <p> <div class='sourceblock ' id='sourceblock1'> <div class='sourceblocktext'><div class="arduino"><span class="co2">#include &lt;ArduinoRobot.h&gt;</span><br /> <br /> <span class="kw1">void</span> <span class="kw3">setup</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br /> &nbsp; Robot.<span class="kw1">begin</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy0">;</span><br /> &nbsp; <span class="kw1">Serial</span>.<span class="kw1">begin</span><span class="br0">&#40;</span><span class="nu0">9600</span><span class="br0">&#41;</span><span class="sy0">;</span><br /> <br /> <span class="br0">&#125;</span><br /> <span class="kw1">void</span> <span class="kw3">loop</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#123;</span><br /> &nbsp; <span class="kw1">Serial</span>.<span class="kw1">println</span><span class="br0">&#40;</span>Robot.<span class="me1">compassRead</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy0">;</span><br /> &nbsp; <span class="kw1">delay</span><span class="br0">&#40;</span><span class="nu0">100</span><span class="br0">&#41;</span><span class="sy0">;</span><br /> <span class="br0">&#125;</span></div></div> <div class='sourceblocklink'><a href='http://arduino.cc/en/Reference/RobotCompassRead?action=sourceblock&amp;num=1' type='text/plain'>[Get Code]</a></div> </div> </p> <p class='vspace'></p><h4>See also</h4> <ul><li><a class='wikilink' href='RobotAnalogRead.html'>analogRead()</a> </li><li><a class='wikilink' href='RobotDigitalWrite.html'>digitalWrite()</a> </li><li><a class='wikilink' href='RobotAnalogWrite.html'>analogWrite()</a> </li></ul><p><a class='wikilink' href='HomePage.html'>Reference Home</a> </p> <p class='vspace'></p><p><em>Corrections, suggestions, and new documentation should be posted to the <a class='urllink' href='http://arduino.cc/forum/index.php/board,23.0.html' rel='nofollow'>Forum</a>.</em> </p> <p class='vspace'></p><p>The text of the Arduino reference is licensed under a <a class='urllink' href='http://creativecommons.org/licenses/by-sa/3.0/' rel='nofollow'>Creative Commons Attribution-ShareAlike 3.0 License</a>. Code samples in the reference are released into the public domain. </p> </div> <!-- AddThis Button Style BEGIN --> <style> .addthis_toolbox { margin: 2em 0 1em; } .addthis_toolbox img { float: left; height: 25px; margin-right: 10px; width: auto; } .addthis_toolbox .social-container { float: left; height: 27px; width: auto; } .addthis_toolbox .social-container .social-content { float: left; margin-top: 2px; max-width: 0; overflow: hidden; -moz-transition: max-width .3s ease-out; -webkit-transition: max-width .3s ease-out; -o-transition: max-width .3s ease-out; transition: max-width .3s ease-out; } .addthis_toolbox .social-container:hover .social-content { max-width: 100px; -moz-transition: max-width .2s ease-in; -webkit-transition: max-width .2s ease-in; -o-transition: max-width .2s ease-in; transition: max-width .2s ease-in; } .addthis_toolbox .social-container .social-content a { float: left; margin-right: 5px; } .addthis_toolbox h3 { font-size: 24px; text-align: left; } </style> <!-- AddThis Button Style END --> <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style"> <h3>Share</h3> <!-- FACEBOOK --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/facebook.png" /> <div class="social-content"> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> </div> </div> <!-- TWITTER --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/twitter.png"> <div class="social-content"> <a class="addthis_button_tweet"></a> </div> </div> <!-- PINTEREST --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/pinterest.png"> <div class="social-content"> <a class="addthis_button_pinterest_pinit" pi:pinit:url="http://www.addthis.com/features/pinterest" pi:pinit:media="http://www.addthis.com/cms-content/images/features/pinterest-lg.png"></a> </div> </div> <!-- G+ --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/gplus.png"> <div class="social-content"> <a class="addthis_button_google_plusone" g:plusone:size="medium"></a> </div> </div> <script type="text/javascript">var addthis_config = {"data_track_addressbar":false};</script> <script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-50573fab238b0d34"></script> </div> <!-- AddThis Button END --> </div> <!-- eof pagetext --> </div> <!-- eof page --> <!--PageFooterFmt--> <div id="pagefooter"> <div id="newsletterModal" class="reveal-modal small"> <form action="http://arduino.cc/subscribe.php" method="post" name="sendy-subscribe-form" id="sendy-subscribe-form" class="form-popup"> <div class="modalHeader"> <h3 style="line-height: 1.8rem;" class="modal-header-alt">This link has expired. <br>Please re-subscribe to our Newsletters.</h3> <h3 class="modal-header-main">Subscribe to our Newsletters</h3> </div> <div class="modalBody" id="newsletterModalBody"> <div id="newsletterEmailField" class="row" style="padding-left: 0"> <div class="large-2 columns"> <label for="email" class="newsletter-form-label inline">Email</label> </div> <div class="large-10 columns" style="padding-left: 0"> <input placeholder="Enter your email address" type="email" name="email" class="subscribe-form-input" /> <p id="emailMissing" class="newsletterPopupError">Please enter a valid email to subscribe</p> </div> </div> <div style="margin-left:20px"> <div style="margin-bottom:0.3em"> <input style="display:none" type="checkbox" checked name="list[]" value="arduino_newsletter_id" id="worldwide" class="newsletter-form-checkbox" /> <label for="worldwide"></label> <div style="display:inline-block" class="newsletter-form-label">Arduino Newsletter</div> </div> <div> <input style="display:none" type="checkbox" checked name="list[]" value="arduino_store_newsletter_id" id="store" class="newsletter-form-checkbox" /> <label for="store"></label> <div style="display:inline-block" class="newsletter-form-label">Arduino Store Newsletter</div> </div> </div> <div> <p class="newsletterPopupError2" id="newsletterSubscribeStatus"></p> </div> </div> <div class="row modalFooter"> <div class="form-buttons-row"> <button type="button" value="Cancel" class="popup-form-button white cancel-modal close-reveal-modal">Cancel</button> <button type="submit" name="Subscribe" id="subscribe-submit-btn" class="popup-form-button">Next</button> </div> </div> </form> <!-- step 2, confirm popup --> <div class="confirm-popup" style="margin-bottom:1em"> <div class="modalHeader"> <h3>Confirm your email address</h3> </div> <div class="modalBody" id="newsletterModalBody" style="padding-right:1em;margin-bottom:0"> <p style="margin-bottom:1em;font-size:15px"> We need to confirm your email address.<br> To complete the subscription, please click the link in the email we just sent you. </p> <p style="margin-bottom:1em;font-size:15px"> Thank you for subscribing! </p> <p style="margin-bottom:1em;font-size:15px"> Arduino<br> via Egeo 16<br> Torino, 10131<br> Italy<br> </p> </div> <div class="row modalFooter"> <div class="form-buttons-row"> <button name="Ok" class="popup-form-button" id="close-confirm-popup">Ok</button> </div> </div> </div> </div><div id="pagefooter" class="pagefooter"> <div class="row"> <div class="large-8 eight columns"> <div class="large-4 four columns newsletter-box"> <!-- Begin Sendy Signup Form --> <h6>Newsletter</h6> <div> <input type="email" name="email" class="email" id="sendy-EMAIL" placeholder="Enter your email to sign up"> <i class="icon-right-small"></i> <input value="Subscribe" name="subscribe" id="sendy-subscribe" class="newsletter-button"> </div> <!--End sendy_embed_signup--> </div> <div class="clearfix"></div> <ul class="inline-list"> <li class="monospace">&copy;2015 Arduino</li> <li><a href="http://arduino.cc/en/Main/CopyrightNotice">Copyright Notice</a></li> <li><a href='http://arduino.cc/en/Main/ContactUs'>Contact us</a></li> <li><a href='http://arduino.cc/Careers'>Careers</a></li> </ul> </div> <div class="large-4 four columns"> <ul id="arduinoSocialLinks" class="arduino-social-links"> <li> <a href="https://twitter.com/arduino"> <img src="../../img/twitter.png" /> </a> </li> <li> <a href="http://www.facebook.com/official.arduino"> <img src="../../img/facebook.png" /> </a> </li> <li> <a href="https://plus.google.com/+Arduino"> <img src="../../img/gplus.png" /> </a> </li> <li> <a href="http://www.flickr.com/photos/arduino_cc"> <img src="../../img/flickr.png" /> </a> </li> <li> <a href="http://youtube.com/arduinoteam"> <img src="../../img/youtube.png" /> </a> </li> </ul> </div> </div> </div> </div> <!--/PageFooterFmt--> <!--[if gte IE 9]><!--> <script src="http://arduino.cc/js/foundation.min.js"></script> <script src="http://arduino.cc/js/foundation.topbar.custom.js"></script> <script> $(document).foundation(); </script> <!--<![endif]--> <!--[if IE 8]> <script src="http://arduino.cc/js/foundation_ie8.min.js"></script> <script src="http://arduino.cc/js/ie8/jquery.foundation.orbit.js"></script> <script src="http://arduino.cc/js/ie8/jquery.foundation.alerts.js"></script> <script src="http://arduino.cc/js/app.js"></script> <script> $(window).load(function(){ $("#featured").orbit(); }); </script> <![endif]--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22581631-3']); _gaq.push(['_setDomainName', 'arduino.cc']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script> $(window).load(function(){ $('a').each (function () { href = $(this).attr ('href'); if (href.substring (0, 4) == 'http' && href.indexOf ('arduino.cc') == -1) $(this).attr ('target', '_blank'); }); }); </script> </body> <!-- Mirrored from arduino.cc/en/Reference/RobotCompassRead by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 06 Feb 2015 20:16:13 GMT --> </html>
{ "content_hash": "4d243035664fa5f212c4e4b543792ba8", "timestamp": "", "source": "github", "line_count": 589, "max_line_length": 642, "avg_line_length": 40.15619694397284, "alnum_prop": 0.6256553357009978, "repo_name": "cpipero/ArduinoLadder", "id": "61479781ae401c34002c6819a46e2de8b105e8ed", "size": "23652", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Libs/arduino-1.6.3-windows/arduino-1.6.3/reference/arduino.cc/en/Reference/RobotCompassRead.html", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "582056" }, { "name": "Batchfile", "bytes": "1156" }, { "name": "C", "bytes": "26315616" }, { "name": "C#", "bytes": "145704" }, { "name": "C++", "bytes": "2743972" }, { "name": "CSS", "bytes": "267605" }, { "name": "HTML", "bytes": "14283672" }, { "name": "Java", "bytes": "5522" }, { "name": "Logos", "bytes": "178885" }, { "name": "Makefile", "bytes": "152417" }, { "name": "Objective-C", "bytes": "58648" }, { "name": "Shell", "bytes": "32272" } ], "symlink_target": "" }
/** @Name: laydate 核心样式 @Author:贤心 @Site:http://sentsin.com/layui/laydate **/ html{_background-image:url(about:blank); _background-attachment:fixed;} .laydate_body .laydate_box, .laydate_body .laydate_box *{margin:0; padding:0;} .laydate-icon, .laydate-icon-default, .laydate-icon-yahui, .laydate-icon-danlan, .laydate-icon-qianhuang, .laydate-icon-yalan, .laydate-icon-dahong{height:22px; line-height:22px; padding-right:20px; background-repeat:no-repeat; background-position:right center; background-color:#fff; outline:0;} .laydate-icon-default{border:1px solid #C6C6C6; background-image:url(../skins/default/icon.png)} .laydate-icon-yahui{border:1px solid #C6C6C6; background-image:url(../skins/yahui/icon.png)} .laydate-icon-danlan{border:1px solid #B1D2EC; background-image:url(../skins/danlan/icon.png)} .laydate-icon-qianhuang{border:1px solid #E7D7CB; background-image:url(../skins/qianhuang/icon.png)} .laydate-icon-yalan{border:1px solid #34AADC; background-image:url(../skins/yalan/icon.png)} .laydate-icon-dahong{border:1px solid #D91600; background-image:url(../skins/dahong/icon.png)} .laydate_body .laydate_box{width:240px; font:12px '\5B8B\4F53'; z-index:99999999; *margin:-2px 0 0 -2px; *overflow:hidden; _margin:0; _position:absolute!important; background-color:#fff;} .laydate_body .laydate_box li{list-style:none;} .laydate_body .laydate_box .laydate_void{cursor:text!important;} .laydate_body .laydate_box a, .laydate_body .laydate_box a:hover{text-decoration:none; blr:expression(this.onFocus=this.blur()); cursor:pointer;} .laydate_body .laydate_box a:hover{text-decoration:none;} .laydate_body .laydate_box cite, .laydate_body .laydate_box label{position:absolute; width:0; height:0; border-width:5px; border-style:dashed; border-color:transparent; overflow:hidden; cursor:pointer;} .laydate_body .laydate_box .laydate_yms, .laydate_body .laydate_box .laydate_time{display:none;} .laydate_body .laydate_box .laydate_show{display:block;} .laydate_body .laydate_box input{outline:0; font-size:14px; background-color:#fff;} .laydate_body .laydate_top{position:relative; height:40px; padding:5px; *width:100%; z-index:99;} .laydate_body .laydate_ym{position:relative; float:left; width height:24px; cursor:pointer;} .laydate_body .laydate_ym input{float:left; height:24px; line-height:24px; text-align:center; border:none; cursor:pointer;} .laydate_body .laydate_ym .laydate_yms{position:absolute; left: -1px; top: 24px; height:181px;} .laydate_body .laydate_y{width:121px; margin-right:6px;} .laydate_body .laydate_y input{width:64px; margin-right:15px;} .laydate_body .laydate_y .laydate_yms{width:121px; text-align:center;} .laydate_body .laydate_y .laydate_yms a{position:relative; display:block; height:20px;} .laydate_body .laydate_y .laydate_yms ul{height:139px; padding:0; *overflow:hidden;} .laydate_body .laydate_y .laydate_yms ul li{float:left; width:60px; height:20px; line-height: 20px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap;} .laydate_body .laydate_m{width:99px;} .laydate_body .laydate_m .laydate_yms{width:99px; padding:0;} .laydate_body .laydate_m input{width:42px; margin-right:15px;} .laydate_body .laydate_m .laydate_yms span{display:block; float:left; width:42px; margin: 5px 0 0 5px; line-height:24px; text-align:center; _display:inline;} .laydate_body .laydate_choose{display:block; float:left; position:relative; width:20px; height:24px;} .laydate_body .laydate_choose cite, .laydate_body .laydate_tab cite{left:50%; top:50%;} .laydate_body .laydate_chtop cite{margin:-7px 0 0 -5px; border-bottom-style:solid;} .laydate_body .laydate_chdown cite, .laydate_body .laydate_ym label{top:50%; margin:-2px 0 0 -5px; border-top-style:solid;} .laydate_body .laydate_chprev cite{margin:-5px 0 0 -7px;} .laydate_body .laydate_chnext cite{margin:-5px 0 0 -2px;} .laydate_body .laydate_ym label{right:28px;} .laydate_body .laydate_table{ width:230px; margin:0 5px; border-collapse:collapse; border-spacing:0px; } .laydate_body .laydate_table td{width:31px; height:19px; line-height:19px; text-align: center; cursor:pointer; font-size: 12px;} .laydate_body .laydate_table thead{height:22px; line-height:22px;} .laydate_body .laydate_table thead th{font-weight:400; font-size:12px;} .laydate_body .laydate_bottom{position:relative; height:32px; line-height:20px; padding:5px; font-size:12px;} .laydate_body .laydate_bottom #laydate_hms{position: relative; z-index: 1; float:left; } .laydate_body .laydate_time{ position:absolute; left:5px; bottom: 26px; width:129px; height:125px; *overflow:hidden;} .laydate_body .laydate_time .laydate_hmsno{ padding:5px 0 0 5px;} .laydate_body .laydate_time .laydate_hmsno span{display:block; float:left; width:24px; height:19px; line-height:19px; text-align:center; cursor:pointer; *margin-bottom:-5px;} .laydate_body .laydate_time1{width:228px; height:154px;} .laydate_body .laydate_time1 .laydate_hmsno{ padding:0; *padding:4px 0 0 5px;} .laydate_body .laydate_msg{left:49px; bottom:67px; width:141px; height:auto; overflow: hidden;} .laydate_body .laydate_msg p{padding:5px 10px;} .laydate_body .laydate_bottom li{float:left; height:20px; line-height:20px; border-right:none; font-weight:900;} .laydate_body .laydate_bottom .laydate_sj{width:33px; text-align:center; font-weight:400;} .laydate_body .laydate_bottom input{float:left; width:21px; height:20px; line-height:20px; border:none; text-align:center; cursor:pointer; font-size:12px; font-weight:400;} .laydate_body .laydate_bottom .laydte_hsmtex{height:20px; line-height:20px; text-align:center;} .laydate_body .laydate_bottom .laydte_hsmtex span{position:absolute; width:20px; top:0; right:0px; cursor:pointer;} .laydate_body .laydate_bottom .laydte_hsmtex span:hover{font-size:14px;} .laydate_body .laydate_bottom .laydate_btn{position:absolute; right:5px; top:5px;} .laydate_body .laydate_bottom .laydate_btn a{float:left; height:20px; padding:0 6px; _padding:0 5px;} .laydate_body .laydate_bottom .laydate_v{position:absolute; left:10px; top:6px; font-family:Courier; z-index:0;}
{ "content_hash": "e022a11dab031142d2ce15fed18b831d", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 202, "avg_line_length": 80.60526315789474, "alnum_prop": 0.7512242899118511, "repo_name": "Heanes/cdn.heanes.com", "id": "02cee996d4236b89b3f5ed3c138112672fb53ffa", "size": "6146", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/dateTimePicker/layDate/need/laydate.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "43520" }, { "name": "Batchfile", "bytes": "5189" }, { "name": "C", "bytes": "543" }, { "name": "C++", "bytes": "306" }, { "name": "CSS", "bytes": "6527801" }, { "name": "HTML", "bytes": "7558860" }, { "name": "Java", "bytes": "11028" }, { "name": "JavaScript", "bytes": "42275612" }, { "name": "Makefile", "bytes": "4739" }, { "name": "PHP", "bytes": "103862" }, { "name": "Python", "bytes": "11881" }, { "name": "Ruby", "bytes": "161" }, { "name": "Shell", "bytes": "1239" }, { "name": "Terra", "bytes": "422" } ], "symlink_target": "" }
<?php namespace DTS\eBaySDK\Trading\Types; /** * * @property string $BotBlockAudioUrl * @property string $BotBlockToken * @property string $BotBlockUrl */ class BotBlockResponseType extends \DTS\eBaySDK\Types\BaseType { /** * @var array Properties belonging to objects of this class. */ private static $propertyTypes = array( 'BotBlockAudioUrl' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'BotBlockAudioUrl' ), 'BotBlockToken' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'BotBlockToken' ), 'BotBlockUrl' => array( 'type' => 'string', 'unbound' => false, 'attribute' => false, 'elementName' => 'BotBlockUrl' ) ); /** * @param array $values Optional properties and values to assign to the object. */ public function __construct(array $values = array()) { list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values); parent::__construct($parentValues); if (!array_key_exists(__CLASS__, self::$properties)) { self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes); } if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) { self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents'; } $this->setValues(__CLASS__, $childValues); } }
{ "content_hash": "e2fc538978189f2ca2db7aef8d823548", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 116, "avg_line_length": 28.771929824561404, "alnum_prop": 0.5536585365853659, "repo_name": "michabbb-backup/ebay-sdk-trading", "id": "72f2c5094ba3402eb58cb64d6b9b51b005d275c3", "size": "2370", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/DTS/eBaySDK/Trading/Types/BotBlockResponseType.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "1963" }, { "name": "PHP", "bytes": "4776677" } ], "symlink_target": "" }
package mil.nga.giat.geowave.cli.debug; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import mil.nga.giat.geowave.adapter.vector.GeotoolsFeatureDataAdapter; import mil.nga.giat.geowave.adapter.vector.query.cql.FilterToCQLTool; import mil.nga.giat.geowave.core.cli.api.Command; import mil.nga.giat.geowave.core.cli.api.DefaultOperation; import mil.nga.giat.geowave.core.cli.api.OperationParams; import mil.nga.giat.geowave.core.cli.operations.config.options.ConfigOptions; import mil.nga.giat.geowave.core.index.ByteArrayId; import mil.nga.giat.geowave.core.store.CloseableIterator; import mil.nga.giat.geowave.core.store.DataStore; import mil.nga.giat.geowave.core.store.adapter.AdapterStore; import mil.nga.giat.geowave.core.store.adapter.DataAdapter; import mil.nga.giat.geowave.core.store.operations.remote.options.StoreLoader; import org.apache.commons.cli.ParseException; import org.apache.log4j.Logger; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.google.common.base.Stopwatch; abstract public class AbstractGeoWaveQuery extends DefaultOperation implements Command { private static Logger LOGGER = Logger.getLogger(AbstractGeoWaveQuery.class); @Parameter(description = "<storename>") private List<String> parameters = new ArrayList<String>(); @Parameter(names = "--indexId", required = false, description = "The name of the index (optional)", converter = StringToByteArrayConverter.class) private ByteArrayId indexId; @Parameter(names = "--adapterId", required = false, description = "Optional ability to provide an adapter ID", converter = StringToByteArrayConverter.class) private ByteArrayId adapterId; @Parameter(names = "--debug", required = false, description = "Print out additional info for debug purposes") private boolean debug = false; @Override public void execute( OperationParams params ) throws ParseException { final Stopwatch stopWatch = new Stopwatch(); // Ensure we have all the required arguments if (parameters.size() != 1) { throw new ParameterException( "Requires arguments: <storename>"); } String storeName = parameters.get(0); // Config file File configFile = (File) params.getContext().get( ConfigOptions.PROPERTIES_FILE_CONTEXT); // Attempt to load store. StoreLoader storeOptions = new StoreLoader( storeName); if (!storeOptions.loadFromConfig(configFile)) { throw new ParameterException( "Cannot find store name: " + storeOptions.getStoreName()); } DataStore dataStore; AdapterStore adapterStore; try { dataStore = storeOptions.createDataStore(); adapterStore = storeOptions.createAdapterStore(); final GeotoolsFeatureDataAdapter adapter; if (adapterId != null) { adapter = (GeotoolsFeatureDataAdapter) adapterStore.getAdapter(adapterId); } else { final CloseableIterator<DataAdapter<?>> it = adapterStore.getAdapters(); adapter = (GeotoolsFeatureDataAdapter) it.next(); it.close(); } if (debug && (adapter != null)) { System.out.println(adapter); } stopWatch.start(); final long results = runQuery( adapter, adapterId, indexId, dataStore, debug); stopWatch.stop(); System.out.println("Got " + results + " results in " + stopWatch.toString()); } catch (IOException e) { LOGGER.warn( "Unable to read adapter", e); } } abstract protected long runQuery( final GeotoolsFeatureDataAdapter adapter, final ByteArrayId adapterId, final ByteArrayId indexId, DataStore dataStore, boolean debug ); public static class StringToByteArrayConverter implements IStringConverter<ByteArrayId> { @Override public ByteArrayId convert( String value ) { return new ByteArrayId( value); } } }
{ "content_hash": "b94672be747723452d96326329e834f7", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 157, "avg_line_length": 30.91269841269841, "alnum_prop": 0.7476251604621309, "repo_name": "chizou/geowave", "id": "4ea4c88eac1c49271b2e716bfa64bdd96fa6cc48", "size": "3895", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "extensions/cli/debug/src/main/java/mil/nga/giat/geowave/cli/debug/AbstractGeoWaveQuery.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "5073" }, { "name": "CMake", "bytes": "2032" }, { "name": "FreeMarker", "bytes": "2879" }, { "name": "Gnuplot", "bytes": "57750" }, { "name": "Groovy", "bytes": "1414" }, { "name": "HTML", "bytes": "1903" }, { "name": "Java", "bytes": "5823710" }, { "name": "Protocol Buffer", "bytes": "1525" }, { "name": "Puppet", "bytes": "4039" }, { "name": "Scala", "bytes": "21759" }, { "name": "Scheme", "bytes": "20491" }, { "name": "Shell", "bytes": "58741" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\MinoltaRaw; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class WBRBLevelsWhiteF extends AbstractTag { protected $Id = 44; protected $Name = 'WB_RBLevelsWhiteF'; protected $FullName = 'MinoltaRaw::RIF'; protected $GroupName = 'MinoltaRaw'; protected $g0 = 'MakerNotes'; protected $g1 = 'MinoltaRaw'; protected $g2 = 'Image'; protected $Type = 'int16u'; protected $Writable = true; protected $Description = 'WB RB Levels White F'; protected $flag_Permanent = true; protected $MaxLength = 2; }
{ "content_hash": "a54f72c975be6a2f65ae3f4145fb06ea", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 52, "avg_line_length": 16.725, "alnum_prop": 0.672645739910314, "repo_name": "bburnichon/PHPExiftool", "id": "1315bd48ba293b4e4aa869a6e1b57bf7e80e7d2e", "size": "893", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/MinoltaRaw/WBRBLevelsWhiteF.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22076400" } ], "symlink_target": "" }
package edu.gatech.gtri.typesafeconfigextensions.factory; import com.typesafe.config.Config; import com.typesafe.config.ConfigParseOptions; import static com.typesafe.config.ConfigFactory.parseResourcesAnySyntax; import static edu.gatech.gtri.typesafeconfigextensions.internal.Check.checkNotNull; final class ClasspathResourceConfigSource extends BaseConfigSource { private final String resourceBasename; ClasspathResourceConfigSource(String resourceBasename) { this.resourceBasename = checkNotNull(resourceBasename); } @Override public Config load(Bindings bindings) { checkNotNull(bindings); Binding<ClassLoader> loader = bindings.get(ClassLoader.class); Binding<ConfigParseOptions> parseOptions = bindings.get(ConfigParseOptions.class); if (loader.isPresent() && parseOptions.isPresent()) { return parseResourcesAnySyntax( loader.get(), resourceBasename, parseOptions.get() ); } if (loader.isPresent()) { return parseResourcesAnySyntax( loader.get(), resourceBasename ); } if (parseOptions.isPresent()) { return parseResourcesAnySyntax( resourceBasename, parseOptions.get() ); } return parseResourcesAnySyntax(resourceBasename); } @Override public String toString() { return String.format( "ConfigSource { classpath: %s }", resourceBasename ); } }
{ "content_hash": "7af8ee0c070c40559673d05103e9d033", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 83, "avg_line_length": 24.71212121212121, "alnum_prop": 0.6296750459840589, "repo_name": "gtri/typesafeconfig-extensions", "id": "597dc2539274bd96f19138aaa43a03817da16b5b", "size": "2255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "factory/src/main/java/edu/gatech/gtri/typesafeconfigextensions/factory/ClasspathResourceConfigSource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "120252" }, { "name": "Scala", "bytes": "45330" }, { "name": "Shell", "bytes": "830" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> <title>Run Thru - Pat's Run</title> <link rel="stylesheet" href="css/style.css" type="text/css" media="screen" /> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script> <script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyAhM3EpW2WfqPqW89ZRDecOMmSMsy0lerQ&sensor=true" type="text/javascript"></script> <script src="http://serverapi.arcgisonline.com/jsapi/gmaps/?v=1.6" type="text/javascript" ></script> <script type="text/javascript" src="js/function.js"></script> <script type="text/javascript" src="js/PatsRun.js"></script> </head> <body onload="initialize()" onunload="GUnload()"> <div id="logo"></div> <h2>Pat's Run</h2> <div id="container"> <div id="map-canvas"> </div> </div> <!-- Button 1 --> <a class="trigger" href="Home.html">Home</a> <!-- Button 2 --> <div class="panel2"> <div style="clear:both;"></div> <div class="columns"> <h3>Ragnar Relay Races</h3> <ul> <li><a href="DelSol.html" title="DelSol">Del Sol</a></li> <li><a href="NapaValley.html" title="NapaValley">Napa Valley</a></li> <li><a href="SoCal.html" title="SoCal">So Cal</a></li> <li><a href="WasatchBack.html" title="WasatchBack">Wasatch Back</a></li> </ul> <h3>Other Races</h3> <ul> <li><a href="PatsRun.html" title="PatsRun">Pat's Run</a></li> </ul> </div> <div style="clear:both;"></div> </div> <a class="trigger2" href="#">Races</a> <!-- Button 3--> <div class="panel3"> <h3>Company Information</h3> <p>Run Thru was created to provide detailed race information for various races.</p> <div style="clear:both;"></div> <div class="columns"> <h3>Contact Us</h3> <ul> <li><a href="mailto:jking.geosci@gmail.com?subject=Run Thru" title="JesseKing">Jesse King</a></li> <li><a href="mailto:trentonrawlinson@gmail.com?subject=Run Thru" title="TrentonRawlinson">Trenton Rawlinson</a></li> <li><a href="mailto:vern.wolfley@gmail.com?subject=Run Thru" title="VernWolfley">Vern Wolfley</a></li> </ul> <h3>Social Stuff</h3> <ul> <li><a href="http://twitter.com/" title="Twitter">Twitter</a></li> <li><a href="http://facebook.com/" title="Facebook">Facebook</a></li> </ul> </div> <div style="clear:both;"></div> </div> <a class="trigger3" href="#">About</a> <!-- Button 4 --> <div class="panel4"> <div style="clear:both;"></div> <div class="columns"> <h3>Running Websites</h3> <ul> <li><a href="http://www.ragnarrelay.com/" target="_blank" title="RagnarRelaySeries">Ragnar Relay Series</a></li> <li><a href="http://runningescapes.com/RunningRelays/" target="_blank" title="RunningRelays">Running Relays</a></li> <li><a href="http://www.digitalrunning.com/" target="_blank" title="DigitalRunning">Digital Running</a></li> </ul> <h3>Running Blogs</h3> <ul> <li><a href="http://completerunning.com/" target="_blank" title="CompleteRunningNetwork">Complete Running Network</a></li> <li><a href="http://www.runningandrambling.com/" target="_blank" title="RunningAndRambling">Running and Rambling</a></li> <li><a href="http://www.runblogger.com/" target="_blank" title="Runblogger">Runblogger</a></li> <li><a href="http://runinfinity.com/" target="_blank" title="RunInfinity">Run Infinity</a></li> </ul> </div> <div style="clear:both;"></div> </div> <a class="trigger4" href="#">Links</a> </body> <footer> </footer> </html>
{ "content_hash": "36f3cac55525cc454a420d0269a79e5e", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 145, "avg_line_length": 43.72826086956522, "alnum_prop": 0.6162068108376834, "repo_name": "vwolfley/runthru", "id": "d9a186e42c650c9dab4dcacae03ad529aa7a6278", "size": "4023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/PatsRun.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "53735" }, { "name": "JavaScript", "bytes": "14604" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_65) on Thu Mar 26 14:24:31 EDT 2015 --> <TITLE> hipi.imagebundle (HIPI - Hadoop Image Processing Interface) </TITLE> <META NAME="date" CONTENT="2015-03-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../hipi/imagebundle/package-summary.html" target="classFrame">hipi.imagebundle</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="AbstractImageBundle.html" title="class in hipi.imagebundle" target="classFrame">AbstractImageBundle</A> <BR> <A HREF="HARImageBundle.html" title="class in hipi.imagebundle" target="classFrame">HARImageBundle</A> <BR> <A HREF="HipiImageBundle.html" title="class in hipi.imagebundle" target="classFrame">HipiImageBundle</A> <BR> <A HREF="HipiImageBundle.FileReader.html" title="class in hipi.imagebundle" target="classFrame">HipiImageBundle.FileReader</A> <BR> <A HREF="SeqImageBundle.html" title="class in hipi.imagebundle" target="classFrame">SeqImageBundle</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
{ "content_hash": "e5cffc268c9d3bd6ecd043901b19c3da", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 126, "avg_line_length": 34.025, "alnum_prop": 0.7156502571638501, "repo_name": "nvoron23/hipi", "id": "ba9da7f46a3b4f2c09a8d2e4ed611cf483c3a6af", "size": "1361", "binary": false, "copies": "1", "ref": "refs/heads/release", "path": "doc/api/hipi/imagebundle/package-frame.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "158119" }, { "name": "MATLAB", "bytes": "410" }, { "name": "Python", "bytes": "1542" }, { "name": "Shell", "bytes": "396" } ], "symlink_target": "" }
import csv import os import re try: import urlparse except ImportError: import urllib.parse as urlparse import pkgutil import inspect import bb import supportedrecipesreport class Columns(object): """Base class for all classes which extend the SUPPORTED_RECIPES_SOURCES report. Typically used to add columns, hence the name. Usage of the class is: - instantiated when starting to write a report - extend_header() - add new columns - extend_row() - add data for new colums to each row as it is getting written To add new classes, create a "lib/supportedrecipesreport" directory in your layer, with an empty "__init__.py" file and one or more classes inheriting from this base class defined in one or more regular .py files. """ def __init__(self, d, all_rows): """Initialize instance. Gets access to the global datastore and all rows that are to be written (unmodified and read-only). """ pass def extend_header(self, row_headers): """Add new columns. Called with a list of field names, in the order in which the resultig .cvs report will have them. extend_header() then may extend the list of fields. See supportedrecipes.py for a list of already present fields. """ pass def extend_row(self, row): """Add data for new columns or modify existing ones. Called with a hash mapping field names to the corresponding data. """ pass def parse_regex(regex, filename, linenumber): try: # must match entire string, hence the '$' return (re.compile(regex + '$'), regex) except Exception as ex: raise RuntimeError("%s.%d: parsing '%s' as regular expression failed: %s" % ( filename, linenumber, regex, str(ex))) class SupportedRecipe: def __init__(self, pattern, supportedby, filename, linenumber): self.supportedby = supportedby self.filename = filename self.pattern = pattern self.linenumber = linenumber parts = pattern.split('@') if len(parts) != 2: raise RuntimeError("%s.%d: entry must have format <recipe name regex>@<collection name regex>, " "splitting by @ found %d parts instead: %s" % (filename, linenumber, len(parts), pattern)) self.pn_re = parse_regex(parts[0], filename, linenumber) self.collection_re = parse_regex(parts[1], filename, linenumber) def is_supportedby(self, pn, collection): # Returns string identifying the team supporting the recipe or # empty string if unsupported. supported = bool((pn is None or self.pn_re[0].match(pn)) and (collection is None or self.collection_re[0].match(collection))) return self.supportedby if supported else '' class SupportedRecipes: def __init__(self): self.supported = [] def append(self, recipe): self.supported.append(recipe) def current_recipe_supportedby(self, d): pn = d.getVar('PN', True) filename = d.getVar('FILE', True) collection = bb.utils.get_file_layer(filename, d) return self.recipe_supportedby(pn, collection) def recipe_supportedby(self, pn, collection): # Returns list of of teams supporting the recipe (could be # more than one or none). result = set() for recipe in self.supported: supportedby = recipe.is_supportedby(pn, collection) if supportedby: result.add(supportedby) return sorted(result) def load_supported_recipes(d): files = [] supported_files = d.getVar('SUPPORTED_RECIPES', True) if not supported_files: bb.fatal('SUPPORTED_RECIPES is not set') supported_recipes = SupportedRecipes() for filename in supported_files.split(): try: base = os.path.basename(filename) supportedby = d.getVarFlag('SUPPORTED_RECIPES', base, True) if not supportedby: supportedby = base.rstrip('.txt') with open(filename) as f: linenumber = 1 for line in f: if line.startswith('#'): continue # TODO (?): sanity check the content to catch # obsolete entries or typos. pn = line.strip() if pn: supported_recipes.append(SupportedRecipe(line.strip(), supportedby, filename, linenumber)) linenumber += 1 files.append(filename) except OSError as ex: bb.fatal('Could not read SUPPORTED_RECIPES = %s: %s' % (supported_files, str(ex))) return (supported_recipes, files) SOURCE_FIELDS = 'component,collection,version,homepage,source,summary,license'.split(',') # Collects information about one recipe during parsing for SUPPORTED_RECIPES_SOURCES. # The dumped information cannot be removed because it might be needed in future # bitbake invocations, so the default location is inside the tmp directory. def dump_sources(d): pn = d.getVar('PN', True) filename = d.getVar('FILE', True) collection = bb.utils.get_file_layer(filename, d) pv = d.getVar('PV', True) summary = d.getVar('SUMMARY', True) or '' homepage = d.getVar('HOMEPAGE', True) or '' src = d.getVar('SRC_URI', True).split() license = d.getVar('LICENSE', True) sources = [] for url in src: scheme, netloc, path, query, fragment = urlparse.urlsplit(url) if scheme != 'file': parts = path.split(';') if len(parts) > 1: path = parts[0] params = dict([x.split('=') if '=' in x else (x, '') for x in parts[1:]]) else: params = {} name = params.get('name', None) sources.append((name, '%s://%s%s' % (scheme, netloc, path))) dumpfile = d.getVar('SUPPORTED_RECIPES_SOURCES_DIR', True) + '/' + pn + filename bb.utils.mkdirhier(os.path.dirname(dumpfile)) with open(dumpfile, 'w') as f: # File intentionally kept small by not writing a header # line. Guaranteed to contain SOURCE_FIELDS. writer = csv.writer(f) for idx, val in enumerate(sources): name, url = val if name and len(sources) != 1: fullname = '%s/%s' % (pn, name) elif idx > 0: fullname = '%s/%d' % (pn, idx) else: fullname = pn writer.writerow((fullname, collection, pv, homepage, url, summary, license)) class IsNative(object): def __init__(self, d): # Always add a trailing $ to ensure a full match. native_recipes = d.getVar('SUPPORTED_RECIPES_NATIVE_RECIPES', True).split() self.isnative_exception = re.compile('(' + '|'.join(native_recipes) + ')$') self.isnative_baseclasses = d.getVar('SUPPORTED_RECIPES_NATIVE_BASECLASSES', True).split() def __call__(self, pn, pndata): for inherited in pndata['inherits']: if os.path.basename(inherited) in self.isnative_baseclasses: return True # Some build recipes do not inherit cross.bbclass and must be skipped explicitly. # The "real" recipes (in cases like glibc) still get checked. Other recipes are OE-core # internal helpers. if self.isnative_exception.match(pn): return True class TruncatedError(Exception): pass def dump_dependencies(depgraph, max_lines, unsupported): # Walk the recipe dependency tree and add one line for each path that ends in # an unsupported recipe. lines = [] current_line = [] # Pre-compute complete dependencies (DEPEND and RDEPEND) for each recipe # instead of doing it each time we reach a recipe. Also identifies those # recipes that nothing depends on. They are the start points for the build. roots = set(depgraph['pn']) deps = {} for task, taskdeps in depgraph['tdepends'].items(): pn = task.split('.')[0] pndeps = deps.setdefault(pn, set()) for taskdep in taskdeps: pndep = taskdep.split('.')[0] if pndep != pn: pndeps.add(pndep) roots.discard(pndep) for pn in deps: deps[pn] = sorted(deps[pn]) # We can prune the search tree a lot by keeping track of those recipes which are already # known to not depend on an unsupported recipe. okay = set() def visit_recipe(pn): if pn in okay: return False if pn in current_line: # Recursive dependency, bail out. Can happen # because we flattened the task dependencies; those don't have # cycles. return False current_line.append(pn) printed = False for dep in deps.get(pn, []): if visit_recipe(dep): printed = True if not printed and \ pn in unsupported and \ not len(current_line) == 1: # Current path is non-trivial, ends in an unsupported recipe and was not alread # included in a longer, printed path. Add a copy to the output. if len(lines) >= max_lines: raise TruncatedError() lines.append(current_line[:]) printed = True if not printed and not pn in unsupported: okay.add(pn) del current_line[-1] return printed truncated = False try: for pn in sorted(roots): visit_recipe(pn) except TruncatedError: truncated = True return lines, truncated def collection_hint(pn, supported_recipes): # Determines whether the recipe would be supported in some other collection. collections = set([supported_recipe.collection_re[1] for supported_recipe in supported_recipes.supported if supported_recipe.is_supportedby(pn, None)]) return ' (would be supported in %s)' % ' '.join(collections) if collections else '' def dump_unsupported(unsupported, supported_recipes): # Turns the mapping from unsupported recipe to is collection # into a sorted list of entries in the final report. lines = [] for pn, collection in unsupported.items(): # Left and right side of the <recipe>@<collection> entries are # regular expressions. In contrast to re.escape(), we only # escape + (as in gtk+3). Escaping all non-alphanumerics # makes many entries (like linux-yocto) unnecessarily less # readable (linux\-yocto). pn = pn.replace('+', r'\+') collection = collection.replace('+', r'\+') hint = collection_hint(pn, supported_recipes) entry = '%s@%s%s' % (pn, collection, hint) lines.append(entry) return sorted(lines) def check_build(d, event): supported_recipes, files = load_supported_recipes(d) supported_recipes_check = d.getVar('SUPPORTED_RECIPES_CHECK', True) if not supported_recipes_check: return isnative = IsNative(d) valid = ('note', 'warn', 'error', 'fatal') if supported_recipes_check not in valid: bb.fatal('SUPPORTED_RECIPES_CHECK must be set to one of %s, currently is: %s' % ('/'.join(valid), supported_recipes_check)) logger = bb.__dict__[supported_recipes_check] # See bitbake/lib/bb/cooker.py buildDependTree() for the content of the depgraph hash. # Basically it mirrors the information dumped by "bitbake -g". depgraph = event._depgraph # import pprint # bb.note('depgraph: %s' % pprint.pformat(depgraph)) dirname = d.getVar('SUPPORTED_RECIPES_SOURCES_DIR', True) report_sources = d.getVar('SUPPORTED_RECIPES_SOURCES', True) unsupported = {} sources = [] for pn, pndata in depgraph['pn'].items(): # We only care about recipes compiled for the target. # Most native ones can be detected reliably because they inherit native.bbclass, # but some special cases have to be hard-coded. # Image recipes also do not matter. if not isnative(pn, pndata): filename = pndata['filename'] collection = bb.utils.get_file_layer(filename, d) supportedby = supported_recipes.recipe_supportedby(pn, collection) if not supportedby: unsupported[pn] = collection if report_sources: dumpfile = os.path.join(dirname, pn + filename) with open(dumpfile) as f: reader = csv.reader(f) for row in reader: row_hash = {f: row[i] for i, f in enumerate(SOURCE_FIELDS)} row_hash['supported'] = 'yes (%s)' % ' '.join(supportedby) \ if supportedby else 'no' sources.append(row_hash) if report_sources: with open(report_sources, 'w') as f: fields = SOURCE_FIELDS[:] # Insert after 'collection'. fields.insert(fields.index('collection') + 1, 'supported') extensions = [] for importer, modname, ispkg in pkgutil.iter_modules(supportedrecipesreport.__path__): module = __import__('supportedrecipesreport.' + modname, fromlist="dummy") for name, clazz in inspect.getmembers(module, inspect.isclass): if issubclass(clazz, Columns): extensions.append(clazz(d, sources)) for e in extensions: e.extend_header(fields) writer = csv.DictWriter(f, fields) writer.writeheader() for row in sources: for e in extensions: e.extend_row(row) # Sort by first column, then second column, etc., after extending all rows. for row in sorted(sources, key=lambda r: [r.get(f, None) for f in fields]): writer.writerow(row) bb.note('Created SUPPORTED_RECIPES_SOURCES = %s file.' % report_sources) if unsupported: max_lines = int(d.getVar('SUPPORTED_RECIPES_CHECK_DEPENDENCY_LINES', True)) dependencies, truncated = dump_dependencies(depgraph, max_lines, unsupported) output = [] output.append('The following unsupported recipes are required for the build:') output.extend([' ' + line for line in dump_unsupported(unsupported, supported_recipes)]) output.append(''' Each unsupported recipe is identified by the recipe name and the collection in which it occurs and has to be marked as supported (see below) using that format. Typically each layer has exactly one collection.''') if dependencies: # Add the optional dependency dump. output.append(''' Here are the dependency chains (including DEPENDS and RDEPENDS) which include one or more of the unsupported recipes. -> means "depends on" and * marks unsupported recipes:''') for line in dependencies: line_entries = [('*' if pn in unsupported else '') + pn for pn in line] output.append(' ' + ' -> '.join(line_entries)) if truncated: output.append('''... Output truncated, to see more increase SUPPORTED_RECIPES_CHECK_DEPENDENCY_LINES (currently %d).''' % max_lines) output.append(''' To avoid this message, several options exist: * Check the dependency chain(s) to see why a recipe gets pulled in and perhaps change recipe configurations or image content to avoid pulling in undesired components. * If the recipe is supported in some other layer, disable the unsupported one with BBMASK. * Add the unsupported recipes to one of the following files: %s Regular expressions are supported on both sides of the @ separator. * Create a new file which lists the unsupported recipes and extend SUPPORTED_RECIPES: SUPPORTED_RECIPES_append = " <path>/recipes-supported-by-me.txt" See meta-refkit/conf/layer.conf and refkit.conf for an example how the path can be derived automatically. The expectation is that SUPPORTED_RECIPES gets set in distro configuration files, depending on the support provided by the distro creator. * Disable the check with SUPPORTED_RECIPES_CHECK = "" in local.conf. 'bitbake -g <build target>' produces .dot files showing these dependencies. ''' % '\n '.join(files)) logger('\n'.join(output))
{ "content_hash": "1d611e7dbd42e0d375c43890ff08059b", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 108, "avg_line_length": 42.114713216957604, "alnum_prop": 0.6040383704405495, "repo_name": "jairglez/intel-iot-refkit", "id": "e9907eae1772761d8c6ab416e23b7d733a20cbc7", "size": "16970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "meta-refkit-core/lib/supportedrecipes.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "11451" }, { "name": "BitBake", "bytes": "95103" }, { "name": "C", "bytes": "133328" }, { "name": "C++", "bytes": "1178" }, { "name": "CMake", "bytes": "838" }, { "name": "Java", "bytes": "504" }, { "name": "JavaScript", "bytes": "25003" }, { "name": "M4", "bytes": "7374" }, { "name": "Makefile", "bytes": "1190" }, { "name": "Mask", "bytes": "599" }, { "name": "PHP", "bytes": "10437" }, { "name": "Pascal", "bytes": "1416" }, { "name": "Python", "bytes": "506975" }, { "name": "Shell", "bytes": "65079" }, { "name": "SourcePawn", "bytes": "2662" } ], "symlink_target": "" }
package org.spongycastle.jce.provider; import java.io.IOException; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Principal; import java.security.Provider; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.cert.CRLException; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.security.auth.x500.X500Principal; import org.spongycastle.asn1.ASN1Encodable; import org.spongycastle.asn1.ASN1Encoding; import org.spongycastle.asn1.ASN1InputStream; import org.spongycastle.asn1.ASN1Integer; import org.spongycastle.asn1.ASN1ObjectIdentifier; import org.spongycastle.asn1.ASN1OctetString; import org.spongycastle.asn1.util.ASN1Dump; import org.spongycastle.asn1.x500.X500Name; import org.spongycastle.asn1.x509.CRLDistPoint; import org.spongycastle.asn1.x509.CRLNumber; import org.spongycastle.asn1.x509.CertificateList; import org.spongycastle.asn1.x509.Extension; import org.spongycastle.asn1.x509.Extensions; import org.spongycastle.asn1.x509.GeneralNames; import org.spongycastle.asn1.x509.IssuingDistributionPoint; import org.spongycastle.asn1.x509.TBSCertList; import org.spongycastle.jce.X509Principal; import org.spongycastle.util.Strings; import org.spongycastle.util.encoders.Hex; /** * The following extensions are listed in RFC 2459 as relevant to CRLs * * Authority Key Identifier * Issuer Alternative Name * CRL Number * Delta CRL Indicator (critical) * Issuing Distribution Point (critical) */ public class X509CRLObject extends X509CRL { private CertificateList c; private String sigAlgName; private byte[] sigAlgParams; private boolean isIndirect; private boolean isHashCodeSet = false; private int hashCodeValue; public static boolean isIndirectCRL(X509CRL crl) throws CRLException { try { byte[] idp = crl.getExtensionValue(Extension.issuingDistributionPoint.getId()); return idp != null && IssuingDistributionPoint.getInstance(ASN1OctetString.getInstance(idp).getOctets()).isIndirectCRL(); } catch (Exception e) { throw new ExtCRLException( "Exception reading IssuingDistributionPoint", e); } } public X509CRLObject( CertificateList c) throws CRLException { this.c = c; try { this.sigAlgName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm()); if (c.getSignatureAlgorithm().getParameters() != null) { this.sigAlgParams = ((ASN1Encodable)c.getSignatureAlgorithm().getParameters()).toASN1Primitive().getEncoded(ASN1Encoding.DER); } else { this.sigAlgParams = null; } this.isIndirect = isIndirectCRL(this); } catch (Exception e) { throw new CRLException("CRL contents invalid: " + e); } } /** * Will return true if any extensions are present and marked * as critical as we currently dont handle any extensions! */ public boolean hasUnsupportedCriticalExtension() { Set extns = getCriticalExtensionOIDs(); if (extns == null) { return false; } extns.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT); extns.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR); return !extns.isEmpty(); } private Set getExtensionOIDs(boolean critical) { if (this.getVersion() == 2) { Extensions extensions = c.getTBSCertList().getExtensions(); if (extensions != null) { Set set = new HashSet(); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier)e.nextElement(); Extension ext = extensions.getExtension(oid); if (critical == ext.isCritical()) { set.add(oid.getId()); } } return set; } } return null; } public Set getCriticalExtensionOIDs() { return getExtensionOIDs(true); } public Set getNonCriticalExtensionOIDs() { return getExtensionOIDs(false); } public byte[] getExtensionValue(String oid) { Extensions exts = c.getTBSCertList().getExtensions(); if (exts != null) { Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid)); if (ext != null) { try { return ext.getExtnValue().getEncoded(); } catch (Exception e) { throw new IllegalStateException("error parsing " + e.toString()); } } } return null; } public byte[] getEncoded() throws CRLException { try { return c.getEncoded(ASN1Encoding.DER); } catch (IOException e) { throw new CRLException(e.toString()); } } public void verify(PublicKey key) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { Signature sig; try { sig = Signature.getInstance(getSigAlgName(), BouncyCastleProvider.PROVIDER_NAME); } catch (Exception e) { sig = Signature.getInstance(getSigAlgName()); } doVerify(key, sig); } public void verify(PublicKey key, String sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { Signature sig; if (sigProvider != null) { sig = Signature.getInstance(getSigAlgName(), sigProvider); } else { sig = Signature.getInstance(getSigAlgName()); } doVerify(key, sig); } public void verify(PublicKey key, Provider sigProvider) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { Signature sig; if (sigProvider != null) { sig = Signature.getInstance(getSigAlgName(), sigProvider); } else { sig = Signature.getInstance(getSigAlgName()); } doVerify(key, sig); } private void doVerify(PublicKey key, Signature sig) throws CRLException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { if (!c.getSignatureAlgorithm().equals(c.getTBSCertList().getSignature())) { throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList."); } sig.initVerify(key); sig.update(this.getTBSCertList()); if (!sig.verify(this.getSignature())) { throw new SignatureException("CRL does not verify with supplied public key."); } } public int getVersion() { return c.getVersionNumber(); } public Principal getIssuerDN() { return new X509Principal(X500Name.getInstance(c.getIssuer().toASN1Primitive())); } public X500Principal getIssuerX500Principal() { try { return new X500Principal(c.getIssuer().getEncoded()); } catch (IOException e) { throw new IllegalStateException("can't encode issuer DN"); } } public Date getThisUpdate() { return c.getThisUpdate().getDate(); } public Date getNextUpdate() { if (c.getNextUpdate() != null) { return c.getNextUpdate().getDate(); } return null; } private Set loadCRLEntries() { Set entrySet = new HashSet(); Enumeration certs = c.getRevokedCertificateEnumeration(); X500Name previousCertificateIssuer = null; // the issuer while (certs.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); X509CRLEntryObject crlEntry = new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); entrySet.add(crlEntry); if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); } } } return entrySet; } public X509CRLEntry getRevokedCertificate(BigInteger serialNumber) { Enumeration certs = c.getRevokedCertificateEnumeration(); X500Name previousCertificateIssuer = null; // the issuer while (certs.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry)certs.nextElement(); if (serialNumber.equals(entry.getUserCertificate().getValue())) { return new X509CRLEntryObject(entry, isIndirect, previousCertificateIssuer); } if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { previousCertificateIssuer = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); } } } return null; } public Set getRevokedCertificates() { Set entrySet = loadCRLEntries(); if (!entrySet.isEmpty()) { return Collections.unmodifiableSet(entrySet); } return null; } public byte[] getTBSCertList() throws CRLException { try { return c.getTBSCertList().getEncoded("DER"); } catch (IOException e) { throw new CRLException(e.toString()); } } public byte[] getSignature() { return c.getSignature().getOctets(); } public String getSigAlgName() { return sigAlgName; } public String getSigAlgOID() { return c.getSignatureAlgorithm().getAlgorithm().getId(); } public byte[] getSigAlgParams() { if (sigAlgParams != null) { byte[] tmp = new byte[sigAlgParams.length]; System.arraycopy(sigAlgParams, 0, tmp, 0, tmp.length); return tmp; } return null; } /** * Returns a string representation of this CRL. * * @return a string representation of this CRL. */ public String toString() { StringBuffer buf = new StringBuffer(); String nl = Strings.lineSeparator(); buf.append(" Version: ").append(this.getVersion()).append( nl); buf.append(" IssuerDN: ").append(this.getIssuerDN()) .append(nl); buf.append(" This update: ").append(this.getThisUpdate()) .append(nl); buf.append(" Next update: ").append(this.getNextUpdate()) .append(nl); buf.append(" Signature Algorithm: ").append(this.getSigAlgName()) .append(nl); byte[] sig = this.getSignature(); buf.append(" Signature: ").append( new String(Hex.encode(sig, 0, 20))).append(nl); for (int i = 20; i < sig.length; i += 20) { if (i < sig.length - 20) { buf.append(" ").append( new String(Hex.encode(sig, i, 20))).append(nl); } else { buf.append(" ").append( new String(Hex.encode(sig, i, sig.length - i))).append(nl); } } Extensions extensions = c.getTBSCertList().getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); if (e.hasMoreElements()) { buf.append(" Extensions: ").append(nl); } while (e.hasMoreElements()) { ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement(); Extension ext = extensions.getExtension(oid); if (ext.getExtnValue() != null) { byte[] octs = ext.getExtnValue().getOctets(); ASN1InputStream dIn = new ASN1InputStream(octs); buf.append(" critical(").append( ext.isCritical()).append(") "); try { if (oid.equals(Extension.cRLNumber)) { buf.append( new CRLNumber(ASN1Integer.getInstance( dIn.readObject()).getPositiveValue())) .append(nl); } else if (oid.equals(Extension.deltaCRLIndicator)) { buf.append( "Base CRL: " + new CRLNumber(ASN1Integer.getInstance( dIn.readObject()).getPositiveValue())) .append(nl); } else if (oid .equals(Extension.issuingDistributionPoint)) { buf.append( IssuingDistributionPoint.getInstance(dIn.readObject())).append(nl); } else if (oid .equals(Extension.cRLDistributionPoints)) { buf.append( CRLDistPoint.getInstance(dIn.readObject())).append(nl); } else if (oid.equals(Extension.freshestCRL)) { buf.append( CRLDistPoint.getInstance(dIn.readObject())).append(nl); } else { buf.append(oid.getId()); buf.append(" value = ").append( ASN1Dump.dumpAsString(dIn.readObject())) .append(nl); } } catch (Exception ex) { buf.append(oid.getId()); buf.append(" value = ").append("*****").append(nl); } } else { buf.append(nl); } } } Set set = getRevokedCertificates(); if (set != null) { Iterator it = set.iterator(); while (it.hasNext()) { buf.append(it.next()); buf.append(nl); } } return buf.toString(); } /** * Checks whether the given certificate is on this CRL. * * @param cert the certificate to check for. * @return true if the given certificate is on this CRL, * false otherwise. */ public boolean isRevoked(Certificate cert) { if (!cert.getType().equals("X.509")) { throw new RuntimeException("X.509 CRL used with non X.509 Cert"); } Enumeration certs = c.getRevokedCertificateEnumeration(); X500Name caName = c.getIssuer(); if (certs != null) { BigInteger serial = ((X509Certificate)cert).getSerialNumber(); while (certs.hasMoreElements()) { TBSCertList.CRLEntry entry = TBSCertList.CRLEntry.getInstance(certs.nextElement()); if (isIndirect && entry.hasExtensions()) { Extension currentCaName = entry.getExtensions().getExtension(Extension.certificateIssuer); if (currentCaName != null) { caName = X500Name.getInstance(GeneralNames.getInstance(currentCaName.getParsedValue()).getNames()[0].getName()); } } if (entry.getUserCertificate().getValue().equals(serial)) { X500Name issuer; if (cert instanceof X509Certificate) { issuer = X500Name.getInstance(((X509Certificate)cert).getIssuerX500Principal().getEncoded()); } else { try { issuer = org.spongycastle.asn1.x509.Certificate.getInstance(cert.getEncoded()).getIssuer(); } catch (CertificateEncodingException e) { throw new RuntimeException("Cannot process certificate"); } } if (!caName.equals(issuer)) { return false; } return true; } } } return false; } public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof X509CRL)) { return false; } if (other instanceof X509CRLObject) { X509CRLObject crlObject = (X509CRLObject)other; if (isHashCodeSet) { boolean otherIsHashCodeSet = crlObject.isHashCodeSet; if (otherIsHashCodeSet) { if (crlObject.hashCodeValue != hashCodeValue) { return false; } } } return this.c.equals(crlObject.c); } return super.equals(other); } public int hashCode() { if (!isHashCodeSet) { isHashCodeSet = true; hashCodeValue = super.hashCode(); } return hashCodeValue; } }
{ "content_hash": "c1c67b2c0108adcc57c924adcf1b6638", "timestamp": "", "source": "github", "line_count": 663, "max_line_length": 151, "avg_line_length": 29.671191553544496, "alnum_prop": 0.5252135014233428, "repo_name": "Skywalker-11/spongycastle", "id": "bfb8d35f9c84580f8f4378be7dbcd50218b1caad", "size": "19672", "binary": false, "copies": "2", "ref": "refs/heads/spongy-master", "path": "prov/src/main/java/org/spongycastle/jce/provider/X509CRLObject.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "56178" }, { "name": "Java", "bytes": "23805898" }, { "name": "Shell", "bytes": "74533" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Tests\Unit\Coverage; use Paraunit\Configuration\TempFilenameFactory; use Paraunit\Coverage\CoverageFetcher; use Paraunit\TestResult\Interfaces\TestResultHandlerInterface; use Tests\BaseUnitTestCase; use Tests\Stub\StubbedParaunitProcess; class CoverageFetcherTest extends BaseUnitTestCase { public function testFetch(): void { $process = new StubbedParaunitProcess('test.php', 'uniqueId'); $filename = $this->getTempFilename(); copy($this->getCoverageStubFilePath(), $filename); $this->assertFileExists($filename, 'Test malformed, stub log file not found'); $tempFilenameFactory = $this->prophesize(TempFilenameFactory::class); $tempFilenameFactory->getFilenameForCoverage('uniqueId') ->shouldBeCalled() ->willReturn($filename); $missingCoverageContainer = $this->prophesize(TestResultHandlerInterface::class); $missingCoverageContainer->addProcessToFilenames($process) ->shouldNotBeCalled(); $fetcher = new CoverageFetcher($tempFilenameFactory->reveal(), $missingCoverageContainer->reveal()); $result = $fetcher->fetch($process); $this->assertSame(['foo' => 'bar'], $result->getTests()); $this->assertFileDoesNotExist($filename, 'Coverage file should be deleted to preserve memory'); } public function testFetchIgnoresMissingCoverageFiles(): void { $process = new StubbedParaunitProcess('test.php', 'uniqueId'); $tempFilenameFactory = $this->prophesize(TempFilenameFactory::class); $tempFilenameFactory->getFilenameForCoverage('uniqueId') ->shouldBeCalled() ->willReturn('/path/to/missing/file'); $missingCoverageContainer = $this->prophesize(TestResultHandlerInterface::class); $missingCoverageContainer->addProcessToFilenames($process) ->shouldBeCalled(); $fetcher = new CoverageFetcher($tempFilenameFactory->reveal(), $missingCoverageContainer->reveal()); $result = $fetcher->fetch($process); $this->assertEmpty($result->getTests()); } public function testFetchIgnoresWrongFiles(): void { $process = new StubbedParaunitProcess('test.php', 'uniqueId'); $filename = $this->getTempFilename(); copy($this->getWrongCoverageStubFilePath(), $filename); $this->assertFileExists($filename, 'Test malformed, stub log file not found'); $tempFilenameFactory = $this->prophesize(TempFilenameFactory::class); $tempFilenameFactory->getFilenameForCoverage('uniqueId') ->shouldBeCalled() ->willReturn($filename); $missingCoverageContainer = $this->prophesize(TestResultHandlerInterface::class); $missingCoverageContainer->addProcessToFilenames($process) ->shouldBeCalled(); $fetcher = new CoverageFetcher($tempFilenameFactory->reveal(), $missingCoverageContainer->reveal()); $result = $fetcher->fetch($process); $this->assertEmpty($result->getTests()); $this->assertFileDoesNotExist($filename, 'Coverage file should be deleted to preserve memory'); } private function getTempFilename(): string { return uniqid(sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'testfile', true) . '.php'; } }
{ "content_hash": "5b961eaa9fea5d6ce9c1160f7295b7d4", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 108, "avg_line_length": 39, "alnum_prop": 0.6845557543231962, "repo_name": "facile-it/paraunit", "id": "a8d6c1a037b2c4ff2547a871810d0c983d51251c", "size": "3354", "binary": false, "copies": "1", "ref": "refs/heads/1.x", "path": "tests/Unit/Coverage/CoverageFetcherTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "718" }, { "name": "Makefile", "bytes": "575" }, { "name": "PHP", "bytes": "343308" }, { "name": "Shell", "bytes": "3051" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Fl. mycol. France (Paris) 75 (1888) #### Original name Agaricus jonquilla Lév., 1855 ### Remarks null
{ "content_hash": "6073e26c6f842fdda84e3d16d1a031e3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 14.538461538461538, "alnum_prop": 0.6984126984126984, "repo_name": "mdoering/backbone", "id": "4fad8f0d988f4a7d9f86bdbb781f2f538e490dbb", "size": "255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Tricholomataceae/Phyllotopsis/Phyllotopsis nidulans/ Syn. Crepidotus jonquilla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Effekseer.GUI { public partial class DockFCurves : DockContent { public DockFCurves() { InitializeComponent(); } public void ScrollPosition(object o) { fCurves.ScrollPosition(o); } } }
{ "content_hash": "da4d353288e738d525774867a463e484", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 47, "avg_line_length": 16.791666666666668, "alnum_prop": 0.7468982630272953, "repo_name": "lltcggie/Effekseer", "id": "d3062c890ae92086a4a7e717c148862f5456096a", "size": "405", "binary": false, "copies": "2", "ref": "refs/heads/desunoya", "path": "Dev/Editor/Effekseer/GUI/DockFCurves.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "18781" }, { "name": "C", "bytes": "1757603" }, { "name": "C#", "bytes": "706503" }, { "name": "C++", "bytes": "1860213" }, { "name": "CMake", "bytes": "15433" }, { "name": "CSS", "bytes": "4182" }, { "name": "FLUX", "bytes": "26926" }, { "name": "HTML", "bytes": "115808" }, { "name": "Objective-C", "bytes": "139991" }, { "name": "Python", "bytes": "7690" }, { "name": "Shell", "bytes": "313" } ], "symlink_target": "" }
#ifndef FREERDP_CODEC_INTERLEAVED_H #define FREERDP_CODEC_INTERLEAVED_H #include <freerdp/api.h> #include <freerdp/types.h> #include <freerdp/codec/color.h> #include <freerdp/codec/bitmap.h> typedef struct S_BITMAP_INTERLEAVED_CONTEXT BITMAP_INTERLEAVED_CONTEXT; #ifdef __cplusplus extern "C" { #endif FREERDP_API BOOL interleaved_decompress(BITMAP_INTERLEAVED_CONTEXT* interleaved, const BYTE* pSrcData, UINT32 SrcSize, UINT32 nSrcWidth, UINT32 nSrcHeight, UINT32 bpp, BYTE* pDstData, UINT32 DstFormat, UINT32 nDstStep, UINT32 nXDst, UINT32 nYDst, UINT32 nDstWidth, UINT32 nDstHeight, const gdiPalette* palette); FREERDP_API BOOL interleaved_compress(BITMAP_INTERLEAVED_CONTEXT* interleaved, BYTE* pDstData, UINT32* pDstSize, UINT32 nWidth, UINT32 nHeight, const BYTE* pSrcData, UINT32 SrcFormat, UINT32 nSrcStep, UINT32 nXSrc, UINT32 nYSrc, const gdiPalette* palette, UINT32 bpp); FREERDP_API BOOL bitmap_interleaved_context_reset(BITMAP_INTERLEAVED_CONTEXT* interleaved); FREERDP_API BITMAP_INTERLEAVED_CONTEXT* bitmap_interleaved_context_new(BOOL Compressor); FREERDP_API void bitmap_interleaved_context_free(BITMAP_INTERLEAVED_CONTEXT* interleaved); #ifdef __cplusplus } #endif #endif /* FREERDP_CODEC_INTERLEAVED_H */
{ "content_hash": "6442e74deaaa6a20d4cb691cab6b7fb3", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 96, "avg_line_length": 39.073170731707314, "alnum_prop": 0.6173533083645443, "repo_name": "awakecoding/FreeRDP", "id": "d2ef02e5a06bb73474ea23b698664d9b06dabb0c", "size": "2320", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "include/freerdp/codec/interleaved.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15084706" }, { "name": "C#", "bytes": "6365" }, { "name": "C++", "bytes": "138156" }, { "name": "CMake", "bytes": "635168" }, { "name": "CSS", "bytes": "5696" }, { "name": "HTML", "bytes": "99139" }, { "name": "Java", "bytes": "371005" }, { "name": "Lua", "bytes": "27390" }, { "name": "Makefile", "bytes": "1677" }, { "name": "Objective-C", "bytes": "517001" }, { "name": "Perl", "bytes": "8044" }, { "name": "Python", "bytes": "53966" }, { "name": "Rich Text Format", "bytes": "937" }, { "name": "Roff", "bytes": "12141" }, { "name": "Shell", "bytes": "33001" } ], "symlink_target": "" }
package com.phonegap.natives.bean; /** * Created by Trust on 17/1/5. */ public class TestBean { /** * systime : 2016-08-03 16:21:49 * lon : 116.47676009385665 * loctime : 1470212510269 * address : * speed : 10.471948623657227 * bearing : 44.10205841064453 * provider : gps * accuracy : 350 * lat : 39.995825200614696 */ private String systime; private double lon; private long loctime; private String address; private double speed; private double bearing; private String provider; private int accuracy; private double lat; public void setSystime(String systime) { this.systime = systime; } public void setLon(double lon) { this.lon = lon; } public void setLoctime(long loctime) { this.loctime = loctime; } public void setAddress(String address) { this.address = address; } public void setSpeed(double speed) { this.speed = speed; } public void setBearing(double bearing) { this.bearing = bearing; } public void setProvider(String provider) { this.provider = provider; } public void setAccuracy(int accuracy) { this.accuracy = accuracy; } public void setLat(double lat) { this.lat = lat; } public String getSystime() { return systime; } public double getLon() { return lon; } public long getLoctime() { return loctime; } public String getAddress() { return address; } public double getSpeed() { return speed; } public double getBearing() { return bearing; } public String getProvider() { return provider; } public int getAccuracy() { return accuracy; } public double getLat() { return lat; } }
{ "content_hash": "b9876605a1b8dc9bbd2a86e80af8e44f", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 46, "avg_line_length": 18.752475247524753, "alnum_prop": 0.5839493136219641, "repo_name": "TrustMy/EBike", "id": "cd18839ada68d897bea971f4df640abc7d510fc8", "size": "1894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EBike11/src/com/phonegap/natives/bean/TestBean.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "24628" }, { "name": "CSS", "bytes": "167158" }, { "name": "HTML", "bytes": "174809" }, { "name": "Java", "bytes": "2261445" }, { "name": "JavaScript", "bytes": "1346321" } ], "symlink_target": "" }
<?php defined('BX_DOL') or die('hack attempt'); class BxBaseCmtsForm extends BxTemplFormView { protected static $_sAttributeMaskId; protected static $_sAttributeMaskName; public function __construct($aInfo, $oTemplate) { parent::__construct($aInfo, $oTemplate); if(empty(self::$_sAttributeMaskId)) self::$_sAttributeMaskId = $this->aFormAttrs['id']; if(empty(self::$_sAttributeMaskName)) self::$_sAttributeMaskName = $this->aFormAttrs['name']; if(isset($this->aInputs['cmt_image'])) { $aFormNested = array( 'params' =>array( 'nested_form_template' => 'comments_uploader_nfw.html' ), 'inputs' => array(), ); $oFormNested = new BxDolFormNested('cmt_image', $aFormNested, 'cmt_submit'); $this->aInputs['cmt_image']['storage_object'] = 'sys_cmts_images'; $this->aInputs['cmt_image']['images_transcoder'] = 'sys_cmts_images_preview'; $this->aInputs['cmt_image']['uploaders'] = !empty($this->aInputs['cmt_image']['value']) ? unserialize($this->aInputs['cmt_image']['value']) : array('sys_cmts_simple'); $this->aInputs['cmt_image']['upload_buttons_titles'] = array('Simple' => 'camera'); $this->aInputs['cmt_image']['multiple'] = true; $this->aInputs['cmt_image']['ghost_template'] = $oFormNested; } } public function getAttributeMask($sAttribute) { $sName = '_sAttributeMask' . bx_gen_method_name($sAttribute); return isset(self::$$sName) ? self::$$sName : ''; } public function getStorageObjectName() { return isset($this->aInputs['cmt_image']['storage_object']) ? $this->aInputs['cmt_image']['storage_object'] : ''; } public function getTranscoderPreviewName() { return isset($this->aInputs['cmt_image']['images_transcoder']) ? $this->aInputs['cmt_image']['images_transcoder'] : ''; } } /** @} */
{ "content_hash": "2ce8239b64d3e70a17d1244498ad20fa", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 179, "avg_line_length": 36.872727272727275, "alnum_prop": 0.5798816568047337, "repo_name": "camperjz/una", "id": "a45f97b0871bf02165f85ac8282083f6ed1528da", "size": "2200", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "template/scripts/BxBaseCmtsForm.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3856790" }, { "name": "HTML", "bytes": "1890197" }, { "name": "JavaScript", "bytes": "15456704" }, { "name": "PHP", "bytes": "69609918" }, { "name": "Shell", "bytes": "1532" } ], "symlink_target": "" }
@charset "UTF-8"; @media all { /*------------------------------------------------------------------------------------------------------*/ /** * @section browser reset * @see http://www.yaml.de/en/documentation/css-components/base-stylesheet.html */ /* (en) Global reset of paddings and margins for all HTML elements */ /* (de) Globales Zurücksetzen der Innen- und Außenabstände für alle HTML-Elemente */ * { margin:0; padding: 0 } /* (en) Correction: margin/padding reset caused too small select boxes. */ /* (de) Korrektur: Das Zurücksetzen der Abstände verursacht zu kleine Selectboxen. */ option { padding-left: 0.4em } /** * (en) Global fix of the Italics bugs in IE 5.x and IE 6 * (de) Globale Korrektur des Italics Bugs des IE 5.x und IE 6 * * @bugfix * @affected IE 5.x/Win, IE6 * @css-for IE 5.x/Win, IE6 * @valid yes */ * html body * { overflow:visible; } * html iframe, * html frame { overflow:auto; } * html frameset { overflow:hidden; } /* (en) Forcing vertical scrollbars in Netscape, Firefox and Safari browsers */ /* (de) Erzwingen vertikaler Scrollbalken in Netscape, Firefox und Safari Browsern */ html { height: 100%; margin-bottom: 1px; } body { /* (en) Fix for rounding errors when scaling font sizes in older versions of Opera browser */ /* (de) Beseitigung von Rundungsfehler beim Skalieren von Schriftgrößen in älteren Opera Versionen */ font-size: 100.01%; /* (en) Standard values for colors and text alignment */ /* (de) Vorgabe der Standardfarben und Textausrichtung */ color: #000; background: #fff; text-align: left; } /* (en) Clear borders for <fieldset> and <img> elements */ /* (de) Rahmen für <fieldset> und <img> Elemente löschen */ fieldset, img { border: 0 solid; } /* (en) new standard values for lists, blockquote and cite */ /* (de) Neue Standardwerte für Listen & Zitate */ ul, ol, dl { margin: 0 0 1em 1em } li { margin-left: 1.5em; line-height: 1.5em; } dt { font-weight: bold; } dd { margin: 0 0 1em 2em; } blockquote { margin: 0 0 1em 1.5em; } /*------------------------------------------------------------------------------------------------------*/ /** * @section base layout | Basis Layout * @see http://www.yaml.de/en/documentation/css-components/base-stylesheet.html * * |-------------------------------| * | #b_header | * |-------------------------------| * | #b_col1 | #b_col3 | #b_col2 | * | 200 px | flexible | 200px | * |-------------------------------| * | #b_footer | * |-------------------------------| */ #b_header { position:relative } #b_topnav { position:absolute; top: 10px; right: 10px; /* (en) essential for correct alignment in Opera 6 ! */ /* (de) Erforderlich, damit im Opera 6 wirklich rechts plaziert ! */ text-align: right; } /* (en) Backup for correct positioning */ /* (de) Absicherung korrekte Positionierung */ #b_header, #b_nav, #b_main, #b_footer { clear:both; } /* (en/de) Standard: 200 Pixel */ #b_col1 { float: left; width: 200px } /* (en/de) Standard: 200 Pixel */ #b_col2 { float:right; width: 200px } /* (en) Standard: center column with flexible width */ /* (de) Standard: Flexible mittlere Spalte */ #b_col3 { width:auto; margin: 0 200px } /* (en) Adjustment: sort #b_col3 behind float columns using z-index */ /* (de) Anpassung: #b_col3 mittels z-index hinter die float-Spalten verschieben */ #b_col1 {z-index: 3} #b_col2 {z-index: 5} #b_col3 {z-index: 1} #b_col1_content {z-index: 4} #b_col2_content {z-index: 6} #b_col3_content {z-index: 2} #b_col1_content, #b_col2_content, #b_col3_content { position:relative } /*------------------------------------------------------------------------------------------------------*/ /** * @section generic classes for layout switching | Generische Klassen zur Layoutumschaltung * @see http://www.yaml.de/en/documentation/css-components/base-stylesheet.html * * .b_hidecol1 -> 2-column-layout (using #b_col2 and #b_col3) * .b_hidecol2 -> 2-column-layout (using #b_col1 and #b_col3) * .b_hideboth -> single-column-layout (using #b_col3) */ .b_hideboth #b_col3 {margin-left: 0; margin-right: 0} .b_hidecol1 #b_col3 {margin-left: 0; margin-right: 200px} .b_hidecol2 #b_col3 {margin-left: 200px; margin-right: 0} .b_hideboth #b_col1, .b_hideboth #b_col2 {display:none} .b_hidecol1 #b_col1 {display:none} .b_hidecol2 #b_col2 {display:none} /*------------------------------------------------------------------------------------------------------*/ /** * @section clearing methods * @see http://yaml.de/en/documentation/basics/general.html */ /* (en) clearfix method for clearing floats */ /* (de) Clearfix-Methode zum Clearen der Float-Umgebungen */ .b_clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden } /* (en) essential for Safari browser !! */ /* (de) Diese Angabe benötigt der Safari-Browser zwingend !! */ .b_clearfix { display: block } /* (en) overflow method for clearing floats */ /* (de) Overflow-Methode zum Clearen der Float-Umgebungen */ .b_floatbox { overflow:hidden } /* (en) IE-Clearing: Only used in Internet Explorer, switched on in iehacks.css */ /* (de) IE-Clearing: Benötigt nur der Internet Explorer und über iehacks.css zugeschaltet */ #b_ie_clearing { display: none } /*------------------------------------------------------------------------------------------------------*/ /** * @section subtemplates * @see http://www.yaml.de/en/documentation/practice/subtemplates.html */ .b_subcolumns, .b_subcolumns_oldgecko { width: 100%; overflow:hidden; } /* (en) alternative class for optional support of old Mozilla/Netscape browers */ /* (de) Alternative Klasse zur optionalen Unterstützung alter Mozilla/Netscape-Brower */ .b_subcolumns_oldgecko { float:left } .b_c50l, .b_c25l, .b_c33l, .b_c38l, .b_c66l, .b_c75l, .b_c62l {float: left; } .b_c50r, .b_c25r, .b_c33r, .b_c38r, .b_c66r, .b_c75r, .b_c62r {float: right; margin-left: -5px; } .b_c25l, .b_c25r { width: 25% } .b_c33l, .b_c33r { width: 33.333% } .b_c50l, .b_c50r { width: 50% } .b_c66l, .b_c66r { width: 66.666% } .b_c75l, .b_c75r { width: 75% } .b_c38l, .b_c38r { width: 38.2% } .b_c62l, .b_c62r { width: 61.8% } .b_subc { padding: 0 0.5em } .b_subcl { padding: 0 1em 0 0 } .b_subcr { padding: 0 0 0 1em } /*------------------------------------------------------------------------------------------------------*/ /** * @section hidden elements | Versteckte Elemente * @see http://www.yaml.de/en/documentation/basics/skip-links.html * * (en) skip links and hidden content * (de) Skip-Links und versteckte Inhalte */ /* (en) classes for invisible elements in the base layout */ /* (de) Klassen für unsichtbare Elemente im Basislayout */ .b_skip, .b_hideme, .b_print { position: absolute; top: -1000em; left: -1000em; height: 1px; width: 1px; } /* (en) make skip links visible when using tab navigation */ /* (de) Skip-Links für Tab-Navigation sichtbar schalten */ .b_skip:focus, .b_skip:active { position: static; top: 0; left: 0; height: auto; width: auto; } }
{ "content_hash": "66fb14dbd9d654462931a093b620d182", "timestamp": "", "source": "github", "line_count": 222, "max_line_length": 107, "avg_line_length": 33.47747747747748, "alnum_prop": 0.5653928955866523, "repo_name": "huihoo/olat", "id": "1dc33677c80109cbd9e150b0838c5ba9304e0cc0", "size": "8006", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "olat7.8/src/main/webapp/static/yaml/core/base.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "24445" }, { "name": "AspectJ", "bytes": "36132" }, { "name": "CSS", "bytes": "2135670" }, { "name": "HTML", "bytes": "2950677" }, { "name": "Java", "bytes": "50804277" }, { "name": "JavaScript", "bytes": "31237972" }, { "name": "PLSQL", "bytes": "64492" }, { "name": "Perl", "bytes": "10717" }, { "name": "Shell", "bytes": "79994" }, { "name": "XSLT", "bytes": "186520" } ], "symlink_target": "" }
#ifndef _ATS_BEACON_INTERCEPT_H #define _ATS_BEACON_INTERCEPT_H #include "ts/ts.h" bool hook_beacon_intercept(TSHttpTxn txnp); #endif
{ "content_hash": "0e16237fbcf564e91d568886684bc657", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 43, "avg_line_length": 13.9, "alnum_prop": 0.7410071942446043, "repo_name": "chenglongwei/trafficserver", "id": "d53d81cae3f03189176a9c6fbba376aa6599dbde", "size": "1016", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "plugins/experimental/ats_pagespeed/ats_beacon_intercept.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13053" }, { "name": "C", "bytes": "3434127" }, { "name": "C++", "bytes": "11584881" }, { "name": "CSS", "bytes": "8089" }, { "name": "HTML", "bytes": "238770" }, { "name": "Java", "bytes": "9881" }, { "name": "JavaScript", "bytes": "1609" }, { "name": "Lex", "bytes": "4029" }, { "name": "Lua", "bytes": "380245" }, { "name": "M4", "bytes": "269298" }, { "name": "Makefile", "bytes": "198577" }, { "name": "Objective-C", "bytes": "13254" }, { "name": "Perl", "bytes": "70414" }, { "name": "Protocol Buffer", "bytes": "4013" }, { "name": "Python", "bytes": "329564" }, { "name": "Roff", "bytes": "2339" }, { "name": "Shell", "bytes": "84512" }, { "name": "Vim script", "bytes": "192" }, { "name": "Yacc", "bytes": "3251" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="zh-Hans"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=0"> <meta name="description" content=""> <meta name="keywords" content=""> <!-- Set render engine for 360 browser --> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <!-- No Baidu Siteapp--> <meta http-equiv="Cache-Control" content="no-siteapp" /> <meta name="format-detection" content="telephone=no"> <title>Document</title> <link rel="stylesheet" href="/static/css/bulma.min.css"> <link rel="stylesheet" href="/static/css/common.css"> <link rel="stylesheet" href="/static/css/animate.css"> <link rel="icon" type="image/png" href="/static/image/logo.png"> </head> <body> <div id="blackmodel" class="blackmodel is-hidden"></div> <script src="/static/js/jquery.min.js"></script> <script> (function () { $(function () { var $navbarBurgers = $('.navbar-burger'); // Check if there are any navbar burgers if ($navbarBurgers.length > 0) { $navbarBurgers.on('click', function () { var target = $(this).data('target'); var blackmodel = $('#blackmodel'); blackmodel.on('click', function () { $navbarBurgers.removeClass('is-active'); $(target).removeClass('is-active'); $(this).addClass('is-hidden'); $('html').css({ 'overflow': 'auto' }); }); // Get the target from the "data-target" attribute if ($(this).hasClass('is-active')) { $(this).removeClass('is-active'); $(target).removeClass('is-active'); blackmodel.addClass('is-hidden'); $('html').css({ 'overflow': 'auto' }); } else { $('html').css({ 'overflow': 'hidden' }); blackmodel.removeClass('is-hidden'); $(this).addClass('is-active'); $(target).addClass('is-active'); } }); } }); })(); </script> </body> </html>
{ "content_hash": "c91d73b9e3d935eee1f0781444e0707b", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 121, "avg_line_length": 34.411764705882355, "alnum_prop": 0.5354700854700855, "repo_name": "shuang6/tutorhelp", "id": "8c2441fae318ba5d33a05e7c5e83b3f73477403d", "size": "2340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "front/views/student/home.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "224117" }, { "name": "HTML", "bytes": "139377" }, { "name": "JavaScript", "bytes": "35399" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <corners android:radius="100dp" /> <solid android:color="#0096ff" /> <padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" /> <size android:width="270dp" android:height="60dp" /> <stroke android:width="3dp" android:color="#0096FF" /> </shape>
{ "content_hash": "517a88948b4d0324f0b33ef02c0d9f16", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 93, "avg_line_length": 20.347826086956523, "alnum_prop": 0.6217948717948718, "repo_name": "vishalkuo/FuturesRevealed", "id": "2a3c191ec1114d108e40a477d845f70ea8db92d0", "size": "468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/app/src/main/res/drawable/btn.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3808" }, { "name": "Java", "bytes": "34848" }, { "name": "JavaScript", "bytes": "2168" }, { "name": "Objective-C", "bytes": "39644" }, { "name": "PHP", "bytes": "1373" } ], "symlink_target": "" }
gnewszombie =========== Because Google News API is retired.
{ "content_hash": "5a974fae1c37d13de61a1c31be8e8f1a", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 36, "avg_line_length": 15.5, "alnum_prop": 0.6451612903225806, "repo_name": "b-e-r-t-o/gnewszombie", "id": "0cf2243fbbeaa2b0df992f6fab68257ba7c9bf52", "size": "62", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2069" } ], "symlink_target": "" }
<?php namespace Drupal\KernelTests\Core\Theme; use Drupal\Core\Path\CurrentPathStack; use Drupal\Core\Path\PathMatcherInterface; use Drupal\Core\Theme\Registry; use Drupal\Core\Utility\ThemeRegistry; use Drupal\KernelTests\KernelTestBase; /** * Tests the behavior of the ThemeRegistry class. * * @group Theme */ class RegistryTest extends KernelTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['theme_test', 'system']; protected $profile = 'testing'; /** * Tests the behavior of the theme registry class. */ public function testRaceCondition() { // The theme registry is not marked as persistable in case we don't have a // proper request. \Drupal::request()->setMethod('GET'); $cid = 'test_theme_registry'; // Directly instantiate the theme registry, this will cause a base cache // entry to be written in __construct(). $cache = \Drupal::cache(); $lock_backend = \Drupal::lock(); $registry = new ThemeRegistry($cid, $cache, $lock_backend, ['theme_registry'], $this->container->get('module_handler')->isLoaded()); $this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.'); // Trigger a cache miss for an offset. $this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry.'); // This will cause the ThemeRegistry class to write an updated version of // the cache entry when it is destroyed, usually at the end of the request. // Before that happens, manually delete the cache entry we created earlier // so that the new entry is written from scratch. \Drupal::cache()->delete($cid); // Destroy the class so that it triggers a cache write for the offset. $registry->destruct(); $this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.'); // Create a new instance of the class. Confirm that both the offset // requested previously, and one that has not yet been requested are both // available. $registry = new ThemeRegistry($cid, $cache, $lock_backend, ['theme_registry'], $this->container->get('module_handler')->isLoaded()); $this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry'); $this->assertTrue($registry->get('theme_test_template_test_2'), 'Offset was returned correctly from the theme registry'); } /** * Tests the theme registry with multiple subthemes. */ public function testMultipleSubThemes() { $theme_handler = \Drupal::service('theme_handler'); $theme_handler->install(['test_basetheme', 'test_subtheme', 'test_subsubtheme']); $registry_subsub_theme = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $theme_handler, \Drupal::service('theme.initialization'), 'test_subsubtheme'); $registry_subsub_theme->setThemeManager(\Drupal::theme()); $registry_sub_theme = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $theme_handler, \Drupal::service('theme.initialization'), 'test_subtheme'); $registry_sub_theme->setThemeManager(\Drupal::theme()); $registry_base_theme = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $theme_handler, \Drupal::service('theme.initialization'), 'test_basetheme'); $registry_base_theme->setThemeManager(\Drupal::theme()); $preprocess_functions = $registry_subsub_theme->get()['theme_test_template_test']['preprocess functions']; $this->assertIdentical([ 'template_preprocess', 'test_basetheme_preprocess_theme_test_template_test', 'test_subtheme_preprocess_theme_test_template_test', 'test_subsubtheme_preprocess_theme_test_template_test', ], $preprocess_functions); $preprocess_functions = $registry_sub_theme->get()['theme_test_template_test']['preprocess functions']; $this->assertIdentical([ 'template_preprocess', 'test_basetheme_preprocess_theme_test_template_test', 'test_subtheme_preprocess_theme_test_template_test', ], $preprocess_functions); $preprocess_functions = $registry_base_theme->get()['theme_test_template_test']['preprocess functions']; $this->assertIdentical([ 'template_preprocess', 'test_basetheme_preprocess_theme_test_template_test', ], $preprocess_functions); $preprocess_functions = $registry_base_theme->get()['theme_test_function_suggestions']['preprocess functions']; $this->assertIdentical([ 'template_preprocess_theme_test_function_suggestions', 'test_basetheme_preprocess_theme_test_function_suggestions', ], $preprocess_functions, "Theme functions don't have template_preprocess but do have template_preprocess_HOOK"); } /** * Tests the theme registry with suggestions. */ public function testSuggestionPreprocessFunctions() { $theme_handler = \Drupal::service('theme_handler'); $theme_handler->install(['test_theme']); $registry_theme = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $theme_handler, \Drupal::service('theme.initialization'), 'test_theme'); $registry_theme->setThemeManager(\Drupal::theme()); $suggestions = ['__kitten', '__flamingo']; $expected_preprocess_functions = [ 'template_preprocess', 'theme_test_preprocess_theme_test_preprocess_suggestions', ]; $suggestion = ''; $hook = 'theme_test_preprocess_suggestions'; do { $hook .= "$suggestion"; $expected_preprocess_functions[] = "test_theme_preprocess_$hook"; $preprocess_functions = $registry_theme->get()[$hook]['preprocess functions']; $this->assertIdentical($expected_preprocess_functions, $preprocess_functions, "$hook has correct preprocess functions."); } while ($suggestion = array_shift($suggestions)); $expected_preprocess_functions = [ 'template_preprocess', 'theme_test_preprocess_theme_test_preprocess_suggestions', 'test_theme_preprocess_theme_test_preprocess_suggestions', 'test_theme_preprocess_theme_test_preprocess_suggestions__kitten', ]; $preprocess_functions = $registry_theme->get()['theme_test_preprocess_suggestions__kitten__meerkat']['preprocess functions']; $this->assertIdentical($expected_preprocess_functions, $preprocess_functions, 'Suggestion implemented as a function correctly inherits preprocess functions.'); $preprocess_functions = $registry_theme->get()['theme_test_preprocess_suggestions__kitten__bearcat']['preprocess functions']; $this->assertIdentical($expected_preprocess_functions, $preprocess_functions, 'Suggestion implemented as a template correctly inherits preprocess functions.'); $this->assertTrue(isset($registry_theme->get()['theme_test_preprocess_suggestions__kitten__meerkat__tarsier__moose']), 'Preprocess function with an unimplemented lower-level suggestion is added to the registry.'); } /** * Tests that the theme registry can be altered by themes. */ public function testThemeRegistryAlterByTheme() { /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */ $theme_handler = \Drupal::service('theme_handler'); $theme_handler->install(['test_theme']); $this->config('system.theme')->set('default', 'test_theme')->save(); $registry = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $theme_handler, \Drupal::service('theme.initialization'), 'test_theme'); $registry->setThemeManager(\Drupal::theme()); $this->assertEqual('value', $registry->get()['theme_test_template_test']['variables']['additional']); } /** * Tests front node theme suggestion generation. */ public function testThemeSuggestions() { // Mock the current page as the front page. /** @var PathMatcherInterface $path_matcher */ $path_matcher = $this->prophesize(PathMatcherInterface::class); $path_matcher->isFrontPage()->willReturn(TRUE); $this->container->set('path.matcher', $path_matcher->reveal()); /** @var CurrentPathStack $path_matcher */ $path_current = $this->prophesize(CurrentPathStack::class); $path_current->getPath()->willReturn('/node/1'); $this->container->set('path.current', $path_current->reveal()); // Check suggestions provided through hook_theme_suggestions_html(). $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_html', [[]]); $this->assertSame([ 'html__node', 'html__node__%', 'html__node__1', 'html__front', ], $suggestions, 'Found expected html node suggestions.'); // Check suggestions provided through hook_theme_suggestions_page(). $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_page', [[]]); $this->assertSame([ 'page__node', 'page__node__%', 'page__node__1', 'page__front', ], $suggestions, 'Found expected page node suggestions.'); } }
{ "content_hash": "51f6a5ba547afec6a2dcf6e5c5c1936b", "timestamp": "", "source": "github", "line_count": 195, "max_line_length": 217, "avg_line_length": 46.34871794871795, "alnum_prop": 0.6896437264881611, "repo_name": "rlnorthcutt/acquia-cd-demo", "id": "a962fecc58f179c768c7f5d784af47149621ba57", "size": "9038", "binary": false, "copies": "194", "ref": "refs/heads/master", "path": "docroot/core/tests/Drupal/KernelTests/Core/Theme/RegistryTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "593326" }, { "name": "Gherkin", "bytes": "47803" }, { "name": "HTML", "bytes": "725686" }, { "name": "JavaScript", "bytes": "1153521" }, { "name": "Makefile", "bytes": "3570" }, { "name": "PHP", "bytes": "40105732" }, { "name": "Ruby", "bytes": "910" }, { "name": "Shell", "bytes": "58234" } ], "symlink_target": "" }
drop table appointment_service; drop table appointment; drop table client; drop table worker_ability; drop table worker; drop table account; drop table service; drop type worker_role; drop view time_available;
{ "content_hash": "eb88ac54b607ce94a14d21d92c9bdaae", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 31, "avg_line_length": 19.272727272727273, "alnum_prop": 0.8018867924528302, "repo_name": "nfrolov/useless-barbershop", "id": "568b159ce643625d6a9918c528fee0f6d048dbcc", "size": "212", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sql/drop-tables.sql", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "39364" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Macro BOOST_UNITS_METRIC_PREFIX</title> <link rel="stylesheet" href="../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="boost_units/Reference.html#header.boost.units.systems.si.prefixes_hpp" title="Header &lt;boost/units/systems/si/prefixes.hpp&gt;"> <link rel="prev" href="boost/units/si/watts.html" title="Global watts"> <link rel="next" href="boost/units/si/pascal.html" title="Global pascal"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../boost.png"></td> <td align="center"><a href="../../index.html">Home</a></td> <td align="center"><a href="../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="boost/units/si/watts.html"><img src="../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="boost_units/Reference.html#header.boost.units.systems.si.prefixes_hpp"><img src="../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost/units/si/pascal.html"><img src="../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="BOOST_UNITS_METRIC_PREFIX_idp343809184"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Macro BOOST_UNITS_METRIC_PREFIX</span></h2> <p>BOOST_UNITS_METRIC_PREFIX</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="boost_units/Reference.html#header.boost.units.systems.si.prefixes_hpp" title="Header &lt;boost/units/systems/si/prefixes.hpp&gt;">boost/units/systems/si/prefixes.hpp</a>&gt; </span>BOOST_UNITS_METRIC_PREFIX(exponent, name)</pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2008 Matthias Christian Schabel<br>Copyright &#169; 2007-2010 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="boost/units/si/watts.html"><img src="../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="boost_units/Reference.html#header.boost.units.systems.si.prefixes_hpp"><img src="../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost/units/si/pascal.html"><img src="../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "24d8a1ae08377ad53c8dfd12c0e4ae3e", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 450, "avg_line_length": 71.74, "alnum_prop": 0.6874825759687762, "repo_name": "ycsoft/FatCat-Server", "id": "10d3b62cfb06c1a566b4875e8e1e9af4c57c5437", "size": "3587", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "LIBS/boost_1_58_0/doc/html/BOOST_UNITS_METRIC_PREFIX_idp343809184.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "195345" }, { "name": "Batchfile", "bytes": "32367" }, { "name": "C", "bytes": "9529739" }, { "name": "C#", "bytes": "41850" }, { "name": "C++", "bytes": "175536080" }, { "name": "CMake", "bytes": "14812" }, { "name": "CSS", "bytes": "282447" }, { "name": "Cuda", "bytes": "26521" }, { "name": "FORTRAN", "bytes": "1856" }, { "name": "Groff", "bytes": "6163" }, { "name": "HTML", "bytes": "148956564" }, { "name": "JavaScript", "bytes": "174868" }, { "name": "Lex", "bytes": "1290" }, { "name": "Makefile", "bytes": "1045258" }, { "name": "Max", "bytes": "37424" }, { "name": "Objective-C", "bytes": "34644" }, { "name": "Objective-C++", "bytes": "246" }, { "name": "PHP", "bytes": "60249" }, { "name": "Perl", "bytes": "37297" }, { "name": "Perl6", "bytes": "2130" }, { "name": "Python", "bytes": "1717781" }, { "name": "QML", "bytes": "613" }, { "name": "QMake", "bytes": "9450" }, { "name": "Rebol", "bytes": "372" }, { "name": "Shell", "bytes": "372652" }, { "name": "Tcl", "bytes": "1205" }, { "name": "TeX", "bytes": "13819" }, { "name": "XSLT", "bytes": "564356" }, { "name": "Yacc", "bytes": "19612" } ], "symlink_target": "" }
#include "tensorflow/python/lib/io/py_record_writer.h" #include "tensorflow/c/tf_status_helper.h" #include "tensorflow/core/lib/core/stringpiece.h" #include "tensorflow/core/lib/io/record_writer.h" #include "tensorflow/core/lib/io/zlib_compression_options.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace io { PyRecordWriter::PyRecordWriter() {} PyRecordWriter* PyRecordWriter::New(const string& filename, const io::RecordWriterOptions& options, TF_Status* out_status) { std::unique_ptr<WritableFile> file; Status s = Env::Default()->NewWritableFile(filename, &file); if (!s.ok()) { Set_TF_Status_from_Status(out_status, s); return nullptr; } PyRecordWriter* writer = new PyRecordWriter; writer->file_ = std::move(file); writer->writer_.reset(new RecordWriter(writer->file_.get(), options)); return writer; } PyRecordWriter::~PyRecordWriter() { // Writer depends on file during close for zlib flush, so destruct first. writer_.reset(); file_.reset(); } void PyRecordWriter::WriteRecord(tensorflow::StringPiece record, TF_Status* out_status) { if (writer_ == nullptr) { TF_SetStatus(out_status, TF_FAILED_PRECONDITION, "Writer not initialized or previously closed"); return; } Status s = writer_->WriteRecord(record); if (!s.ok()) { Set_TF_Status_from_Status(out_status, s); } } void PyRecordWriter::Flush(TF_Status* out_status) { if (writer_ == nullptr) { TF_SetStatus(out_status, TF_FAILED_PRECONDITION, "Writer not initialized or previously closed"); return; } Status s = writer_->Flush(); if (s.ok()) { // Per the RecordWriter contract, flushing the RecordWriter does not // flush the underlying file. Here we need to do both. s = file_->Flush(); } if (!s.ok()) { Set_TF_Status_from_Status(out_status, s); return; } } void PyRecordWriter::Close(TF_Status* out_status) { if (writer_ != nullptr) { Status s = writer_->Close(); if (!s.ok()) { Set_TF_Status_from_Status(out_status, s); return; } writer_.reset(nullptr); } if (file_ != nullptr) { Status s = file_->Close(); if (!s.ok()) { Set_TF_Status_from_Status(out_status, s); return; } file_.reset(nullptr); } } } // namespace io } // namespace tensorflow
{ "content_hash": "f5745804be0cb571435358d8a07a2b33", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 75, "avg_line_length": 28.01123595505618, "alnum_prop": 0.6321700762133975, "repo_name": "DavidNorman/tensorflow", "id": "03f24d0f8f4278db9595ef70827bea1894c834ce", "size": "3161", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "tensorflow/python/lib/io/py_record_writer.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "4913" }, { "name": "Batchfile", "bytes": "15272" }, { "name": "C", "bytes": "774469" }, { "name": "C#", "bytes": "8562" }, { "name": "C++", "bytes": "74659044" }, { "name": "CMake", "bytes": "6545" }, { "name": "Dockerfile", "bytes": "79827" }, { "name": "Go", "bytes": "1670422" }, { "name": "HTML", "bytes": "4680032" }, { "name": "Java", "bytes": "827737" }, { "name": "Jupyter Notebook", "bytes": "540800" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "1004638" }, { "name": "Makefile", "bytes": "66660" }, { "name": "Objective-C", "bytes": "105247" }, { "name": "Objective-C++", "bytes": "297569" }, { "name": "PHP", "bytes": "23553" }, { "name": "Pascal", "bytes": "3752" }, { "name": "Pawn", "bytes": "14529" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "37406546" }, { "name": "RobotFramework", "bytes": "891" }, { "name": "Ruby", "bytes": "4706" }, { "name": "Shell", "bytes": "452517" }, { "name": "Smarty", "bytes": "31460" }, { "name": "Swift", "bytes": "62814" } ], "symlink_target": "" }
<?php /** * Created by Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru>. * Author: Kutuzov Alexey Konstantinovich <lexus.1995@mail.ru> * Project: jungle * IDE: PhpStorm * Date: 14.07.2016 * Time: 23:19 */ namespace Jungle\Application\Strategy { use Jungle\Application\RequestInterface; use Jungle\Application\ResponseInterface; use Jungle\Application\Strategy; use Jungle\Application\Strategy\Http\Router as HTTP_Router; use Jungle\Application\View; use Jungle\Application\View\ViewStrategyInterface; use Jungle\Application\ViewInterface; use Jungle\Util\Communication\HttpFoundation\RequestInterface as HTTP_RequestInterface; use Jungle\Util\Communication\HttpFoundation\ResponseSettableInterface as HTTP_ResponseSettableInterface; /** * Class Http * @package Jungle\Application\Strategy */ abstract class Http extends Strategy{ /** @var string */ protected $name = 'http'; /** * @param RequestInterface $request * @return bool */ public static function check(RequestInterface $request){ return $request instanceof HTTP_RequestInterface; } /** * @param ResponseInterface|HTTP_ResponseSettableInterface $response * @param ViewInterface $view * @internal param RendererInterface $renderer */ public function complete(ResponseInterface $response, ViewInterface $view){ if($renderer = $view->getLastRenderer()){ $content_mime_type = $renderer->getMimeType(); $response->setContentType($content_mime_type); /** @var ViewStrategyInterface $view_strategy */ $lastRendererAlias = $view->getLastRendererAlias(); $view_strategy = $this->getShared('view_strategy'); $view_strategy->complete($lastRendererAlias,$renderer,$response, $view); } parent::complete($response, $view); } } }
{ "content_hash": "8db3e40a1a2b5cfe49cd0a24ff8680dd", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 106, "avg_line_length": 29.733333333333334, "alnum_prop": 0.7382286995515696, "repo_name": "Lexus27/Jungle", "id": "fa15c93518c18d27f767f763c6b93fb53ea9a6e2", "size": "1784", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Jungle/Application/Strategy/Http.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "1930558" } ], "symlink_target": "" }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "MenuAnchor.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnMenuOpenChangedEvent, bool, bIsOpen); /** * The Menu Anchor allows you to specify an location that a popup menu should be anchored to, * and should be summoned from. * ● Single Child * ● Popup */ UCLASS() class UMG_API UMenuAnchor : public UContentWidget { GENERATED_UCLASS_BODY() public: /** * The widget class to spawn when the menu is required. Creates the widget freshly each time. * If you want to customize the creation of the popup, you should bind a function to OnGetMenuContentEvent * instead. */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Menu Anchor") TSubclassOf<class UUserWidget> MenuClass; /** Called when the menu content is requested to allow a more customized handling over what to display */ UPROPERTY(EditAnywhere, Category="Events") FGetWidget OnGetMenuContentEvent; /** The placement location of the summoned widget. */ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Menu Anchor") TEnumAsByte<EMenuPlacement> Placement; public: /** Called when the opened state of the menu changes */ UPROPERTY(BlueprintAssignable, Category="Menu Anchor|Event") FOnMenuOpenChangedEvent OnMenuOpenChanged; public: //TODO UMG Add Set MenuClass //TODO UMG Add Set Placement public: /** * Toggles the menus open state. * * @param bFocusOnOpen Should we focus the popup as soon as it opens? */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") void ToggleOpen(bool bFocusOnOpen); /** Opens the menu if it is not already open */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") void Open(bool bFocusMenu); /** Closes the menu if it is currently open. */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") void Close(); /** @return true if the popup is open; false otherwise. */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") bool IsOpen() const; /** * @return true if we should open the menu due to a click. Sometimes we should not, if * the same MouseDownEvent that just closed the menu is about to re-open it because it * happens to land on the button. */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") bool ShouldOpenDueToClick() const; /** @return The current menu position */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") FVector2D GetMenuPosition() const; /** @return Whether this menu has open submenus */ UFUNCTION(BlueprintCallable, Category="Menu Anchor") bool HasOpenSubMenus() const; virtual void ReleaseSlateResources(bool bReleaseChildren) override; #if WITH_EDITOR virtual const FSlateBrush* GetEditorIcon() override; virtual const FText GetPaletteCategory() override; #endif protected: // UPanelWidget virtual void OnSlotAdded(UPanelSlot* Slot) override; virtual void OnSlotRemoved(UPanelSlot* Slot) override; // End UPanelWidget // UWidget interface virtual TSharedRef<SWidget> RebuildWidget() override; // End of UWidget interface protected: TSharedRef<SWidget> HandleGetMenuContent(); void HandleMenuOpenChanged(bool bIsOpen); protected: TSharedPtr<SMenuAnchor> MyMenuAnchor; };
{ "content_hash": "a2380497cec910ea4301575428e0881c", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 108, "avg_line_length": 29.431192660550458, "alnum_prop": 0.7581047381546134, "repo_name": "PopCap/GameIdea", "id": "477e3a868e779d8434709b1e3dfab17297a63d32", "size": "3214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Engine/Source/Runtime/UMG/Public/Components/MenuAnchor.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "238055" }, { "name": "Assembly", "bytes": "184134" }, { "name": "Batchfile", "bytes": "116983" }, { "name": "C", "bytes": "84264210" }, { "name": "C#", "bytes": "9612596" }, { "name": "C++", "bytes": "242290999" }, { "name": "CMake", "bytes": "548754" }, { "name": "CSS", "bytes": "134910" }, { "name": "GLSL", "bytes": "96780" }, { "name": "HLSL", "bytes": "124014" }, { "name": "HTML", "bytes": "4097051" }, { "name": "Java", "bytes": "757767" }, { "name": "JavaScript", "bytes": "2742822" }, { "name": "Makefile", "bytes": "1976144" }, { "name": "Objective-C", "bytes": "75778979" }, { "name": "Objective-C++", "bytes": "312592" }, { "name": "PAWN", "bytes": "2029" }, { "name": "PHP", "bytes": "10309" }, { "name": "PLSQL", "bytes": "130426" }, { "name": "Pascal", "bytes": "23662" }, { "name": "Perl", "bytes": "218656" }, { "name": "Python", "bytes": "21593012" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "2889614" }, { "name": "Tcl", "bytes": "1452" } ], "symlink_target": "" }
package cn.com.cennavi.rtic.decoder.match; import cn.com.cennavi.rtic.decoder.bean.RTICMesage; import cn.com.cennavi.visualizer.service.parsedata.translate.CommRttData; public interface IRTICMatcher { public RTICMesage match(CommRttData item); }
{ "content_hash": "439cbbb685866b30dc35b4883756e91d", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 73, "avg_line_length": 23.09090909090909, "alnum_prop": 0.8070866141732284, "repo_name": "fenghlkevin/rtt-visualizer", "id": "c56475e28545b0c553ae9305cfb5fba71220f294", "size": "254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/cn/com/cennavi/rtic/decoder/match/IRTICMatcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "96367" }, { "name": "HTML", "bytes": "81541" }, { "name": "Java", "bytes": "299532" }, { "name": "JavaScript", "bytes": "2813488" } ], "symlink_target": "" }
import { extendObservable } from 'mobx'; import Counter from './Counter'; import getAuth from './Auth'; export default class Store { constructor(data = {}) { const { counter, auth, ...rest } = data; this.counter = new Counter(counter); this.auth = getAuth(auth); extendObservable(this, rest); } }
{ "content_hash": "c3fa4ba5405d21040547b7435d4b7998", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 44, "avg_line_length": 26.5, "alnum_prop": 0.6540880503144654, "repo_name": "kennethtruong/react-webapp", "id": "aa0ea43c614bae1d74b6ffd310b8507c519aaaa6", "size": "318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "shared/store/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2008" }, { "name": "JavaScript", "bytes": "124412" } ], "symlink_target": "" }
package com.google.devtools.build.android.desugar.corelibadapter; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.flogger.GoogleLogger; import com.google.devtools.build.android.desugar.io.BootClassPathDigest; import com.google.devtools.build.android.desugar.langmodel.ClassName; import com.google.devtools.build.android.desugar.langmodel.MemberUseKind; import com.google.devtools.build.android.desugar.langmodel.MethodDeclInfo; import com.google.devtools.build.android.desugar.langmodel.MethodInvocationSite; import com.google.devtools.build.android.desugar.langmodel.MethodKey; import com.google.devtools.build.android.desugar.typehierarchy.HierarchicalMethodKey; import com.google.devtools.build.android.desugar.typehierarchy.HierarchicalMethodQuery; import com.google.devtools.build.android.desugar.typehierarchy.TypeHierarchy; import java.util.Optional; import org.objectweb.asm.Type; /** * Static utilities that serve conversions between desugar-shadowed platform types and their * desugared-mirrored counterparts. */ public class ShadowedApiAdapterHelper { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); private ShadowedApiAdapterHelper() {} /** * Returns {@code true} if the desugar tool transforms given invocation site in an inline * strategy, i.e. inserting the parameter type conversion instructions before the give invocation * site. * * @param verbatimInvocationSite The invocation site parsed directly from the desugar input jar. * No in-process label, such as "__desugar__/", is attached to this invocation site. * @param typeHierarchy The type hierarchy context of for this query API. * @param bootClassPathDigest The boot class path context used for complication. * @param enclosingMethod The method that holds the invocation instruction. */ static boolean shouldUseInlineTypeConversion( MethodInvocationSite verbatimInvocationSite, TypeHierarchy typeHierarchy, BootClassPathDigest bootClassPathDigest, MethodDeclInfo enclosingMethod) { if (verbatimInvocationSite.invocationKind() != MemberUseKind.INVOKESPECIAL) { return false; } // invokespecial on a private method in the same class. if (verbatimInvocationSite.owner().equals(enclosingMethod.owner())) { return false; } // Absent of desugar-shadowed type in the method header. if (verbatimInvocationSite.method().getHeaderTypeNameSet().stream() .noneMatch(ClassName::isDesugarShadowedType)) { return false; } if (verbatimInvocationSite.isConstructorInvocation()) { return bootClassPathDigest.containsType(verbatimInvocationSite.owner()); } // Upon on a super call, trace to the adjusted owner with code. ClassName adjustedGrossOwner = verbatimInvocationSite.owner(); HierarchicalMethodQuery verbatimMethod = HierarchicalMethodKey.from(verbatimInvocationSite.method()).inTypeHierarchy(typeHierarchy); if (!verbatimMethod.isPresent()) { HierarchicalMethodKey resolvedMethod = verbatimMethod.getFirstBaseClassMethod(); if (resolvedMethod == null) { logger.atSevere().log("Missing base method lookup: %s", verbatimInvocationSite); } else { adjustedGrossOwner = resolvedMethod.owner().type(); } } return adjustedGrossOwner.isAndroidDomainType() && bootClassPathDigest.containsType(adjustedGrossOwner); } /** * Returns {@code true} if the desugar tool transforms given invocation site in an adapter * strategy, that is to replace the original invocation with its corresponding adapter method. * * @param verbatimInvocationSite The invocation site parsed directly from the desugar input jar. * No in-process label, such as "__desugar__/", is attached to this invocation site. */ static boolean shouldUseApiTypeAdapter( MethodInvocationSite verbatimInvocationSite, BootClassPathDigest bootClassPathDigest) { return verbatimInvocationSite.invocationKind() != MemberUseKind.INVOKESPECIAL && verbatimInvocationSite.owner().isAndroidDomainType() && bootClassPathDigest.containsType(verbatimInvocationSite.owner()) && verbatimInvocationSite.method().getHeaderTypeNameSet().stream() .anyMatch(ClassName::isDesugarShadowedType); } /** * Returns {@code true} if the current method overrides a platform API with desugar-shadowed types * and should emit an overriding bridge method for the integrity of method dynamic dispatching. */ static boolean shouldEmitApiOverridingBridge( MethodDeclInfo methodDeclInfo, TypeHierarchy typeHierarchy, BootClassPathDigest bootClassPathDigest) { if (bootClassPathDigest.containsType(methodDeclInfo.owner()) || methodDeclInfo.methodKey().isConstructor() || methodDeclInfo.isStaticMethod() || methodDeclInfo.isPrivateAccess() || methodDeclInfo.headerTypeNameSet().stream() .noneMatch(ClassName::isDesugarShadowedType)) { return false; } HierarchicalMethodKey baseMethod = HierarchicalMethodKey.from(methodDeclInfo.methodKey()) .inTypeHierarchy(typeHierarchy) .getFirstBaseClassMethod(); boolean queryResult = baseMethod != null && baseMethod.owner().type().isAndroidDomainType() && bootClassPathDigest.containsType(baseMethod.owner().type()); if (queryResult) { logger.atInfo().log( "----> Shadowed Method Overriding Bridge eligible for %s due to base method %s", methodDeclInfo.methodKey(), baseMethod.toMethodKey()); } return queryResult; } /** * Returns an optional {@link MethodInvocationSite}, present if the given {@link ClassName} is * eligible for transforming a desugar-mirrored type to a desugar-shadowed platform type. */ static Optional<MethodInvocationSite> anyMirroredToBuiltinTypeConversion(ClassName className) { return className.isDesugarMirroredType() ? Optional.of( MethodInvocationSite.builder() .setInvocationKind(MemberUseKind.INVOKESTATIC) .setMethod( MethodKey.create( className.mirroredToShadowed().typeConverterOwner(), "to", Type.getMethodDescriptor( className.mirroredToShadowed().toAsmObjectType(), className.toAsmObjectType()))) .setIsInterface(false) .build()) : Optional.empty(); } /** * Returns an {@link MethodInvocationSite} that serves transforming a {@code * shadowedTypeName}-represented type to its desugar-mirrored counterpart. */ public static MethodInvocationSite shadowedToMirroredTypeConversionSite( ClassName shadowedTypeName) { checkArgument( shadowedTypeName.isDesugarShadowedType(), "Expected desugar-shadowed type: Actual (%s)", shadowedTypeName); return MethodInvocationSite.builder() .setInvocationKind(MemberUseKind.INVOKESTATIC) .setMethod( MethodKey.create( shadowedTypeName.typeConverterOwner(), "from", Type.getMethodDescriptor( shadowedTypeName.shadowedToMirrored().toAsmObjectType(), shadowedTypeName.toAsmObjectType()))) .setIsInterface(false) .build(); } /** * Returns an {@link MethodInvocationSite} that serves transforming a {@code * mirroredTypeName}-represented type to its desugar-shadowed counterpart. */ static MethodInvocationSite mirroredToShadowedTypeConversionSite(ClassName mirroredTypeName) { checkArgument( mirroredTypeName.isDesugarMirroredType(), "Expected mirrored type: Actual (%s)", mirroredTypeName); return MethodInvocationSite.builder() .setInvocationKind(MemberUseKind.INVOKESTATIC) .setMethod( MethodKey.create( mirroredTypeName.mirroredToShadowed().typeConverterOwner(), "to", Type.getMethodDescriptor( mirroredTypeName.mirroredToShadowed().toAsmObjectType(), mirroredTypeName.toAsmObjectType()))) .setIsInterface(false) .build(); } /** * Returns an {@link MethodInvocationSite} that serves as an adapter between desugar-mirrored * invocations and desugar-shadowed invocations. */ static MethodInvocationSite getAdapterInvocationSite(MethodInvocationSite methodInvocationSite) { return MethodInvocationSite.builder() .setInvocationKind(MemberUseKind.INVOKESTATIC) .setMethod( methodInvocationSite .method() .toAdapterMethodForArgsAndReturnTypes( methodInvocationSite.isStaticInvocation(), methodInvocationSite.hashCode())) .setIsInterface(false) .build(); } }
{ "content_hash": "315fe6109045bff6b40e3ab5d2c8125b", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 100, "avg_line_length": 42.74528301886792, "alnum_prop": 0.7077907746634297, "repo_name": "ButterflyNetwork/bazel", "id": "9cdb1c575cbe8fc5fd76a4ed9519c44831e7564d", "size": "9683", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tools/android/java/com/google/devtools/build/android/desugar/corelibadapter/ShadowedApiAdapterHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2997" }, { "name": "C", "bytes": "32099" }, { "name": "C++", "bytes": "1662789" }, { "name": "HTML", "bytes": "24644" }, { "name": "Java", "bytes": "42330495" }, { "name": "Makefile", "bytes": "248" }, { "name": "Objective-C", "bytes": "10818" }, { "name": "Objective-C++", "bytes": "1043" }, { "name": "PowerShell", "bytes": "15431" }, { "name": "Python", "bytes": "3617074" }, { "name": "Shell", "bytes": "2600517" }, { "name": "Smarty", "bytes": "30219" }, { "name": "Starlark", "bytes": "26704" } ], "symlink_target": "" }
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import ApolloClient, { createNetworkInterface } from 'apollo-client' import gql from 'graphql-tag' class App extends Component { client = new ApolloClient({ networkInterface: createNetworkInterface({ uri: 'http://localhost:3001/graphql' }) }) state = { stories: null } async componentDidMount() { const result = await this.client.query({ query: gql` query { stories(page: 2, count: 10) { by { id about } title type } } ` }) console.dir(result) this.setState({ stories: result.data.stories }) } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> <p className="App-intro"> To get started, edit <code>src/App.js</code> and save to reload. </p> <ul> {this.state.stories ? this.state.stories.map(story => <li>{story.title}</li>) : <span>Loading...</span>} </ul> </div> ); } } export default App;
{ "content_hash": "cbe8fce1e70ca109f5eedaa9828e8fe1", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 74, "avg_line_length": 21.916666666666668, "alnum_prop": 0.5186311787072243, "repo_name": "jfresco/graphql-workshop-es", "id": "ee768090c0f9daee34e8cdde0561cac262b5f12b", "size": "1315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ex/06/src/src/App.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "404" }, { "name": "HTML", "bytes": "1590" }, { "name": "JavaScript", "bytes": "14291" } ], "symlink_target": "" }
Rails.application.routes.draw do mount OpenStax::Connect::Engine => "/connect" namespace :api do post "dummy", :to => "dummy#dummy" resource :application_users, :only => :create end root :to => "application#index" end
{ "content_hash": "fa98019070b2e416407d25d662f8a07f", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 49, "avg_line_length": 21.545454545454547, "alnum_prop": 0.6666666666666666, "repo_name": "openstax/connect-rails", "id": "e7b783c6fff2b2a3533511b487d40eea44b57dcf", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/dummy/config/routes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2166" }, { "name": "JavaScript", "bytes": "1923" }, { "name": "Ruby", "bytes": "61659" } ], "symlink_target": "" }
#include <winpr/config.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <winpr/crt.h> #include <winpr/collections.h> /** * C equivalent of the C# CountdownEvent Class * http://msdn.microsoft.com/en-us/library/dd235708/ */ /** * Properties */ /** * Gets the number of remaining signals required to set the event. */ DWORD CountdownEvent_CurrentCount(wCountdownEvent* countdown) { return countdown->count; } /** * Gets the numbers of signals initially required to set the event. */ DWORD CountdownEvent_InitialCount(wCountdownEvent* countdown) { return countdown->initialCount; } /** * Determines whether the event is set. */ BOOL CountdownEvent_IsSet(wCountdownEvent* countdown) { BOOL status = FALSE; if (WaitForSingleObject(countdown->event, 0) == WAIT_OBJECT_0) status = TRUE; return status; } /** * Gets a WaitHandle that is used to wait for the event to be set. */ HANDLE CountdownEvent_WaitHandle(wCountdownEvent* countdown) { return countdown->event; } /** * Methods */ /** * Increments the CountdownEvent's current count by a specified value. */ void CountdownEvent_AddCount(wCountdownEvent* countdown, DWORD signalCount) { EnterCriticalSection(&countdown->lock); countdown->count += signalCount; if (countdown->count > 0) ResetEvent(countdown->event); LeaveCriticalSection(&countdown->lock); } /** * Registers multiple signals with the CountdownEvent, decrementing the value of CurrentCount by the * specified amount. */ BOOL CountdownEvent_Signal(wCountdownEvent* countdown, DWORD signalCount) { BOOL status; BOOL newStatus; BOOL oldStatus; status = newStatus = oldStatus = FALSE; EnterCriticalSection(&countdown->lock); if (WaitForSingleObject(countdown->event, 0) == WAIT_OBJECT_0) oldStatus = TRUE; if (signalCount <= countdown->count) countdown->count -= signalCount; else countdown->count = 0; if (countdown->count == 0) newStatus = TRUE; if (newStatus && (!oldStatus)) { SetEvent(countdown->event); status = TRUE; } LeaveCriticalSection(&countdown->lock); return status; } /** * Resets the InitialCount property to a specified value. */ void CountdownEvent_Reset(wCountdownEvent* countdown, DWORD count) { countdown->initialCount = count; } /** * Construction, Destruction */ wCountdownEvent* CountdownEvent_New(DWORD initialCount) { wCountdownEvent* countdown = NULL; if (!(countdown = (wCountdownEvent*)calloc(1, sizeof(wCountdownEvent)))) return NULL; countdown->count = initialCount; countdown->initialCount = initialCount; if (!InitializeCriticalSectionAndSpinCount(&countdown->lock, 4000)) goto fail_critical_section; if (!(countdown->event = CreateEvent(NULL, TRUE, FALSE, NULL))) goto fail_create_event; if (countdown->count == 0) if (!SetEvent(countdown->event)) goto fail_set_event; return countdown; fail_set_event: CloseHandle(countdown->event); fail_create_event: DeleteCriticalSection(&countdown->lock); fail_critical_section: free(countdown); return NULL; } void CountdownEvent_Free(wCountdownEvent* countdown) { if (!countdown) return; DeleteCriticalSection(&countdown->lock); CloseHandle(countdown->event); free(countdown); }
{ "content_hash": "93f6165db272a61e31936896ad1206ea", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 100, "avg_line_length": 18.45402298850575, "alnum_prop": 0.7271877919651198, "repo_name": "erbth/FreeRDP", "id": "e119f87f8c27f538e092270a91b1256178314487", "size": "3898", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "winpr/libwinpr/utils/collections/CountdownEvent.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "15047579" }, { "name": "C#", "bytes": "6365" }, { "name": "C++", "bytes": "138156" }, { "name": "CMake", "bytes": "635206" }, { "name": "CSS", "bytes": "5696" }, { "name": "HTML", "bytes": "99139" }, { "name": "Java", "bytes": "371005" }, { "name": "Lua", "bytes": "27390" }, { "name": "Makefile", "bytes": "1677" }, { "name": "Objective-C", "bytes": "517066" }, { "name": "Perl", "bytes": "8044" }, { "name": "Python", "bytes": "53966" }, { "name": "Rich Text Format", "bytes": "937" }, { "name": "Roff", "bytes": "12141" }, { "name": "Shell", "bytes": "32964" } ], "symlink_target": "" }
#include <jni.h> #include <assert.h> #include "webrtc/examples/android/media_demo/jni/jni_helpers.h" #include "webrtc/examples/android/media_demo/jni/video_engine_jni.h" #include "webrtc/examples/android/media_demo/jni/voice_engine_jni.h" #include "webrtc/video_engine/include/vie_base.h" #include "webrtc/voice_engine/include/voe_base.h" // Macro for native functions that can be found by way of jni-auto discovery. // Note extern "C" is needed for "discovery" of native methods to work. #define JOWW(rettype, name) \ extern "C" rettype JNIEXPORT JNICALL Java_org_webrtc_webrtcdemo_##name static JavaVM* g_vm = NULL; extern "C" jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { // Only called once. CHECK(!g_vm, "OnLoad called more than once"); g_vm = vm; return JNI_VERSION_1_4; } JOWW(void, NativeWebRtcContextRegistry_register)( JNIEnv* jni, jclass, jobject context) { webrtc_examples::SetVoeDeviceObjects(g_vm); webrtc_examples::SetVieDeviceObjects(g_vm); CHECK(webrtc::VideoEngine::SetAndroidObjects(g_vm) == 0, "Failed to register android objects to video engine"); CHECK(webrtc::VoiceEngine::SetAndroidObjects(g_vm, jni, context) == 0, "Failed to register android objects to voice engine"); } JOWW(void, NativeWebRtcContextRegistry_unRegister)( JNIEnv* jni, jclass) { CHECK(webrtc::VoiceEngine::SetAndroidObjects(NULL, NULL, NULL) == 0, "Failed to unregister android objects from voice engine"); webrtc_examples::ClearVieDeviceObjects(); webrtc_examples::ClearVoeDeviceObjects(); }
{ "content_hash": "ecdf547deb757f47cb543176ba6be371", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 77, "avg_line_length": 35.32608695652174, "alnum_prop": 0.7095384615384616, "repo_name": "surge-/libwebrtc", "id": "27a2394b3d52f33ab0307fe202baede4ecaa88bc", "size": "2037", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "examples/android/media_demo/jni/on_load.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "118926" }, { "name": "C", "bytes": "4684627" }, { "name": "C++", "bytes": "13503517" }, { "name": "Java", "bytes": "188746" }, { "name": "JavaScript", "bytes": "17615" }, { "name": "Matlab", "bytes": "79659" }, { "name": "Objective-C", "bytes": "206026" }, { "name": "Python", "bytes": "116717" }, { "name": "Shell", "bytes": "6389" } ], "symlink_target": "" }
'use strict'; var extend = require('xtend'); var CountedReadySignal = require('ready-signal/counted'); var test = require('tape'); var util = require('util'); var TChannel = require('../../channel.js'); var parallel = require('run-parallel'); var debugLogtron = require('debug-logtron'); module.exports = allocCluster; function allocCluster(opts) { opts = opts || {}; var host = 'localhost'; var logger = debugLogtron('tchannel', { enabled: true, verbose: !!opts.logVerbose }); var cluster = { logger: logger, hosts: new Array(opts.numPeers), channels: new Array(opts.numPeers), destroy: destroy, ready: CountedReadySignal(opts.numPeers), assertCleanState: assertCleanState, assertEmptyState: assertEmptyState, connectChannels: connectChannels, connectChannelToChannels: connectChannelToChannels, timers: opts.timers }; var channelOptions = extend({ logger: logger, timeoutFuzz: 0, traceSample: 1 }, opts.channelOptions || opts); for (var i = 0; i < opts.numPeers; i++) { createChannel(i); } return cluster; function assertCleanState(assert, expected) { cluster.channels.forEach(function eachChannel(chan, i) { var chanExpect = expected.channels[i]; if (!chanExpect) { assert.fail(util.format('unexpected channel[%s]', i)); return; } var peers = chan.peers.values(); assert.equal(peers.length, chanExpect.peers.length, util.format( 'channel[%s] should have %s peer(s)', i, chanExpect.peers.length)); peers.forEach(function eachPeer(peer, j) { var peerExpect = chanExpect.peers[j]; if (!peerExpect) { assert.fail(util.format( 'unexpected channel[%s] peer[%s]', i, j)); return; } peer.connections.forEach(function eachConn(conn, k) { var connExpect = peerExpect.connections[k]; if (!connExpect) { assert.fail(util.format( 'unexpected channel[%s] peer[%s] conn[%s]', i, j, k)); return; } Object.keys(connExpect).forEach(function eachProp(prop) { var desc = util.format( 'channel[%s] peer[%s] conn[%s] should .%s', i, j, k, prop); var pending = conn.ops.getPending(); var handler = conn.handler; switch (prop) { case 'inReqs': assert.equal(pending.in, connExpect.inReqs, desc); break; case 'outReqs': assert.equal(pending.out, connExpect.outReqs, desc); break; case 'streamingReq': var streamingReq = Object.keys(handler.streamingReq).length; assert.equal(streamingReq, connExpect.streamingReq, desc); break; case 'streamingRes': var streamingRes = Object.keys(handler.streamingRes).length; assert.equal(streamingRes, connExpect.streamingRes, desc); break; default: assert.equal(conn[prop], connExpect[prop], desc); } }); }); }); }); } function assertEmptyState(assert) { assertCleanState(assert, { channels: cluster.channels.map(function build(channel) { var peers = channel.peers.values(); return { peers: peers.map(function b(p) { var conn = p.connections; return { connections: conn.map(function k(c) { return { direction: c.direction, inReqs: 0, outReqs: 0, streamingReq: 0, streamingRes: 0 }; }) }; }) }; }) }); } function createChannel(i) { var chan = TChannel(extend(channelOptions)); var port = opts.listen && opts.listen[i] || 0; chan.on('listening', chanReady); chan.listen(port, host); cluster.channels[i] = chan; function chanReady() { var port = chan.address().port; cluster.hosts[i] = util.format('%s:%s', host, port); cluster.ready.signal(cluster); } } function destroy(cb) { parallel(cluster.channels.map(function(chan) { return function(done) { if (!chan.destroyed) chan.quit(done); }; }), cb); } } function clusterTester(opts, t) { if (typeof opts === 'number') { opts = { numPeers: opts }; } if (typeof opts === 'function') { t = opts; opts = {}; } if (opts.timers && opts.channelOptions) { opts.channelOptions.timers = opts.timers; } return t2; function t2(assert) { opts.assert = assert; allocCluster(opts).ready(function clusterReady(cluster) { assert.once('end', function testEnded() { cluster.assertEmptyState(assert); cluster.destroy(); }); t(cluster, assert); }); } } allocCluster.test = function testCluster(desc, opts, t) { if (opts === undefined) { return test(desc); } test(desc, clusterTester(opts, t)); }; allocCluster.test.only = function testClusterOnly(desc, opts, t) { test.only(desc, clusterTester(opts, t)); }; function connectChannels(channels, callback) { return parallel(channels.map(function (channel) { return function connectChannelToHosts(callback) { return connectChannelToChannels(channel, channels, callback); }; }), callback); } function connectChannelToChannels(channel, channels, callback) { return parallel(channels.map(function (peerChannel) { return function connectChannelToHost(callback) { if (channel.hostPort === peerChannel.hostPort) { return callback(); } var peer = channel.peers.add(peerChannel.hostPort); var connection = peer.connect(); connection.identifiedEvent.on(onIdentified); // TODO impl connect on self connect function onIdentified() { callback(); } }; }), callback); } allocCluster.Pool = require('./resource_pool');
{ "content_hash": "ab968fe52a9eb1aa44e9ce620f9e0919", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 88, "avg_line_length": 33.31797235023041, "alnum_prop": 0.49363762102351316, "repo_name": "chenwenbin928/tchannel", "id": "4500f65ba02815b2ca0e1d3bc2285b97a06cf0f6", "size": "8352", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "node/test/lib/alloc-cluster.js", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "506483" }, { "name": "JavaScript", "bytes": "1482501" }, { "name": "Makefile", "bytes": "5890" }, { "name": "Shell", "bytes": "7124" }, { "name": "Thrift", "bytes": "11160" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /******************************************************************************* * Model das transportadoras. *******************************************************************************/ class Transportadoras_model extends CI_Model{ public function __construct(){ parent::__construct(); } public function tabela_fretes(){ $this->db->select("concat('<a href=./transportadoras/excluir/',id,'>',id,'</a>') as Excluir"); $this->db->select("peso_de as 'De Kg',peso_ate as 'Ate Kg',preco as R$,adicional_kg as 'R$ por Kg Adicional',uf as Estado"); return $this->db->get('tb_transporte_preco'); } public function adicionar($peso_de,$peso_ate,$preco,$adicional_kg,$uf){ $dados['peso_de'] = $peso_de; $dados['peso_ate'] = $peso_ate; $dados['preco'] = $preco; $dados['adicional_kg'] = $adicional_kg; $dados['uf'] = $uf; return $this->db->insert('tb_transporte_preco',$dados); } public function excluir($excluir){ $this->db->where('id',$excluir); return $this->db->delete('tb_transporte_preco'); } }
{ "content_hash": "b929eae8ff5b2b1b3c2ef2eaa31cac74", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 126, "avg_line_length": 42.666666666666664, "alnum_prop": 0.5347222222222222, "repo_name": "christiancms/lojaphp", "id": "bc070f1681091590ce64564e44927d251b2ffa6a", "size": "1152", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/Transportadoras_model.php", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "364" }, { "name": "CSS", "bytes": "19195" }, { "name": "HTML", "bytes": "5377377" }, { "name": "JavaScript", "bytes": "74369" }, { "name": "PHP", "bytes": "3740221" } ], "symlink_target": "" }