code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/**************************************************************************** ** ** Name: MicoFileStat.c ** ** Description: ** Implements _fstat, called by Newlib C library file functions ** ** $Revision: $ ** ** Disclaimer: ** ** This source code is intended as a design reference which ** illustrates how these types of functions can be implemented. It ** is the user's responsibility to verify their design for ** consistency and functionality through the use of formal ** verification methods. Lattice Semiconductor provides no warranty ** regarding the use or functionality of this code. ** ** -------------------------------------------------------------------- ** ** Lattice Semiconductor Corporation ** 5555 NE Moore Court ** Hillsboro, OR 97214 ** U.S.A ** ** TEL: 1-800-Lattice (USA and Canada) ** (503)268-8001 (other locations) ** ** web: http://www.latticesemi.com ** email: [email protected] ** ** -------------------------------------------------------------------------- ** ** Change History (Latest changes on top) ** ** Ver Date Description ** -------------------------------------------------------------------------- ** ** 3.0 Mar-25-2008 Added Header ** **--------------------------------------------------------------------------- *****************************************************************************/ #include <_ansi.h> #include <_syslist.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include "MicoFileDevices.h" #ifdef __cplusplus extern "C" { #endif /****************************************************************** * * * Implements _read required by NewLibC's _read_r function * * * ******************************************************************/ int _fstat(int fd, struct stat *pstat) { MicoFileDesc_t *pFD; int retValue =-1; /* given the file-id, fetch the associated file-descriptor */ if(MicoGetFDEntry(fd, &pFD) != 0) return(-1); /* ask the device to write the data if it is capable of writing data */ if(pFD->pFileOpsTable->stat) retValue = pFD->pFileOpsTable->stat(pFD, pstat); /* all done */ return(retValue); } #ifdef __cplusplus } #endif
ptracton/wb_soc_template
rtl/lm32_top/drivers/service/MicoFileStat.c
C
mit
2,525
package uk.org.fyodor.generators; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; import org.junit.Test; import uk.org.fyodor.BaseTest; public class PercentageChanceGeneratorTest extends BaseTest { Multiset<Boolean> results = HashMultiset.create(); @Test public void percentageChances(){ for (int p = 1; p < 100; p++) { Generator<Boolean> percentageChance = RDG.percentageChanceOf(p); for (int i = 0; i < 10000; i++) { results.add(percentageChance.next()); } print(p); print("True: " + results.count(Boolean.TRUE)); print("False: " + results.count(Boolean.FALSE)); results.clear(); } } }
KarlWalsh/fyodor
fyodor-core/src/test/java/uk/org/fyodor/generators/PercentageChanceGeneratorTest.java
Java
mit
766
var searchData= [ ['clear',['clear',['../d8/d84/a00001.html#a11dc3b617f2fedbb3b499971493b9c4f',1,'ArrayBase']]] ];
bdfoster/cpp-templates
docs/html/search/functions_1.js
JavaScript
mit
117
// // VTDNearTermDateRelation.h // // Copyright (c) 2014 Mutual Mobile (http://www.mutualmobile.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> typedef NS_ENUM(NSUInteger, VTDNearTermDateRelation) { VTDNearTermDateRelationOutOfRange, VTDNearTermDateRelationToday, VTDNearTermDateRelationTomorrow, VTDNearTermDateRelationLaterThisWeek, VTDNearTermDateRelationNextWeek };
mutualmobile/VIPER-TODO
VIPER TODO/Classes/Common/Model/VTDNearTermDateRelation.h
C
mit
1,460
<h1>Chat</h1>
Atvaark/Emurado
HaloOnline.Server.App/app/views/chat.html
HTML
mit
16
h1 { font-family: 'Noto Sans', sans-serif; font-size: 30px; margin: 5px 0px 5px 0px; color: #444444; } h4 { font-family: 'Noto Sans', sans-serif; color: #444444; font-size: 16px; padding-top: 0; margin-top: 0; } .header { margin-top: 10px; margin-bottom: 30px; } .ursar-logo { margin-right: 20px; width: 70px; float:left; } .form-control { background: #f7f7f7; margin-top: 30px; border: 1px solid #F7F7F7; box-shadow: none; } .link-list { list-style: none; margin: 0; padding: 0; } .link-container { margin-top: 10px; background-color: #eee; border-radius: 10px; width: 100%; } .link { margin-bottom: 20px; background: #f7f7f7; width: 100%; } .link:hover { background: #E6E6E6; } .link .url { font-size: 18px; margin: 10px 0px 0px 0px; } .link .url img { max-width: 100%; width: auto; } .link .metadata { font-size: 11px; color: #aea8a8; margin: 5px 0px 5px 0px; text-transform: uppercase; } .link .metadata span { margin-right: 5px; } .link .description { color: #444444; } .link a { color: #444444; } #spinner { position: relative; margin-top: 50px; } .spinner { top: 0; left: 0; bottom: 0; right: 0; } @media (max-width: 400px) { h1, h4 { display: none; } .ursar-logo { width: 100%; } } @media (min-width: 401px) and (max-width: 450px) { h1 { font-size: 27px; } h4 { font-size: 12px; } }
academia-de-ursarie/website
resources/css/ursar.css
CSS
mit
1,554
/* Copyright 2006 by Sean Luke Licensed under the Academic Free License version 3.0 See the file "LICENSE" for more information */ package ec.app.parity.func; import ec.*; import ec.app.parity.*; import ec.gp.*; import ec.util.*; /* * D31.java * * Created: Wed Nov 3 18:31:38 1999 * By: Sean Luke */ /** * @author Sean Luke * @version 1.0 */ public class D31 extends GPNode { public String toString() { return "D31"; } /* public void checkConstraints(final EvolutionState state, final int tree, final GPIndividual typicalIndividual, final Parameter individualBase) { super.checkConstraints(state,tree,typicalIndividual,individualBase); if (children.length!=0) state.output.error("Incorrect number of children for node " + toStringForError() + " at " + individualBase); } */ public int expectedChildren() { return 0; } public void eval(final EvolutionState state, final int thread, final GPData input, final ADFStack stack, final GPIndividual individual, final Problem problem) { ((ParityData)input).x = ((((Parity)problem).bits >>> 31 ) & 1); } }
meiyi1986/GPJSS
src/ec/app/parity/func/D31.java
Java
mit
1,195
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="robots" content="noindex, nofollow"/> <script src="../internal.js"></script> <link rel="stylesheet" href="scrawl.css"> </head> <body> <div class="main" id="J_wrap"> <div class="hot"> <div class="drawBoard border_style1"> <canvas id="J_brushBoard" class="brushBorad" width="360" height="300"></canvas> <div id="J_picBoard" class="picBoard" style="width: 360px;height: 300px"></div> </div> <div id="J_operateBar" class="operateBar"> <span id="J_previousStep" class="previousStep"> <em class="icon"></em> <em class="text"><var id="lang_input_previousStep"></var></em> </span> <span id="J_nextStep" class="nextStep"> <em class="icon"></em> <em class="text"><var id="lang_input_nextsStep"></var></em> </span> <span id="J_clearBoard" class="clearBoard"> <em class="icon"></em> <em class="text"><var id="lang_input_clear"></var></em> </span> <span id="J_sacleBoard" class="scaleBoard"> <em class="icon"></em> <em class="text"><var id="lang_input_ScalePic"></var></em> </span> </div> </div> <div class="drawToolbar border_style1"> <div id="J_colorBar" class="colorBar"></div> <div id="J_brushBar" class="sectionBar"> <em class="brushIcon"></em> <a href="javascript:void(0)" class="size1">1</a> <a href="javascript:void(0)" class="size2">3</a> <a href="javascript:void(0)" class="size3">5</a> <a href="javascript:void(0)" class="size4">7</a> </div> <div id="J_eraserBar" class="sectionBar"> <em class="eraserIcon"></em> <a href="javascript:void(0)" class="size1">1</a> <a href="javascript:void(0)" class="size2">3</a> <a href="javascript:void(0)" class="size3">5</a> <a href="javascript:void(0)" class="size4">7</a> </div> <div class="sectionBar"> <div id="J_addImg" class="addImgH"> <em class="icon"></em> <em class="text"><var id="lang_input_addPic"></var></em> <form method="post" id="fileForm" enctype="multipart/form-data" class="addImgH_form" target="up"> <input type="file" name="upfile" id="J_imgTxt" accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp"/> </form> <iframe name="up" style="display: none"></iframe> </div> </div> <div class="sectionBar"> <span id="J_removeImg" class="removeImg"> <em class="icon"></em> <em class="text"><var id="lang_input_removePic"></var></em> </span> </div> </div> </div> <div id="J_maskLayer" class="maskLayerNull"></div> <script src="scrawl.js"></script> <script> var settings = { drawBrushSize:3, //画笔初始大小 drawBrushColor:"#4bacc6", //画笔初始颜色 colorList:['c00000', 'ff0000', 'ffc000', 'ffff00', '92d050', '00b050', '00b0f0', '0070c0', '002060', '7030a0', 'ffffff', '000000', 'eeece1', '1f497d', '4f81bd', 'c0504d', '9bbb59', '8064a2', '4bacc6', 'f79646'], //画笔选择颜色 saveNum:10 //撤销次数 }; var scrawlObj = new scrawl( settings ); scrawlObj.isCancelScrawl = false; dialog.onok = function () { exec( scrawlObj ); return false; }; dialog.oncancel = function () { scrawlObj.isCancelScrawl = true; }; </script> </body> </html>
duruitang/anteditor
dist/utf8-php/dialogs/scrawl/scrawl.html
HTML
mit
3,848
/* * @require ../../bower_components/html5-boilerplate/dist/css/normalize.css * @require ../../bower_components/html5-boilerplate/dist/css/main.css * @require ../../bower_components/bootstrap/dist/css/bootstrap.css * @require ../iconfont/iconfont.css * */ /* cover bootstrap style * ===================== */ .y-text-red { color: #f25050; } .y-color-red { color: #f25050; } .y-text-blue { color: #099fdd; } .y-color-blue { color: #099fdd; } body { /*background-color: #e6e6e6;*/ font-family: "microsoft yahei", "Helvetica Neue", Helvetica, Arial, sans-serif; } .list-group-item.active, .list-group-item.active:focus, .list-group-item.active:hover { background-color: #099fdd; border-color: #099fdd; } .modal-content .close { font-size: 30px; } .panel-default .panel-heading { color: #333; background-color: #f5f5f5; border-color: #ddd; } /* Expand bootstrap style * ====================== */ .y-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .text-truncate { overflow: hidden; text-overflow: ellipsis; white-space: normal; } .text-indent2 { text-indent: 2em; } .text-xs-left { text-align: left !important; } .text-xs-right { text-align: right !important; } .text-xs-center { text-align: center !important; } @media (min-width: 544px) { .text-sm-left { text-align: left !important; } .text-sm-right { text-align: right !important; } .text-sm-center { text-align: center !important; } } @media (min-width: 768px) { .text-md-left { text-align: left !important; } .text-md-right { text-align: right !important; } .text-md-center { text-align: center !important; } } @media (min-width: 992px) { .text-lg-left { text-align: left !important; } .text-lg-right { text-align: right !important; } .text-lg-center { text-align: center !important; } } @media (min-width: 1200px) { .text-xl-left { text-align: left !important; } .text-xl-right { text-align: right !important; } .text-xl-center { text-align: center !important; } } .sidebar { position: fixed; top: 90px; bottom: 0; left: 0; z-index: 1000; display: block; padding: 20px; overflow-x: hidden; overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */ background-color: #fff; border-right: 1px solid #eee; min-width: 200px; } /* Sidebar navigation */ .nav-sidebar { margin-right: -21px; margin-bottom: 20px; margin-left: -20px; } .nav-sidebar li { border-top: 1px solid #dfdfdf; border-bottom: 1px solid #dfdfdf; margin-top: -1px; } .nav-sidebar > li > a { color: #7f7f7f; padding-right: 20px; padding-left: 20px; font-size: 16px; } .nav-sidebar > .active > a, .nav-sidebar > .active > a:hover, .nav-sidebar > .active > a:focus { color: #fff; background-color: #099fdd; } /*y-navbar*/ .y-navbar-info {} .y-navbar-info .navbar-nav > li > a { color: #333; border-radius: 6px; font-size: 16px; } .y-navbar-info .navbar-nav > li > a:hover, .y-navbar-info .navbar-nav > li > a:focus { color: #099fdd; background-color: transparent; } .y-navbar-info .navbar-nav > .active > a, .y-navbar-info .navbar-nav > .active > a:hover, .y-navbar-info .navbar-nav > .active > a:focus { color: #fff; background-color: #099fdd; } .y-navbar-info .navbar-toggle { border-color: #099fdd; } .y-navbar-info .navbar-toggle:hover, .y-navbar-info .navbar-toggle:focus { background-color: #f9f9f9; } .y-navbar-info .navbar-toggle .icon-bar { background-color: #099fdd; } .y-navbar-info .navbar-collapse, .y-navbar-info .navbar-form { border-color: #e7e7e7; } .y-btn-blue { color: #fff; background-color: #099fdd; border-color: #0799d9; } .y-btn-blue:focus, .y-btn-blue.focus, .y-btn-blue:hover { color: #fff; background-color: #0996d2; border-color: #0794d1; } .y-btn-blue:active, .y-btn-blue.active, .open > .dropdown-toggle.y-btn-blue { color: #fff; background-color: #0996d2; border-color: #0e5aa7; } .y-btn-blue:active:hover, .y-btn-blue.active:hover, .open > .dropdown-toggle.y-btn-blue:hover, .y-btn-blue:active:focus, .y-btn-blue.active:focus, .open > .dropdown-toggle.y-btn-blue:focus, .y-btn-blue:active.focus, .y-btn-blue.active.focus, .open > .dropdown-toggle.y-btn-blue.focus { color: #fff; background-color: #0794d0; border-color: #1b6d85; } .y-btn-blue:active, .y-btn-blue.active, .open > .dropdown-toggle.y-btn-blue { background-image: none; } .y-btn-blue.disabled:hover, .y-btn-blue[disabled]:hover, fieldset[disabled] .y-btn-blue:hover, .y-btn-blue.disabled:focus, .y-btn-blue[disabled]:focus, fieldset[disabled] .y-btn-blue:focus, .y-btn-blue.disabled.focus, .y-btn-blue[disabled].focus, fieldset[disabled] .y-btn-blue.focus { background-color: #099fdd; border-color: #0799d9; } .y-btn-blue .badge { color: #099fdd; background-color: #fff; } .y-btn-red { color: #fff; background-color: #099fdd; border-color: #0799d9; } .y-btn-red:focus, .y-btn-red.focus, .y-btn-red:hover { color: #fff; background-color: #0996d2; border-color: #0794d1; } .y-btn-red:active, .y-btn-red.active, .open > .dropdown-toggle.y-btn-red { color: #fff; background-color: #0996d2; border-color: #0e5aa7; } .y-btn-red:active:hover, .y-btn-red.active:hover, .open > .dropdown-toggle.y-btn-red:hover, .y-btn-red:active:focus, .y-btn-red.active:focus, .open > .dropdown-toggle.y-btn-red:focus, .y-btn-red:active.focus, .y-btn-red.active.focus, .open > .dropdown-toggle.y-btn-red.focus { color: #fff; background-color: #0794d0; border-color: #1b6d85; } .y-btn-red:active, .y-btn-red.active, .open > .dropdown-toggle.y-btn-red { background-image: none; } .y-btn-red.disabled:hover, .y-btn-red[disabled]:hover, fieldset[disabled] .y-btn-red:hover, .y-btn-red.disabled:focus, .y-btn-red[disabled]:focus, fieldset[disabled] .y-btn-red:focus, .y-btn-red.disabled.focus, .y-btn-red[disabled].focus, fieldset[disabled] .y-btn-red.focus { background-color: #099fdd; border-color: #0799d9; } .y-btn-red .badge { color: #099fdd; background-color: #fff; } /*progressbar*/ .y-progress-step { max-width: 1600px; margin-left: auto; margin-right: auto; margin-bottom: 30px; overflow: hidden; padding-left: 0; /*CSS counters to number the steps*/ counter-reset: step; } .y-progress-step li { list-style-type: none; color: #a9a9a9; text-transform: uppercase; font-size: 18px; width: 33.33%; float: left; position: relative; text-align: center; } .y-progress-step li:before { content: counter(step); counter-increment: step; width: 30px; line-height: 30px; display: block; font-size: 16px; color: #fff; background: #a9a9a9; border-radius: 50%; margin: 0 auto 5px auto; } /*progressbar connectors*/ .y-progress-step li:after { content: ''; width: 100%; height: 2px; background: #a9a9a9; position: absolute; left: -50%; top: 14px; z-index: -1; /*put it behind the numbers*/ } .y-progress-step li:first-child:after { /*connector not needed before the first step*/ content: none; } /*marking active/completed steps green*/ /*The number of the step and the connector before it = green*/ .y-progress-step li.active:before, .y-progress-step li.active:after { background: #099fdd; color: white; } .y-progress-step li.active:before, .y-progress-step li.active:after { background: #099fdd; color: white; } .y-progress-step .active .y-turn-blue { color: #099fdd; } /* base style * ========== */ .y-box-sm { width: 90%; max-width: 120px; margin: auto; padding: 8px; border: solid 1px #666; border-radius: 4px; } .y-color-white { color: #fff } .y-color-default { color: #666; } .y-color-silver { color: #c0c0c0 } .y-color-lightGray { color: #d3d3d3 } .y-color-whiteSmoke { color: #f5f5f5 } .y-bg-fff { background-color: #fff; } .y-bg-ebebeb { background-color: #ebebeb; } .y-iconfont-xs { position: relative; font-size: 30px; } .y-iconfont-sm { position: relative; font-size: 60px; } .y-iconfont-md { position: relative; font-size: 100px; } .y-hide { display: none; } .y-font-sm { font-size: 18px; } .y-font-b { font-weight: 700; } .y-fs16 { font-size: 16px; } .y-fs18 { font-size: 18px; } .y-fs26 { font-size: 26px; } .y-hl36 { height: 36px } .y-lh52 { line-height: 52px; } .y-mb0 { margin-bottom: 0px; } .y-mb10 { margin-bottom: 10px; } .y-mb20 { margin-bottom: 20px; } .y-mb40 { margin-bottom: 40px; } .y-mg0 { margin: 0px; } .y-mb60 { margin-bottom: 60px; } .y-mlr0 { margin-left: 0 !important; margin-right: 0 !important; } .y-ml2 { margin-left: 2px; } .y-ml20 { margin-left: 20px; } .y-mlr10 { margin-left: 10px; margin-right: 10px; } .y-mr20 { margin-right: 20px; } .y-mt-10 { margin-top: -10px; } .y-mt-30 { margin-top: -30px; } .y-mt6 { margin-top: 6px; } .y-mt15 { margin-top: 15px; } .y-mt30 { margin-top: 30px; } .y-mt34 { margin-top: 34px; } .y-mt40 { margin-top: 40px; } .y-mt60 { margin-top: 60px; } .y-mt90 { margin-top: 90px; } .y-mt120 { margin-top: 120px; } .y-mt160 { margin-top: 160px; } .y-min-h300 { min-height: 300px; } .y-pd30 { padding: 30px; } .y-pt20 { padding-top: 20px; } .y-pt30 { padding-top: 30px; } .y-pt40 { padding-top: 40px; } .y-pt60 { padding-top: 60px; } .y-pb20 { padding-bottom: 20px; } .y-pb40 { padding-bottom: 40px; } .y-pb60 { padding-bottom: 60px; } .y-wd60 { width: 60%; } .y-wd80 { width: 80%; } .y-input-md { margin-top: 10px; margin-bottom: 24px; } .y-modal-header-default { background: #f5f5f5; border-top-left-radius: 5px; border-top-right-radius: 5px; } .y-notice { text-align: left; margin-top: 8px; color: #f25050; } .y-card-md { width: 80%; max-width: 720px; margin-left: auto; margin-right: auto; } @media (max-width:420px) { .y-card-md { width: 100%; } } .y-card-body-sm { width: 80%; margin: 10px auto; } .y-card-empty-md { padding: 40px 40px 60px 40px; } .y-l-sm { left: 15%; } @media (min-width:420px) { .y-l-sm { left: 15%; } } .y-scroll-y-md { max-height: 480px; overflow-y: scroll; } .y-modal-footer-default { background: #f5f5f5; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; } .y-panel-title { line-height: 52px; text-align: center; font-size: 20px; font-weight: bold; } .y-panel-btn { line-height: 52px; text-align: center; } .y-table-md > thead > tr > th { line-height: 36px; font-size: 16px; text-align: center; } .y-table-md > tbody > tr > td { line-height: 36px; } .y-btn-sm-sm { padding: 6px 12px; font-size: 14px; } @media (min-width:768px) and (max-width:991px) { .y-btn-sm-sm { padding: 4px 8px !important; font-size: 12px !important; } } @media (max-width:768px) { .y-border-none-xs { border: none !important; } } .y-transition-border-color-info { -webkit-transition: border-color 0.4s ease-out 0s; -moz-transition: border-color 0.4s ease-out 0s; transition: border-color 0.4s ease-out 0s; } .y-transition-border-color-info:hover, .y-transition-border-color-info:focus { border-color: #099fdd; } .y-transition-color-info { -webkit-transition: color 0.4s ease-out 0s; -moz-transition: color 0.4s ease-out 0s; transition: color 0.4s ease-out 0s; } .y-transition-color-info:hover, .y-transition-color-info:focus { color: #099fdd; } .y-panel-display h3, .y-panel-display-money p, .y-panel-display-user p, .y-panel-display-money i, .y-panel-display .y-num, .y-panel-display-set i, .y-panel-display-set p, .y-panel-display-user i, .y-dashboard-set-platform i, .y-dashboard-set-demo i, .y-undeveloped i { -webkit-transition: color 0.4s ease-out 0s; -moz-transition: color 0.4s ease-out 0s; transition: color 0.4s ease-out 0s; } .y-panel-display h3:hover, .y-panel-display h3:focus, .y-panel-display .y-num:hover, .y-panel-display .y-num:focus, .y-panel-display-money i:hover, .y-panel-display-money i:focus, .y-panel-display-user i:hover, .y-panel-display-user i:focus, .y-panel-display-money p:hover, .y-panel-display-money p:focus, .y-panel-display-user p:hover, .y-panel-display-user p:focus, .y-dashboard-set-platform i:hover, .y-dashboard-set-platform i:focus, .y-dashboard-set-demo i:hover, .y-dashboard-set-demo i:focus, .y-undeveloped i:hover, .y-undeveloped i:focus { color: #099fdd; } .y-panel-display-set i:hover, .y-panel-display-set i:focus, .y-panel-display-set p:hover, .y-panel-display-set p:focus { color: #3a3a3a; } /* header style * ============ */ .y-header .navbar-collapse { margin-top: 15px; } .y-header .navbar { background: #fff; box-shadow: 2px 3px 9px 0 rgba(0, 0, 0, 0.06); border-color: #e7e7e7; } .y-header .navbar-toggle { margin-top: 24px; margin-right: 18px; } .y-header .y-header-logo img { height: 100%; width: auto; margin-left: 10px; } .y-header-logo { float: left; height: 80px; margin-right: 20px; } .y-header-search { color: #099fdd; } .y-header-search input { height: 36px; } @media (max-width: 768px) { .y-header-close { width: 100%; text-align: center; } } .y-header-close { color: #777; } .y-header-close:hover, .y-header-close:focus { color: #f25050; background-color: transparent; } .y-header-close i { font-size: 40px; margin: auto 20px; } .y-header-help { border: solid 1px #099fdd; color: #099fdd; } @media (min-width: 768px) { .y-header-help { margin-left: 20px; } } .y-header-help i { font-size: 22px; margin-left: 8px; } .y-header-help i, .y-header-help span { color: #099fdd; } .y-header-search { height: 36px; } /* body style * ============ */ .y-body { margin-top: 130px; text-align: center; } .y-body .panel { box-shadow: 0 0 9px 5px rgba(255, 255, 255, 0.04); -webkit-box-shadow: 0 0 9px 5px rgba(255, 255, 255, 0.04); -webkit-transition: box-shadow 0.3s ease-out 0s; -moz-transition: box-shadow 0.3s ease-out 0s; transition: box-shadow 0.3s ease-out 0s; } .y-body .panel:hover, .y-body .panel:focus { -webkit-box-shadow: 0 0 11px 7px rgba(0, 0, 0, 0.2); box-shadow: 0 0 11px 7px rgba(0, 0, 0, 0.1); }
yhtml5/YHTML5-APP
pc/dashboard/app/server/head.css
CSS
mit
13,906
If you are reporting bug/issue, please provide detailed Repro instructions. ## Repro Steps 1. 2. ## Actual Behavior ## Expected Behavior ## Version Info SDK Version (version of https://www.nuget.org/packages/Microsoft.ApplicationInsights.AspNetCore) : .NET Core Version (TargetFramework in your .csproj file) : How Application was onboarded with SDK(Installed Nugets/VisualStudio/Azure WebAppExtension) : OS : Hosting Info (IIS/Azure Web Apps/Running From Visual Studio etc) :
Microsoft/ApplicationInsights-aspnetcore
NETCORE/.github/ISSUE_TEMPLATE.md
Markdown
mit
494
// Copyright (c) 2015 ZZZ Projects. All rights reserved // Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) // Website: http://www.zzzprojects.com/ // Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 // All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library public static partial class Extensions { /// <summary> /// A string extension method that get the string between the two specified string. /// </summary> /// <param name="this">The @this to act on.</param> /// <param name="before">The string before to search.</param> /// <param name="after">The string after to search.</param> /// <returns>The string between the two specified string.</returns> public static string GetBetween(this string @this, string before, string after) { int beforeStartIndex = @this.IndexOf(before); int startIndex = beforeStartIndex + before.Length; int afterStartIndex = @this.IndexOf(after, startIndex); if (beforeStartIndex == -1 || afterStartIndex == -1) { return ""; } return @this.Substring(startIndex, afterStartIndex - startIndex); } }
huoxudong125/Z.ExtensionMethods
src/Z.Core/System.String/String.GetBetween.cs
C#
mit
1,266
using System; using System.Threading.Tasks; using Orleans; using Tester.CodeGenTests; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace DefaultCluster.Tests.General { [TestCategory("CodeGen")] public class CodeGeneratorTests_AccessibilityChecks : HostedTestClusterEnsureDefaultStarted { /// <summary> /// Tests that compile-time code generation supports classes marked as internal and that /// runtime code generation does not. /// </summary> /// <returns>A <see cref="Task"/> representing the work performed.</returns> [Fact, TestCategory("BVT")] public async Task CodeGenInterfaceAccessibilityCheckTest() { // Runtime codegen does not support internal interfaces. Assert.Throws<InvalidOperationException>(() => GrainFactory.GetGrain<IRuntimeInternalPingGrain>(9)); // Compile-time codegen supports internal interfaces. var grain = GrainFactory.GetGrain<IInternalPingGrain>(0); await grain.Ping(); } } internal interface IRuntimeInternalPingGrain : IGrainWithIntegerKey { Task Ping(); } internal class InternalPingGrain : Grain, IInternalPingGrain, IRuntimeInternalPingGrain { public Task Ping() => Task.FromResult(0); } }
rrector/orleans
test/DefaultCluster.Tests/CodeGeneratorTests_AccessibilityChecks.cs
C#
mit
1,347
#include "macros.h" #include "thread.h" using namespace std; ndb_thread::~ndb_thread() { } void ndb_thread::start() { thd_ = std::move(thread(&ndb_thread::run, this)); if (daemon_) thd_.detach(); } void ndb_thread::join() { ALWAYS_ASSERT(!daemon_); thd_.join(); } // can be overloaded by subclasses void ndb_thread::run() { ALWAYS_ASSERT(body_); body_(); }
stephentu/silo
thread.cc
C++
mit
378
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <base data-ice="baseUrl" href="../../../../"> <title data-ice="title">src/middle_level/shaders/HalfLambertAndWrapLightingShader.js | glboost</title> <link type="text/css" rel="stylesheet" href="css/style.css"> <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css"> <script src="script/prettify/prettify.js"></script> <script src="script/manual.js"></script> <meta name="description" content="A New WebGL Rendering Library for 3D Graphics Geeks"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="glboost"><meta property="twitter:description" content="A New WebGL Rendering Library for 3D Graphics Geeks"></head> <body class="layout-container" data-ice="rootContainer"> <header> <a href="./">Home</a> <a href="identifiers.html">Reference</a> <a href="source.html">Source</a> <div class="search-box"> <span> <img src="./image/search.png"> <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span> </span> <ul class="search-result"></ul> </div> <a style="position:relative; top:3px;" href="https://github.com/emadurandal/GLBoost"><img width="20px" src="./image/github.png"></a></header> <nav class="navigation" data-ice="nav"><div> <ul> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#auxiliaries">auxiliaries</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/auxiliaries/AnimationPlayer.js~AnimationPlayer.html">AnimationPlayer</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-auxiliaries-camera-controllers">low_level/auxiliaries/camera_controllers</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/auxiliaries/camera_controllers/L_CameraController.js~L_CameraController.html">L_CameraController</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/auxiliaries/camera_controllers/L_WalkThroughCameraController.js~L_WalkThroughCameraController.html">L_WalkThroughCameraController</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-components">low_level/components</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/components/AnimationComponent.js~AnimationComponent.html">AnimationComponent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/components/SceneGraphComponent.js~SceneGraphComponent.html">SceneGraphComponent</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/components/TransformComponent.js~TransformComponent.html">TransformComponent</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-core">low_level/core</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/Component.js~Component.html">Component</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/ComponentRepository.js~ComponentRepository.html">ComponentRepository</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/Entity.js~Entity.html">Entity</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/EntityRepository.js~EntityRepository.html">EntityRepository</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/GLBoostLowContext.js~GLBoostLowContext.html">GLBoostLowContext</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/GLBoostObject.js~GLBoostObject.html">GLBoostObject</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/GLBoostSystem.js~GLBoostSystem.html">GLBoostSystem</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/GLContext.js~GLContext.html">GLContext</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/GLExtensionsManager.js~GLExtensionsManager.html">GLExtensionsManager</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/L_GLBoostMonitor.js~L_GLBoostMonitor.html">L_GLBoostMonitor</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/core/MemoryManager.js~MemoryManager.html">MemoryManager</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-elements">low_level/elements</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/elements/L_Element.js~L_Element.html">L_Element</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-elements-cameras">low_level/elements/cameras</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/elements/cameras/L_AbstractCamera.js~L_AbstractCamera.html">L_AbstractCamera</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/elements/cameras/L_FrustumCamera.js~L_FrustumCamera.html">L_FrustumCamera</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/elements/cameras/L_OrthoCamera.js~L_OrthoCamera.html">L_OrthoCamera</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/elements/cameras/L_PerspectiveCamera.js~L_PerspectiveCamera.html">L_PerspectiveCamera</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-geometries">low_level/geometries</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/geometries/BlendShapeGeometry.js~BlendShapeGeometry.html">BlendShapeGeometry</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/geometries/Geometry.js~Geometry.html">Geometry</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-impl">low_level/impl</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/impl/GLContextImpl.js~GLContextImpl.html">GLContextImpl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/impl/GLContextWebGL1Impl.js~GLContextWebGL1Impl.html">GLContextWebGL1Impl</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/impl/GLContextWebGL2Impl.js~GLContextWebGL2Impl.html">GLContextWebGL2Impl</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-materials">low_level/materials</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/materials/ClassicMaterial.js~ClassicMaterial.html">ClassicMaterial</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/materials/L_AbstractMaterial.js~L_AbstractMaterial.html">L_AbstractMaterial</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/materials/PBRMetallicRoughnessMaterial.js~PBRMetallicRoughnessMaterial.html">PBRMetallicRoughnessMaterial</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-math">low_level/math</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/AABB.js~AABB.html">AABB</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/MathClassUtil.js~MathClassUtil.html">MathClassUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/MathUtil.js~MathUtil.html">MathUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/Matrix33.js~Matrix33.html">Matrix33</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/Matrix44.js~Matrix44.html">Matrix44</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/Quaternion.js~Quaternion.html">Quaternion</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/Vector2.js~Vector2.html">Vector2</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/Vector3.js~Vector3.html">Vector3</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/math/Vector4.js~Vector4.html">Vector4</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-misc">low_level/misc</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/AnimationUtil.js~AnimationUtil.html">AnimationUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/ArrayUtil.js~ArrayUtil.html">ArrayUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/DataUtil.js~DataUtil.html">DataUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/Hash.js~Hash.html">Hash</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/InputUtil.js~InputUtil.html">InputUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/MiscUtil.js~MiscUtil.html">MiscUtil</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/misc/TypedArrayWrapper.js~TypedArrayWrapper.html">TypedArrayWrapper</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-variable">V</span><span data-ice="name"><span><a href="variable/index.html#static-variable-IsUtil">IsUtil</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-primitives">low_level/primitives</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Arrow.js~Arrow.html">Arrow</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Axis.js~Axis.html">Axis</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Cube.js~Cube.html">Cube</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/CubeAbsolute.js~CubeAbsolute.html">CubeAbsolute</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Grid.js~Grid.html">Grid</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/JointPrimitive.js~JointPrimitive.html">JointPrimitive</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Line.js~Line.html">Line</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Particle.js~Particle.html">Particle</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Plane.js~Plane.html">Plane</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Screen.js~Screen.html">Screen</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/primitives/Sphere.js~Sphere.html">Sphere</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-shaders">low_level/shaders</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/shaders/Shader.js~Shader.html">Shader</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#low-level-textures">low_level/textures</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/textures/AbstractTexture.js~AbstractTexture.html">AbstractTexture</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/textures/CubeTexture.js~CubeTexture.html">CubeTexture</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/textures/InternalDataTexture.js~InternalDataTexture.html">InternalDataTexture</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/textures/MutableTexture.js~MutableTexture.html">MutableTexture</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/textures/PhinaTexture.js~PhinaTexture.html">PhinaTexture</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/low_level/textures/Texture.js~Texture.html">Texture</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level">middle_level</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/Renderer.js~Renderer.html">Renderer</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-core">middle_level/core</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/core/GLBoostMiddleContext.js~GLBoostMiddleContext.html">GLBoostMiddleContext</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/core/M_GLBoostMonitor.js~M_GLBoostMonitor.html">M_GLBoostMonitor</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-draw-kickers">middle_level/draw_kickers</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/draw_kickers/DrawKickerWorld.js~DrawKickerWorld.html">DrawKickerWorld</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-elements">middle_level/elements</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/M_Element.js~M_Element.html">M_Element</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/M_Group.js~M_Group.html">M_Group</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/M_Scene.js~M_Scene.html">M_Scene</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-elements-cameras">middle_level/elements/cameras</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/cameras/M_AbstractCamera.js~M_AbstractCamera.html">M_AbstractCamera</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/cameras/M_FrustumCamera.js~M_FrustumCamera.html">M_FrustumCamera</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/cameras/M_OrthoCamera.js~M_OrthoCamera.html">M_OrthoCamera</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/cameras/M_PerspectiveCamera.js~M_PerspectiveCamera.html">M_PerspectiveCamera</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-elements-gizmos">middle_level/elements/gizmos</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_AABBGizmo.js~M_AABBGizmo.html">M_AABBGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_AxisGizmo.js~M_AxisGizmo.html">M_AxisGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_DirectionalLightGizmo.js~M_DirectionalLightGizmo.html">M_DirectionalLightGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_Gizmo.js~M_Gizmo.html">M_Gizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_GridGizmo.js~M_GridGizmo.html">M_GridGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_HeightLineGizmo.js~M_HeightLineGizmo.html">M_HeightLineGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_JointGizmo.js~M_JointGizmo.html">M_JointGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_OutlineGizmo.js~M_OutlineGizmo.html">M_OutlineGizmo</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/gizmos/M_PointLightGizmo.js~M_PointLightGizmo.html">M_PointLightGizmo</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-elements-lights">middle_level/elements/lights</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/lights/M_AbstractLight.js~M_AbstractLight.html">M_AbstractLight</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/lights/M_AmbientLight.js~M_AmbientLight.html">M_AmbientLight</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/lights/M_DirectionalLight.js~M_DirectionalLight.html">M_DirectionalLight</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/lights/M_PointLight.js~M_PointLight.html">M_PointLight</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/lights/M_SpotLight.js~M_SpotLight.html">M_SpotLight</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-elements-meshes">middle_level/elements/meshes</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/meshes/M_Mesh.js~M_Mesh.html">M_Mesh</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/meshes/M_ScreenMesh.js~M_ScreenMesh.html">M_ScreenMesh</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/meshes/M_SkeletalMesh.js~M_SkeletalMesh.html">M_SkeletalMesh</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-elements-skeletons">middle_level/elements/skeletons</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/skeletons/JointGizmoUpdater.js~JointGizmoUpdater.html">JointGizmoUpdater</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/elements/skeletons/M_Joint.js~M_Joint.html">M_Joint</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-expressions">middle_level/expressions</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/expressions/Expression.js~Expression.html">Expression</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/expressions/RenderPass.js~RenderPass.html">RenderPass</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-geometries">middle_level/geometries</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/geometries/M_SkeletalGeometry.js~M_SkeletalGeometry.html">M_SkeletalGeometry</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-loader">middle_level/loader</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/loader/GLBoostGLTFLoaderExtension.js~GLBoostGLTFLoaderExtension.html">GLBoostGLTFLoaderExtension</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/loader/GLTF2Exporter.js~GLTF2Exporter.html">GLTF2Exporter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/loader/GLTF2Loader.js~GLTF2Loader.html">GLTF2Loader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/loader/GLTFLoader.js~GLTFLoader.html">GLTFLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/loader/ModelConverter.js~ModelConverter.html">ModelConverter</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/loader/ObjLoader.js~ObjLoader.html">ObjLoader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-function">F</span><span data-ice="name"><span><a href="function/index.html#static-function-formatDetector">formatDetector</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-plugins">middle_level/plugins</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/plugins/EffekseerElement.js~EffekseerElement.html">EffekseerElement</a></span></span></li> <li data-ice="doc"><a data-ice="dirPath" class="nav-dir-path" href="identifiers.html#middle-level-shaders">middle_level/shaders</a><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/BlendShapeShader.js~BlendShapeShaderSource.html">BlendShapeShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/BlinnPhongShader.js~BlinnPhongShader.html">BlinnPhongShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/BlinnPhongShader.js~BlinnPhongShaderSource.html">BlinnPhongShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/DecalShader.js~DecalShader.html">DecalShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/DecalShader.js~DecalShaderSource.html">DecalShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/DepthDisplayShader.js~DepthDisplayShader.html">DepthDisplayShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/DepthDisplayShader.js~DepthDisplayShaderSource.html">DepthDisplayShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/EnvironmentMapShader.js~EnvironmentMapShader.html">EnvironmentMapShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/EnvironmentMapShader.js~EnvironmentMapShaderSource.html">EnvironmentMapShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/FragmentSimpleShader.js~FragmentSimpleShader.html">FragmentSimpleShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/FragmentSimpleShader.js~FragmentSimpleShaderSource.html">FragmentSimpleShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/FreeShader.js~FreeShader.html">FreeShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/HalfLambertAndWrapLightingShader.js~HalfLambertAndWrapLightingShader.html">HalfLambertAndWrapLightingShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/HalfLambertAndWrapLightingShader.js~HalfLambertAndWrapLightingShaderSource.html">HalfLambertAndWrapLightingShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/HalfLambertShader.js~HalfLambertShader.html">HalfLambertShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/HalfLambertShader.js~HalfLambertShaderSource.html">HalfLambertShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/LambertShader.js~LambertShader.html">LambertShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/LambertShader.js~LambertShaderSource.html">LambertShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/PBRPrincipledShader.js~PBRPrincipledShader.html">PBRPrincipledShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/PBRPrincipledShader.js~PBRPrincipledShaderSource.html">PBRPrincipledShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/ParticleShader.js~ParticleShaderSource.html">ParticleShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/PassThroughShader.js~PassThroughShader.html">PassThroughShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/PassThroughShader.js~PassThroughShaderSource.html">PassThroughShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/PhongShader.js~PhongShader.html">PhongShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/PhongShader.js~PhongShaderSource.html">PhongShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/SkeletalShader.js~SkeletalShaderSource.html">SkeletalShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/VertexWorldShader.js~VertexWorldShaderSource.html">VertexWorldShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/VertexWorldShadowShader.js~VertexWorldShadowShaderSource.html">VertexWorldShadowShaderSource</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/WireframeShader.js~WireframeShader.html">WireframeShader</a></span></span></li> <li data-ice="doc"><span data-ice="kind" class="kind-class">C</span><span data-ice="name"><span><a href="class/src/middle_level/shaders/WireframeShader.js~WireframeShaderSource.html">WireframeShaderSource</a></span></span></li> </ul> </div> </nav> <div class="content" data-ice="content"><h1 data-ice="title">src/middle_level/shaders/HalfLambertAndWrapLightingShader.js</h1> <pre class="source-code line-number raw-source-code"><code class="prettyprint linenums" data-ice="content">import Shader from &apos;../../low_level/shaders/Shader&apos;; import DecalShader from &apos;./DecalShader&apos;; import Vector3 from &apos;../../low_level/math/Vector3&apos;; import Vector4 from &apos;../../low_level/math/Vector4&apos;; export class HalfLambertAndWrapLightingShaderSource { FSDefine_HalfLambertAndWrapLightingShaderSource(in_, f, lights) { var sampler2D = this._sampler2DShadow_func(); var shaderText = &apos;&apos;; shaderText += `uniform vec4 Kd;\n`; shaderText += `uniform vec3 wrap;\n`; shaderText += &apos;uniform vec4 ambient;\n&apos;; // Ka * amount of ambient lights let lightNumExceptAmbient = lights.filter((light)=&gt;{return !light.isTypeAmbient();}).length; if (lightNumExceptAmbient &gt; 0) { shaderText += `uniform highp ${sampler2D} uDepthTexture[${lightNumExceptAmbient}];\n`; shaderText += `${in_} vec4 v_shadowCoord[${lightNumExceptAmbient}];\n`; shaderText += `uniform int isShadowCasting[${lightNumExceptAmbient}];\n`; } return shaderText; } FSShade_HalfLambertAndWrapLightingShaderSource(f, gl, lights) { var shaderText = &apos;&apos;; shaderText += &apos; vec4 surfaceColor = rt0;\n&apos;; shaderText += &apos; rt0 = vec4(0.0, 0.0, 0.0, 0.0);\n&apos;; for (let i=0; i&lt;lights.length; i++) { let light = lights[i]; let isShadowEnabledAsTexture = (light.camera &amp;&amp; light.camera.texture) ? true:false; shaderText += &apos; {\n&apos;; shaderText += Shader._generateLightStr(i); shaderText += Shader._generateShadowingStr(gl, i, isShadowEnabledAsTexture); shaderText += &apos; float diffuse = max(dot(lightDirection, normal), 0.0)*0.5+0.5;\n&apos;; shaderText += &apos; diffuse *= diffuse;\n&apos;; shaderText += &apos; vec3 diffuseVec = vec3(diffuse, diffuse, diffuse);\n&apos;; shaderText += &apos; diffuseVec = (diffuseVec+wrap) / (1.0 + wrap);\n&apos;; shaderText += ` rt0 += spotEffect * vec4(visibility, visibility, visibility, 1.0) * Kd * lightDiffuse[${i}] * vec4(diffuseVec, 1.0) * surfaceColor;\n`; shaderText += &apos; }\n&apos;; } shaderText += &apos; rt0.xyz += ambient.xyz;\n&apos;; return shaderText; } prepare_HalfLambertAndWrapLightingShaderSource(gl, shaderProgram, expression, vertexAttribs, existCamera_f, lights, material, extraData) { var vertexAttribsAsResult = []; material.setUniform(shaderProgram, &apos;uniform_Kd&apos;, this._glContext.getUniformLocation(shaderProgram, &apos;Kd&apos;)); material.setUniform(shaderProgram, &apos;uniform_wrap&apos;, this._glContext.getUniformLocation(shaderProgram, &apos;wrap&apos;)); material.setUniform(shaderProgram, &apos;uniform_ambient&apos;, this._glContext.getUniformLocation(shaderProgram, &apos;ambient&apos;)); return vertexAttribsAsResult; } } export default class HalfLambertAndWrapLightingShader extends DecalShader { constructor(glBoostContext, basicShader) { super(glBoostContext, basicShader); HalfLambertAndWrapLightingShader.mixin(HalfLambertAndWrapLightingShaderSource); this._wrap = new Vector3(0.6, 0.3, 0.0); } setUniforms(gl, glslProgram, scene, material, camera, mesh, lights) { super.setUniforms(gl, glslProgram, scene, material, camera, mesh, lights); var Kd = material.diffuseColor; let Ka = material.ambientColor; this._glContext.uniform4f(material.getUniform(glslProgram, &apos;uniform_Kd&apos;), Kd.x, Kd.y, Kd.z, Kd.w, true); this._glContext.uniform3f(material.getUniform(glslProgram, &apos;uniform_wrap&apos;), this._wrap.x, this._wrap.y, this._wrap.z, true); let ambient = Vector4.multiplyVector(Ka, scene.getAmountOfAmbientLightsIntensity()); this._glContext.uniform4f(material.getUniform(glslProgram, &apos;uniform_ambient&apos;), ambient.x, ambient.y, ambient.z, ambient.w, true); } set wrap(value) { this._wrap = value; } get wrap() { return this._wrap; } } GLBoost[&apos;HalfLambertAndWrapLightingShader&apos;] = HalfLambertAndWrapLightingShader; </code></pre> </div> <footer class="footer"> Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.1.0)</span><img src="./image/esdoc-logo-mini-black.png"></a> </footer> <script src="script/search_index.js"></script> <script src="script/search.js"></script> <script src="script/pretty-print.js"></script> <script src="script/inherited-summary.js"></script> <script src="script/test-summary.js"></script> <script src="script/inner-link.js"></script> <script src="script/patch-for-local.js"></script> </body> </html>
cx20/GLBoost
docs/documents/api/file/src/middle_level/shaders/HalfLambertAndWrapLightingShader.js.html
HTML
mit
38,464
/*jslint node: true, vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 2, maxerr: 50*/ /*global define, $, brackets, Mustache, window, appshell*/ define(function (require, exports, module) { "use strict"; // HEADER >> var NodeConnection = brackets.getModule("utils/NodeConnection"), Menus = brackets.getModule("command/Menus"), CommandManager = brackets.getModule("command/CommandManager"), Commands = brackets.getModule("command/Commands"), PreferencesManager = brackets.getModule("preferences/PreferencesManager"), _ = brackets.getModule("thirdparty/lodash"), KeyBindingManager = brackets.getModule("command/KeyBindingManager"); var ExtensionDiagnosis = require("modules/ExtensionDiagnosis"), Log = require("modules/Log"), Panel = require("modules/Panel"), FileTreeView = require("modules/FileTreeView"), Strings = require("strings"); var treeViewContextMenu = null; var _nodeConnection = null; var showMainPanel, initTreeViewContextMenu, setRootMenu, setDebugMenu, reloadBrackets, treeViewContextMenuState; var _disableTreeViewContextMenuAllItem; //<< var ContextMenuIds = { TREEVIEW_CTX_MENU: "kohei-synapse-treeview-context-menu" }; var ContextMenuCommandIds = { SYNAPSE_FILE_NEW: "kohei.synapse.file_new", SYNAPSE_DIRECTORY_NEW: "kohei.synapse.directory_new", SYNAPSE_FILE_REFRESH: "kohei.synapse.file_refresh", SYNAPSE_FILE_RENAME: "kohei.synapse.file_rename", SYNAPSE_DELETE: "kohei.synapse.delete" }; var MenuText = { SYNAPSE_CTX_FILE_NEW: Strings.SYNAPSE_CTX_FILE_NEW, SYNAPSE_CTX_DIRECTORY_NEW: Strings.SYNAPSE_CTX_DIRECTORY_NEW, SYNAPSE_CTX_FILE_REFRESH: Strings.SYNAPSE_CTX_FILE_REFRESH, SYNAPSE_CTX_FILE_RENAME: Strings.SYNAPSE_CTX_FILE_RENAME, SYNAPSE_CTX_DELETE: Strings.SYNAPSE_CTX_DELETE }; var Open_TreeView_Context_Menu_On_Directory_State = [ ContextMenuCommandIds.SYNAPSE_FILE_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DELETE, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH, ContextMenuCommandIds.SYNAPSE_FILE_RENAME ]; var Open_TreeView_Context_Menu_On_Linked_Directory_State = [ ContextMenuCommandIds.SYNAPSE_FILE_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DELETE, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH ]; var Open_TreeView_Context_Menu_On_File_State = [ ContextMenuCommandIds.SYNAPSE_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_DELETE ]; var Open_TreeView_Context_Menu_On_Linked_File_State = [ ContextMenuCommandIds.SYNAPSE_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_DELETE ]; var Open_TreeView_Context_Menu_On_Root_State = [ ContextMenuCommandIds.SYNAPSE_FILE_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH ]; showMainPanel = function () { CommandManager.execute("kohei.synapse.mainPanel"); }; treeViewContextMenuState = function (entity) { _disableTreeViewContextMenuAllItem(); if (entity.class === "treeview-root") { Open_TreeView_Context_Menu_On_Root_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } if (entity.class === "treeview-directory") { Open_TreeView_Context_Menu_On_Directory_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } else if (entity.class === "treeview-ldirectory") { Open_TreeView_Context_Menu_On_Linked_Directory_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } else if (entity.class === "treeview-file") { Open_TreeView_Context_Menu_On_File_State.forEach(function (id) { CommandManager.get(id).setEnabled(true); }); return; } }; setRootMenu = function (domain) { var menu = CommandManager.register( "Synapse", "kohei.synapse.mainPanel", Panel.showMain); var topMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU); topMenu.addMenuDivider(); topMenu.addMenuItem(menu, { key: "Ctrl-Shift-Alt-Enter", displayKey: "Ctrl-Shift-Alt-Enter" }); //For Debug > //Panel.showMain(); setDebugMenu(); return new $.Deferred().resolve(domain).promise(); }; setDebugMenu = function () { var menu = CommandManager.register( "Reload App wiz Node", "kohei.syanpse.reloadBrackets", reloadBrackets); var topMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU); topMenu.addMenuDivider(); topMenu.addMenuItem(menu, { key: "Ctrl-Shift-F6", displeyKey: "Ctrl-Shift-F6" }); }; reloadBrackets = function () { try { _nodeConnection.domains.base.restartNode(); CommandManager.execute(Commands.APP_RELOAD); } catch (e) { console.log("SYNAPSE ERROR - Failed trying to restart Node", e); } }; initTreeViewContextMenu = function () { var d = new $.Deferred(); CommandManager .register(MenuText.SYNAPSE_CTX_FILE_REFRESH, ContextMenuCommandIds.SYNAPSE_FILE_REFRESH, FileTreeView.refresh); CommandManager .register(MenuText.SYNAPSE_CTX_FILE_RENAME, ContextMenuCommandIds.SYNAPSE_FILE_RENAME, FileTreeView.rename); CommandManager .register(MenuText.SYNAPSE_CTX_FILE_NEW, ContextMenuCommandIds.SYNAPSE_FILE_NEW, FileTreeView.newFile); CommandManager .register(MenuText.SYNAPSE_CTX_DIRECTORY_NEW, ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, FileTreeView.newDirectory); CommandManager .register(MenuText.SYNAPSE_CTX_DELETE, ContextMenuCommandIds.SYNAPSE_DELETE, FileTreeView.removeFile); treeViewContextMenu = Menus.registerContextMenu(ContextMenuIds.TREEVIEW_CTX_MENU); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_REFRESH); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_RENAME, null, Menus.LAST, null); treeViewContextMenu .addMenuDivider(); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_FILE_NEW, null, Menus.LAST, null); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_DIRECTORY_NEW, null, Menus.LAST, null); treeViewContextMenu .addMenuDivider(); treeViewContextMenu .addMenuItem(ContextMenuCommandIds.SYNAPSE_DELETE, null, Menus.LAST, null); $("#synapse-treeview-container").contextmenu(function (e) { FileTreeView.onTreeViewContextMenu(e, treeViewContextMenu); }); return d.resolve().promise(); }; /* Private Methods */ _disableTreeViewContextMenuAllItem = function () { if (treeViewContextMenu === null) { return; } _.forIn(ContextMenuCommandIds, function (val, key) { CommandManager.get(val).setEnabled(false); }); }; /* for Debug */ _nodeConnection = new NodeConnection(); _nodeConnection.connect(true); exports.showMainPanel = showMainPanel; exports.setRootMenu = setRootMenu; exports.initTreeViewContextMenu = initTreeViewContextMenu; exports.ContextMenuCommandIds = ContextMenuCommandIds; exports.ContextMenuIds = ContextMenuIds; exports.treeViewContextMenuState = treeViewContextMenuState; exports.getModuleName = function () { return module.id; }; });
marcandrews/brackets-synapse
modules/Menu.js
JavaScript
mit
7,210
{% load crispy_forms_tags %} <div class="auth-wrapper signup-wrapper"> <form role="form" method="post" action="{% url 'create_user' %}"> {% csrf_token %} <h2>Sign Up</h2> {{form | crispy }} <div class="extra-errors"></div> <button type="submit" class="btn btn-primary" data-disable-with="Signing Up…"> Sign Up </button> <span class="pull-right auth-alt-method"><a href="{% url 'my_profile' %}">Log In</a></span> <input type="hidden" name="next" value="{{ request.GET.next }}" /> </form> </div>
expfactory/expfactory-docker
expdj/apps/users/templates/registration/_signup.html
HTML
mit
582
'output dimensionalities for each column' import csv import sys import re import math from collections import defaultdict def get_words( text ): text = text.replace( "'", "" ) text = re.sub( r'\W+', ' ', text ) text = text.lower() text = text.split() words = [] for w in text: if w in words: continue words.append( w ) return words ### csv.field_size_limit( 1000000 ) input_file = sys.argv[1] target_col = 'SalaryNormalized' cols2tokenize = [ 'Title', 'FullDescription' ] cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ] cols2drop = [ 'SalaryRaw' ] ### i_f = open( input_file ) reader = csv.reader( i_f ) headers = reader.next() target_index = headers.index( target_col ) indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize ) indexes2binarize = map( lambda x: headers.index( x ), cols2binarize ) indexes2drop = map( lambda x: headers.index( x ), cols2drop ) n = 0 unique_values = defaultdict( set ) for line in reader: for i in indexes2binarize: value = line[i] unique_values[i].add( value ) for i in indexes2tokenize: words = get_words( line[i] ) unique_values[i].update( words ) n += 1 if n % 10000 == 0: print n # print counts for i in sorted( unique_values ): l = len( unique_values[i] ) print "index: %s, count: %s" % ( i, l ) if l < 100: pass # print unique_values[i]
zygmuntz/kaggle-advertised-salaries
optional/cols_dimensionality.py
Python
mit
1,451
#include <seqan/sequence.h> #include <seqan/basic.h> #include <seqan/find_motif.h> #include <seqan/file.h> #include <iostream> using namespace seqan; template<typename TString>//String<char> void countOneMers(TString const& str){ Iterator<TString>::Type StringIterator = begin(str); Iterator<TString>::Type EndIterator = end(str); String<unsigned int> counter; resize(counter, 26,0);//26 = AlphSize unsigned int normalize =ordValue('a'); unsigned int a=0; while(StringIterator != EndIterator){ a= ordValue(*StringIterator); std::cout<<a-normalize<<std::endl; ++value(counter,(a-normalize)); ++StringIterator; } StringIterator = begin(str); //Iterator<String<unsigned int> >::Type countIterator = begin(counter); int i=0; while(i<26){ if(counter[i]>0) std::cout<<char(i+'a')<<" "<<counter[i]<<std::endl; ++i; } } void replaceAs(String<char>& str){ str="hi"; } int main(){ String<char> str = "helloworld"; //countOneMers(str); replaceAs(str); std::cout<<str; return 0; }
bkahlert/seqan-research
raw/pmbs12/pmsb13-data-20120615/sources/brbym28nz827lxic/93/sandbox/meyerclp/demos/Sequences.cpp
C++
mit
1,018
/* Default MDL font size */ .wj-control, .wj-control input { font-size: 16px; } /* Extra padding in grids and listboxes */ .wj-flexgrid .wj-cell { padding: 6px; } .wj-listbox-item { padding: 6px 10px; } /* Backgrounds */ .wj-content, div[wj-part='cells'] { background: #ffffff; color: #212121; } .wj-content .wj-input-group .wj-form-control { background: #ffffff; color: #212121; } /* Headers */ .wj-header { background: #e8e8e8; color: black; } /* FlexGrid */ div[wj-part='root'] { background: #ffffff; } .wj-state-selected { background: #e91e63; color: #ffffff; } .wj-state-multi-selected { background: #f06493; color: #ffffff; } .wj-input-group .wj-form-control, .wj-grid-editor { background: #ffffff; color: #212121; } .wj-flexgrid .wj-cell { border-right: none; border-bottom: 1px solid rgba(0, 0, 0, 0.1); } [dir="rtl"] .wj-cell { border-left: 1px solid rgba(0, 0, 0, 0.1); } /* Default grid cell color */ .wj-flexgrid .wj-cell:not(.wj-header):not(.wj-group):not(.wj-alt):not(.wj-state-selected):not(.wj-state-multi-selected) { background: #ffffff; } /* Alternate grid cell color */ .wj-flexgrid .wj-alt:not(.wj-header):not(.wj-group):not(.wj-state-selected):not(.wj-state-multi-selected) { background: #ffffff; } /* Group row background */ .wj-flexgrid .wj-group:not(.wj-state-selected):not(.wj-state-multi-selected) { background: #aa1145; color: #ffffff; } /* Default frozen boundaries */ .wj-flexgrid .wj-cell.wj-frozen-row { border-bottom-color: black; border-width: 1px; } .wj-flexgrid .wj-cell.wj-frozen-col { border-right-color: black; border-width: 1px; } /* Grid headers */ .wj-flexgrid .wj-header.wj-state-multi-selected { background: #d5d5d5; } .wj-flexgrid .wj-colheaders .wj-header.wj-state-multi-selected { border-bottom: 3px solid #e91e63; } .wj-flexgrid .wj-rowheaders .wj-header.wj-state-multi-selected { border-right: 3px solid #e91e63; } /* Marquee */ .wj-flexgrid .wj-marquee { position: absolute; box-sizing: border-box; border: 2px solid #e91e63; } .wj-flexsheet .wj-marquee { border: 2px solid #e91e63; } /* Drag marker */ .wj-flexgrid .wj-marker { background: #f44336; } /* Input Controls */ .wj-control.wj-content.wj-dropdown, .wj-inputnumber { background-color: transparent; border: none; border-bottom: 1px solid rgba(0, 0, 0, 0.12); } .wj-control.wj-content .wj-input-group input.wj-form-control { background-color: transparent; padding-bottom: 0; padding-top: 0; } .wj-content .wj-input-group-btn > .wj-btn:hover, .wj-content .wj-btn-group > .wj-btn:hover { background-color: rgba(0, 0, 0, 0.1); } .wj-content .wj-input-group-btn > .wj-btn, .wj-content .wj-btn-group > .wj-btn { border-style: none; border-radius: 2px; background-color: rgba(0, 0, 0, 0.02); color: rgba(0, 0, 0, 0.8); min-width: 32px; } /* Border Radii */ .wj-content, .wj-input-group, .wj-btn-group, .wj-btn-group-vertical, .wj-tooltip { border-radius: 0; } /* Tooltip */ /* style tooltips like https://www.getmdl.io/customize/index.html */ .wj-tooltip { padding: 20px; color: white; font-weight: bold; background-color: rgba(128, 128, 128, 0.85); border: none; } /* Gauges */ .wj-gauge .wj-pointer { fill: #e91e63; } .wj-gauge.wj-state-focused circle.wj-pointer { fill: #f44336; transition: fill .2s; /* delay used in MDL */ }
NoahOliverRigonan/InnosoftSolutionsWebsiteAngularUI
app/styles/themes/material/wijmo.theme.material.pink-red.css
CSS
mit
3,348
package dbfiles import ( "encoding/csv" "io" "github.com/juju/errgo" ) type Driver interface { Extention() string Write(io.Writer, []string) error Read(io.Reader) ([][]string, error) } type CSV struct{} func (driver CSV) Extention() string { return "csv" } func (driver CSV) Write(writer io.Writer, values []string) error { csvwriter := csv.NewWriter(writer) err := csvwriter.WriteAll([][]string{values}) if err != nil { return errgo.Notef(err, "can not write to csv writer") } return nil } func (driver CSV) Read(reader io.Reader) ([][]string, error) { csvreader := csv.NewReader(reader) csvreader.FieldsPerRecord = -1 var values [][]string values, err := csvreader.ReadAll() if err != nil { return nil, errgo.Notef(err, "can not read all records from file") } return values, nil }
AlexanderThaller/lablog
vendor/github.com/AlexanderThaller/dbfiles/driver.go
GO
mit
818
const ASSETS_MODS_LENGTH = 13;//'/assets/mods/'.length; const CONTENT_TYPES = { 'css': 'text/css', 'js': 'text/javascript', 'json': 'application/json', 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'html': 'text/html', 'htm': 'text/html' }; /** * @type {Map<string, JSZip>} */ const jszipCache = new Map(); //Not exported because serviceworkers can't use es6 modules // eslint-disable-next-line no-unused-vars class PackedManager { /** * * @param {string} url */ async get(url) { try { const zip = await this._openZip(url); const file = zip.file(this._assetPath(url)); if (file === null) { return new Response(new Blob(), { status: 404, statusText: 'not found' }); } return new Response(await file.async('blob'), { headers: { 'Content-Type': this._contentType(url) }, status: 200, statusText: 'ok' }); } catch (e) { console.error('An error occured while reading a packed mod', e); return e; } } /** * * @param {string} url * @returns {Promise<string[]>} */ async getFiles(url) { const zip = await this._openZip(url); const folder = this._openFolder(zip, this._assetPath(url)); const result = []; folder.forEach((relativePath, file) => { if (!file.dir) { result.push(relativePath); } }); return result; } /** * * @param {string} url * @returns {Promise<boolean>} */ async isDirectory(url) { const zip = await this._openZip(url); const file = zip.file(this._assetPath(url)); return file && file.dir; } /** * * @param {string} url * @returns {Promise<boolean>} */ async isFile(url) { const zip = await this._openZip(url); const file = zip.file(this._assetPath(url)); return !!file; } /** * * @param {string} url */ packedName(url) { url = this._normalize(url); return decodeURIComponent(url.substring(ASSETS_MODS_LENGTH, url.indexOf('/', ASSETS_MODS_LENGTH))); } /** * * @param {string} url */ async _openZip(url) { const zip = this._zipPath(url); const cached = jszipCache.get(zip); if (cached) { return cached; } const request = new Request('http://' + location.hostname + '.cc' + zip); const cache = await caches.open('zips'); let response = await cache.match(request); if (!response) { response = await fetch(zip); cache.put(request, response.clone()); } const result = await JSZip.loadAsync(response.blob()); jszipCache.set(zip, result); return result; } /** * * @param {JSZip} root * @param {string} path */ _openFolder(root, path) { const folders = path.split(/\//g); for (const folder of folders) { root = root.folder(folder); } return root; } /** * @param {string} url * @returns {string} */ _contentType(url) { url = this._normalize(url); return CONTENT_TYPES[url.substr(url.lastIndexOf('.') + 1)] || 'text/plain'; } /** * * @param {string} url */ _zipPath(url) { url = this._normalize(url); return url.substr(0, url.indexOf('/', ASSETS_MODS_LENGTH)); } /** * * @param {string} url */ _assetPath(url) { url = this._normalize(url); return url.substr(url.indexOf('/', ASSETS_MODS_LENGTH) + 1); } /** * * @param {string} url */ _normalize(url) { url = url.replace(/\\/g, '/').replace(/\/\//, '/'); //TODO: resolve absolute paths if (!url.startsWith('/')) { url = '/' + url; } if (url.startsWith('/ccloader')) { url = url.substr(9); // '/ccloader'.length } return url; } }
2767mr/CCLoader
ccloader/js/packed.js
JavaScript
mit
3,555
## # This code was generated by # \ / _ _ _| _ _ # | (_)\/(_)(_|\/| |(/_ v1.0.0 # / / # # frozen_string_literal: true require 'spec_helper.rb' describe 'ExportConfiguration' do it "can fetch" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.bulkexports.v1.export_configuration('resource_type').fetch() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'get', url: 'https://bulkexports.twilio.com/v1/Exports/resource_type/Configuration', ))).to eq(true) end it "receives fetch responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "url": "https://bulkexports.twilio.com/v1/Exports/Messages/Configuration", "enabled": true, "webhook_url": "", "webhook_method": "", "resource_type": "Messages" } ] )) actual = @client.bulkexports.v1.export_configuration('resource_type').fetch() expect(actual).to_not eq(nil) end it "can update" do @holodeck.mock(Twilio::Response.new(500, '')) expect { @client.bulkexports.v1.export_configuration('resource_type').update() }.to raise_exception(Twilio::REST::TwilioError) expect( @holodeck.has_request?(Holodeck::Request.new( method: 'post', url: 'https://bulkexports.twilio.com/v1/Exports/resource_type/Configuration', ))).to eq(true) end it "receives update responses" do @holodeck.mock(Twilio::Response.new( 200, %q[ { "url": "https://bulkexports.twilio.com/v1/Exports/Messages/Configuration", "enabled": true, "webhook_url": "", "resource_type": "Messages", "webhook_method": "" } ] )) actual = @client.bulkexports.v1.export_configuration('resource_type').update() expect(actual).to_not eq(nil) end end
philnash/twilio-ruby
spec/integration/bulkexports/v1/export_configuration_spec.rb
Ruby
mit
1,959
<?php /** * Author: Nil Portugués Calderó <[email protected]> * Date: 12/18/15 * Time: 11:36 PM. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace NilPortugues\SchemaOrg\Classes; use NilPortugues\SchemaOrg\SchemaClass; /** * METHODSTART. * * @method static \NilPortugues\SchemaOrg\Properties\BranchOfProperty branchOf() * @method static \NilPortugues\SchemaOrg\Properties\BranchCodeProperty branchCode() * @method static \NilPortugues\SchemaOrg\Properties\CurrenciesAcceptedProperty currenciesAccepted() * @method static \NilPortugues\SchemaOrg\Properties\OpeningHoursProperty openingHours() * @method static \NilPortugues\SchemaOrg\Properties\PaymentAcceptedProperty paymentAccepted() * @method static \NilPortugues\SchemaOrg\Properties\PriceRangeProperty priceRange() * @method static \NilPortugues\SchemaOrg\Properties\HasOfferCatalogProperty hasOfferCatalog() * @method static \NilPortugues\SchemaOrg\Properties\AddressProperty address() * @method static \NilPortugues\SchemaOrg\Properties\AggregateRatingProperty aggregateRating() * @method static \NilPortugues\SchemaOrg\Properties\AlumniProperty alumni() * @method static \NilPortugues\SchemaOrg\Properties\AreaServedProperty areaServed() * @method static \NilPortugues\SchemaOrg\Properties\AwardProperty award() * @method static \NilPortugues\SchemaOrg\Properties\AwardsProperty awards() * @method static \NilPortugues\SchemaOrg\Properties\ParentOrganizationProperty parentOrganization() * @method static \NilPortugues\SchemaOrg\Properties\BrandProperty brand() * @method static \NilPortugues\SchemaOrg\Properties\ContactPointProperty contactPoint() * @method static \NilPortugues\SchemaOrg\Properties\ContactPointsProperty contactPoints() * @method static \NilPortugues\SchemaOrg\Properties\DepartmentProperty department() * @method static \NilPortugues\SchemaOrg\Properties\DunsProperty duns() * @method static \NilPortugues\SchemaOrg\Properties\EmailProperty email() * @method static \NilPortugues\SchemaOrg\Properties\EmployeeProperty employee() * @method static \NilPortugues\SchemaOrg\Properties\EmployeesProperty employees() * @method static \NilPortugues\SchemaOrg\Properties\EventProperty event() * @method static \NilPortugues\SchemaOrg\Properties\EventsProperty events() * @method static \NilPortugues\SchemaOrg\Properties\FaxNumberProperty faxNumber() * @method static \NilPortugues\SchemaOrg\Properties\FounderProperty founder() * @method static \NilPortugues\SchemaOrg\Properties\FoundersProperty founders() * @method static \NilPortugues\SchemaOrg\Properties\DissolutionDateProperty dissolutionDate() * @method static \NilPortugues\SchemaOrg\Properties\FoundingDateProperty foundingDate() * @method static \NilPortugues\SchemaOrg\Properties\GlobalLocationNumberProperty globalLocationNumber() * @method static \NilPortugues\SchemaOrg\Properties\HasPOSProperty hasPOS() * @method static \NilPortugues\SchemaOrg\Properties\IsicV4Property isicV4() * @method static \NilPortugues\SchemaOrg\Properties\LegalNameProperty legalName() * @method static \NilPortugues\SchemaOrg\Properties\LocationProperty location() * @method static \NilPortugues\SchemaOrg\Properties\LogoProperty logo() * @method static \NilPortugues\SchemaOrg\Properties\MakesOfferProperty makesOffer() * @method static \NilPortugues\SchemaOrg\Properties\MemberProperty member() * @method static \NilPortugues\SchemaOrg\Properties\MemberOfProperty memberOf() * @method static \NilPortugues\SchemaOrg\Properties\MembersProperty members() * @method static \NilPortugues\SchemaOrg\Properties\NaicsProperty naics() * @method static \NilPortugues\SchemaOrg\Properties\NumberOfEmployeesProperty numberOfEmployees() * @method static \NilPortugues\SchemaOrg\Properties\OwnsProperty owns() * @method static \NilPortugues\SchemaOrg\Properties\ReviewProperty review() * @method static \NilPortugues\SchemaOrg\Properties\ReviewsProperty reviews() * @method static \NilPortugues\SchemaOrg\Properties\SeeksProperty seeks() * @method static \NilPortugues\SchemaOrg\Properties\ServiceAreaProperty serviceArea() * @method static \NilPortugues\SchemaOrg\Properties\SubOrganizationProperty subOrganization() * @method static \NilPortugues\SchemaOrg\Properties\TaxIDProperty taxID() * @method static \NilPortugues\SchemaOrg\Properties\TelephoneProperty telephone() * @method static \NilPortugues\SchemaOrg\Properties\VatIDProperty vatID() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty additionalType() * @method static \NilPortugues\SchemaOrg\Properties\AlternateNameProperty alternateName() * @method static \NilPortugues\SchemaOrg\Properties\DescriptionProperty description() * @method static \NilPortugues\SchemaOrg\Properties\ImageProperty image() * @method static \NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty mainEntityOfPage() * @method static \NilPortugues\SchemaOrg\Properties\NameProperty name() * @method static \NilPortugues\SchemaOrg\Properties\SameAsProperty sameAs() * @method static \NilPortugues\SchemaOrg\Properties\UrlProperty url() * @method static \NilPortugues\SchemaOrg\Properties\PotentialActionProperty potentialAction() * @method static \NilPortugues\SchemaOrg\Properties\ContainedInPlaceProperty containedInPlace() * @method static \NilPortugues\SchemaOrg\Properties\ContainsPlaceProperty containsPlace() * @method static \NilPortugues\SchemaOrg\Properties\ContainedInProperty containedIn() * @method static \NilPortugues\SchemaOrg\Properties\GeoProperty geo() * @method static \NilPortugues\SchemaOrg\Properties\HasMapProperty hasMap() * @method static \NilPortugues\SchemaOrg\Properties\MapProperty map() * @method static \NilPortugues\SchemaOrg\Properties\MapsProperty maps() * @method static \NilPortugues\SchemaOrg\Properties\OpeningHoursSpecificationProperty openingHoursSpecification() * @method static \NilPortugues\SchemaOrg\Properties\PhotoProperty photo() * @method static \NilPortugues\SchemaOrg\Properties\PhotosProperty photos() * @method static \NilPortugues\SchemaOrg\Properties\AdditionalPropertyProperty additionalProperty() * METHODEND. * * An electrician. */ class Electrician extends SchemaClass { /** * @var string */ protected static $schemaUrl = 'http://schema.org/Electrician'; /** * @var array */ protected static $supportedMethods = [ 'additionalProperty' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalPropertyProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'additionalType' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AdditionalTypeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'address' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AddressProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'aggregateRating' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AggregateRatingProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'alternateName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlternateNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'alumni' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AlumniProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'areaServed' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AreaServedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'award' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AwardProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'awards' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\AwardsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'branchCode' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BranchCodeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'branchOf' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BranchOfProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'brand' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\BrandProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'contactPoint' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContactPointProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'contactPoints' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContactPointsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'containedIn' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainedInProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'containedInPlace' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainedInPlaceProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'containsPlace' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ContainsPlaceProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'currenciesAccepted' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\CurrenciesAcceptedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'department' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DepartmentProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'description' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DescriptionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'dissolutionDate' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DissolutionDateProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'duns' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\DunsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'email' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmailProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'employee' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmployeeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'employees' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EmployeesProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'event' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EventProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'events' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\EventsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'faxNumber' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FaxNumberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'founder' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FounderProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'founders' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FoundersProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'foundingDate' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\FoundingDateProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'geo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\GeoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'globalLocationNumber' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\GlobalLocationNumberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'hasMap' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasMapProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'hasOfferCatalog' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasOfferCatalogProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'hasPOS' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\HasPOSProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'image' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ImageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'isicV4' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\IsicV4Property', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'legalName' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LegalNameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'location' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LocationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'logo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\LogoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'mainEntityOfPage' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MainEntityOfPageProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'makesOffer' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MakesOfferProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'map' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MapProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'maps' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MapsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'member' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MemberProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'memberOf' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MemberOfProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'members' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\MembersProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'naics' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NaicsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'name' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NameProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'numberOfEmployees' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\NumberOfEmployeesProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'openingHours' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OpeningHoursProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'openingHoursSpecification' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OpeningHoursSpecificationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'owns' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\OwnsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'parentOrganization' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ParentOrganizationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'paymentAccepted' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PaymentAcceptedProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'photo' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PhotoProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'photos' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PhotosProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'potentialAction' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PotentialActionProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'priceRange' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\PriceRangeProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\LocalBusiness', ], 'review' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ReviewProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'reviews' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ReviewsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'sameAs' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SameAsProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'seeks' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SeeksProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'serviceArea' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\ServiceAreaProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'subOrganization' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\SubOrganizationProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'taxID' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\TaxIDProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], 'telephone' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\TelephoneProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Place', ], 'url' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\UrlProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Thing', ], 'vatID' => [ 'propertyClass' => '\NilPortugues\SchemaOrg\Properties\VatIDProperty', 'schemaClass' => '\NilPortugues\SchemaOrg\Classes\Organization', ], ]; }
nilportugues/schema.org-mapping
src/Classes/Electrician.php
PHP
mit
20,303
/* micropolisJS. Adapted by Graeme McCutcheon from Micropolis. * * This code is released under the GNU GPL v3, with some additional terms. * Please see the files LICENSE and COPYING for details. Alternatively, * consult http://micropolisjs.graememcc.co.uk/LICENSE and * http://micropolisjs.graememcc.co.uk/COPYING * */ Micro.GameTools = function (map) { return { airport: new Micro.BuildingTool(10000, Tile.AIRPORT, map, 6, false), bulldozer: new Micro.BulldozerTool(map), coal: new Micro.BuildingTool(3000, Tile.POWERPLANT, map, 4, false), commercial: new Micro.BuildingTool(100, Tile.COMCLR, map, 3, false), fire: new Micro.BuildingTool(500, Tile.FIRESTATION, map, 3, false), industrial: new Micro.BuildingTool(100, Tile.INDCLR, map, 3, false), nuclear: new Micro.BuildingTool(5000, Tile.NUCLEAR, map, 4, true), park: new Micro.ParkTool(map), police: new Micro.BuildingTool(500, Tile.POLICESTATION, map, 3, false), port: new Micro.BuildingTool(3000, Tile.PORT, map, 4, false), rail: new Micro.RailTool(map), residential: new Micro.BuildingTool(100, Tile.FREEZ, map, 3, false), road: new Micro.RoadTool(map), query: new Micro.QueryTool(map), stadium: new Micro.BuildingTool(5000, Tile.STADIUM, map, 4, false), wire: new Micro.WireTool(map), }; };
ArcherSys/ArcherSys
game/3d.city-gh-pages/src/tool/GameTools.js
JavaScript
mit
1,390
/**************************************************************************************** Copyright (C) 2013 Autodesk, Inc. All rights reserved. Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ****************************************************************************************/ //! \file fbxstatus.h #ifndef _FBXSDK_CORE_BASE_STATUS_H_ #define _FBXSDK_CORE_BASE_STATUS_H_ #include <fbxsdk/fbxsdk_def.h> #include <fbxsdk/core/base/fbxstring.h> #include <fbxsdk/fbxsdk_nsbegin.h> /** This class facilitates the testing/reporting of errors. It encapsulates the * status code and the internal FBXSDK error code as returned by the API functions. * \nosubgrouping */ class FBXSDK_DLL FbxStatus { public: //! Available status codes. enum EStatusCode { eSuccess = 0, //!< Operation was successful eFailure, //!< Operation failed eInsufficientMemory, //!< Operation failed due to insufficient memory eInvalidParameter, //!< An invalid parameter was provided eIndexOutOfRange, //!< Index value outside the valid range ePasswordError, //!< Operation on FBX file password failed eInvalidFileVersion, //!< File version not supported (anymore or yet) eInvalidFile //!< Operation on the file access failed }; //! Default constructor. FbxStatus(); FbxStatus(EStatusCode pCode); FbxStatus(const FbxStatus& rhs); FbxStatus& operator=(const FbxStatus& rhs); /** Equivalence operator. * \param rhs Status object to compare. * \return \c True if all the members of \e rhs are equal to this instance members and \c False otherwise. */ bool operator==(const FbxStatus& rhs) const { return (mCode == rhs.mCode); } /** Equivalence operator. * \param pCode Status code to compare. * \return \c True if the code member of this instance equals \e pCode and \c False otherwise. */ bool operator==(const EStatusCode pCode) const { return (mCode == pCode); } /** Non-Equivalence operator. * \param rhs Status object to compare. * \return \c True if at least one member of \e rhs is not equal to this instance member and \c True otherwise. */ bool operator!=(const FbxStatus& rhs) const { return (mCode != rhs.mCode); } /** Non-Equivalence operator. * \param rhs Status code to compare. * \return \c True if the code member of this instance equals \e rhs and \c False otherwise. */ bool operator!=(const EStatusCode rhs) const { return (mCode != rhs); } /** The conversion operator that converts a FbxStatus object to bool. * The result it returns will be \c True if the FbxStatus does not contain * an error, and \c False if it does. */ operator bool() const { return mCode==eSuccess; } /** Determines whether there is an error. * \return \c True if an error occured and \c False if the operation was sucessful. */ bool Error() const { return !this->operator bool(); } //! Clear error code and message from the instance. After this call, it will behave as if it contained eSuccess. void Clear(); //! Retrieve the type of error that occurred, as specified in the enumeration. EStatusCode GetCode() const { return mCode; } /** Change the current code of the instance. * \param rhs New code value. */ void SetCode(const EStatusCode rhs); /** Change the current code of the instance. * \param rhs New code value. * \param pErrorMsg Optional error description string. This string can have formatting characters * The function will use the vsnprintf function to assemble the final string * using an internal buffer of 4096 characters. */ void SetCode(const EStatusCode rhs, const char* pErrorMsg, ...); //! Get the error message string corresponding to the current code. const char* GetErrorString() const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS private: EStatusCode mCode; FbxString mErrorString; #endif /* !DOXYGEN_SHOULD_SKIP_THIS */ }; #include <fbxsdk/fbxsdk_nsend.h> #endif /* _FBXSDK_CORE_BASE_STATUS_H_ */
VajraFramework/PipelineTools
FbxExporter/Source/FbxSdk/include/fbxsdk/core/base/fbxstatus.h
C
mit
5,198
export { default as createShallow } from './createShallow'; export { default as createMount } from './createMount'; export { default as createRender } from './createRender'; export { default as findOutermostIntrinsic, wrapsIntrinsicElement } from './findOutermostIntrinsic'; export { default as getClasses } from './getClasses'; export { default as unwrap } from './unwrap';
lgollut/material-ui
packages/material-ui/src/test-utils/index.js
JavaScript
mit
375
var expect = require("chai").expect; var reindeerRace = require("../../src/day-14/reindeer-race"); describe("--- Day 14: (1/2) distance traveled --- ", () => { it("counts the distance traveled after 1000s", () => { var reindeerSpecs = [ "Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.", "Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds." ]; expect(reindeerRace.race(reindeerSpecs, 1000).winnerByDistance.distanceTraveled).to.equal(1120); }); }); describe("--- Day 14: (2/2) points awarded --- ", () => { it("counts the points awarded for being in the lead after 1000s", () => { var reindeerSpecs = [ "Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.", "Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds." ]; expect(reindeerRace.race(reindeerSpecs, 1000).winnerByPoints.pointsAwarded).to.equal(689); }); });
gbranchaudrubenovitch/advent-of-code
test/day-14/reindeer-race-test.js
JavaScript
mit
969
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var jsdom = require("jsdom"); var chai_1 = require("chai"); var ColorManager_1 = require("./ColorManager"); describe('ColorManager', function () { var cm; var dom; var document; var window; beforeEach(function () { dom = new jsdom.JSDOM(''); window = dom.window; document = window.document; window.HTMLCanvasElement.prototype.getContext = function () { return ({ createLinearGradient: function () { return null; }, fillRect: function () { }, getImageData: function () { return { data: [0, 0, 0, 0xFF] }; } }); }; cm = new ColorManager_1.ColorManager(document, false); }); describe('constructor', function () { it('should fill all colors with values', function () { for (var _i = 0, _a = Object.keys(cm.colors); _i < _a.length; _i++) { var key = _a[_i]; if (key !== 'ansi') { chai_1.assert.ok(cm.colors[key].css.length >= 7); } } chai_1.assert.equal(cm.colors.ansi.length, 256); }); it('should fill 240 colors with expected values', function () { chai_1.assert.equal(cm.colors.ansi[16].css, '#000000'); chai_1.assert.equal(cm.colors.ansi[17].css, '#00005f'); chai_1.assert.equal(cm.colors.ansi[18].css, '#000087'); chai_1.assert.equal(cm.colors.ansi[19].css, '#0000af'); chai_1.assert.equal(cm.colors.ansi[20].css, '#0000d7'); chai_1.assert.equal(cm.colors.ansi[21].css, '#0000ff'); chai_1.assert.equal(cm.colors.ansi[22].css, '#005f00'); chai_1.assert.equal(cm.colors.ansi[23].css, '#005f5f'); chai_1.assert.equal(cm.colors.ansi[24].css, '#005f87'); chai_1.assert.equal(cm.colors.ansi[25].css, '#005faf'); chai_1.assert.equal(cm.colors.ansi[26].css, '#005fd7'); chai_1.assert.equal(cm.colors.ansi[27].css, '#005fff'); chai_1.assert.equal(cm.colors.ansi[28].css, '#008700'); chai_1.assert.equal(cm.colors.ansi[29].css, '#00875f'); chai_1.assert.equal(cm.colors.ansi[30].css, '#008787'); chai_1.assert.equal(cm.colors.ansi[31].css, '#0087af'); chai_1.assert.equal(cm.colors.ansi[32].css, '#0087d7'); chai_1.assert.equal(cm.colors.ansi[33].css, '#0087ff'); chai_1.assert.equal(cm.colors.ansi[34].css, '#00af00'); chai_1.assert.equal(cm.colors.ansi[35].css, '#00af5f'); chai_1.assert.equal(cm.colors.ansi[36].css, '#00af87'); chai_1.assert.equal(cm.colors.ansi[37].css, '#00afaf'); chai_1.assert.equal(cm.colors.ansi[38].css, '#00afd7'); chai_1.assert.equal(cm.colors.ansi[39].css, '#00afff'); chai_1.assert.equal(cm.colors.ansi[40].css, '#00d700'); chai_1.assert.equal(cm.colors.ansi[41].css, '#00d75f'); chai_1.assert.equal(cm.colors.ansi[42].css, '#00d787'); chai_1.assert.equal(cm.colors.ansi[43].css, '#00d7af'); chai_1.assert.equal(cm.colors.ansi[44].css, '#00d7d7'); chai_1.assert.equal(cm.colors.ansi[45].css, '#00d7ff'); chai_1.assert.equal(cm.colors.ansi[46].css, '#00ff00'); chai_1.assert.equal(cm.colors.ansi[47].css, '#00ff5f'); chai_1.assert.equal(cm.colors.ansi[48].css, '#00ff87'); chai_1.assert.equal(cm.colors.ansi[49].css, '#00ffaf'); chai_1.assert.equal(cm.colors.ansi[50].css, '#00ffd7'); chai_1.assert.equal(cm.colors.ansi[51].css, '#00ffff'); chai_1.assert.equal(cm.colors.ansi[52].css, '#5f0000'); chai_1.assert.equal(cm.colors.ansi[53].css, '#5f005f'); chai_1.assert.equal(cm.colors.ansi[54].css, '#5f0087'); chai_1.assert.equal(cm.colors.ansi[55].css, '#5f00af'); chai_1.assert.equal(cm.colors.ansi[56].css, '#5f00d7'); chai_1.assert.equal(cm.colors.ansi[57].css, '#5f00ff'); chai_1.assert.equal(cm.colors.ansi[58].css, '#5f5f00'); chai_1.assert.equal(cm.colors.ansi[59].css, '#5f5f5f'); chai_1.assert.equal(cm.colors.ansi[60].css, '#5f5f87'); chai_1.assert.equal(cm.colors.ansi[61].css, '#5f5faf'); chai_1.assert.equal(cm.colors.ansi[62].css, '#5f5fd7'); chai_1.assert.equal(cm.colors.ansi[63].css, '#5f5fff'); chai_1.assert.equal(cm.colors.ansi[64].css, '#5f8700'); chai_1.assert.equal(cm.colors.ansi[65].css, '#5f875f'); chai_1.assert.equal(cm.colors.ansi[66].css, '#5f8787'); chai_1.assert.equal(cm.colors.ansi[67].css, '#5f87af'); chai_1.assert.equal(cm.colors.ansi[68].css, '#5f87d7'); chai_1.assert.equal(cm.colors.ansi[69].css, '#5f87ff'); chai_1.assert.equal(cm.colors.ansi[70].css, '#5faf00'); chai_1.assert.equal(cm.colors.ansi[71].css, '#5faf5f'); chai_1.assert.equal(cm.colors.ansi[72].css, '#5faf87'); chai_1.assert.equal(cm.colors.ansi[73].css, '#5fafaf'); chai_1.assert.equal(cm.colors.ansi[74].css, '#5fafd7'); chai_1.assert.equal(cm.colors.ansi[75].css, '#5fafff'); chai_1.assert.equal(cm.colors.ansi[76].css, '#5fd700'); chai_1.assert.equal(cm.colors.ansi[77].css, '#5fd75f'); chai_1.assert.equal(cm.colors.ansi[78].css, '#5fd787'); chai_1.assert.equal(cm.colors.ansi[79].css, '#5fd7af'); chai_1.assert.equal(cm.colors.ansi[80].css, '#5fd7d7'); chai_1.assert.equal(cm.colors.ansi[81].css, '#5fd7ff'); chai_1.assert.equal(cm.colors.ansi[82].css, '#5fff00'); chai_1.assert.equal(cm.colors.ansi[83].css, '#5fff5f'); chai_1.assert.equal(cm.colors.ansi[84].css, '#5fff87'); chai_1.assert.equal(cm.colors.ansi[85].css, '#5fffaf'); chai_1.assert.equal(cm.colors.ansi[86].css, '#5fffd7'); chai_1.assert.equal(cm.colors.ansi[87].css, '#5fffff'); chai_1.assert.equal(cm.colors.ansi[88].css, '#870000'); chai_1.assert.equal(cm.colors.ansi[89].css, '#87005f'); chai_1.assert.equal(cm.colors.ansi[90].css, '#870087'); chai_1.assert.equal(cm.colors.ansi[91].css, '#8700af'); chai_1.assert.equal(cm.colors.ansi[92].css, '#8700d7'); chai_1.assert.equal(cm.colors.ansi[93].css, '#8700ff'); chai_1.assert.equal(cm.colors.ansi[94].css, '#875f00'); chai_1.assert.equal(cm.colors.ansi[95].css, '#875f5f'); chai_1.assert.equal(cm.colors.ansi[96].css, '#875f87'); chai_1.assert.equal(cm.colors.ansi[97].css, '#875faf'); chai_1.assert.equal(cm.colors.ansi[98].css, '#875fd7'); chai_1.assert.equal(cm.colors.ansi[99].css, '#875fff'); chai_1.assert.equal(cm.colors.ansi[100].css, '#878700'); chai_1.assert.equal(cm.colors.ansi[101].css, '#87875f'); chai_1.assert.equal(cm.colors.ansi[102].css, '#878787'); chai_1.assert.equal(cm.colors.ansi[103].css, '#8787af'); chai_1.assert.equal(cm.colors.ansi[104].css, '#8787d7'); chai_1.assert.equal(cm.colors.ansi[105].css, '#8787ff'); chai_1.assert.equal(cm.colors.ansi[106].css, '#87af00'); chai_1.assert.equal(cm.colors.ansi[107].css, '#87af5f'); chai_1.assert.equal(cm.colors.ansi[108].css, '#87af87'); chai_1.assert.equal(cm.colors.ansi[109].css, '#87afaf'); chai_1.assert.equal(cm.colors.ansi[110].css, '#87afd7'); chai_1.assert.equal(cm.colors.ansi[111].css, '#87afff'); chai_1.assert.equal(cm.colors.ansi[112].css, '#87d700'); chai_1.assert.equal(cm.colors.ansi[113].css, '#87d75f'); chai_1.assert.equal(cm.colors.ansi[114].css, '#87d787'); chai_1.assert.equal(cm.colors.ansi[115].css, '#87d7af'); chai_1.assert.equal(cm.colors.ansi[116].css, '#87d7d7'); chai_1.assert.equal(cm.colors.ansi[117].css, '#87d7ff'); chai_1.assert.equal(cm.colors.ansi[118].css, '#87ff00'); chai_1.assert.equal(cm.colors.ansi[119].css, '#87ff5f'); chai_1.assert.equal(cm.colors.ansi[120].css, '#87ff87'); chai_1.assert.equal(cm.colors.ansi[121].css, '#87ffaf'); chai_1.assert.equal(cm.colors.ansi[122].css, '#87ffd7'); chai_1.assert.equal(cm.colors.ansi[123].css, '#87ffff'); chai_1.assert.equal(cm.colors.ansi[124].css, '#af0000'); chai_1.assert.equal(cm.colors.ansi[125].css, '#af005f'); chai_1.assert.equal(cm.colors.ansi[126].css, '#af0087'); chai_1.assert.equal(cm.colors.ansi[127].css, '#af00af'); chai_1.assert.equal(cm.colors.ansi[128].css, '#af00d7'); chai_1.assert.equal(cm.colors.ansi[129].css, '#af00ff'); chai_1.assert.equal(cm.colors.ansi[130].css, '#af5f00'); chai_1.assert.equal(cm.colors.ansi[131].css, '#af5f5f'); chai_1.assert.equal(cm.colors.ansi[132].css, '#af5f87'); chai_1.assert.equal(cm.colors.ansi[133].css, '#af5faf'); chai_1.assert.equal(cm.colors.ansi[134].css, '#af5fd7'); chai_1.assert.equal(cm.colors.ansi[135].css, '#af5fff'); chai_1.assert.equal(cm.colors.ansi[136].css, '#af8700'); chai_1.assert.equal(cm.colors.ansi[137].css, '#af875f'); chai_1.assert.equal(cm.colors.ansi[138].css, '#af8787'); chai_1.assert.equal(cm.colors.ansi[139].css, '#af87af'); chai_1.assert.equal(cm.colors.ansi[140].css, '#af87d7'); chai_1.assert.equal(cm.colors.ansi[141].css, '#af87ff'); chai_1.assert.equal(cm.colors.ansi[142].css, '#afaf00'); chai_1.assert.equal(cm.colors.ansi[143].css, '#afaf5f'); chai_1.assert.equal(cm.colors.ansi[144].css, '#afaf87'); chai_1.assert.equal(cm.colors.ansi[145].css, '#afafaf'); chai_1.assert.equal(cm.colors.ansi[146].css, '#afafd7'); chai_1.assert.equal(cm.colors.ansi[147].css, '#afafff'); chai_1.assert.equal(cm.colors.ansi[148].css, '#afd700'); chai_1.assert.equal(cm.colors.ansi[149].css, '#afd75f'); chai_1.assert.equal(cm.colors.ansi[150].css, '#afd787'); chai_1.assert.equal(cm.colors.ansi[151].css, '#afd7af'); chai_1.assert.equal(cm.colors.ansi[152].css, '#afd7d7'); chai_1.assert.equal(cm.colors.ansi[153].css, '#afd7ff'); chai_1.assert.equal(cm.colors.ansi[154].css, '#afff00'); chai_1.assert.equal(cm.colors.ansi[155].css, '#afff5f'); chai_1.assert.equal(cm.colors.ansi[156].css, '#afff87'); chai_1.assert.equal(cm.colors.ansi[157].css, '#afffaf'); chai_1.assert.equal(cm.colors.ansi[158].css, '#afffd7'); chai_1.assert.equal(cm.colors.ansi[159].css, '#afffff'); chai_1.assert.equal(cm.colors.ansi[160].css, '#d70000'); chai_1.assert.equal(cm.colors.ansi[161].css, '#d7005f'); chai_1.assert.equal(cm.colors.ansi[162].css, '#d70087'); chai_1.assert.equal(cm.colors.ansi[163].css, '#d700af'); chai_1.assert.equal(cm.colors.ansi[164].css, '#d700d7'); chai_1.assert.equal(cm.colors.ansi[165].css, '#d700ff'); chai_1.assert.equal(cm.colors.ansi[166].css, '#d75f00'); chai_1.assert.equal(cm.colors.ansi[167].css, '#d75f5f'); chai_1.assert.equal(cm.colors.ansi[168].css, '#d75f87'); chai_1.assert.equal(cm.colors.ansi[169].css, '#d75faf'); chai_1.assert.equal(cm.colors.ansi[170].css, '#d75fd7'); chai_1.assert.equal(cm.colors.ansi[171].css, '#d75fff'); chai_1.assert.equal(cm.colors.ansi[172].css, '#d78700'); chai_1.assert.equal(cm.colors.ansi[173].css, '#d7875f'); chai_1.assert.equal(cm.colors.ansi[174].css, '#d78787'); chai_1.assert.equal(cm.colors.ansi[175].css, '#d787af'); chai_1.assert.equal(cm.colors.ansi[176].css, '#d787d7'); chai_1.assert.equal(cm.colors.ansi[177].css, '#d787ff'); chai_1.assert.equal(cm.colors.ansi[178].css, '#d7af00'); chai_1.assert.equal(cm.colors.ansi[179].css, '#d7af5f'); chai_1.assert.equal(cm.colors.ansi[180].css, '#d7af87'); chai_1.assert.equal(cm.colors.ansi[181].css, '#d7afaf'); chai_1.assert.equal(cm.colors.ansi[182].css, '#d7afd7'); chai_1.assert.equal(cm.colors.ansi[183].css, '#d7afff'); chai_1.assert.equal(cm.colors.ansi[184].css, '#d7d700'); chai_1.assert.equal(cm.colors.ansi[185].css, '#d7d75f'); chai_1.assert.equal(cm.colors.ansi[186].css, '#d7d787'); chai_1.assert.equal(cm.colors.ansi[187].css, '#d7d7af'); chai_1.assert.equal(cm.colors.ansi[188].css, '#d7d7d7'); chai_1.assert.equal(cm.colors.ansi[189].css, '#d7d7ff'); chai_1.assert.equal(cm.colors.ansi[190].css, '#d7ff00'); chai_1.assert.equal(cm.colors.ansi[191].css, '#d7ff5f'); chai_1.assert.equal(cm.colors.ansi[192].css, '#d7ff87'); chai_1.assert.equal(cm.colors.ansi[193].css, '#d7ffaf'); chai_1.assert.equal(cm.colors.ansi[194].css, '#d7ffd7'); chai_1.assert.equal(cm.colors.ansi[195].css, '#d7ffff'); chai_1.assert.equal(cm.colors.ansi[196].css, '#ff0000'); chai_1.assert.equal(cm.colors.ansi[197].css, '#ff005f'); chai_1.assert.equal(cm.colors.ansi[198].css, '#ff0087'); chai_1.assert.equal(cm.colors.ansi[199].css, '#ff00af'); chai_1.assert.equal(cm.colors.ansi[200].css, '#ff00d7'); chai_1.assert.equal(cm.colors.ansi[201].css, '#ff00ff'); chai_1.assert.equal(cm.colors.ansi[202].css, '#ff5f00'); chai_1.assert.equal(cm.colors.ansi[203].css, '#ff5f5f'); chai_1.assert.equal(cm.colors.ansi[204].css, '#ff5f87'); chai_1.assert.equal(cm.colors.ansi[205].css, '#ff5faf'); chai_1.assert.equal(cm.colors.ansi[206].css, '#ff5fd7'); chai_1.assert.equal(cm.colors.ansi[207].css, '#ff5fff'); chai_1.assert.equal(cm.colors.ansi[208].css, '#ff8700'); chai_1.assert.equal(cm.colors.ansi[209].css, '#ff875f'); chai_1.assert.equal(cm.colors.ansi[210].css, '#ff8787'); chai_1.assert.equal(cm.colors.ansi[211].css, '#ff87af'); chai_1.assert.equal(cm.colors.ansi[212].css, '#ff87d7'); chai_1.assert.equal(cm.colors.ansi[213].css, '#ff87ff'); chai_1.assert.equal(cm.colors.ansi[214].css, '#ffaf00'); chai_1.assert.equal(cm.colors.ansi[215].css, '#ffaf5f'); chai_1.assert.equal(cm.colors.ansi[216].css, '#ffaf87'); chai_1.assert.equal(cm.colors.ansi[217].css, '#ffafaf'); chai_1.assert.equal(cm.colors.ansi[218].css, '#ffafd7'); chai_1.assert.equal(cm.colors.ansi[219].css, '#ffafff'); chai_1.assert.equal(cm.colors.ansi[220].css, '#ffd700'); chai_1.assert.equal(cm.colors.ansi[221].css, '#ffd75f'); chai_1.assert.equal(cm.colors.ansi[222].css, '#ffd787'); chai_1.assert.equal(cm.colors.ansi[223].css, '#ffd7af'); chai_1.assert.equal(cm.colors.ansi[224].css, '#ffd7d7'); chai_1.assert.equal(cm.colors.ansi[225].css, '#ffd7ff'); chai_1.assert.equal(cm.colors.ansi[226].css, '#ffff00'); chai_1.assert.equal(cm.colors.ansi[227].css, '#ffff5f'); chai_1.assert.equal(cm.colors.ansi[228].css, '#ffff87'); chai_1.assert.equal(cm.colors.ansi[229].css, '#ffffaf'); chai_1.assert.equal(cm.colors.ansi[230].css, '#ffffd7'); chai_1.assert.equal(cm.colors.ansi[231].css, '#ffffff'); chai_1.assert.equal(cm.colors.ansi[232].css, '#080808'); chai_1.assert.equal(cm.colors.ansi[233].css, '#121212'); chai_1.assert.equal(cm.colors.ansi[234].css, '#1c1c1c'); chai_1.assert.equal(cm.colors.ansi[235].css, '#262626'); chai_1.assert.equal(cm.colors.ansi[236].css, '#303030'); chai_1.assert.equal(cm.colors.ansi[237].css, '#3a3a3a'); chai_1.assert.equal(cm.colors.ansi[238].css, '#444444'); chai_1.assert.equal(cm.colors.ansi[239].css, '#4e4e4e'); chai_1.assert.equal(cm.colors.ansi[240].css, '#585858'); chai_1.assert.equal(cm.colors.ansi[241].css, '#626262'); chai_1.assert.equal(cm.colors.ansi[242].css, '#6c6c6c'); chai_1.assert.equal(cm.colors.ansi[243].css, '#767676'); chai_1.assert.equal(cm.colors.ansi[244].css, '#808080'); chai_1.assert.equal(cm.colors.ansi[245].css, '#8a8a8a'); chai_1.assert.equal(cm.colors.ansi[246].css, '#949494'); chai_1.assert.equal(cm.colors.ansi[247].css, '#9e9e9e'); chai_1.assert.equal(cm.colors.ansi[248].css, '#a8a8a8'); chai_1.assert.equal(cm.colors.ansi[249].css, '#b2b2b2'); chai_1.assert.equal(cm.colors.ansi[250].css, '#bcbcbc'); chai_1.assert.equal(cm.colors.ansi[251].css, '#c6c6c6'); chai_1.assert.equal(cm.colors.ansi[252].css, '#d0d0d0'); chai_1.assert.equal(cm.colors.ansi[253].css, '#dadada'); chai_1.assert.equal(cm.colors.ansi[254].css, '#e4e4e4'); chai_1.assert.equal(cm.colors.ansi[255].css, '#eeeeee'); }); }); describe('setTheme', function () { it('should not throw when not setting all colors', function () { chai_1.assert.doesNotThrow(function () { cm.setTheme({}); }); }); it('should set a partial set of colors, using the default if not present', function () { chai_1.assert.equal(cm.colors.background.css, '#000000'); chai_1.assert.equal(cm.colors.foreground.css, '#ffffff'); cm.setTheme({ background: '#FF0000', foreground: '#00FF00' }); chai_1.assert.equal(cm.colors.background.css, '#FF0000'); chai_1.assert.equal(cm.colors.foreground.css, '#00FF00'); cm.setTheme({ background: '#0000FF' }); chai_1.assert.equal(cm.colors.background.css, '#0000FF'); chai_1.assert.equal(cm.colors.foreground.css, '#ffffff'); }); }); }); //# sourceMappingURL=ColorManager.test.js.map
SpawnTree/SpawnTree.github.io
js/xterm/lib/renderer/ColorManager.test.js
JavaScript
mit
18,828
/** * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint maxlen: false */ 'use strict'; var createAPIRequest = require('../../lib/apirequest'); /** * Admin Directory API * * @classdesc The Admin SDK Directory API lets you view and manage enterprise resources such as users and groups, administrative notifications, security features, and more. * @namespace admin * @version directory_v1 * @variation directory_v1 * @this Admin * @param {object=} options Options for Admin */ function Admin(options) { var self = this; this._options = options || {}; this.asps = { /** * directory.asps.delete * * @desc Delete an ASP issued by a user. * * @alias directory.asps.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {integer} params.codeId - The unique ID of the ASP to be deleted. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}', method: 'DELETE' }, params: params, requiredParams: ['userKey', 'codeId'], pathParams: ['codeId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.asps.get * * @desc Get information about an ASP issued by a user. * * @alias directory.asps.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {integer} params.codeId - The unique ID of the ASP. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps/{codeId}', method: 'GET' }, params: params, requiredParams: ['userKey', 'codeId'], pathParams: ['codeId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.asps.list * * @desc List the ASPs issued by a user. * * @alias directory.asps.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/asps', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.channels = { /** * admin.channels.stop * * @desc Stop watching resources through this channel * * @alias admin.channels.stop * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ stop: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/admin/directory_v1/channels/stop', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); } }; this.chromeosdevices = { /** * directory.chromeosdevices.get * * @desc Retrieve Chrome OS Device * * @alias directory.chromeosdevices.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.deviceId - Immutable id of Chrome OS Device * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}', method: 'GET' }, params: params, requiredParams: ['customerId', 'deviceId'], pathParams: ['customerId', 'deviceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.chromeosdevices.list * * @desc Retrieve all Chrome OS Devices of a customer (paginated) * * @alias directory.chromeosdevices.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {string=} params.query - Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333 * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.chromeosdevices.patch * * @desc Update Chrome OS Device. This method supports patch semantics. * * @alias directory.chromeosdevices.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.deviceId - Immutable id of Chrome OS Device * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}', method: 'PATCH' }, params: params, requiredParams: ['customerId', 'deviceId'], pathParams: ['customerId', 'deviceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.chromeosdevices.update * * @desc Update Chrome OS Device * * @alias directory.chromeosdevices.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.deviceId - Immutable id of Chrome OS Device * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/chromeos/{deviceId}', method: 'PUT' }, params: params, requiredParams: ['customerId', 'deviceId'], pathParams: ['customerId', 'deviceId'], context: self }; return createAPIRequest(parameters, callback); } }; this.groups = { /** * directory.groups.delete * * @desc Delete Group * * @alias directory.groups.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'DELETE' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.get * * @desc Retrieve Group * * @alias directory.groups.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'GET' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.insert * * @desc Create Group * * @alias directory.groups.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.list * * @desc Retrieve all groups in a domain (paginated) * * @alias directory.groups.list * @memberOf! admin(directory_v1) * * @param {object=} params - Parameters for request * @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain. * @param {string=} params.domain - Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead. * @param {integer=} params.maxResults - Maximum number of results to return. Default is 200 * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.userKey - Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups', method: 'GET' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.patch * * @desc Update Group. This method supports patch semantics. * * @alias directory.groups.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'PATCH' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.update * * @desc Update Group * * @alias directory.groups.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}', method: 'PUT' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, aliases: { /** * directory.groups.aliases.delete * * @desc Remove a alias for the group * * @alias directory.groups.aliases.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.alias - The alias to be removed * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases/{alias}', method: 'DELETE' }, params: params, requiredParams: ['groupKey', 'alias'], pathParams: ['alias', 'groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.aliases.insert * * @desc Add a alias for the group * * @alias directory.groups.aliases.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases', method: 'POST' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.groups.aliases.list * * @desc List all aliases for a group * * @alias directory.groups.aliases.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/aliases', method: 'GET' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); } } }; this.members = { /** * directory.members.delete * * @desc Remove membership. * * @alias directory.members.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {string} params.memberKey - Email or immutable Id of the member * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'DELETE' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.get * * @desc Retrieve Group Member * * @alias directory.members.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {string} params.memberKey - Email or immutable Id of the member * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'GET' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.insert * * @desc Add user to the specified group. * * @alias directory.members.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members', method: 'POST' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.list * * @desc Retrieve all members in a group (paginated) * * @alias directory.members.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group * @param {integer=} params.maxResults - Maximum number of results to return. Default is 200 * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.roles - Comma separated role values to filter list results on. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members', method: 'GET' }, params: params, requiredParams: ['groupKey'], pathParams: ['groupKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.patch * * @desc Update membership of a user in the specified group. This method supports patch semantics. * * @alias directory.members.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {string} params.memberKey - Email or immutable Id of the user. If Id, it should match with id of member object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'PATCH' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.members.update * * @desc Update membership of a user in the specified group. * * @alias directory.members.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.groupKey - Email or immutable Id of the group. If Id, it should match with id of group object * @param {string} params.memberKey - Email or immutable Id of the user. If Id, it should match with id of member object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/groups/{groupKey}/members/{memberKey}', method: 'PUT' }, params: params, requiredParams: ['groupKey', 'memberKey'], pathParams: ['groupKey', 'memberKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.mobiledevices = { /** * directory.mobiledevices.action * * @desc Take action on Mobile Device * * @alias directory.mobiledevices.action * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.resourceId - Immutable id of Mobile Device * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ action: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}/action', method: 'POST' }, params: params, requiredParams: ['customerId', 'resourceId'], pathParams: ['customerId', 'resourceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.mobiledevices.delete * * @desc Delete Mobile Device * * @alias directory.mobiledevices.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.resourceId - Immutable id of Mobile Device * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}', method: 'DELETE' }, params: params, requiredParams: ['customerId', 'resourceId'], pathParams: ['customerId', 'resourceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.mobiledevices.get * * @desc Retrieve Mobile Device * * @alias directory.mobiledevices.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {string} params.resourceId - Immutable id of Mobile Device * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile/{resourceId}', method: 'GET' }, params: params, requiredParams: ['customerId', 'resourceId'], pathParams: ['customerId', 'resourceId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.mobiledevices.list * * @desc Retrieve all Mobile Devices of a customer (paginated) * * @alias directory.mobiledevices.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - Restrict information returned to a set of selected fields. * @param {string=} params.query - Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/devices/mobile', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); } }; this.notifications = { /** * directory.notifications.delete * * @desc Deletes a notification * * @alias directory.notifications.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. * @param {string} params.notificationId - The unique ID of the notification. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'DELETE' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.get * * @desc Retrieves a notification. * * @alias directory.notifications.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource. * @param {string} params.notificationId - The unique ID of the notification. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'GET' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.list * * @desc Retrieves a list of notifications. * * @alias directory.notifications.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. * @param {string=} params.language - The ISO 639-1 code of the language notifications are returned in. The default is English (en). * @param {integer=} params.maxResults - Maximum number of notifications to return per page. The default is 100. * @param {string=} params.pageToken - The token to specify the page of results to retrieve. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications', method: 'GET' }, params: params, requiredParams: ['customer'], pathParams: ['customer'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.patch * * @desc Updates a notification. This method supports patch semantics. * * @alias directory.notifications.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. * @param {string} params.notificationId - The unique ID of the notification. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'PATCH' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.notifications.update * * @desc Updates a notification. * * @alias directory.notifications.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customer - The unique ID for the customer's Google account. * @param {string} params.notificationId - The unique ID of the notification. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customer}/notifications/{notificationId}', method: 'PUT' }, params: params, requiredParams: ['customer', 'notificationId'], pathParams: ['customer', 'notificationId'], context: self }; return createAPIRequest(parameters, callback); } }; this.orgunits = { /** * directory.orgunits.delete * * @desc Remove Organization Unit * * @alias directory.orgunits.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'DELETE' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.get * * @desc Retrieve Organization Unit * * @alias directory.orgunits.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'GET' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.insert * * @desc Add Organization Unit * * @alias directory.orgunits.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits', method: 'POST' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.list * * @desc Retrieve all Organization Units * * @alias directory.orgunits.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string=} params.orgUnitPath - the URL-encoded organization unit * @param {string=} params.type - Whether to return all sub-organizations or just immediate children * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.patch * * @desc Update Organization Unit. This method supports patch semantics. * * @alias directory.orgunits.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'PATCH' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.orgunits.update * * @desc Update Organization Unit * * @alias directory.orgunits.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.orgUnitPath - Full path of the organization unit * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/orgunits/{orgUnitPath}', method: 'PUT' }, params: params, requiredParams: ['customerId', 'orgUnitPath'], pathParams: ['customerId', 'orgUnitPath'], context: self }; return createAPIRequest(parameters, callback); } }; this.schemas = { /** * directory.schemas.delete * * @desc Delete schema * * @alias directory.schemas.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'DELETE' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.get * * @desc Retrieve schema * * @alias directory.schemas.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'GET' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.insert * * @desc Create schema. * * @alias directory.schemas.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas', method: 'POST' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.list * * @desc Retrieve all schemas for a customer * * @alias directory.schemas.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas', method: 'GET' }, params: params, requiredParams: ['customerId'], pathParams: ['customerId'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.patch * * @desc Update schema. This method supports patch semantics. * * @alias directory.schemas.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'PATCH' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.schemas.update * * @desc Update schema * * @alias directory.schemas.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.customerId - Immutable id of the Google Apps account * @param {string} params.schemaKey - Name or immutable Id of the schema. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/customer/{customerId}/schemas/{schemaKey}', method: 'PUT' }, params: params, requiredParams: ['customerId', 'schemaKey'], pathParams: ['customerId', 'schemaKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.tokens = { /** * directory.tokens.delete * * @desc Delete all access tokens issued by a user for an application. * * @alias directory.tokens.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.clientId - The Client ID of the application the token is issued to. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}', method: 'DELETE' }, params: params, requiredParams: ['userKey', 'clientId'], pathParams: ['clientId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.tokens.get * * @desc Get information about an access token issued by a user. * * @alias directory.tokens.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.clientId - The Client ID of the application the token is issued to. * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens/{clientId}', method: 'GET' }, params: params, requiredParams: ['userKey', 'clientId'], pathParams: ['clientId', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.tokens.list * * @desc Returns the set of tokens specified user has issued to 3rd party applications. * * @alias directory.tokens.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/tokens', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }; this.users = { /** * directory.users.delete * * @desc Delete user * * @alias directory.users.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'DELETE' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.get * * @desc retrieve user * * @alias directory.users.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.projection - What subset of fields to fetch for this user. * @param {string} params.userKey - Email or immutable Id of the user * @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.insert * * @desc create user. * * @alias directory.users.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.list * * @desc Retrieve either deleted users or all users in a domain (paginated) * * @alias directory.users.list * @memberOf! admin(directory_v1) * * @param {object=} params - Parameters for request * @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. * @param {string=} params.domain - Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100. Max allowed is 500 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - What subset of fields to fetch for this user. * @param {string=} params.query - Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users * @param {string=} params.showDeleted - If set to true retrieves the list of deleted users. Default is false * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. * @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users', method: 'GET' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.makeAdmin * * @desc change admin status of a user * * @alias directory.users.makeAdmin * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user as admin * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ makeAdmin: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/makeAdmin', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.patch * * @desc update user. This method supports patch semantics. * * @alias directory.users.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user. If Id, it should match with id of user object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'PATCH' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.undelete * * @desc Undelete a deleted user * * @alias directory.users.undelete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - The immutable id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ undelete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/undelete', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.update * * @desc update user * * @alias directory.users.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user. If Id, it should match with id of user object * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}', method: 'PUT' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.watch * * @desc Watch for changes in users list * * @alias directory.users.watch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.customFieldMask - Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.customer - Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. * @param {string=} params.domain - Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {integer=} params.maxResults - Maximum number of results to return. Default is 100. Max allowed is 500 * @param {string=} params.orderBy - Column to use for sorting results * @param {string=} params.pageToken - Token to specify next page in the list * @param {string=} params.projection - What subset of fields to fetch for this user. * @param {string=} params.query - Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users * @param {string=} params.showDeleted - If set to true retrieves the list of deleted users. Default is false * @param {string=} params.sortOrder - Whether to return results in ascending or descending order. * @param {string=} params.viewType - Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/watch', method: 'POST' }, params: params, requiredParams: [], pathParams: [], context: self }; return createAPIRequest(parameters, callback); }, aliases: { /** * directory.users.aliases.delete * * @desc Remove a alias for the user * * @alias directory.users.aliases.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.alias - The alias to be removed * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/{alias}', method: 'DELETE' }, params: params, requiredParams: ['userKey', 'alias'], pathParams: ['alias', 'userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.aliases.insert * * @desc Add a alias for the user * * @alias directory.users.aliases.insert * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ insert: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.aliases.list * * @desc List all aliases for a user * * @alias directory.users.aliases.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.aliases.watch * * @desc Watch for changes in user aliases list * * @alias directory.users.aliases.watch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string=} params.event - Event on which subscription is intended (if subscribing) * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ watch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/aliases/watch', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }, photos: { /** * directory.users.photos.delete * * @desc Remove photos for the user * * @alias directory.users.photos.delete * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ delete: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'DELETE' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.photos.get * * @desc Retrieve photo of a user * * @alias directory.users.photos.get * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ get: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.photos.patch * * @desc Add a photo for the user. This method supports patch semantics. * * @alias directory.users.photos.patch * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ patch: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'PATCH' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.users.photos.update * * @desc Add a photo for the user * * @alias directory.users.photos.update * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {object} params.resource - Request body data * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ update: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/photos/thumbnail', method: 'PUT' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } } }; this.verificationCodes = { /** * directory.verificationCodes.generate * * @desc Generate new backup verification codes for the user. * * @alias directory.verificationCodes.generate * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ generate: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/generate', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.verificationCodes.invalidate * * @desc Invalidate the current backup verification codes for the user. * * @alias directory.verificationCodes.invalidate * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Email or immutable Id of the user * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ invalidate: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes/invalidate', method: 'POST' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); }, /** * directory.verificationCodes.list * * @desc Returns the current set of valid backup verification codes for the specified user. * * @alias directory.verificationCodes.list * @memberOf! admin(directory_v1) * * @param {object} params - Parameters for request * @param {string} params.userKey - Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {callback} callback - The callback that handles the response. * @return {object} Request object */ list: function(params, callback) { var parameters = { options: { url: 'https://www.googleapis.com/admin/directory/v1/users/{userKey}/verificationCodes', method: 'GET' }, params: params, requiredParams: ['userKey'], pathParams: ['userKey'], context: self }; return createAPIRequest(parameters, callback); } }; } /** * Exports Admin object * @type Admin */ module.exports = Admin;
MonoHearted/Flowerbless
node_modules/google-api/apis/admin/directory_v1.js
JavaScript
mit
71,632
// sol2 // The MIT License (MIT) // Copyright (c) 2013-2021 Rapptz, ThePhD and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include <sol/protected_function_result.hpp>
ThePhD/sol2
tests/inclusion/source/protected_function_result.cpp
C++
mit
1,206
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using OpenTK; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Timing; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; namespace osu.Game.Tests.Visual { [TestFixture] public class TestCaseScrollingHitObjects : OsuTestCase { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(Playfield) }; private readonly TestPlayfield[] playfields = new TestPlayfield[4]; public TestCaseScrollingHitObjects() { Add(new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { playfields[0] = new TestPlayfield(ScrollingDirection.Up), playfields[1] = new TestPlayfield(ScrollingDirection.Down) }, new Drawable[] { playfields[2] = new TestPlayfield(ScrollingDirection.Left), playfields[3] = new TestPlayfield(ScrollingDirection.Right) } } }); AddSliderStep("Time range", 100, 10000, 5000, v => playfields.ForEach(p => p.VisibleTimeRange.Value = v)); AddStep("Add control point", () => addControlPoint(Time.Current + 5000)); } protected override void LoadComplete() { base.LoadComplete(); playfields.ForEach(p => p.HitObjects.AddControlPoint(new MultiplierControlPoint(0))); for (int i = 0; i <= 5000; i += 1000) addHitObject(Time.Current + i); Scheduler.AddDelayed(() => addHitObject(Time.Current + 5000), 1000, true); } private void addHitObject(double time) { playfields.ForEach(p => { var hitObject = new TestDrawableHitObject(time); setAnchor(hitObject, p); p.Add(hitObject); }); } private void addControlPoint(double time) { playfields.ForEach(p => { p.HitObjects.AddControlPoint(new MultiplierControlPoint(time) { DifficultyPoint = { SpeedMultiplier = 3 } }); p.HitObjects.AddControlPoint(new MultiplierControlPoint(time + 2000) { DifficultyPoint = { SpeedMultiplier = 2 } }); p.HitObjects.AddControlPoint(new MultiplierControlPoint(time + 3000) { DifficultyPoint = { SpeedMultiplier = 1 } }); TestDrawableControlPoint createDrawablePoint(double t) { var obj = new TestDrawableControlPoint(p.Direction, t); setAnchor(obj, p); return obj; } p.Add(createDrawablePoint(time)); p.Add(createDrawablePoint(time + 2000)); p.Add(createDrawablePoint(time + 3000)); }); } private void setAnchor(DrawableHitObject obj, TestPlayfield playfield) { switch (playfield.Direction) { case ScrollingDirection.Up: obj.Anchor = Anchor.TopCentre; break; case ScrollingDirection.Down: obj.Anchor = Anchor.BottomCentre; break; case ScrollingDirection.Left: obj.Anchor = Anchor.CentreLeft; break; case ScrollingDirection.Right: obj.Anchor = Anchor.CentreRight; break; } } private class TestPlayfield : ScrollingPlayfield { public readonly ScrollingDirection Direction; public TestPlayfield(ScrollingDirection direction) : base(direction) { Direction = direction; Padding = new MarginPadding(2); Content.Masking = true; AddInternal(new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.5f, Depth = float.MaxValue }); } } private class TestDrawableControlPoint : DrawableHitObject<HitObject> { public TestDrawableControlPoint(ScrollingDirection direction, double time) : base(new HitObject { StartTime = time }) { Origin = Anchor.Centre; InternalChild = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both }; switch (direction) { case ScrollingDirection.Up: case ScrollingDirection.Down: RelativeSizeAxes = Axes.X; Height = 2; break; case ScrollingDirection.Left: case ScrollingDirection.Right: RelativeSizeAxes = Axes.Y; Width = 2; break; } } protected override void UpdateState(ArmedState state) { } } private class TestDrawableHitObject : DrawableHitObject<HitObject> { public TestDrawableHitObject(double time) : base(new HitObject { StartTime = time }) { Origin = Anchor.Centre; AutoSizeAxes = Axes.Both; InternalChild = new Box { Size = new Vector2(75) }; } protected override void UpdateState(ArmedState state) { } } } }
NeoAdonis/osu
osu.Game.Tests/Visual/TestCaseScrollingHitObjects.cs
C#
mit
6,296
package no.nextgentel.oss.akkatools.aggregate import akka.actor.ActorPath import akka.persistence.AtLeastOnceDelivery.UnconfirmedWarning import akka.persistence.{DeleteMessagesFailure, DeleteMessagesSuccess, SaveSnapshotFailure, SaveSnapshotSuccess, SnapshotOffer} import no.nextgentel.oss.akkatools.persistence.{EnhancedPersistentShardingActor, GetState, SendAsDM} import scala.reflect.ClassTag /** * Dispatcher - When sending something to an ES, use its dispatcher * Command - Dispatchable message - When sent to the dispatcher, it will be sent to the correct ES. * * Event - Represents a change of state for an ES * * State is immutable. * Represents the full state of the entity. based on its state it can accept or reject an event. * Has with method transition(event) - if ok, it returns new state. If not, an error is thrown. * * Can be used to try an event (since it is mutable) * * DurableMessage: method of sending a message which with retry-mechanism until confirm() is called. * * GeneralAggregate pseudocode: * * for each received cmd: * convert it to event * try the event (by calling state.transition() ) * if it failed: maybe do something * if it works: * persist event * generate and send DurableMessages * change our current state (by calling state.transition() and keeping the result ) * * @param dmSelf dmSelf is used as the address where the DM-confirmation-messages should be sent. * In a sharding environment, this has to be our dispatcher which knows how to reach the sharding mechanism. * If null, we'll fallback to self - useful when testing * @tparam E Superclass/trait representing your events * @tparam S The type representing your state */ abstract class GeneralAggregateBase[E:ClassTag, S <: AggregateStateBase[E, S]:ClassTag] ( dmSelf:ActorPath ) extends EnhancedPersistentShardingActor[E, AggregateError](dmSelf) { var state:S private val defaultSuccessHandler = () => log.debug("No cmdSuccess-handler executed") private val defaultErrorHandler = (errorMsg:String) => log.debug("No cmdFailed-handler executed") protected override def onSnapshotOffer(offer : SnapshotOffer) : Unit = { state = offer.snapshot.asInstanceOf[S] } //Override to handle aggregate specific restriction on snapshots, accepts all by default protected def acceptSnapshotRequest(request : SaveSnapshotOfCurrentState) : Boolean = { true } def cmdToEvent:PartialFunction[AggregateCmd, ResultingEvent[E]] override protected def stateInfo(): String = state.toString override protected def onAlreadyProcessedCmdViaDMReceivedAgain(cmd: AnyRef): Unit = { super.onAlreadyProcessedCmdViaDMReceivedAgain(cmd) cmd match { case c:AggregateCmd => // Since the successHandler for receiving this cmd might resend the DM with new payload, // and in that way forward the confirm-responsibility, // we'll try to invoke the success-handler so that it might do that.. // If not, this duplicate DM will just be confirmed val defaultCmdToEvent:(AggregateCmd) => ResultingEvent[E] = {(q) => ResultingEvent(List[E]())} // Do nothing.. // Invoke cmdToEvent - not to use the event, but to try to invoke its successHandler. val eventResult:ResultingEvent[E] = cmdToEvent.applyOrElse(c, defaultCmdToEvent) Option(eventResult.successHandler).map( _.apply() ) case _ => Unit // Nothing we can do.. } } final def tryCommand = { case x: AggregateCmd => // Can't get pattern-matching to work with generics.. if (x.isInstanceOf[GetState]) { sender ! state } else if (x.isInstanceOf[SaveSnapshotOfCurrentState]) { val msg = x.asInstanceOf[SaveSnapshotOfCurrentState] val accepted = acceptSnapshotRequest(msg) if (accepted && this.isInSnapshottableState()) { saveSnapshot(state,msg.deleteEvents) } else { log.warning(s"Rejected snapshot request $msg when in state $state") sender ! AggregateRejectedSnapshotRequest(this.persistenceId, lastSequenceNr, state) } } else { val cmd = x val defaultCmdToEvent:(AggregateCmd) => ResultingEvent[E] = {(q) => throw new AggregateError("Do not know how to process cmd of type " + q.getClass)} val eventResult:ResultingEvent[E] = cmdToEvent.applyOrElse(cmd, defaultCmdToEvent) // Test the events try { var eventsToProcessList:List[E] = eventResult.events.apply() var testState = state var allEvents = List[E]() while( eventsToProcessList.nonEmpty ) { val nextEvent = eventsToProcessList.head if( log.isDebugEnabled ) log.debug("Trying event: " + nextEvent) allEvents = allEvents :+ nextEvent // Add this event to list of all events eventsToProcessList = eventsToProcessList.tail val stateTransition = testState.transitionState(nextEvent) testState = stateTransition.newState // If this stateTransition resulted in new event, we must add it to the front of eventsToProcessList eventsToProcessList = stateTransition.newEvent match { case Some(newEvent) => if( log.isDebugEnabled ) log.debug("Adding new event: " + newEvent) newEvent :: eventsToProcessList // add this new event to the front of eventsToProcessList case _ => eventsToProcessList // unchanged } } // it was valid Option(eventResult.afterValidationSuccessHandler).map(_.apply()) val runTheSuccessHandler = () => Option(eventResult.successHandler).getOrElse(defaultSuccessHandler).apply() if (allEvents.isEmpty) { // We have no events to persist - run the successHandler any way runTheSuccessHandler.apply() } else { // we can persist it persistAndApplyEvents(allEvents, successHandler = { () => // run the successHandler runTheSuccessHandler.apply() }) } } catch { case error:AggregateError => if ( error.skipErrorHandler ) { log.debug("Skipping eventResult-errorHandler") } else { Option(eventResult.errorHandler).getOrElse(defaultErrorHandler).apply(error.getMessage) } throw error } } case x:AnyRef => throw new AggregateError("Do not know how to process cmd of type " + x.getClass) } // Called AFTER event has been applied to state def generateDMs(event:E, previousState:S):ResultingDMs def onEvent = { case e:E => val resultingDMs: ResultingDMs = { val stateBackup = state try { val previousState:S = state state = state.transitionState(e).newState // make the new state current generateDMs(e, previousState) } catch { case e:Exception => state = stateBackup // Must revert changes to state throw e // rethrow it } } // From java resultingDMs might be null.. Wrap it optional Option(resultingDMs).map { rdm => rdm.list.foreach { msg => if(log.isDebugEnabled) log.debug(s"Sending generated DurableMessage: $msg") sendAsDM(msg) } } } private var tmpStateWhileProcessingUnconfirmedWarning:AggregateStateBase[E, S] = null.asInstanceOf[AggregateStateBase[E, S]] // We need to override this so that we can use a fresh copy of the state while we process // all the unconfirmed messages override protected def internalProcessUnconfirmedWarning(unconfirmedWarning: UnconfirmedWarning): Unit = { tmpStateWhileProcessingUnconfirmedWarning = state // since we're maybe goint to validate multiple events in a row, // we need to have a copy of the state that we can modify during the processing/validation super.internalProcessUnconfirmedWarning(unconfirmedWarning) tmpStateWhileProcessingUnconfirmedWarning = null.asInstanceOf[S] } /** * If doUnconfirmedWarningProcessing is turned on, then override this method * to try to do something useful before we give up * * @param originalPayload */ override protected def durableMessageNotDeliveredHandler(originalPayload: Any, errorMsg: String): Unit = { // call generateEventsForFailedDurableMessage to let the app decide if this should result in any events that should be persisted. val events = generateEventsForFailedDurableMessage(originalPayload, errorMsg) var tmpState = tmpStateWhileProcessingUnconfirmedWarning // we must validate that the events are valid events.foreach { e => tmpState = tmpState.transitionState(e).newState } // all events passed validation => we can persist them persistAndApplyEvents(events.toList) tmpStateWhileProcessingUnconfirmedWarning = tmpState } /** * Override this to decide if the failed outbound durableMessage should result in a persisted event. * If so, return these events. * When these have been persisted, generateDMs() will be called as usual enabling * you to perform some outbound action. * * @param originalPayload * @param errorMsg * @return */ def generateEventsForFailedDurableMessage(originalPayload: Any, errorMsg: String):Seq[E] = Seq() // default implementation } abstract class GeneralAggregateDMViaState[E:ClassTag, S <: AggregateStateBase[E, S]:ClassTag] ( dmSelf:ActorPath ) extends GeneralAggregateBase[E, S](dmSelf) { // Called AFTER event has been applied to state override def generateDMs(event: E, previousState: S): ResultingDMs = generateDMs.applyOrElse(state, (s:S) => ResultingDMs(List())) def generateDMs:PartialFunction[S, ResultingDMs] } abstract class GeneralAggregateDMViaStateAndEvent[E:ClassTag, S <: AggregateStateBase[E, S]:ClassTag] ( dmSelf:ActorPath ) extends GeneralAggregateBase[E, S](dmSelf) { // Called AFTER event has been applied to state override def generateDMs(event: E, previousState: S): ResultingDMs = generateDMs.applyOrElse((state,event), (t:(S,E)) => ResultingDMs(List())) def generateDMs:PartialFunction[(S,E), ResultingDMs] } abstract class GeneralAggregateDMViaEvent[E:ClassTag, S <: AggregateState[E, S]:ClassTag] ( dmSelf:ActorPath ) extends GeneralAggregateBase[E, S](dmSelf) { // Called AFTER event has been applied to state override def generateDMs(event: E, previousState: S): ResultingDMs = generateDMs.applyOrElse(event, (t:E) => ResultingDMs(List())) def generateDMs:PartialFunction[E, ResultingDMs] } case class ResultingDMs(list:List[SendAsDM]) object ResultingDMs { def apply(message:AnyRef, destination:ActorPath):ResultingDMs = ResultingDMs(List(SendAsDM(message, destination))) def apply(sendAsDM: SendAsDM):ResultingDMs = ResultingDMs(List(sendAsDM)) }
mbknor/akka-tools
akka-tools-persistence/src/main/scala/no/nextgentel/oss/akkatools/aggregate/GeneralAggregateBase.scala
Scala
mit
11,373
<?php class Admin_Page_Scraper_Facebook extends Admin_Page_Abstract { public function prepare(CM_Frontend_Environment $environment, CM_Frontend_ViewResponse $viewResponse) { /** @var Denkmal_Site_Default $site */ $site = $environment->getSite(); $region = $site->hasRegion() ? $site->getRegion() : null; $page = $this->_params->getPage(); $facebookPageList = new Denkmal_Paging_FacebookPage_ListScraper($region); $facebookPageList->setPage($page, 50); $viewResponse->set('region', $region); $viewResponse->set('facebookPageList', $facebookPageList); } public function ajax_removeFacebookPage(CM_Params $params, CM_Frontend_JavascriptContainer_View $handler, CM_Http_Response_View_Ajax $response) { /** @var Denkmal_Params $params */ /** @var Denkmal_Site_Default $site */ $site = $response->getSite(); $region = $site->hasRegion() ? $site->getRegion() : null; $facebookPage = $params->getFacebookPage('facebookPage'); $facebookPageList = new Denkmal_Paging_FacebookPage_ListScraper($region); $facebookPageList->remove($facebookPage); $response->reloadComponent(); } }
njam/denkmal.org
library/Admin/library/Admin/Page/Scraper/Facebook.php
PHP
mit
1,220
package mahout; /** * Date: 12/11/14 * Time: 8:33 PM * To change this template use File | Settings | File Templates. */ public class AppConstants { public static final String TEST_FILE = "dataset.csv"; }
syednasar/datascience
recommendations/mahoutrecommender/src/main/java/mahout/AppConstants.java
Java
mit
213
<!DOCTYPE html> <html> <head> <title>AngularJS</title> <meta charset="utf-8"> <link href="../content/shared/styles/examples-offline.css" rel="stylesheet"> <link href="../../styles/kendo.common.min.css" rel="stylesheet"> <link href="../../styles/kendo.rtl.min.css" rel="stylesheet"> <link href="../../styles/kendo.default.min.css" rel="stylesheet"> <link href="../../styles/kendo.default.mobile.min.css" rel="stylesheet"> <script src="../../js/jquery.min.js"></script> <script src="../../js/jszip.min.js"></script> <script src="../../js/angular.min.js"></script> <script src="../../js/kendo.all.min.js"></script> <script src="../content/shared/js/console.js"></script> <script> </script> </head> <body> <a class="offline-button" href="../index.html">Back</a> <div id="example" ng-app="KendoDemos"> <div class="demo-section k-content" ng-controller="MyCtrl"> <h4>Select time:</h4> <input kendo-time-picker ng-model="str" k-ng-model="obj" style="width: 100%;" /> <pre> str: {{ str }} obj: {{ obj }} typeof obj: {{ getType(obj) }} obj instanceof Date: {{ isDate(obj) }} </pre> </div> </div> <script> angular.module("KendoDemos", [ "kendo.directives" ]) .controller("MyCtrl", function($scope){ $scope.getType = function(x) { return typeof x; }; $scope.isDate = function(x) { return x instanceof Date; }; }) </script> </body> </html>
jclementdev/Proto1
kendoUI/examples/timepicker/angular.html
HTML
mit
1,584
package common import ( "testing" "github.com/stretchr/testify/assert" ) // Matasano 2.1 func Test_Pad_PKCS7(t *testing.T) { input := []byte("YELLOW SUBMARINE") received := Pad_PKCS7(input, 4) expected := []byte("YELLOW SUBMARINE\x04\x04\x04\x04") assert.Equal(t, expected, received) }
cngkaygusuz/matasano-challenges
golang/common/pad_test.go
GO
mit
295
using Scripts.Game.Defined.Characters; using Scripts.Game.Defined.Serialized.Statistics; using Scripts.Game.Dungeons; using Scripts.Game.Serialized; using Scripts.Game.Undefined.Characters; using Scripts.Model.Acts; using Scripts.Model.Buffs; using Scripts.Model.Characters; using Scripts.Model.Interfaces; using Scripts.Model.Pages; using Scripts.Model.Processes; using Scripts.Model.Spells; using Scripts.Model.Stats; using Scripts.Model.TextBoxes; using Scripts.Presenter; using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Scripts.Game.Pages { /// <summary> /// The hub of the game, from which all other parts can be visited. /// </summary> public class Camp : Model.Pages.PageGroup { /// <summary> /// Missing percentage to restore when resting /// </summary> private const float MISSING_REST_RESTORE_PERCENTAGE = .2f; private Flags flags; private Party party; /// <summary> /// Main /// </summary> /// <param name="party">Party for this particular game.</param> /// <param name="flags">Flags for this particular game.</param> public Camp(Party party, Flags flags) : base(new Page("Campsite")) { this.party = party; this.flags = flags; SetupCamp(); } /// <summary> /// Setup on enter events. /// </summary> private void SetupCamp() { Page root = Get(ROOT_INDEX); root.OnEnter = () => { root.Location = flags.CurrentArea.GetDescription(); root.Icon = Areas.AreaList.AREA_SPRITES[flags.CurrentArea]; // If this isn't first Resting will advance to wrong time if (flags.ShouldAdvanceTimeInCamp) { AdvanceTime(root); flags.ShouldAdvanceTimeInCamp = false; } foreach (Character partyMember in party.Collection) { if (partyMember.Stats.HasUnassignedStatPoints) { root.AddText( string.Format( "<color=cyan>{0}</color> has unallocated stat points. Points can be allocated in the <color=yellow>Party</color> page.", partyMember.Look.DisplayName)); } } Model.Pages.PageGroup dungeonSelectionPage = new StagePages(root, party, flags); root.AddCharacters(Side.LEFT, party.Collection); root.Actions = new IButtonable[] { SubPageWrapper(dungeonSelectionPage, "Visit the stages for this World. When all stages are completed, the next World is unlocked."), SubPageWrapper(new PlacePages(root, flags, party), "Visit a place in this World. Places are unique to a world and can offer you a place to spend your wealth."), SubPageWrapper(new WorldPages(root, flags, party), "Return to a previously unlocked World. Worlds consist of unique Stages and Places."), SubPageWrapper(new LevelUpPages(Root, party), "View party member stats and distribute stat points."), PageUtil.GenerateGroupSpellBooks(root, root, party.Collection), SubPageWrapper(new InventoryPages(root, party), "View the party's shared inventory and use items."), SubPageWrapper(new EquipmentPages(root, party), "View and manage the equipment of your party members."), RestProcess(root), SubPageWrapper(new SavePages(root, party, flags), "Save and exit the game.") }; PostTime(root); }; } private Process SubPageWrapper(PageGroup pg, string description) { return new Process( pg.ButtonText, pg.Sprite, description, () => pg.Invoke(), () => pg.IsInvokable ); } /// <summary> /// Posts the time onto the textholder. /// </summary> /// <param name="current"></param> private void PostTime(Page current) { current.AddText(string.Format("{0} of day {1}.", flags.Time.GetDescription(), flags.DayCount)); if (flags.Time == TimeOfDay.NIGHT) { current.AddText("It is too dark to leave camp."); } } /// <summary> /// Creates the process for resting. /// </summary> /// <param name="current">Current page</param> /// <returns>A rest process.</returns> private Process RestProcess(Page current) { TimeOfDay[] times = Util.EnumAsArray<TimeOfDay>(); int currentIndex = (int)flags.Time; int newIndex = (currentIndex + 1) % times.Length; bool isLastTime = (currentIndex == (times.Length - 1)); return new Process( isLastTime ? "Sleep" : "Rest", isLastTime ? Util.GetSprite("bed") : Util.GetSprite("health-normal"), isLastTime ? string.Format("Sleep to the next day ({0}).\nFully restores most stats and removes most status conditions.", flags.DayCount + 1) : string.Format("Take a short break, advancing the time of day to {0}.\nSomewhat restores most stats.", times[newIndex].GetDescription()), () => { foreach (Character c in party) { c.Stats.RestoreResourcesByMissingPercentage(isLastTime ? 1 : MISSING_REST_RESTORE_PERCENTAGE); if (isLastTime) { c.Buffs.DispelAllBuffs(); } } if (isLastTime) { flags.DayCount %= int.MaxValue; flags.DayCount++; } flags.Time = times[newIndex]; current.AddText(string.Format("The party {0}s.", isLastTime ? "sleep" : "rest")); current.OnEnter(); } ); } /// <summary> /// Makes time go forward in camp. From visiting places. /// </summary> /// <param name="current">The current page.</param> private void AdvanceTime(Page current) { TimeOfDay[] times = Util.EnumAsArray<TimeOfDay>(); int currentIndex = (int)flags.Time; int newIndex = (currentIndex + 1) % times.Length; flags.Time = times[newIndex]; current.AddText("Some time has passed."); } } }
Cinnamon18/runityscape
Assets/Scripts/Game/Camp/Camp.cs
C#
mit
6,751
<?xml version="1.0" encoding="utf-8"?> <!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" xml:lang="en" lang="en"> <head> <title>Rails::Rack</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" /> <script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.1.8</span><br /> <h1> <span class="type">Module</span> Rails::Rack </h1> <ul class="files"> <li><a href="../../files/__/__/__/__/usr/local/share/gems/gems/railties-4_1_8/lib/rails/rack_rb.html">/usr/local/share/gems/gems/railties-4.1.8/lib/rails/rack.rb</a></li> <li><a href="../../files/__/__/__/__/usr/local/share/gems/gems/railties-4_1_8/lib/rails/rack/debugger_rb.html">/usr/local/share/gems/gems/railties-4.1.8/lib/rails/rack/debugger.rb</a></li> <li><a href="../../files/__/__/__/__/usr/local/share/gems/gems/railties-4_1_8/lib/rails/rack/log_tailer_rb.html">/usr/local/share/gems/gems/railties-4.1.8/lib/rails/rack/log_tailer.rb</a></li> <li><a href="../../files/__/__/__/__/usr/local/share/gems/gems/railties-4_1_8/lib/rails/rack/logger_rb.html">/usr/local/share/gems/gems/railties-4.1.8/lib/rails/rack/logger.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <!-- Namespace --> <div class="sectiontitle">Namespace</div> <ul> <li> <span class="type">CLASS</span> <a href="Rack/Debugger.html">Rails::Rack::Debugger</a> </li> <li> <span class="type">CLASS</span> <a href="Rack/LogTailer.html">Rails::Rack::LogTailer</a> </li> <li> <span class="type">CLASS</span> <a href="Rack/Logger.html">Rails::Rack::Logger</a> </li> </ul> <!-- Methods --> </div> </div> </body> </html>
mojo1643/Dalal_v2
doc/api/classes/Rails/Rack.html
HTML
mit
2,793
Unauthenticated REST Interface ============================== The REST API can be enabled with the `-rest` option. The interface runs on the same port as the JSON-RPC interface, by default port 8332 for mainnet and port 18332 for testnet. Supported API ------------- ####Transactions `GET /rest/tx/<TX-HASH>.<bin|hex|json>` Given a transaction hash: returns a transaction in binary, hex-encoded binary, or JSON formats. For full TX query capability, one must enable the transaction index via "txindex=1" command line / configuration option. ####Blocks `GET /rest/block/<BLOCK-HASH>.<bin|hex|json>` `GET /rest/block/notxdetails/<BLOCK-HASH>.<bin|hex|json>` Given a block hash: returns a block, in binary, hex-encoded binary or JSON formats. The HTTP request and response are both handled entirely in-memory, thus making maximum memory usage at least 2.66MB (1 MB max block, plus hex encoding) per request. With the /notxdetails/ option JSON response will only contain the transaction hash instead of the complete transaction details. The option only affects the JSON response. ####Blockheaders `GET /rest/headers/<COUNT>/<BLOCK-HASH>.<bin|hex|json>` Given a block hash: returns <COUNT> amount of blockheaders in upward direction. ####Chaininfos `GET /rest/chaininfo.json` Returns various state info regarding block chain processing. Only supports JSON as output format. * chain : (string) current network name as defined in BIP70 (main, test, regtest) * blocks : (numeric) the current number of blocks processed in the server * headers : (numeric) the current number of headers we have validated * bestblockhash : (string) the hash of the currently best block * difficulty : (numeric) the current difficulty * verificationprogress : (numeric) estimate of verification progress [0..1] * chainwork : (string) total amount of work in active chain, in hexadecimal * pruned : (boolean) if the blocks are subject to pruning * pruneheight : (numeric) heighest block available * softforks : (array) status of softforks in progress ####Query UTXO set `GET /rest/getutxos/<checkmempool>/<txid>-<n>/<txid>-<n>/.../<txid>-<n>.<bin|hex|json>` The getutxo command allows querying of the UTXO set given a set of outpoints. See BIP64 for input and output serialisation: https://github.com/bitcoin/bips/blob/master/bip-0064.mediawiki Example: ``` $ curl localhost:19332/rest/getutxos/checkmempool/b2cdfd7b89def827ff8af7cd9bff7627ff72e5e8b0f71210f92ea7a4000c5d75-0.json 2>/dev/null | json_pp { "chaintipHash" : "00000000fb01a7f3745a717f8caebee056c484e6e0bfe4a9591c235bb70506fb", "chainHeight" : 325347, "utxos" : [ { "scriptPubKey" : { "addresses" : [ "mi7as51dvLJsizWnTMurtRmrP8hG2m1XvD" ], "type" : "pubkeyhash", "hex" : "76a9141c7cebb529b86a04c683dfa87be49de35bcf589e88ac", "reqSigs" : 1, "asm" : "OP_DUP OP_HASH160 1c7cebb529b86a04c683dfa87be49de35bcf589e OP_EQUALVERIFY OP_CHECKSIG" }, "value" : 8.8687, "height" : 2147483647, "txvers" : 1 } ], "bitmap" : "1" } ``` ####Memory pool `GET /rest/mempool/info.json` Returns various information about the TX mempool. Only supports JSON as output format. * size : (numeric) the number of transactions in the TX mempool * bytes : (numeric) size of the TX mempool in bytes * usage : (numeric) total TX mempool memory usage `GET /rest/mempool/contents.json` Returns transactions in the TX mempool. Only supports JSON as output format. Risks ------------- Running a web browser on the same node with a REST enabled solarcoind can be a risk. Accessing prepared XSS websites could read out tx/block data of your node by placing links like `<script src="http://127.0.0.1:9332/rest/tx/1234567890.json">` which might break the nodes privacy.
ruby32/solarcoin
doc/REST-interface.md
Markdown
mit
3,844
package org.jinstagram.auth.model; import org.jinstagram.http.Request; import org.jinstagram.http.Verbs; import java.util.HashMap; import java.util.Map; /** * The representation of an OAuth HttpRequest. * * Adds OAuth-related functionality to the {@link Request} */ public class OAuthRequest extends Request { private static final String OAUTH_PREFIX = "oauth_"; private Map<String, String> oauthParameters; /** * Default constructor. * * @param verb Http verb/method * @param url resource URL */ public OAuthRequest(Verbs verb, String url) { super(verb, url); this.oauthParameters = new HashMap<String, String>(); } /** * Adds an OAuth parameter. * * @param key name of the parameter * @param value value of the parameter * * @throws IllegalArgumentException if the parameter is not an OAuth * parameter */ public void addOAuthParameter(String key, String value) { oauthParameters.put(checkKey(key), value); } private static String checkKey(String key) { if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) { return key; } else { throw new IllegalArgumentException(String.format( "OAuth parameters must either be '%s' or start with '%s'", OAuthConstants.SCOPE, OAUTH_PREFIX)); } } /** * Returns the {@link Map} containing the key-value pair of parameters. * * @return parameters as map */ public Map<String, String> getOauthParameters() { return oauthParameters; } @Override public String toString() { return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl()); } }
zauberlabs/jInstagram
src/main/java/org/jinstagram/auth/model/OAuthRequest.java
Java
mit
1,596
package tracker.message.handlers; import elasta.composer.message.handlers.MessageHandler; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonObject; /** * Created by sohan on 2017-07-26. */ public interface ReplayMessageHandler extends MessageHandler<JsonObject> { @Override void handle(Message<JsonObject> event); }
codefacts/Elastic-Components
tracker/src/main/java/tracker/message/handlers/ReplayMessageHandler.java
Java
mit
347
# -*- coding: utf-8 -*- import pyqtgraph as pg from pyqtgraph.Qt import QtGui, QtCore import numpy as np import csv, gzip, os from pyqtgraph import Point class GlassDB: """ Database of dispersion coefficients for Schott glasses + Corning 7980 """ def __init__(self, fileName='schott_glasses.csv'): path = os.path.dirname(__file__) fh = gzip.open(os.path.join(path, 'schott_glasses.csv.gz'), 'rb') r = csv.reader(map(str, fh.readlines())) lines = [x for x in r] self.data = {} header = lines[0] for l in lines[1:]: info = {} for i in range(1, len(l)): info[header[i]] = l[i] self.data[l[0]] = info self.data['Corning7980'] = { ## Thorlabs UV fused silica--not in schott catalog. 'B1': 0.68374049400, 'B2': 0.42032361300, 'B3': 0.58502748000, 'C1': 0.00460352869, 'C2': 0.01339688560, 'C3': 64.49327320000, 'TAUI25/250': 0.95, ## transmission data is fabricated, but close. 'TAUI25/1400': 0.98, } for k in self.data: self.data[k]['ior_cache'] = {} def ior(self, glass, wl): """ Return the index of refraction for *glass* at wavelength *wl*. The *glass* argument must be a key in self.data. """ info = self.data[glass] cache = info['ior_cache'] if wl not in cache: B = list(map(float, [info['B1'], info['B2'], info['B3']])) C = list(map(float, [info['C1'], info['C2'], info['C3']])) w2 = (wl/1000.)**2 n = np.sqrt(1.0 + (B[0]*w2 / (w2-C[0])) + (B[1]*w2 / (w2-C[1])) + (B[2]*w2 / (w2-C[2]))) cache[wl] = n return cache[wl] def transmissionCurve(self, glass): data = self.data[glass] keys = [int(x[7:]) for x in data.keys() if 'TAUI25' in x] keys.sort() curve = np.empty((2,len(keys))) for i in range(len(keys)): curve[0][i] = keys[i] key = 'TAUI25/%d' % keys[i] val = data[key] if val == '': val = 0 else: val = float(val) curve[1][i] = val return curve GLASSDB = GlassDB() def wlPen(wl): """Return a pen representing the given wavelength""" l1 = 400 l2 = 700 hue = np.clip(((l2-l1) - (wl-l1)) * 0.8 / (l2-l1), 0, 0.8) val = 1.0 if wl > 700: val = 1.0 * (((700-wl)/700.) + 1) elif wl < 400: val = wl * 1.0/400. #print hue, val color = pg.hsvColor(hue, 1.0, val) pen = pg.mkPen(color) return pen class ParamObj(object): # Just a helper for tracking parameters and responding to changes def __init__(self): self.__params = {} def __setitem__(self, item, val): self.setParam(item, val) def setParam(self, param, val): self.setParams(**{param:val}) def setParams(self, **params): """Set parameters for this optic. This is a good function to override for subclasses.""" self.__params.update(params) self.paramStateChanged() def paramStateChanged(self): pass def __getitem__(self, item): # bug in pyside 1.2.2 causes getitem to be called inside QGraphicsObject.parentItem: return self.getParam(item) # PySide bug: https://bugreports.qt.io/browse/PYSIDE-441 def getParam(self, param): return self.__params[param] class Optic(pg.GraphicsObject, ParamObj): sigStateChanged = QtCore.Signal() def __init__(self, gitem, **params): ParamObj.__init__(self) pg.GraphicsObject.__init__(self) #, [0,0], [1,1]) self.gitem = gitem self.surfaces = gitem.surfaces gitem.setParentItem(self) self.roi = pg.ROI([0,0], [1,1]) self.roi.addRotateHandle([1, 1], [0.5, 0.5]) self.roi.setParentItem(self) defaults = { 'pos': Point(0,0), 'angle': 0, } defaults.update(params) self._ior_cache = {} self.roi.sigRegionChanged.connect(self.roiChanged) self.setParams(**defaults) def updateTransform(self): self.resetTransform() self.setPos(0, 0) self.translate(Point(self['pos'])) self.rotate(self['angle']) def setParam(self, param, val): ParamObj.setParam(self, param, val) def paramStateChanged(self): """Some parameters of the optic have changed.""" # Move graphics item self.gitem.setPos(Point(self['pos'])) self.gitem.resetTransform() self.gitem.rotate(self['angle']) # Move ROI to match try: self.roi.sigRegionChanged.disconnect(self.roiChanged) br = self.gitem.boundingRect() o = self.gitem.mapToParent(br.topLeft()) self.roi.setAngle(self['angle']) self.roi.setPos(o) self.roi.setSize([br.width(), br.height()]) finally: self.roi.sigRegionChanged.connect(self.roiChanged) self.sigStateChanged.emit() def roiChanged(self, *args): pos = self.roi.pos() # rotate gitem temporarily so we can decide where it will need to move self.gitem.resetTransform() self.gitem.rotate(self.roi.angle()) br = self.gitem.boundingRect() o1 = self.gitem.mapToParent(br.topLeft()) self.setParams(angle=self.roi.angle(), pos=pos + (self.gitem.pos() - o1)) def boundingRect(self): return QtCore.QRectF() def paint(self, p, *args): pass def ior(self, wavelength): return GLASSDB.ior(self['glass'], wavelength) class Lens(Optic): def __init__(self, **params): defaults = { 'dia': 25.4, ## diameter of lens 'r1': 50., ## positive means convex, use 0 for planar 'r2': 0, ## negative means convex 'd': 4.0, 'glass': 'N-BK7', 'reflect': False, } defaults.update(params) d = defaults.pop('d') defaults['x1'] = -d/2. defaults['x2'] = d/2. gitem = CircularSolid(brush=(100, 100, 130, 100), **defaults) Optic.__init__(self, gitem, **defaults) def propagateRay(self, ray): """Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays""" """ NOTE:: We can probably use this to compute refractions faster: (from GLSL 120 docs) For the incident vector I and surface normal N, and the ratio of indices of refraction eta, return the refraction vector. The result is computed by k = 1.0 - eta * eta * (1.0 - dot(N, I) * dot(N, I)) if (k < 0.0) return genType(0.0) else return eta * I - (eta * dot(N, I) + sqrt(k)) * N The input parameters for the incident vector I and the surface normal N must already be normalized to get the desired results. eta == ratio of IORs For reflection: For the incident vector I and surface orientation N, returns the reflection direction: I – 2 ∗ dot(N, I) ∗ N N must already be normalized in order to achieve the desired result. """ iors = [self.ior(ray['wl']), 1.0] for i in [0,1]: surface = self.surfaces[i] ior = iors[i] p1, ai = surface.intersectRay(ray) #print "surface intersection:", p1, ai*180/3.14159 #trans = self.sceneTransform().inverted()[0] * surface.sceneTransform() #p1 = trans.map(p1) if p1 is None: ray.setEnd(None) break p1 = surface.mapToItem(ray, p1) #print "adjusted position:", p1 #ior = self.ior(ray['wl']) rd = ray['dir'] a1 = np.arctan2(rd[1], rd[0]) ar = a1 - ai + np.arcsin((np.sin(ai) * ray['ior'] / ior)) #print [x for x in [a1, ai, (np.sin(ai) * ray['ior'] / ior), ar]] #print ai, np.sin(ai), ray['ior'], ior ray.setEnd(p1) dp = Point(np.cos(ar), np.sin(ar)) #p2 = p1+dp #p1p = self.mapToScene(p1) #p2p = self.mapToScene(p2) #dpp = Point(p2p-p1p) ray = Ray(parent=ray, ior=ior, dir=dp) return [ray] class Mirror(Optic): def __init__(self, **params): defaults = { 'r1': 0, 'r2': 0, 'd': 0.01, } defaults.update(params) d = defaults.pop('d') defaults['x1'] = -d/2. defaults['x2'] = d/2. gitem = CircularSolid(brush=(100,100,100,255), **defaults) Optic.__init__(self, gitem, **defaults) def propagateRay(self, ray): """Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays""" surface = self.surfaces[0] p1, ai = surface.intersectRay(ray) if p1 is not None: p1 = surface.mapToItem(ray, p1) rd = ray['dir'] a1 = np.arctan2(rd[1], rd[0]) ar = a1 + np.pi - 2*ai ray.setEnd(p1) dp = Point(np.cos(ar), np.sin(ar)) ray = Ray(parent=ray, dir=dp) else: ray.setEnd(None) return [ray] class CircularSolid(pg.GraphicsObject, ParamObj): """GraphicsObject with two circular or flat surfaces.""" def __init__(self, pen=None, brush=None, **opts): """ Arguments for each surface are: x1,x2 - position of center of _physical surface_ r1,r2 - radius of curvature d1,d2 - diameter of optic """ defaults = dict(x1=-2, r1=100, d1=25.4, x2=2, r2=100, d2=25.4) defaults.update(opts) ParamObj.__init__(self) self.surfaces = [CircleSurface(defaults['r1'], defaults['d1']), CircleSurface(-defaults['r2'], defaults['d2'])] pg.GraphicsObject.__init__(self) for s in self.surfaces: s.setParentItem(self) if pen is None: self.pen = pg.mkPen((220,220,255,200), width=1, cosmetic=True) else: self.pen = pg.mkPen(pen) if brush is None: self.brush = pg.mkBrush((230, 230, 255, 30)) else: self.brush = pg.mkBrush(brush) self.setParams(**defaults) def paramStateChanged(self): self.updateSurfaces() def updateSurfaces(self): self.surfaces[0].setParams(self['r1'], self['d1']) self.surfaces[1].setParams(-self['r2'], self['d2']) self.surfaces[0].setPos(self['x1'], 0) self.surfaces[1].setPos(self['x2'], 0) self.path = QtGui.QPainterPath() self.path.connectPath(self.surfaces[0].path.translated(self.surfaces[0].pos())) self.path.connectPath(self.surfaces[1].path.translated(self.surfaces[1].pos()).toReversed()) self.path.closeSubpath() def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def paint(self, p, *args): p.setRenderHints(p.renderHints() | p.Antialiasing) p.setPen(self.pen) p.fillPath(self.path, self.brush) p.drawPath(self.path) class CircleSurface(pg.GraphicsObject): def __init__(self, radius=None, diameter=None): """center of physical surface is at 0,0 radius is the radius of the surface. If radius is None, the surface is flat. diameter is of the optic's edge.""" pg.GraphicsObject.__init__(self) self.r = radius self.d = diameter self.mkPath() def setParams(self, r, d): self.r = r self.d = d self.mkPath() def mkPath(self): self.prepareGeometryChange() r = self.r d = self.d h2 = d/2. self.path = QtGui.QPainterPath() if r == 0: ## flat surface self.path.moveTo(0, h2) self.path.lineTo(0, -h2) else: ## half-height of surface can't be larger than radius h2 = min(h2, abs(r)) #dx = abs(r) - (abs(r)**2 - abs(h2)**2)**0.5 #p.moveTo(-d*w/2.+ d*dx, d*h2) arc = QtCore.QRectF(0, -r, r*2, r*2) #self.surfaces.append((arc.center(), r, h2)) a1 = np.arcsin(h2/r) * 180. / np.pi a2 = -2*a1 a1 += 180. self.path.arcMoveTo(arc, a1) self.path.arcTo(arc, a1, a2) #if d == -1: #p1 = QtGui.QPainterPath() #p1.addRect(arc) #self.paths.append(p1) self.h2 = h2 def boundingRect(self): return self.path.boundingRect() def paint(self, p, *args): return ## usually we let the optic draw. #p.setPen(pg.mkPen('r')) #p.drawPath(self.path) def intersectRay(self, ray): ## return the point of intersection and the angle of incidence #print "intersect ray" h = self.h2 r = self.r p, dir = ray.currentState(relativeTo=self) # position and angle of ray in local coords. #print " ray: ", p, dir p = p - Point(r, 0) ## move position so center of circle is at 0,0 #print " adj: ", p, r if r == 0: #print " flat" if dir[0] == 0: y = 0 else: y = p[1] - p[0] * dir[1]/dir[0] if abs(y) > h: return None, None else: return (Point(0, y), np.arctan2(dir[1], dir[0])) else: #print " curve" ## find intersection of circle and line (quadratic formula) dx = dir[0] dy = dir[1] dr = (dx**2 + dy**2) ** 0.5 D = p[0] * (p[1]+dy) - (p[0]+dx) * p[1] idr2 = 1.0 / dr**2 disc = r**2 * dr**2 - D**2 if disc < 0: return None, None disc2 = disc**0.5 if dy < 0: sgn = -1 else: sgn = 1 br = self.path.boundingRect() x1 = (D*dy + sgn*dx*disc2) * idr2 y1 = (-D*dx + abs(dy)*disc2) * idr2 if br.contains(x1+r, y1): pt = Point(x1, y1) else: x2 = (D*dy - sgn*dx*disc2) * idr2 y2 = (-D*dx - abs(dy)*disc2) * idr2 pt = Point(x2, y2) if not br.contains(x2+r, y2): return None, None raise Exception("No intersection!") norm = np.arctan2(pt[1], pt[0]) if r < 0: norm += np.pi #print " norm:", norm*180/3.1415 dp = p - pt #print " dp:", dp ang = np.arctan2(dp[1], dp[0]) #print " ang:", ang*180/3.1415 #print " ai:", (ang-norm)*180/3.1415 #print " intersection:", pt return pt + Point(r, 0), ang-norm class Ray(pg.GraphicsObject, ParamObj): """Represents a single straight segment of a ray""" sigStateChanged = QtCore.Signal() def __init__(self, **params): ParamObj.__init__(self) defaults = { 'ior': 1.0, 'wl': 500, 'end': None, 'dir': Point(1,0), } self.params = {} pg.GraphicsObject.__init__(self) self.children = [] parent = params.get('parent', None) if parent is not None: defaults['start'] = parent['end'] defaults['wl'] = parent['wl'] self['ior'] = parent['ior'] self['dir'] = parent['dir'] parent.addChild(self) defaults.update(params) defaults['dir'] = Point(defaults['dir']) self.setParams(**defaults) self.mkPath() def clearChildren(self): for c in self.children: c.clearChildren() c.setParentItem(None) self.scene().removeItem(c) self.children = [] def paramStateChanged(self): pass def addChild(self, ch): self.children.append(ch) ch.setParentItem(self) def currentState(self, relativeTo=None): pos = self['start'] dir = self['dir'] if relativeTo is None: return pos, dir else: trans = self.itemTransform(relativeTo)[0] p1 = trans.map(pos) p2 = trans.map(pos + dir) return Point(p1), Point(p2-p1) def setEnd(self, end): self['end'] = end self.mkPath() def boundingRect(self): return self.path.boundingRect() def paint(self, p, *args): #p.setPen(pg.mkPen((255,0,0, 150))) p.setRenderHints(p.renderHints() | p.Antialiasing) p.setCompositionMode(p.CompositionMode_Plus) p.setPen(wlPen(self['wl'])) p.drawPath(self.path) def mkPath(self): self.prepareGeometryChange() self.path = QtGui.QPainterPath() self.path.moveTo(self['start']) if self['end'] is not None: self.path.lineTo(self['end']) else: self.path.lineTo(self['start']+500*self['dir']) def trace(rays, optics): if len(optics) < 1 or len(rays) < 1: return for r in rays: r.clearChildren() o = optics[0] r2 = o.propagateRay(r) trace(r2, optics[1:]) class Tracer(QtCore.QObject): """ Simple ray tracer. Initialize with a list of rays and optics; calling trace() will cause rays to be extended by propagating them through each optic in sequence. """ def __init__(self, rays, optics): QtCore.QObject.__init__(self) self.optics = optics self.rays = rays for o in self.optics: o.sigStateChanged.connect(self.trace) self.trace() def trace(self): trace(self.rays, self.optics)
pmaunz/pyqtgraph
examples/optics/pyoptic.py
Python
mit
18,598
/******************************************************************************* *//** * @mainpage * @section section1 Introduction: * Having studied this LAB you will able to: \n * - Understand the GPIO functions \n * - Study the programs related to the LCD Display. * * @section section2 Example6 : * Objective: Program to display Empty Triangle for one character. * * @section section3 Program Description: * This program demonstrates interfacing of LCD display and display empty triangle on it * * @section section4 Included Files: * * | Header Files | Source Files | * | :------------------------:| :------------------------:| * | @ref stm32f4xx_hal_conf.h | @ref stm32f4xx_hal_msp.c | * | @ref stm32f4xx_it.h | @ref stm32f4xx_it.c | * | @ref stm32f4_ask25_lcd.h | @ref stm32f4_ask25_lcd.c | * | | @ref main.c | * * \n * * @section section5 Pin Assignments * * | STM32F407 Reference | Device(ASK-25-LCD) | * | :------------------:| :----------------: | * | P1.21 GPIOB.1 | RS | * | P2.25 GPIOB.4 | R/W | * | P2.26 GPIOB.5 | EN | * | P1.26 GPIOE.8 | D0 | * | P1.27 GPIOE.9 | D1 | * | P1.28 GPIOE.10 | D2 | * | P1.29 GPIOE.11 | D3 | * | P1.30 GPIOE.12 | D4 | * | P1.31 GPIOE.13 | D5 | * | P1.32 GPIOE.14 | D6 | * | P1.33 GPIOE.15 | D7 | * * @section section6 Connection * | STM32F407 Reference | Device | * | :------------------:| :-------------: | * | J6 | ASK-25 (PL3) | * * @section section7 Program Folder Location * <Eg6> * * * @section section8 Part List * - STM32F4Discovery Board \n * - Flat cable \n * - USB cable \n * - Eclipse IDE \n * - PC \n * - ASK-25 Rev2.0 \n * * @section section9 Hardware Configuration * - Connect ASK 25 to educational practice board using flat cable. * - Connect the board using USB port of PC using USB cable. * - Apply Reset condition by pressing the Reset switch to ensure proper communication. * - Using download tool (STM ST-LINK Utility) download the .hex file developed using available tools. * - Reset the board. * - Observe the Output. * * @section section10 Output: * On LCD display you will see a empty triangle for only one character on starting location *\n *\n *******************************************************************************/
bhavindarji/STM32F4-Dev
Example Projects/ASK25/LCD/CGRAM/Eg6/Inc/doxy_wb.h
C
mit
2,725
import logging from urllib.parse import urljoin import lxml.etree # noqa: S410 import requests from django.conf import settings as django_settings from django.utils import timezone logger = logging.getLogger(__name__) class ClientError(Exception): pass class ResponseParseError(ClientError): pass class ResponseStatusError(ClientError): pass class RequestError(ClientError): def __init__(self, message, response=None): super(RequestError, self).__init__(message) self.response = response class UnknownStatusError(ResponseParseError): pass class Response: ns_namespace = 'http://uri.etsi.org/TS102204/v1.1.2#' def __init__(self, content): etree = lxml.etree.fromstring(content) # noqa: S320 self.init_response_attributes(etree) def init_response_attributes(self, etree): """ Define response attributes based on valimo request content """ raise NotImplementedError class Request: url = NotImplemented template = NotImplemented response_class = NotImplemented settings = getattr(django_settings, 'WALDUR_AUTH_VALIMO', {}) @classmethod def execute(cls, **kwargs): url = cls._get_url() headers = { 'content-type': 'text/xml', 'SOAPAction': url, } data = cls.template.strip().format( AP_ID=cls.settings['AP_ID'], AP_PWD=cls.settings['AP_PWD'], Instant=cls._format_datetime(timezone.now()), DNSName=cls.settings['DNSName'], **kwargs ) cert = (cls.settings['cert_path'], cls.settings['key_path']) # TODO: add verification logger.debug( 'Executing POST request to %s with data:\n %s \nheaders: %s', url, data, headers, ) response = requests.post( url, data=data, headers=headers, cert=cert, verify=cls.settings['verify_ssl'], ) if response.ok: return cls.response_class(response.content) else: message = ( 'Failed to execute POST request against %s endpoint. Response [%s]: %s' % (url, response.status_code, response.content) ) raise RequestError(message, response) @classmethod def _format_datetime(cls, d): return d.strftime('%Y-%m-%dT%H:%M:%S.000Z') @classmethod def _format_transaction_id(cls, transaction_id): return ('_' + transaction_id)[:32] # such formation is required by server. @classmethod def _get_url(cls): return urljoin(cls.settings['URL'], cls.url) class SignatureResponse(Response): def init_response_attributes(self, etree): try: self.backend_transaction_id = etree.xpath('//MSS_SignatureResp')[0].attrib[ 'MSSP_TransID' ] self.status = etree.xpath( '//ns6:StatusCode', namespaces={'ns6': self.ns_namespace} )[0].attrib['Value'] except (IndexError, KeyError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse signature response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) class SignatureRequest(Request): url = '/MSSP/services/MSS_Signature' template = """ <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <MSS_Signature xmlns=""> <MSS_SignatureReq MajorVersion="1" MessagingMode="{MessagingMode}" MinorVersion="1" TimeOut="300"> <ns1:AP_Info AP_ID="{AP_ID}" AP_PWD="{AP_PWD}" AP_TransID="{AP_TransID}" Instant="{Instant}" xmlns:ns1="http://uri.etsi.org/TS102204/v1.1.2#"/> <ns2:MSSP_Info xmlns:ns2="http://uri.etsi.org/TS102204/v1.1.2#"> <ns2:MSSP_ID> <ns2:DNSName>{DNSName}</ns2:DNSName> </ns2:MSSP_ID> </ns2:MSSP_Info> <ns3:MobileUser xmlns:ns3="http://uri.etsi.org/TS102204/v1.1.2#"> <ns3:MSISDN>{MSISDN}</ns3:MSISDN> </ns3:MobileUser> <ns4:DataToBeSigned Encoding="UTF-8" MimeType="text/plain" xmlns:ns4="http://uri.etsi.org/TS102204/v1.1.2#"> {DataToBeSigned} </ns4:DataToBeSigned> <ns5:SignatureProfile xmlns:ns5="http://uri.etsi.org/TS102204/v1.1.2#"> <ns5:mssURI>{SignatureProfile}</ns5:mssURI> </ns5:SignatureProfile> <ns6:MSS_Format xmlns:ns6="http://uri.etsi.org/TS102204/v1.1.2#"> <ns6:mssURI>http://uri.etsi.org/TS102204/v1.1.2#PKCS7</ns6:mssURI> </ns6:MSS_Format> </MSS_SignatureReq> </MSS_Signature> </soapenv:Body> </soapenv:Envelope> """ response_class = SignatureResponse @classmethod def execute(cls, transaction_id, phone, message): kwargs = { 'MessagingMode': 'asynchClientServer', 'AP_TransID': cls._format_transaction_id(transaction_id), 'MSISDN': phone, 'DataToBeSigned': '%s %s' % (cls.settings['message_prefix'], message), 'SignatureProfile': cls.settings['SignatureProfile'], } return super(SignatureRequest, cls).execute(**kwargs) class Statuses: OK = 'OK' PROCESSING = 'Processing' ERRED = 'Erred' @classmethod def map(cls, status_code): if status_code == '502': return cls.OK elif status_code == '504': return cls.PROCESSING else: raise UnknownStatusError( 'Received unsupported status in response: %s' % status_code ) class StatusResponse(Response): def init_response_attributes(self, etree): try: status_code = etree.xpath( '//ns5:StatusCode', namespaces={'ns5': self.ns_namespace} )[0].attrib['Value'] except (IndexError, KeyError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse status response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) self.status = Statuses.map(status_code) try: civil_number_tag = etree.xpath( '//ns4:UserIdentifier', namespaces={'ns4': self.ns_namespace} )[0] except IndexError: # civil number tag does not exist - this is possible if request is still processing return else: try: self.civil_number = civil_number_tag.text.split('=')[1] except IndexError: raise ResponseParseError( 'Cannot get civil_number from tag text: %s' % civil_number_tag.text ) class ErredStatusResponse(Response): soapenv_namespace = 'http://www.w3.org/2003/05/soap-envelope' def init_response_attributes(self, etree): self.status = Statuses.ERRED try: self.details = etree.xpath( '//soapenv:Text', namespaces={'soapenv': self.soapenv_namespace} )[0].text except (IndexError, lxml.etree.XMLSchemaError) as e: raise ResponseParseError( 'Cannot parse error status response: %s. Response content: %s' % (e, lxml.etree.tostring(etree)) ) class StatusRequest(Request): url = '/MSSP/services/MSS_StatusPort' template = """ <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <MSS_StatusQuery xmlns=""> <MSS_StatusReq MajorVersion="1" MinorVersion="1"> <ns1:AP_Info AP_ID="{AP_ID}" AP_PWD="{AP_PWD}" AP_TransID="{AP_TransID}" Instant="{Instant}" xmlns:ns1="http://uri.etsi.org/TS102204/v1.1.2#"/> <ns2:MSSP_Info xmlns:ns2="http://uri.etsi.org/TS102204/v1.1.2#"> <ns2:MSSP_ID> <ns2:DNSName>{DNSName}</ns2:DNSName> </ns2:MSSP_ID> </ns2:MSSP_Info> <ns3:MSSP_TransID xmlns:ns3="http://uri.etsi.org/TS102204/v1.1.2#">{MSSP_TransID}</ns3:MSSP_TransID> </MSS_StatusReq> </MSS_StatusQuery> </soapenv:Body> </soapenv:Envelope> """ response_class = StatusResponse @classmethod def execute(cls, transaction_id, backend_transaction_id): kwargs = { 'AP_TransID': cls._format_transaction_id(transaction_id), 'MSSP_TransID': backend_transaction_id, } try: return super(StatusRequest, cls).execute(**kwargs) except RequestError as e: # If request was timed out or user canceled login - Valimo would return response with status 500 return ErredStatusResponse(e.response.content)
opennode/nodeconductor-assembly-waldur
src/waldur_auth_valimo/client.py
Python
mit
9,636
#### Scripts ##### CrowdStrikeUrlParse - Updated the Docker image to: *demisto/python:2.7.18.24398*.
demisto/content
Packs/CrowdStrikeHost/ReleaseNotes/1_1_6.md
Markdown
mit
101
<?php namespace Yandex\Locator\Exception; /** * Class ServerError * @package Yandex\Locator\Exception * @author Dmitry Kuznetsov <[email protected]> * @license The MIT License (MIT) */ class ServerError extends \Yandex\Locator\Exception { }
dmkuznetsov/php-yandex-locator
source/Yandex/Locator/Exception/ServerError.php
PHP
mit
250
/* * Copyright 2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'underscore', 'jquery', 'find/idol/app/page/dashboard/widgets/updating-widget', 'find/idol/app/page/dashboard/update-tracker-model' ], function(_, $, UpdatingWidget, UpdateTrackerModel) { 'use strict'; const spies = jasmine.createSpyObj('spies', ['onComplete', 'onIncrement', 'onCancelled', 'doUpdate']); const TestUpdatingWidget = UpdatingWidget.extend(spies); describe('Updating Widget', function() { beforeEach(function() { jasmine.addMatchers({ toShowLoadingSpinner: function() { return { compare: function(actual) { const pass = !actual.$loadingSpinner.hasClass('hide'); return { pass: pass, message: 'Expected the view ' + (pass ? 'not ' : '') + 'to show a loading spinner' }; } } } }); this.widget = new TestUpdatingWidget({ name: 'Test Widget' }); this.widget.render(); this.updateDeferred = $.Deferred(); this.updateTrackerModel = new UpdateTrackerModel(); }); afterEach(function() { _.each(spies, function(spy) { spy.calls.reset(); }) }); describe('when the update is synchronous', function() { beforeEach(function() { this.widget.doUpdate.and.callFake(function(done) { done(); }); this.widget.update(this.updateTrackerModel); }); it('it should increment the model when the done callback is called', function() { expect(this.updateTrackerModel.get('count')).toBe(1); }); it('should call onIncrement when the count increases', function() { // count increased when the widget updated expect(this.widget.onIncrement.calls.count()).toBe(1); }); it('should call onComplete when the model is set to complete', function() { this.updateTrackerModel.set('complete', true); expect(this.widget.onComplete.calls.count()).toBe(1); }); it('should call onCancelled when the model is set to cancelled', function() { this.updateTrackerModel.set('cancelled', true); expect(this.widget.onCancelled.calls.count()).toBe(1); }); }); describe('when the update is asynchronous', function() { beforeEach(function() { // when a test resolves the deferred, call the done callback this.widget.doUpdate.and.callFake(function(done) { this.updateDeferred.done(done); }.bind(this)); }); describe('and the update is called', function() { beforeEach(function() { this.widget.update(this.updateTrackerModel); }); it('should show the loading spinner until the update completes', function() { expect(this.widget).toShowLoadingSpinner(); this.updateDeferred.resolve(); expect(this.widget).not.toShowLoadingSpinner(); }); it('should not increment the model until the update is complete', function() { expect(this.updateTrackerModel.get('count')).toBe(0); this.updateDeferred.resolve(); expect(this.updateTrackerModel.get('count')).toBe(1); }); it('should call onIncrement when the count increases', function() { this.updateTrackerModel.increment(); expect(this.widget.onIncrement.calls.count()).toBe(1); }); it('should call onComplete when the model is set to complete', function() { this.updateTrackerModel.set('complete', true); expect(this.widget.onComplete.calls.count()).toBe(1); }); it('should call onCancelled when the model is set to cancelled', function() { this.updateTrackerModel.set('cancelled', true); expect(this.widget.onCancelled.calls.count()).toBe(1); }); }); }) }); });
hpe-idol/find
webapp/idol/src/test/js/spec/app/page/dashboard/widgets/updating-widget.js
JavaScript
mit
4,835
import 'rxjs/add/operator/map'; import {Injectable} from '@angular/core'; import {Http, RequestMethod} from '@angular/http'; import {Observable} from 'rxjs/Observable'; import {Cube} from '../models/cube'; import 'rxjs/add/operator/mergeMap'; import {Algorithm} from '../models/analysis/algorithm'; import {Input, InputTypes} from '../models/analysis/input'; import {Output, OutputTypes} from '../models/analysis/output'; import {environment} from '../../environments/environment'; import {ExecutionConfiguration} from '../models/analysis/executionConfiguration'; import {Configuration} from 'jasmine-spec-reporter/built/configuration'; @Injectable() export class AlgorithmsService { private API_DAM_PATH: string = environment.DAMUrl ; constructor(private http: Http) { } getActualCompatibleAlgorithms(): Observable<Algorithm[]> { // console.log(JSON.stringify({time_series: AlgorithmsService.dummyTimeSeries().serialize(), descriptive_statistics: AlgorithmsService.dummyDescriptiveStatistics().serialize(), clustering: AlgorithmsService.dummyClustering().serialize()})); return this.http.get(`${environment.DAMUrl}/services/meta/all`) .map(res => { let algorithms = []; let response = res.json(); for (let key of Object.keys(response)){ let algorithm = new Algorithm().deserialize(response[key]); algorithms.push(algorithm); } return algorithms; }); } getActualCompatibleAlgorithm( algorithmName): Observable<Algorithm> { return this.http.get(`${environment.DAMUrl}/services/meta/${algorithmName}`) .map(res => { let response = res.json(); return new Algorithm().deserialize(response); }); } getTimeSeriesAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('time_series'); } getDescriptiveStatisticsAlgorithm(): Observable<Algorithm> { return this.getActualCompatibleAlgorithm('descriptive_statistics'); } getClusteringAlgorithm(): Observable<Algorithm> { return this.getActualCompatibleAlgorithm('clustering'); } getOutlierDetectionAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('outlier_detection'); /*return Observable.create(function (observer: any) { observer.next(AlgorithmsService.dummyOutlierDetection()); });*/ } getRuleMiningAlgorithm(): Observable<Algorithm> { let that = this; return this.getActualCompatibleAlgorithm('rule_mining'); /*return Observable.create(function (observer: any) { observer.next(AlgorithmsService.dummyOutlierDetection()); });*/ } getAlgorithm(name, cube: Cube): Observable<Algorithm> { switch (name) { case 'time_series': return this.getTimeSeriesAlgorithm(); case 'descriptive_statistics': return this.getDescriptiveStatisticsAlgorithm(); case 'clustering': return this.getClusteringAlgorithm(); case 'outlier_detection': return this.getOutlierDetectionAlgorithm(); case 'rule_mining': return this.getRuleMiningAlgorithm(); default: return this.http.get(`${this.API_DAM_PATH}/${name}`) .map(res => { let response = res.json(); return new Algorithm().deserialize(response); }); } } }
okgreece/indigo
src/app/services/algorithms.ts
TypeScript
mit
3,392
--- title: Հիսուսը որպես ուսուցիչ date: 16/11/2020 --- Աստվածաշունչը բազմաթիվ եզրույթներ է օգտագործում Հիսուսին նկարագրելու համար։ Նա Աստծո Որդին է, Մեսիան, մարդու Որդին, Փրկիչը, Փրկագնողը, Տերը, Աստծո Գառը, և սրանք դեռ մի քանիսն են։ Սակայն այն մարդկանց համար, ովքեր Նրան շատ ավելի մոտիկից էին ճանաչում Հուդայում և Գալիլեայում Նրա՝ երեքից ավելի տևած հանրային ծառայության տարիներին, Նա ուսուցիչ էր։ Նրանք Նրան անվանում էին «Վարդապետ» կամ «Ռաբբի»։ Երկուսն էլ նույն նշանակությունն ունեն՝ «Ուսուցիչ»։ Ուստի ուսուցչի մասնագիտությունը և ուսուցման գործը պիտի որ հատկապես հարմար միջոց եղած լինեին Հիսուսի համար՝ իրականացնելու Իր հանրային ծառայությունը։ Նրա փրկագնման գործն ինչ-որ կերպ մոտ է ուսուցման գործին։ Ավելին, այն կանխագուշակվել է Ավետարանի մարգարեի կողմից։ `Կարդացե՛ք Եսայի 11.1–9 համարները։ Ի՞նչ են դրանք բացահայտում Հիսուսի ուսուցման դերի մասին։` Սուրբ Գրքի ամենացնցող մեսիական մարգարեություններից մեկը զետեղված է Եսայի մարգարեության 11-րդ գլխում։ 1–3-րդ համարները Մեսիայի գալուստը նկարագրում են կրթական եզրույթներով, ի մասնավորի՝ որպես մեկը, ով բերում է գիտելիք, խորհուրդ, իմաստություն և հանճար։ Ողջ հատվածը եզրափակվում է հետևյալ ուշագրավ խոստմամբ. «Տիրոջ գիտությունը պիտի լցնի երկիրը, ինչպես ջրերը, որոնք ծածկում են ծովը» (Եսայի 11.9): Գուցե և Սուրբ Գրքի նման դասերն են ոգեշնչել Էլեն Ուայթին կրթության մասին իր գրքում նշել, որ կրթության և փրկագնման գործերը մեկ են (տե՛ս Դաստիարակություն, էջ 30)։ Կարդացե՛ք Հովհաննես 3.1–3 համարները: Նիկոդեմոսը Հիսուսին դիմում է որպես ռաբբի, իսկ հետագայում, Հիսուսի արած նշաններից (հատկապես Նրա հրաշքները և կյանքի իմաստի ընկալումը) ելնելով՝ Հիսուսի ուսուցման պարգևը որակեց որպես Աստծուց եկող։ Հիսուսն ընդունեց, եթե ոչ Իրեն շնորհված տիտղոսը, ապա հաստատապես Իր ուսուցման պարգևի սկզբնաղբյուրի մասին միտքը, երբ պատասխանեց Նիկոդեմոսին, որ վերջինս պետք է վերստին ծնվի, որպեսզի տեսնի (և՛ հասկանա, և՛ մտնի) Աստծո արքայությունը։ Սա նշանակում է, որ ուրիշներին սովորեցնելու իշխանությունը, նույնիսկ Հիսուսի դեպքում, գալիս է Աստծուց։ Իսկապես որ ուսուցանումն Աստծո պարգևն է։ Այն հանձնարարել է Աստված, որդեգրվել Հիսուսի կողմից և ճանաչվել աստվածային հեղինակություն ունեցող նրանց կողմից, ովքեր ուսուցանվում են։ `Ի՞նչ դեր մենք ունենք Տիրոջ գիտությունն ամբողջ աշխարհում տարածվելու մասին այս մարգարեության իրականացման մեջ։`
imasaru/sabbath-school-lessons
src/hy/2020-04/08/03.md
Markdown
mit
4,090
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>basic_io_object::operator=</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../basic_io_object.html" title="basic_io_object"> <link rel="prev" href="implementation_type.html" title="basic_io_object::implementation_type"> <link rel="next" href="service_type.html" title="basic_io_object::service_type"> </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="implementation_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_io_object.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="service_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.basic_io_object.operator_eq_"></a><a class="link" href="operator_eq_.html" title="basic_io_object::operator=">basic_io_object::operator=</a> </h4></div></div></div> <p> <a class="indexterm" name="boost_asio.indexterm.basic_io_object.operator_eq_"></a> Move-assign a <a class="link" href="../basic_io_object.html" title="basic_io_object"><code class="computeroutput">basic_io_object</code></a>. </p> <pre class="programlisting">basic_io_object &amp; operator=( basic_io_object &amp;&amp; other); </pre> <p> Performs: </p> <pre class="programlisting">get_service().move_assign(get_implementation(), other.get_service(), other.get_implementation()); </pre> <h6> <a name="boost_asio.reference.basic_io_object.operator_eq_.h0"></a> <span class="phrase"><a name="boost_asio.reference.basic_io_object.operator_eq_.remarks"></a></span><a class="link" href="operator_eq_.html#boost_asio.reference.basic_io_object.operator_eq_.remarks">Remarks</a> </h6> <p> Available only for services that support movability, </p> </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 © 2003-2021 Christopher M. Kohlhoff<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="implementation_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_io_object.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="service_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
davehorton/drachtio-server
deps/boost_1_77_0/doc/html/boost_asio/reference/basic_io_object/operator_eq_.html
HTML
mit
3,903
<?php namespace Nathanmac\Utilities\Parser\Formats; use Nathanmac\Utilities\Parser\Exceptions\ParserException; /** * XML Formatter * * @package Nathanmac\Utilities\Parser\Formats * @author Nathan Macnamara <[email protected]> * @license https://github.com/nathanmac/Parser/blob/master/LICENSE.md MIT */ class XML implements FormatInterface { /** * Parse Payload Data * * @param string $payload * * @throws ParserException * @return array * */ public function parse($payload) { if ($payload) { try { $xml = simplexml_load_string($payload, 'SimpleXMLElement', LIBXML_NOCDATA); $ns = ['' => null] + $xml->getDocNamespaces(true); return $this->recursive_parse($xml, $ns); } catch (\Exception $ex) { throw new ParserException('Failed To Parse XML'); } } return []; } protected function recursive_parse($xml, $ns) { $xml_string = (string)$xml; if ($xml->count() == 0 and $xml_string != '') { if (count($xml->attributes()) == 0) { if (trim($xml_string) == '') { $result = null; } else { $result = $xml_string; } } else { $result = array('#text' => $xml_string); } } else { $result = null; } foreach ($ns as $nsName => $nsUri) { foreach ($xml->attributes($nsUri) as $attName => $attValue) { if (!empty($nsName)) { $attName = "{$nsName}:{$attName}"; } $result["@{$attName}"] = (string)$attValue; } foreach ($xml->children($nsUri) as $childName => $child) { if (!empty($nsName)) { $childName = "{$nsName}:{$childName}"; } $child = $this->recursive_parse($child, $ns); if (is_array($result) and array_key_exists($childName, $result)) { if (is_array($result[$childName]) and is_numeric(key($result[$childName]))) { $result[$childName][] = $child; } else { $temp = $result[$childName]; $result[$childName] = [$temp, $child]; } } else { $result[$childName] = $child; } } } return $result; } }
tgoettel9401/Homepage-Schachclub-Niedermohr
vendor/nathanmac/parser/src/Formats/XML.php
PHP
mit
2,603
import PropTypes from 'prop-types' import React from 'react' import { List } from 'immutable' import Modal from './warningmodal.js' import Path from 'path' const FilesList = ({ folders, folderPathToRemove, actions }) => { const addStorageLocation = () => actions.addFolderAskPathSize() const removeStorageLocation = folder => () => { actions.removeFolder(folder) actions.updateFolderToRemove() } const onResizeStorageLocationClick = folder => () => actions.resizeFolder(folder) const onRemoveStorageLocationClick = folder => () => actions.updateFolderToRemove(folder.get('path')) const hideRemoveStorageModal = () => actions.updateFolderToRemove() // sort folders by their name const sortedFolders = folders.sortBy(folder => folder.get('path')) const FileList = sortedFolders.map((folder, key) => ( <div className='property pure-g' key={key}> <div className='pure-u-3-4'> <div className='name'>{folder.get('path')}</div> </div> <div className='pure-u-1-12'> <div>{Math.floor(folder.get('free')).toString()} GB</div> </div> <div className='pure-u-1-12'> <div>{Math.floor(folder.get('size')).toString()} GB</div> </div> <div className='pure-u-1-24' onClick={onResizeStorageLocationClick(folder)} > <div> <i className='fa fa-edit button' /> </div> </div> <div className='pure-u-1-24' onClick={onRemoveStorageLocationClick(folder)} > <div> <i className='fa fa-remove button' /> </div> </div> {folderPathToRemove && folderPathToRemove === folder.get('path') ? ( <Modal title={`Remove "${Path.basename(folder.get('path'))}"?`} message='No longer use this folder for storage? You may lose collateral if you do not have enough space to fill all contracts.' actions={{ acceptModal: removeStorageLocation(folder), declineModal: hideRemoveStorageModal }} /> ) : null} </div> )) return ( <div className='files section'> <div className='property row'> <div className='title' /> <div className='controls full'> <div className='button left' id='edit' onClick={addStorageLocation}> <i className='fa fa-folder-open' /> Add Storage Folder </div> <div className='pure-u-1-12' style={{ textAlign: 'left' }}> Free </div> <div className='pure-u-1-12' style={{ textAlign: 'left' }}> Max </div> <div className='pure-u-1-12' /> </div> </div> {FileList} </div> ) } FilesList.propTypes = { folderPathToRemove: PropTypes.string, folders: PropTypes.instanceOf(List).isRequired } export default FilesList
NebulousLabs/Sia-UI
plugins/Hosting/js/components/fileslist.js
JavaScript
mit
2,874
<?php return unserialize('a:2:{i:0;O:30:"Doctrine\\ORM\\Mapping\\ManyToOne":4:{s:12:"targetEntity";s:5:"Cargo";s:7:"cascade";N;s:5:"fetch";s:4:"LAZY";s:10:"inversedBy";N;}i:1;O:32:"Doctrine\\ORM\\Mapping\\JoinColumns":1:{s:5:"value";a:1:{i:0;O:31:"Doctrine\\ORM\\Mapping\\JoinColumn":7:{s:4:"name";s:8:"CARGO_PK";s:20:"referencedColumnName";s:8:"CARGO_PK";s:6:"unique";b:0;s:8:"nullable";b:0;s:8:"onDelete";N;s:16:"columnDefinition";N;s:9:"fieldName";N;}}}}');
pacordovad/project3
app/cache/prod/annotations/0010890661eca685047ddcd7ea6661ad8672d2e5$cargoPk.cache.php
PHP
mit
460
from PyQt4 import QtCore import acq4.Manager import acq4.util.imageAnalysis as imageAnalysis run = True man = acq4.Manager.getManager() cam = man.getDevice('Camera') frames = [] def collect(frame): global frames frames.append(frame) cam.sigNewFrame.connect(collect) def measure(): if len(frames) == 0: QtCore.QTimer.singleShot(100, measure) return global run if run: global frames frame = frames[-1] frames = [] img = frame.data() w,h = img.shape img = img[2*w/5:3*w/5, 2*h/5:3*h/5] w,h = img.shape fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0]) # convert sigma to full width at 1/e fit[0][3] *= 2 * 2**0.5 print "WIDTH:", fit[0][3] * frame.info()['pixelSize'][0] * 1e6, "um" print " fit:", fit else: global frames frames = [] QtCore.QTimer.singleShot(2000, measure) measure()
tropp/acq4
acq4/analysis/scripts/beamProfiler.py
Python
mit
976
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: calculator.pro Example File (demos/declarative/calculator/calculator.pro)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">calculator.pro Example File</h1> <span class="small-subtitle">demos/declarative/calculator/calculator.pro</span> <!-- $$$demos/declarative/calculator/calculator.pro-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> # Add more folders to ship with the application, here folder_01.source = qml/calculator folder_01.target = qml DEPLOYMENTFOLDERS = folder_01 # Additional import path used to resolve QML modules in Creator's code model QML_IMPORT_PATH = symbian:TARGET.UID3 = 0xE8BEAB39 # Smart Installer package's UID # This UID is from the protected range and therefore the package will # fail to install if self-signed. By default qmake uses the unprotected # range value if unprotected UID is defined for the application and # 0x2002CCCF value if protected UID is given to the application #symbian:DEPLOYMENT.installer_header = 0x2002CCCF # Allow network access on Symbian symbian:TARGET.CAPABILITY += NetworkServices # If your application uses the Qt Mobility libraries, uncomment the following # lines and add the respective components to the MOBILITY variable. # CONFIG += mobility # MOBILITY += # Speed up launching on MeeGo/Harmattan when using applauncherd daemon # CONFIG += qdeclarative-boostable # Add dependency to Symbian components # CONFIG += qt-components # The .cpp file which was generated for your project. Feel free to hack it. SOURCES += main.cpp # Please do not modify the following two lines. Required for deployment. desktopInstallPrefix=$$[QT_INSTALL_DEMOS]/declarative/calculator exists(qmlapplicationviewer/qmlapplicationviewer.pri):include(qmlapplicationviewer/qmlapplicationviewer.pri) else:include(../../helper/qmlapplicationviewer/qmlapplicationviewer.pri) qtcAddDeployment()</pre> </div> <!-- @@@demos/declarative/calculator/calculator.pro --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
stephaneAG/PengPod700
QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/demos-declarative-calculator-calculator-pro.html
HTML
mit
10,847
<!doctype html> <html lang="en"> <head> <title>Code coverage report for ol/interaction/dragboxinteraction.js</title> <meta charset="utf-8" /> <link rel="stylesheet" href="../../prettify.css" /> <link rel="stylesheet" href="../../base.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type='text/css'> .coverage-summary .sorter { background-image: url(../../sort-arrow-sprite.png); } </style> </head> <body> <div class='wrapper'> <div class='pad1'> <h1> <a href="../../index.html">all files</a> / <a href="index.html">ol/interaction/</a> dragboxinteraction.js </h1> <div class='clearfix'> <div class='fl pad1y space-right2'> <span class="strong">55.1% </span> <span class="quiet">Statements</span> <span class='fraction'>27/49</span> </div> <div class='fl pad1y space-right2'> <span class="strong">22.22% </span> <span class="quiet">Branches</span> <span class='fraction'>4/18</span> </div> <div class='fl pad1y space-right2'> <span class="strong">50% </span> <span class="quiet">Functions</span> <span class='fraction'>3/6</span> </div> <div class='fl pad1y space-right2'> <span class="strong">55.1% </span> <span class="quiet">Lines</span> <span class='fraction'>27/49</span> </div> </div> </div> <div class='status-line medium'></div> <pre><table class="coverage"> <tr><td class="line-count quiet">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201</td><td class="line-coverage quiet"><span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">118×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1×</span> <span class="cline-any cline-yes">60×</span> <span class="cline-any cline-yes">60×</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">// FIXME draw drag box goog.provide('ol.DragBoxEvent'); goog.provide('ol.interaction.DragBox'); &nbsp; goog.require('goog.events.Event'); goog.require('ol'); goog.require('ol.events.ConditionType'); goog.require('ol.events.condition'); goog.require('ol.interaction.Pointer'); goog.require('ol.render.Box'); &nbsp; &nbsp; /** * @const * @type {number} */ ol.DRAG_BOX_HYSTERESIS_PIXELS_SQUARED = ol.DRAG_BOX_HYSTERESIS_PIXELS * ol.DRAG_BOX_HYSTERESIS_PIXELS; &nbsp; &nbsp; /** * @enum {string} */ ol.DragBoxEventType = { /** * Triggered upon drag box start. * @event ol.DragBoxEvent#boxstart * @api stable */ BOXSTART: 'boxstart', /** * Triggered upon drag box end. * @event ol.DragBoxEvent#boxend * @api stable */ BOXEND: 'boxend' }; &nbsp; &nbsp; &nbsp; /** * @classdesc * Events emitted by {@link ol.interaction.DragBox} instances are instances of * this type. * * @param {string} type The event type. * @param {ol.Coordinate} coordinate The event coordinate. * @extends {goog.events.Event} * @constructor * @implements {oli.DragBoxEvent} */ ol.DragBoxEvent = <span class="fstat-no" title="function not covered" >function(type, coordinate) {</span> <span class="cstat-no" title="statement not covered" > goog.base(this, type);</span> &nbsp; /** * The coordinate of the drag event. * @const * @type {ol.Coordinate} * @api stable */ <span class="cstat-no" title="statement not covered" > this.coordinate = coordinate;</span> &nbsp; }; goog.inherits(ol.DragBoxEvent, goog.events.Event); &nbsp; &nbsp; &nbsp; /** * @classdesc * Allows the user to draw a vector box by clicking and dragging on the map, * normally combined with an {@link ol.events.condition} that limits * it to when the shift or other key is held down. This is used, for example, * for zooming to a specific area of the map * (see {@link ol.interaction.DragZoom} and * {@link ol.interaction.DragRotateAndZoom}). * * This interaction is only supported for mouse devices. * * @constructor * @extends {ol.interaction.Pointer} * @fires ol.DragBoxEvent * @param {olx.interaction.DragBoxOptions=} opt_options Options. * @api stable */ ol.interaction.DragBox = function(opt_options) { &nbsp; goog.base(this, { handleDownEvent: ol.interaction.DragBox.handleDownEvent_, handleDragEvent: ol.interaction.DragBox.handleDragEvent_, handleUpEvent: ol.interaction.DragBox.handleUpEvent_ }); &nbsp; var options = opt_options ? opt_options : <span class="branch-1 cbranch-no" title="branch not covered" >{};</span> &nbsp; /** * @type {ol.render.Box} * @private */ this.box_ = new ol.render.Box(options.className || <span class="branch-1 cbranch-no" title="branch not covered" >'ol-dragbox')</span>; &nbsp; /** * @type {ol.Pixel} * @private */ this.startPixel_ = null; &nbsp; /** * @private * @type {ol.events.ConditionType} */ this.condition_ = options.condition ? options.condition : <span class="branch-1 cbranch-no" title="branch not covered" >ol.events.condition.always;</span> &nbsp; }; goog.inherits(ol.interaction.DragBox, ol.interaction.Pointer); &nbsp; &nbsp; /** * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event. * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleDragEvent_ = <span class="fstat-no" title="function not covered" >function(mapBrowserEvent) {</span> <span class="cstat-no" title="statement not covered" > if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > return;</span> } &nbsp; <span class="cstat-no" title="statement not covered" > this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);</span> }; &nbsp; &nbsp; /** * Returns geometry of last drawn box. * @return {ol.geom.Polygon} Geometry. * @api stable */ ol.interaction.DragBox.prototype.getGeometry = function() { return this.box_.getGeometry(); }; &nbsp; &nbsp; /** * To be overriden by child classes. * FIXME: use constructor option instead of relying on overridding. * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. * @protected */ ol.interaction.DragBox.prototype.onBoxEnd = ol.nullFunction; &nbsp; &nbsp; /** * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event. * @return {boolean} Stop drag sequence? * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleUpEvent_ = <span class="fstat-no" title="function not covered" >function(mapBrowserEvent) {</span> <span class="cstat-no" title="statement not covered" > if (!ol.events.condition.mouseOnly(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > return true;</span> } &nbsp; <span class="cstat-no" title="statement not covered" > this.box_.setMap(null);</span> &nbsp; <span class="cstat-no" title="statement not covered" > var deltaX = mapBrowserEvent.pixel[0] - this.startPixel_[0];</span> <span class="cstat-no" title="statement not covered" > var deltaY = mapBrowserEvent.pixel[1] - this.startPixel_[1];</span> &nbsp; <span class="cstat-no" title="statement not covered" > if (deltaX * deltaX + deltaY * deltaY &gt;=</span> ol.DRAG_BOX_HYSTERESIS_PIXELS_SQUARED) { <span class="cstat-no" title="statement not covered" > this.onBoxEnd(mapBrowserEvent);</span> <span class="cstat-no" title="statement not covered" > this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXEND,</span> mapBrowserEvent.coordinate)); } <span class="cstat-no" title="statement not covered" > return false;</span> }; &nbsp; &nbsp; /** * @param {ol.MapBrowserPointerEvent} mapBrowserEvent Event. * @return {boolean} Start drag sequence? * @this {ol.interaction.DragBox} * @private */ ol.interaction.DragBox.handleDownEvent_ = function(mapBrowserEvent) { <span class="missing-if-branch" title="else path not taken" >E</span>if (!ol.events.condition.mouseOnly(mapBrowserEvent)) { return false; } &nbsp; <span class="cstat-no" title="statement not covered" > var browserEvent = mapBrowserEvent.browserEvent;</span> <span class="cstat-no" title="statement not covered" > if (browserEvent.isMouseActionButton() &amp;&amp; this.condition_(mapBrowserEvent)) {</span> <span class="cstat-no" title="statement not covered" > this.startPixel_ = mapBrowserEvent.pixel;</span> <span class="cstat-no" title="statement not covered" > this.box_.setMap(mapBrowserEvent.map);</span> <span class="cstat-no" title="statement not covered" > this.box_.setPixels(this.startPixel_, this.startPixel_);</span> <span class="cstat-no" title="statement not covered" > this.dispatchEvent(new ol.DragBoxEvent(ol.DragBoxEventType.BOXSTART,</span> mapBrowserEvent.coordinate)); <span class="cstat-no" title="statement not covered" > return true;</span> } else { <span class="cstat-no" title="statement not covered" > return false;</span> } }; &nbsp;</pre></td></tr> </table></pre> <div class='push'></div><!-- for sticky footer --> </div><!-- /wrapper --> <div class='footer quiet pad2 space-top1 center small'> Code coverage generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Fri Nov 06 2015 19:36:11 GMT+0100 (CET) </div> </div> <script src="../../prettify.js"></script> <script> window.onload = function () { if (typeof prettyPrint === 'function') { prettyPrint(); } }; </script> <script src="../../sorter.js"></script> </body> </html>
LeoLombardi/tos-laimas-compass
tos-laimas-compass-win32-x64/resources/app/node_modules/openlayers/coverage/ol/interaction/dragboxinteraction.js.html
HTML
mit
19,989
import {browser, by, element, ExpectedConditions} from 'protractor'; import { ProjectsPage } from './projects.page'; export class BellowsProjectSettingsPage { private readonly projectsPage = new ProjectsPage(); conditionTimeout: number = 3000; settingsMenuLink = element(by.id('settings-dropdown-button')); projectSettingsLink = element(by.id('dropdown-project-settings')); // Get the projectSettings for project projectName get(projectName: string) { this.projectsPage.get(); this.projectsPage.clickOnProject(projectName); browser.wait(ExpectedConditions.visibilityOf(this.settingsMenuLink), this.conditionTimeout); this.settingsMenuLink.click(); browser.wait(ExpectedConditions.visibilityOf(this.projectSettingsLink), this.conditionTimeout); this.projectSettingsLink.click(); } noticeList = element.all(by.repeater('notice in $ctrl.notices()')); firstNoticeCloseButton = this.noticeList.first().element(by.buttonText('×')); tabDivs = element.all(by.className('tab-pane')); activePane = element(by.css('div.tab-pane.active')); /* Would like to use id locators, but the pui-tab directive that is used in the project settingsPage in scripture forge is currently making it hard to assign an id to the tab element. This should be updated, but due to time shortage, it will be left as is. - Mark W 2018-01-15 */ tabs = { project: element(by.linkText('Project Properties')), // reports: element(by.linkText('Reports')), // This feature is never tested // archive: element(by.linkText('Archive')), // This is a disabled feature remove: element(by.linkText('Delete')) }; projectTab = { name: element(by.model('project.projectName')), code: element(by.model('project.projectCode')), projectOwner: element(by.binding('project.ownerRef.username')), saveButton: element(by.id('project-properties-save-button')) }; // placeholder since we don't have Reports tests reportsTab = { }; // Archive tab currently disabled // this.archiveTab = { // archiveButton: this.activePane.element(by.buttonText('Archive this project')) // }; deleteTab = { deleteBoxText: this.activePane.element(by.id('deletebox')), deleteButton: this.activePane.element(by.id('deleteProject')) }; }
ermshiperete/web-languageforge
test/app/bellows/shared/project-settings.page.ts
TypeScript
mit
2,290
#ifndef AC_GEPT3DAR_H #define AC_GEPT3DAR_H // // (C) Copyright 1993-1999, 2010 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // DESCRIPTION: // // This file contains the definition for a dynamic array, called // AcGePoint3dArray, of objects of type "AcGePoint3d". // // "Dynamic array" means that the array can grow without bounds, // unlike declaring an array of objects of type "AcGePoint3d" in the // usual manner. For example declaring "AcGePoint3d myArray[10]" // is limited to holding only ten entries. // // In order to use the class AcGePoint3dArray, you need to understand // a couple of simple, yet key, concepts: // // 1) The logical length of the array. // - How many entries have been placed into the array, // initially always zero. // 2) The physical length of the array. // - How many entries the array will hold before it // automatically "grows" larger. // 3) The grow length of the array. // - How much the array will grow when required. // // The physical length of the array is the actual length of the // physically allocated, but perhaps not fully used, array. // As a point of clarification, the size in bytes of the array // buffer for an array called `myArray' would be: // // sizeOf(AcGePoint3d) * myArray.physicalLength(). // // The physical length of the array can be zero or any positive // integer. // // The logical length of the array (or just the "length()") reflects // how many elements of AcGePoint3d have been placed into the array // with, for example, append() or insertAt(). Many member-functions // are only valid for indices that are greater than or equal to // zero AND less than length(). For example, indexing into the // array with the operator[] is only valid for indices in this range. // // You can explicitly set the logical length() to any value and // if the physical length is not large enough the array will grow to // that length. Note that if the logical length is explicitly reset // to a larger value, then all the entries from the old length up // to the new length may contain garbage values, therefor they must be // initialized explicitly. // // The logical length is always less than or equal to the physical // length. NOTE that the array ALWAYS starts out empty, i.e., the // length() always starts at zero regardless of the initial physical // length. // // If you add an element to the array causing the logical length // to become greater than the physical length of the array then // the "grow length" determines how much additional space to // allocate, and the physical length will increase by the grow length. // // The grow length must be a positive number, that is, zero is an illegal // grow length. #include "adesk.h" #include "assert.h" #include "gepnt3d.h" #include "acarray.h" typedef AcArray<AcGePoint3d> AcGePoint3dArray; #if GE_LOCATED_NEW GE_DLLEXPIMPORT AcGe::metaTypeIndex AcGeGetMetaTypeIndex(AcGePoint3dArray* pT); #endif #endif
kevinzhwl/ObjectARXCore
2012/inc/gept3dar.h
C
mit
3,990
/** * Framework APIs (global - app.*) * * Note: View APIs are in view.js (view - view.*) * * @author Tim Lauv * @created 2015.07.29 * @updated 2017.04.04 */ ;(function(app){ /** * Universal app object creation api entry point * ---------------------------------------------------- * @deprecated Use the detailed apis instead. */ app.create = function(type, config){ console.warn('DEV::Application::create() method is deprecated, use methods listed in ', app._apis, ' for alternatives'); }; /** * Detailed api entry point * ------------------------ * If you don't want to use .create() there you go: */ _.extend(app, { //----------------view------------------ //pass in [name,] options to define view (named view will be registered) //pass in name to get registered view def //pass in options, true to create anonymous view view: function(name /*or options*/, options /*or instance flag*/){ if(_.isString(name) && _.isPlainObject(options)){ return app.Core.View.register(name, options); } if(_.isPlainObject(name)){ var instance = options; options = name; var Def = app.Core.View.register(options); if(_.isBoolean(instance) && instance) return Def.create(); return Def; } return app.Core.View.get(name); }, //@deprecated--------------------- //pass in [name,] options to register (always requires a name) //pass in [name] to get (name can be of path form) context: function(name /*or options*/, options){ if(!options) { if(_.isString(name) || !name) return app.Core.Context.get(name); else options = name; } else _.extend(options, {name: name}); console.warn('DEV::Application::context() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.Core.Context.register(options); }, //-------------------------------- //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) widget: function(name, options /*or factory*/){ if(!options) return app.Core.Widget.get(name); if(_.isFunction(options)) //register return app.Core.Widget.register(name, options); return app.Core.Widget.create(name, options); //you can not register the definition when providing name, options. }, //pass in name, factory to register //pass in name, options to create //pass in [name] to get (name can be of path form) editor: function(name, options /*or factory*/){ if(!options) return app.Core.Editor.get(name); if(_.isFunction(options)) //register return app.Core.Editor.register(name, options); return app.Core.Editor.create(name, options); //you can not register the definition when providing name, options. }, //@deprecated--------------------- regional: function(name, options){ options = options || {}; if(_.isString(name)) _.extend(options, {name: name}); else _.extend(options, name); console.warn('DEV::Application::regional() method is deprecated, use .view() instead for', options.name || options /*as an indicator of anonymous view*/); return app.view(options, !options.name); }, //-------------------------------- //(name can be of path form) has: function(name, type){ type = type || 'View'; if(name) return app.Core[type] && app.Core[type].has(name); _.each(['Context', 'View', 'Widget', 'Editor'], function(t){ if(!type && app.Core[t].has(name)) type = t; }); return type; }, //(name can be of path form) //always return View definition. get: function(name, type, options){ if(!name) return { 'Context': app.Core.Context.get(), 'View': app.Core.View.get(), 'Widget': app.Core.Widget.get(), 'Editor': app.Core.Editor.get() }; if(_.isPlainObject(type)){ options = type; type = undefined; } var Reusable, t = type || 'View'; options = _.extend({fallback: false, override: false}, options); //try local if(!options.override) Reusable = (app.Core[t] && app.Core[t].get(name)) || (options.fallback && app.Core['View'].get(name)); //try remote, if we have app.viewSrcs set to load the View def dynamically if(!Reusable && app.config && app.config.viewSrcs){ var targetJS = _.compact([app.config.viewSrcs, t.toLowerCase()/*not view.category yet*/, app.nameToPath(name)]).join('/') + '.js'; app.inject.js( targetJS, true //sync ).done(function(){ app.debug(t, name, 'injected', 'from', app.config.viewSrcs); if(app.has(name, t) || (options.fallback && app.has(name))) Reusable = app.get(name, t, {fallback: true}); else throw new Error('DEV::Application::get() loaded definitions other than required ' + name + ' of type ' + t + ' from ' + targetJS + ', please check your view name in that file!'); }).fail(function(jqXHR, settings, e){ if(!options.fallback || (t === 'View')) throw new Error('DEV::Application::get() can NOT load definition for ' + name + ' - [' + e + ']'); else Reusable = app.get(name, 'View'); }); } return Reusable; }, //**Caveat**: spray returns the region (created on $anchor), upon returning, its 'show' event has already passed. spray: function($anchor, View /*or template or name or instance or options or svg draw(paper){} func */, options, parentCt){ var $el = $($anchor); parentCt = parentCt || app.mainView; //check if $anchor is already a region var region = $el.data('region'); var regionName = region && region._name; if(!regionName){ regionName = $el.attr('region') || _.uniqueId('anonymous-region-'); $el.attr('region', regionName); region = parentCt.addRegion(regionName, '[region="' + regionName + '"]'); region.ensureEl(parentCt); } else parentCt = region.parentCt; //see if it is an svg draw(paper){} function if(_.isFunction(View) && View.length === 1){ //svg return parentCt.show(regionName, { template: '<div svg="canvas"></div>', data: options && options.data, //only honor options.data if passed in. svg: { canvas: View }, onPaperCleared: function(paper){ paper._fit($el); }, }); }else //view return parentCt.show(regionName, View, options); //returns the sub-regional view. }, icing: function(name, flag, View, options){ if(_.isBoolean(name)){ options = View; View = flag; flag = name; name = 'default'; } var regionName = ['icing', 'region', name].join('-'); if(!app.mainView.getRegion(regionName) && !_.isBoolean(name)){ options = flag; View = name; flag = true; name = 'default'; } regionName = ['icing', 'region', name].join('-'); var ir = app.mainView.getRegion(regionName); if(flag === false){ ir.$el.hide(); ir.currentView && ir.currentView.close(); } else { ir.$el.show(); app.mainView.show(regionName, View, options); } }, coop: function(event){ var args = _.toArray(arguments); args.unshift('app:coop'); app.trigger.apply(app, args); args = args.slice(2); args.unshift('app:coop-' + event); app.trigger.apply(app, args); return app; }, pathToName: function(path){ if(!_.isString(path)) throw new Error('DEV::Application::pathToName() You must pass in a valid path string.'); if(_.contains(path, '.')) return path; return path.split('/').map(_.string.humanize).map(_.string.classify).join('.'); }, nameToPath: function(name){ if(!_.isString(name)) throw new Error('DEV::Application::nameToPath() You must pass in a Reusable view name.'); if(_.contains(name, '/')) return name; return name.split('.').map(_.string.humanize).map(_.string.slugify).join('/'); }, //----------------navigation----------- navigate: function(options, silent){ return app.trigger('app:navigate', options, silent); }, navPathArray: function(){ return _.compact(window.location.hash.replace('#navigate', '').split('/')); }, //-----------------mutex--------------- lock: function(topic){ return app.Core.Lock.lock(topic); }, unlock: function(topic){ return app.Core.Lock.unlock(topic); }, available: function(topic){ return app.Core.Lock.available(topic); }, //-----------------remote data------------ //returns jqXHR object (use promise pls) remote: function(options /*or url*/, payload, restOpt){ options = options || {}; if(options.payload || payload){ payload = options.payload || payload; return app.Core.Remote.change(options, _.extend({payload: payload}, restOpt)); } else return app.Core.Remote.get(options, restOpt); }, download: function(ticket /*or url*/, options /*{params:{...}} only*/){ return app.Util.download(ticket, options); }, upload: function(url, options){ return app.Util.upload(url, options); }, //data push //(ws channels) _websockets: {}, /** * returns a promise. * * Usage * ----- * register: app.config.defaultWebsocket or app.ws(socketPath); * receive (e): view.coop['ws-data-[channel]'] or app.onWsData = custom fn; * send (json): app.ws(socketPath) * .then(function(ws){ws.channel(...).json({...});}); default per channel data * .then(function(ws){ws.send(); or ws.json();}); anything by any contract * e.websocket = ws in .then(function(ws){}) * * Default messaging contract * -------------------------- * Nodejs /devserver: json {channel: '..:..', payload: {..data..}} through ws.channel('..:..').json({..data..}) * Python ASGI: json {stream: '...', payload: {..data..}} through ws.stream('...').json({..data..}) * * Reconnecting websockets * ----------------------- * websocket path ends with '+' will be reconnecting websocket when created. * */ ws: function(socketPath, coopEvent /*or callback or options*/){ if(!app.detect('websockets')) throw new Error('DEV::Application::ws() Websocket is not supported by your browser!'); socketPath = socketPath || app.config.defaultWebsocket || '/ws'; var reconnect = false; if(_.string.endsWith(socketPath, '+')){ socketPath = socketPath.slice(0, socketPath.length - 1); reconnect = true; } var d = $.Deferred(); if(!app._websockets[socketPath]) { app._websockets[socketPath] = new WebSocket(location.protocol.replace('http', 'ws') + '//' + location.host + socketPath); app._websockets[socketPath].path = socketPath; app._websockets[socketPath].reconnect = reconnect; //events: 'open', 'error', 'close', 'message' = e.data //apis: send(), +json(), +channel().json(), close() app._websockets[socketPath].json = function(data){ app._websockets[socketPath].send(JSON.stringify(data)); }; app._websockets[socketPath].channel = function(channel){ return { name: channel, websocket: app._websockets[socketPath], json: function(data){ app._websockets[socketPath].json({ channel: channel, stream: channel, //alias for ASGI backends payload: data }); } }; }; app._websockets[socketPath].stream = app._websockets[socketPath].channel; //alias for ASGI backends app._websockets[socketPath].onclose = function(){ var ws = app._websockets[socketPath]; delete app._websockets[socketPath]; if(ws.reconnect) app.ws(ws.path + '+'); }; app._websockets[socketPath].onopen = function(){ return d.resolve(app._websockets[socketPath]); }; //general ws data stub //server need to always send default json contract string {"channel/stream": "...", "payload": "..."} //Opt: override this through app.ws(path).then(function(ws){ws.onmessage=...}); app._websockets[socketPath].onmessage = function(e){ //opt a. override app.onWsData to active otherwise app.trigger('app:ws-data', {websocket: app._websockets[socketPath], raw: e.data}); //opt b. use global coop event 'ws-data-[channel]' in views directly (default json contract) try { var data = JSON.parse(e.data); app.coop('ws-data-' + (data.channel || data.stream), data.payload, app._websockets[socketPath].channel(data.channel || data.stream)); }catch(ex){ console.warn('DEV::Application::ws() Websocket is getting non-default {channel: ..., payload: ...} json contract strings...'); } }; //register coopEvent or callback function or callback options if(coopEvent){ //onmessage callback function if(_.isFunction(coopEvent)){ //overwrite onmessage callback function defined by framework app._websockets[socketPath].onmessage = function(e){ coopEvent(e.data, e, app._websockets[socketPath]); }; } //object may contain onmessage, onerror, since onopen and onclose is done by the framework else if(_.isPlainObject(coopEvent)){ //traverse through object to register all callback events _.each(coopEvent, function(fn, eventName){ //guard events if(_.contains(['onmessage', 'onerror'], eventName)) app._websockets[socketPath][eventName] = fn; }); } //app coop event else if(_.isString(coopEvent)){ //trigger coop event with data from sse's onmessage callback app._websockets[socketPath].onmessage = function(e){ app.coop('ws-data-' + coopEvent, e.data, e, app._websockets[socketPath]); }; } //type is not right else console.warn('DEV::Application::ws() The coopEvent or callback function or callbacks\' options you give is not right.'); } }else d.resolve(app._websockets[socketPath]); return d.promise(); }, //data polling //(through later.js) and emit data events/or invoke callback _polls: {}, poll: function(url /*or {options} for app.remote()*/, occurrence, coopEvent /*or callback or options*/) { //stop everything if (url === false){ return _.map(this._polls, function(card) { return card.cancel(); }); } var schedule; if (_.isString(occurrence) && !Number.parseInt(occurrence)) { schedule = app.later.parse.text(occurrence); if (schedule.error !== -1) throw new Error('DEV::Application::poll() occurrence string unrecognizable...'); } else if (_.isPlainObject(occurrence)) schedule = occurrence; else //number schedule = Number(occurrence); //make a key from url, or {url: ..., params/querys} var key = url; if (_.isPlainObject(key)) key = [key.url, _.reduce((_.map(key.params || key.querys, function(qV, qKey) { return [qKey, qV].join('='); })).sort(), function(qSignature, more) { return [more, qSignature].join('&'); }, '')].join('?'); //cancel polling if (occurrence === false) { if (this._polls[key]) return this._polls[key].cancel(); console.warn('DEV::Application::poll() No polling card registered yet for ' + key); return; } //cancel previous polling if (this._polls[key]) this._polls[key].cancel(); //register polling card if (!occurrence || !coopEvent) throw new Error('DEV::Application::poll() You must specify an occurrence and a coop event or callback...'); var card = { _key: key, url: url, eof: coopEvent, timerId: undefined, failed: 0, valid: true, occurrence: occurrence, //info only }; this._polls[key] = card; var call = _.isNumber(schedule) ? window.setTimeout : app.later.setTimeout; //if coopEvent is an object. register options events before calling app.remote if(_.isPlainObject(coopEvent)){ //save url var temp = url; //build url as an object for app.remote url = { url: temp }; _.each(coopEvent, function(fn, eventName){ //guard for only allowing $.ajax events if(_.contains(['beforeSend', 'error', 'dataFilter', 'success', 'complete'], eventName)) url[eventName] = fn; }); } var worker = function() { app.remote(url).done(function(data) { //callback if (_.isFunction(card.eof)) card.eof(data, card); //coop event else app.coop('poll-data-' + card.eof, data, card); }).fail(function() { card.failed++; //Warning: Hardcoded 3 attemps here! if (card.failed >= 3) card.cancel(); }).always(function() { //go schedule the next call if (card.valid) card.timerId = call(worker, schedule); }); }; //+timerType card.timerType = (call === window.setTimeout) ? 'native' : 'later.js'; //+cancel() var that = this; card.cancel = function() { this.valid = false; if (this.timerType === 'native') !_.isUndefined(this.timerId) && window.clearTimeout(this.timerId); else !_.isUndefined(this.timerId) && this.timerId.clear(); delete that._polls[this._key]; return this; }; //make the 1st call (eagerly) worker(); }, //-----------------ee/observer with built-in state-machine---------------- //use start('stateB') or trigger('stateA-->stateB') to swap between states //use ['stateA-->stateB', 'stateC<-->stateB', 'stateA<--stateC', ...] in edges to constrain state changes. ee: function(data, evtmap, edges){ //+on/once, off, +start/reset/stop/getState/getEdges; +listenTo/Once, stopListening; +trigger*; var dispatcher; data = _.extend({}, data, {cid: _.uniqueId('ee')}); evtmap = _.extend({ 'initialize': _.noop, 'finalize': _.noop, }, evtmap); edges = _.reduce(edges || {}, function(mem, val, index){ var bi = val.match('(.*)<-->(.*)'), left = val.match('(.*)<--(.*)'), right = val.match('(.*)-->(.*)'); if(bi){ mem[bi[1] + '-->' + bi[2]] = true; mem[bi[2] + '-->' + bi[1]] = true; } else if (left) mem[left[2] + '-->' + left[1]] = true; else if (right) mem[val] = true; else console.warn('DEV::Application::ee() illegal edge format: ' + val); return mem; }, {}); if(!_.size(edges)) edges = undefined; dispatcher = _.extend(data, Backbone.Events); var oldTriggerFn = dispatcher.trigger; var currentState = ''; //add a state-machine friendly .trigger method; dispatcher.trigger = function(){ var changeOfStates = arguments[0] && arguments[0].match('(.*)-->(.*)'); if(changeOfStates && changeOfStates.length){ var from = _.string.trim(changeOfStates[1]), to = _.string.trim(changeOfStates[2]); //check edge constraints if(from && to && edges && !edges[arguments[0]]){ console.warn('DEV::Application::ee() edge constraint: ' + from + '-x->' + to); return this; } //check current state if(from != currentState){ console.warn('DEV::Application::ee() current state is ' + (currentState || '\'\'') + ' not ' + from); return this; } this.trigger('leave', {to: to}); //unregister event listeners in [from] state _.each(evtmap[from], function(listener, e){ dispatcher.off(from + ':' + e); }); //register event listeners in [to] state _.each(evtmap[to], function(listener, e){ dispatcher.on(to + ':' + e, listener); }); currentState = to; this.trigger('enter', {from: from}); } else { if(evtmap[currentState] && evtmap[currentState][arguments[0]]) arguments[0] = currentState + ':' + arguments[0]; oldTriggerFn.apply(this, arguments); } return this; }; //add an internal worker swap method; dispatcher._swap = function(targetState){ targetState = targetState || ''; this.trigger(currentState + '-->' + targetState); return this; }; //add a start method; (start at any state) dispatcher.start = function(targetState){ targetState = targetState || currentState; return this._swap(targetState); }; //add a reset method; (reset to '' state) dispatcher.reset = function(){ return this._swap(); }; //add a clean-up method; dispatcher.stop = function(){ this.trigger('finalize'); this.off(); this.stopListening(); }; //add some getters; dispatcher.getState = function(){ return currentState; }; dispatcher.getEdges = function(){ return edges; }; //mount shared events _.each(evtmap, function(listener, eOrStateName){ if(!_.isFunction(listener)) return; dispatcher.on(eOrStateName, listener); }); this.trigger('initialize'); return dispatcher; }, model: function(data, flat){ if(_.isBoolean(data)){ flat = data; data = undefined; } if(flat) return new Backbone.Model(data); //Warning: Possible performance impact...(default) return new Backbone.DeepModel(data); ///////////////////////////////////////// }, collection: function(data){ if(data && !_.isArray(data)) throw new Error('DEV::Application::collection You need to specify an array to init a collection'); return new Backbone.Collection(data); }, //bridge extract from app.Util.deepObjectKeys extract: function(keypath, from){ return app.Util.deepObjectKeys.extract(keypath, from); }, //bridge pack from app.Util.deepObjectKeys pack: function(keypathObj, to){ return app.Util.deepObjectKeys.pack(keypathObj, to); }, mock: function(schema, provider/*optional*/, url/*optional*/){ return app.Util.mock(schema, provider, url); }, //----------------url params--------------------------------- param: function(key, defaultVal){ var params = app.uri(window.location.href).search(true) || {}; if(key) return params[key] || defaultVal; return params; }, //----------------raw animation (DON'T mix with jQuery fx)--------------- //(specifically, don't call $.animate() inside updateFn) //(you also can NOT control the rate the browser calls updateFn, its 60 FPS all the time...) animation: function(updateFn, condition, ctx){ var id; var stepFn = function(t){ updateFn.call(ctx);//...update...(1 tick) if(!condition || (condition && condition.call(ctx)))//...condition...(to continue) move(); }; var move = function(){ if(id === undefined) return; id = app._nextFrame(stepFn); }; var stop = function(){ app._cancelFrame(id); id = undefined; }; return { start: function(){id = -1; move();}, stop: stop }; }, _nextFrame: function(stepFn){ //return request id return window.requestAnimationFrame(stepFn); }, _cancelFrame: function(id){ return window.cancelAnimationFrame(id); }, //effects see https://daneden.github.io/animate.css/ //sample usage: 'ready' --> app.animateItems(); animateItems: function(selector /*or $items*/, effect, stagger){ var $selector = $(selector); if(_.isNumber(effect)){ stagger = effect; effect = undefined; } effect = effect || 'flipInX'; stagger = stagger || 150; var inOrOut = /In/.test(effect)? 1: (/Out/.test(effect)? -1: 0); $selector.each(function(i, el){ var $el = $(el); //////////////////different than region.show effect because of stagger delay////////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 0); else $el.css('opacity', 1); ////////////////////////////////////////////////////////////////////////////////////////////// _.delay(function($el){ var fxName = effect + ' animated'; $el.anyone(app.ADE, function(){ $el.removeClass(fxName); }).addClass(fxName); ///////////////reset opacity immediately, not after ADE/////////////// if(inOrOut) if(inOrOut === 1) $el.css('opacity', 1); else $el.css('opacity', 0); ////////////////////////////////////////////////////////////////////// }, i * stagger, $el); }); }, //Built-in web worker utility, bridged from app.Util.worker. worker: function(name/*web worker's name*/, coopEOrCallbackOrOpts){ return app.Util.worker(name, coopEOrCallbackOrOpts); }, //Built-in Server-Sent Event(SSE) utility, bridged from app.Util.sse sse: function(url/*sse's url*/, topics/*['...', '...']*/, coopEOrCallbackOrOpts){ return app.Util.sse(url, topics, coopEOrCallbackOrOpts); }, //----------------config.rapidEventDelay wrapped util-------------------- //**Caveat**: if using cached version, pass `this` and other upper scope vars into fn as arguments, else //these in fn will be cached forever and might no longer exist or point to the right thing when called... throttle: function(fn, ms, cacheId){ ms = ms || app.config.rapidEventDelay; fn = _.throttle(fn, ms); if(!cacheId) return fn; //cached version (so you can call right after wrapping it) this._tamedFns = this._tamedFns || {}; var key = fn + cacheId + '-throttle' + ms; if(!this._tamedFns[key]) this._tamedFns[key] = fn; return this._tamedFns[key]; }, debounce: function(fn, ms, cacheId){ ms = ms || app.config.rapidEventDelay; fn = _.debounce(fn, ms); if(!cacheId) return fn; //cached version (so you can call right after wrapping it) this._tamedFns = this._tamedFns || {}; var key = fn + cacheId + '-debounce' + ms; if(!this._tamedFns[key]) this._tamedFns[key] = fn; return this._tamedFns[key]; }, //app wide e.preventDefault() util preventDefaultE: function(e){ var $el = $(e.target); //Caveat: this clumsy bit here is due to the in-ability to check on the 'action-*' attributes on e.target... if($el.is('label') || $el.is('i') || $el.is('img') || $el.is('span') || $el.is('input') || $el.is('textarea') || $el.is('select') || ($el.is('a') && $el.attr('href'))) return; e.preventDefault(); }, //wait until all targets fires e (asynchronously) then call the callback with targets (e.g [this.show(), ...], 'ready') until: function(targets, e, callback){ targets = _.compact(targets); cb = _.after(targets.length, function(){ callback(targets); }); _.each(targets, function(t){ t.once(e, cb); }); }, //----------------markdown------------------- //options.marked, options.hljs //https://guides.github.com/features/mastering-markdown/ //our addition: // ^^^class class2 class3 ... // ... // ^^^ markdown: function(md, $anchor /*or options*/, options){ options = options || (!_.isjQueryObject($anchor) && $anchor) || {}; //render content var html = marked(md, app.debug('marked options are', _.extend(app.config.marked, (options.marked && options.marked) || options, _.isjQueryObject($anchor) && $anchor.data('marked')))), hljs = window.hljs; //highlight code (use ```language to specify type) if(hljs){ hljs.configure(app.debug('hljs options are', _.extend(app.config.hljs, options.hljs, _.isjQueryObject($anchor) && $anchor.data('hljs')))); var $html = $('<div>' + html + '</div>'); $html.find('pre code').each(function(){ hljs.highlightBlock(this); }); html = $html.html(); } if(_.isjQueryObject($anchor)) return $anchor.html(html).addClass('md-content'); return html; }, //----------------notify/overlay/popover--------------------- notify: function(title /*or options*/, msg, type /*or otherOptions*/, otherOptions){ if(_.isString(title)){ if(_.isPlainObject(type)){ otherOptions = type; type = undefined; } if(otherOptions && otherOptions.icon){ //theme awesome ({.icon, .more}) $.amaran(_.extend({ theme: 'awesome ' + (type || 'ok'), //see http://ersu.me/article/amaranjs/amaranjs-themes for types content: { title: title, message: msg, info: otherOptions.more || ' ', icon: otherOptions.icon } }, otherOptions)); } else { //custom theme $.amaran(_.extend({ content: { themeName: 'stagejs', title: title, message: msg, type: type || 'info', }, themeTemplate: app.NOTIFYTPL }, otherOptions)); } } else $.amaran(title); }, //overlay or popover prompt: function(view, anchor, placement, options){ if(_.isFunction(view)) view = new view(); else if(_.isString(view)) view = app.get(view).create(); //is popover if(_.isString(placement)){ options = options || {}; options.placement = placement; return view.popover(anchor, options); } //is overlay options = placement; return view.overlay(anchor, options); }, //----------------i18n----------------------- i18n: function(key, ns){ if(key){ //insert translations to current locale if(_.isPlainObject(key)) return I18N.insertTrans(key); //return a translation for specified key, ns/module return String(key).i18n(ns); } //otherwise, collect available strings (so far) into an i18n object. return I18N.getResourceJSON(null, false); }, //----------------debug---------------------- //bridge app.debug() debug: function(){ return app.Util.debugHelper.debug.apply(null, arguments); }, //bridge app.locate() locate: function(name /*el or $el*/){ return app.Util.debugHelper.locate(name); }, //bridge app.profile() profile: function(name /*el or $el*/){ return app.Util.debugHelper.profile(name); }, //bridge app.mark() mark: function(name /*el or $el*/){ return app.Util.debugHelper.mark(name); }, //bridge app.reload() reload: function(name, override/*optional*/){ return app.Util.debugHelper.reload(name, override); }, inject: { js: function(){ return app.Util.inject.apply(null, arguments); }, tpl: function(){ return app.Util.Tpl.remote.apply(app.Util.Tpl, arguments); }, css: function(){ return loadCSS.apply(null, arguments); } }, detect: function(feature, provider/*optional*/){ if(!provider) provider = Modernizr; return app.extract(feature, provider) || false; }, //--------3rd party lib pass-through--------- // js-cookie (former jquery-cookie) //.set(), .get(), .remove() cookie: Cookies, // store.js (localStorage) //.set(), .get(), .getAll(), .remove(), .clear() store: store.enabled && store, // validator.js (var type and val validation, e.g form editor validation) validator: validator, // moment.js (date and time) moment: moment, // URI.js (uri,query and hash in the url, e.g in app.param()) uri: URI, // later.js (schedule repeated workers, e.g in app.poll()) later: later, // faker.js (mock data generator, e.g in app.mock()) faker: faker, }); //editor rules app.editor.validator = app.editor.rule = function(name, fn){ if(!_.isString(name)) throw new Error('DEV::Validator:: You must specify a validator/rule name to use.'); return app.Core.Editor.addRule(name, fn); }; //alias app.page = app.context; app.area = app.regional; app.curtain = app.icing; /** * API summary */ app._apis = [ 'ee', 'model', 'collection', 'mock', //view registery 'view', 'widget', 'editor', 'editor.validator - @alias:editor.rule', //global action locks 'lock', 'unlock', 'available', //utils 'has', 'get', 'spray', 'coop', 'navigate', 'navPathArray', 'icing/curtain', 'i18n', 'param', 'animation', 'animateItems', 'throttle', 'debounce', 'preventDefaultE', 'until', //com 'remote', 'download', 'upload', 'ws', 'poll', 'worker', 'sse', //3rd-party lib short-cut 'extract', 'markdown', 'notify', 'prompt', //wraps 'cookie', 'store', 'moment', 'uri', 'validator', 'later', 'faker', //direct refs //supportive 'debug', 'detect', 'reload', 'locate', 'profile', 'mark', 'nameToPath', 'pathToName', 'inject.js', 'inject.tpl', 'inject.css', //@deprecated 'create - @deprecated', 'regional - @deprecated', 'context - @alias:page - @deprecated' ]; /** * Statics */ //animation done events used in Animate.css //Caveat: if you use $el.one(app.ADE) but still got 2+ callback calls, the browser is firing the default and prefixed events at the same time... //use $el.anyone() to fix the problem in using $el.one() app.ADE = 'animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd'; //notification template app.NOTIFYTPL = Handlebars.compile('<div class="alert alert-dismissable alert-{{type}}"><button data-dismiss="alert" class="close" type="button">×</button><strong>{{title}}</strong> {{{message}}}</div>'); })(Application);
mr-beaver/Stage.js
implementation/js/src/infrastructure/api.js
JavaScript
mit
32,954
// Base64 encoder/decoder with UTF-8 support // // Copyright (c) 2011 Vitaly Puzrin // Copyright (c) 2011 Aleksey V Zapparov // // Author: Aleksey V Zapparov AKA ixti (http://www.ixti.net/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Based on original artworks of base64 encoder/decoder by [Mozilla][1] // [1]: http://lxr.mozilla.org/mozilla/source/extensions/xml-rpc/src/nsXmlRpcClient.js 'use strict'; /* eslint-env browser */ /* eslint-disable no-bitwise */ function noop() {} var logger = { warn: noop, error: noop }, padding = '=', chrTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' + '0123456789+/', binTable = [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 ]; if (window.console) { logger = window.console; logger.warn = logger.warn || logger.error || logger.log || noop; logger.error = logger.error || logger.warn || logger.log || noop; } // internal helpers ////////////////////////////////////////////////////////// function utf8Encode(str) { var bytes = [], offset = 0, length, char; str = encodeURI(str); length = str.length; while (offset < length) { char = str.charAt(offset); offset += 1; if (char !== '%') { bytes.push(char.charCodeAt(0)); } else { char = str.charAt(offset) + str.charAt(offset + 1); bytes.push(parseInt(char, 16)); offset += 2; } } return bytes; } function utf8Decode(bytes) { var chars = [], offset = 0, length = bytes.length, c1, c2, c3; while (offset < length) { c1 = bytes[offset]; c2 = bytes[offset + 1]; c3 = bytes[offset + 2]; if (c1 < 128) { chars.push(String.fromCharCode(c1)); offset += 1; } else if (191 < c1 && c1 < 224) { chars.push(String.fromCharCode(((c1 & 31) << 6) | (c2 & 63))); offset += 2; } else { chars.push(String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))); offset += 3; } } return chars.join(''); } // public api //////////////////////////////////////////////////////////////// function encode(str) { var result = '', bytes = utf8Encode(str), length = bytes.length, i; // Convert every three bytes to 4 ascii characters. for (i = 0; i < (length - 2); i += 3) { result += chrTable[bytes[i] >> 2]; result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[((bytes[i + 1] & 0x0f) << 2) + (bytes[i + 2] >> 6)]; result += chrTable[bytes[i + 2] & 0x3f]; } // Convert the remaining 1 or 2 bytes, pad out to 4 characters. if (length % 3) { i = length - (length % 3); result += chrTable[bytes[i] >> 2]; if ((length % 3) === 2) { result += chrTable[((bytes[i] & 0x03) << 4) + (bytes[i + 1] >> 4)]; result += chrTable[(bytes[i + 1] & 0x0f) << 2]; result += padding; } else { result += chrTable[(bytes[i] & 0x03) << 4]; result += padding + padding; } } return result; } function decode(data) { var value, code, idx = 0, bytes = [], leftbits = 0, // number of bits decoded, but yet to be appended leftdata = 0; // bits decoded, but yet to be appended // Convert one by one. for (idx = 0; idx < data.length; idx += 1) { code = data.charCodeAt(idx); value = binTable[code & 0x7F]; if (value === -1) { // Skip illegal characters and whitespace logger.warn('Illegal characters (code=' + code + ') in position ' + idx); } else { // Collect data into leftdata, update bitcount leftdata = (leftdata << 6) | value; leftbits += 6; // If we have 8 or more bits, append 8 bits to the result if (leftbits >= 8) { leftbits -= 8; // Append if not padding. if (padding !== data.charAt(idx)) { bytes.push((leftdata >> leftbits) & 0xFF); } leftdata &= (1 << leftbits) - 1; } } } // If there are any bits left, the base64 string was corrupted if (leftbits) { logger.error('Corrupted base64 string'); return null; } return utf8Decode(bytes); } exports.encode = encode; exports.decode = decode;
minj/js-yaml
support/demo_template/base64.js
JavaScript
mit
5,692
module.exports = require("npm:[email protected]/dist/acorn");
TelerikFrenchConnection/JS-Applications-Teamwork
JavaScript
mit
55
require 'rr' require 'awesome_print' %w"xiki/core/core_ext xiki/core/ol".each {|o| require o} # RSpec::Runner.configure do |config| RSpec.configure do |config| config.mock_with :rr end module Xiki def self.dir File.expand_path("#{File.dirname(__FILE__)}/..") + "/" end end def stub_menu_path_dirs xiki_dir = Xiki.dir list = ["#{xiki_dir}spec/fixtures/menu", "#{xiki_dir}menu"] stub(Xiki).menu_path_dirs {list} end # Put this here until we can put it in a better place # - Maybe so it'll be used by main xiki and conf AwesomePrint.defaults = { :indent => -2, # left-align hash keys :index => false, :multiline => true, } include Xiki # Allows all specs to use classes in the Xiki module without "Xiki::"
stanwmusic/xiki
spec/spec_helper.rb
Ruby
mit
738
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2015-2017 The Dash developers // Copyright (c) 2015-2017 The Bitsend developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITSEND_WARNINGS_H #define BITSEND_WARNINGS_H #include <stdlib.h> #include <string> void SetMiscWarning(const std::string& strWarning); void SetfLargeWorkForkFound(bool flag); bool GetfLargeWorkForkFound(); void SetfLargeWorkInvalidChainFound(bool flag); bool GetfLargeWorkInvalidChainFound(); std::string GetWarnings(const std::string& strFor); static const bool DEFAULT_TESTSAFEMODE = false; #endif // BITSEND_WARNINGS_H
madzebra/BitSend
src/warnings.h
C
mit
774
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils from alembic import op from sqlalchemy.engine.reflection import Inspector # revision identifiers, used by Alembic. revision = '97bbc733896c' down_revision = '44ab9963e8cf' branch_labels = () depends_on = '9848d0149abd' def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.String(length=255), nullable=False), sa.Column( 'extra_data', sqlalchemy_utils.JSONType(), nullable=False), sa.ForeignKeyConstraint(['user_id'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'client_id') ) op.create_table( 'oauthclient_useridentity', sa.Column('id', sa.String(length=255), nullable=False), sa.Column('method', sa.String(length=255), nullable=False), sa.Column('id_user', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['id_user'], [u'accounts_user.id'], ), sa.PrimaryKeyConstraint('id', 'method') ) op.create_index( 'useridentity_id_user_method', 'oauthclient_useridentity', ['id_user', 'method'], unique=True ) op.create_table( 'oauthclient_remotetoken', sa.Column('id_remote_account', sa.Integer(), nullable=False), sa.Column('token_type', sa.String(length=40), nullable=False), sa.Column( 'access_token', sqlalchemy_utils.EncryptedType(), nullable=False), sa.Column('secret', sa.Text(), nullable=False), sa.ForeignKeyConstraint( ['id_remote_account'], [u'oauthclient_remoteaccount.id'], name='fk_oauthclient_remote_token_remote_account' ), sa.PrimaryKeyConstraint('id_remote_account', 'token_type') ) def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( op.f(fk['name']), 'oauthclient_useridentity', type_='foreignkey' ) op.drop_index( 'useridentity_id_user_method', table_name='oauthclient_useridentity') op.drop_table('oauthclient_useridentity') op.drop_table('oauthclient_remoteaccount')
tiborsimko/invenio-oauthclient
invenio_oauthclient/alembic/97bbc733896c_create_oauthclient_tables.py
Python
mit
2,898
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Platform; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { protected override string Header => "Updates"; [BackgroundDependencyLoader] private void load(Storage storage, OsuConfigManager config) { Children = new Drawable[] { new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }, new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, } }; } } }
NeoAdonis/osu
osu.Game/Overlays/Settings/Sections/General/UpdateSettings.cs
C#
mit
1,060
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.eventhubs.v2017_04_01.implementation; import java.util.List; import org.joda.time.DateTime; import com.microsoft.azure.management.eventhubs.v2017_04_01.EntityStatus; import com.microsoft.azure.management.eventhubs.v2017_04_01.CaptureDescription; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.ProxyResource; /** * Single item in List or Get Event Hub operation. */ @JsonFlatten public class EventhubInner extends ProxyResource { /** * Current number of shards on the Event Hub. */ @JsonProperty(value = "properties.partitionIds", access = JsonProperty.Access.WRITE_ONLY) private List<String> partitionIds; /** * Exact time the Event Hub was created. */ @JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime createdAt; /** * The exact time the message was updated. */ @JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY) private DateTime updatedAt; /** * Number of days to retain the events for this Event Hub, value should be * 1 to 7 days. */ @JsonProperty(value = "properties.messageRetentionInDays") private Long messageRetentionInDays; /** * Number of partitions created for the Event Hub, allowed values are from * 1 to 32 partitions. */ @JsonProperty(value = "properties.partitionCount") private Long partitionCount; /** * Enumerates the possible values for the status of the Event Hub. Possible * values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', * 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. */ @JsonProperty(value = "properties.status") private EntityStatus status; /** * Properties of capture description. */ @JsonProperty(value = "properties.captureDescription") private CaptureDescription captureDescription; /** * Get current number of shards on the Event Hub. * * @return the partitionIds value */ public List<String> partitionIds() { return this.partitionIds; } /** * Get exact time the Event Hub was created. * * @return the createdAt value */ public DateTime createdAt() { return this.createdAt; } /** * Get the exact time the message was updated. * * @return the updatedAt value */ public DateTime updatedAt() { return this.updatedAt; } /** * Get number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @return the messageRetentionInDays value */ public Long messageRetentionInDays() { return this.messageRetentionInDays; } /** * Set number of days to retain the events for this Event Hub, value should be 1 to 7 days. * * @param messageRetentionInDays the messageRetentionInDays value to set * @return the EventhubInner object itself. */ public EventhubInner withMessageRetentionInDays(Long messageRetentionInDays) { this.messageRetentionInDays = messageRetentionInDays; return this; } /** * Get number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @return the partitionCount value */ public Long partitionCount() { return this.partitionCount; } /** * Set number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. * * @param partitionCount the partitionCount value to set * @return the EventhubInner object itself. */ public EventhubInner withPartitionCount(Long partitionCount) { this.partitionCount = partitionCount; return this; } /** * Get enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @return the status value */ public EntityStatus status() { return this.status; } /** * Set enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'. * * @param status the status value to set * @return the EventhubInner object itself. */ public EventhubInner withStatus(EntityStatus status) { this.status = status; return this; } /** * Get properties of capture description. * * @return the captureDescription value */ public CaptureDescription captureDescription() { return this.captureDescription; } /** * Set properties of capture description. * * @param captureDescription the captureDescription value to set * @return the EventhubInner object itself. */ public EventhubInner withCaptureDescription(CaptureDescription captureDescription) { this.captureDescription = captureDescription; return this; } }
selvasingh/azure-sdk-for-java
sdk/eventhubs/mgmt-v2017_04_01/src/main/java/com/microsoft/azure/management/eventhubs/v2017_04_01/implementation/EventhubInner.java
Java
mit
5,503
import actionTypes from '../../client/actions/types'; const defaultState = { data: {}, errors: 'Not Found', }; export default function domainDetailReducer(state = defaultState, action = {}) { switch (action.type) { case actionTypes.getDomainDetail: return Object.assign({}, state, { data: action.data.domain, errors: action.errors, }); default: return state; } }
willopez/domainsjs
shared/report/domain-detail.js
JavaScript
mit
415
import {createStore, combineReducers} from 'redux'; import {todos} from '../reducers/todos'; export function configureStore() { const store = createStore(combineReducers({todos})); return store; }
ShyykoSerhiy/typescript-webpack-react-todolist
src/store/store.tsx
TypeScript
mit
206
<!DOCTYPE html> <html> <head> <title>选项</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="style.css" > <script src="options.js"></script> </head> <body> <div id="options_content"> <span id="message"></span> <h4>发音</h4> <input type="checkbox" name="auto" id="auto"> <label for="auto">自动发音</label> <h4>释义</h4> <input type="checkbox" name="zh_definitions" id="zh_definitions"> <label for="zh_definitions">显示中文释义</label> <input type="checkbox" name="en_definitions" id="en_definitions"> <label for="en_definitions">显示英语释义</label> <br /> <br /> <button id="reset">重置</button> <button id="save">保存</button> <a href="popup.html" id="return">返回</a> </div> </body> </html>
tangzheng1900/MyEye
options.html
HTML
mit
879
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2019, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "transfer.h" #include "url.h" #include "connect.h" #include "progress.h" #include "easyif.h" #include "share.h" #include "psl.h" #include "multiif.h" #include "sendf.h" #include "timeval.h" #include "http.h" #include "select.h" #include "warnless.h" #include "speedcheck.h" #include "conncache.h" #include "multihandle.h" #include "sigpipe.h" #include "vtls/vtls.h" #include "connect.h" #include "http_proxy.h" #include "http2.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97 to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every CURL handle takes 45-50 K memory, therefore this 3K are not significant. */ #ifndef CURL_SOCKET_HASH_TABLE_SIZE #define CURL_SOCKET_HASH_TABLE_SIZE 911 #endif #ifndef CURL_CONNECTION_HASH_SIZE #define CURL_CONNECTION_HASH_SIZE 97 #endif #define CURL_MULTI_HANDLE 0x000bab1e #define GOOD_MULTI_HANDLE(x) \ ((x) && (x)->type == CURL_MULTI_HANDLE) static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data); static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d); static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms); static void process_pending_handles(struct Curl_multi *multi); static void detach_connnection(struct Curl_easy *data); #ifdef DEBUGBUILD static const char * const statename[]={ "INIT", "CONNECT_PEND", "CONNECT", "WAITRESOLVE", "WAITCONNECT", "WAITPROXYCONNECT", "SENDPROTOCONNECT", "PROTOCONNECT", "DO", "DOING", "DO_MORE", "DO_DONE", "PERFORM", "TOOFAST", "DONE", "COMPLETED", "MSGSENT", }; #endif /* function pointer called once when switching TO a state */ typedef void (*init_multistate_func)(struct Curl_easy *data); static void Curl_init_completed(struct Curl_easy *data) { /* this is a completed transfer */ /* Important: reset the conn pointer so that we don't point to memory that could be freed anytime */ detach_connnection(data); Curl_expire_clear(data); /* stop all timers */ } /* always use this function to change state, to make debugging easier */ static void mstate(struct Curl_easy *data, CURLMstate state #ifdef DEBUGBUILD , int lineno #endif ) { CURLMstate oldstate = data->mstate; static const init_multistate_func finit[CURLM_STATE_LAST] = { NULL, /* INIT */ NULL, /* CONNECT_PEND */ Curl_init_CONNECT, /* CONNECT */ NULL, /* WAITRESOLVE */ NULL, /* WAITCONNECT */ NULL, /* WAITPROXYCONNECT */ NULL, /* SENDPROTOCONNECT */ NULL, /* PROTOCONNECT */ Curl_connect_free, /* DO */ NULL, /* DOING */ NULL, /* DO_MORE */ NULL, /* DO_DONE */ NULL, /* PERFORM */ NULL, /* TOOFAST */ NULL, /* DONE */ Curl_init_completed, /* COMPLETED */ NULL /* MSGSENT */ }; #if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS) (void) lineno; #endif if(oldstate == state) /* don't bother when the new state is the same as the old state */ return; data->mstate = state; #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) if(data->mstate >= CURLM_STATE_CONNECT_PEND && data->mstate < CURLM_STATE_COMPLETED) { long connection_id = -5000; if(data->conn) connection_id = data->conn->connection_id; infof(data, "STATE: %s => %s handle %p; line %d (connection #%ld)\n", statename[oldstate], statename[data->mstate], (void *)data, lineno, connection_id); } #endif if(state == CURLM_STATE_COMPLETED) /* changing to COMPLETED means there's one less easy handle 'alive' */ data->multi->num_alive--; /* if this state has an init-function, run it */ if(finit[state]) finit[state](data); } #ifndef DEBUGBUILD #define multistate(x,y) mstate(x,y) #else #define multistate(x,y) mstate(x,y, __LINE__) #endif /* * We add one of these structs to the sockhash for each socket */ struct Curl_sh_entry { struct curl_hash transfers; /* hash of transfers using this socket */ unsigned int action; /* what combined action READ/WRITE this socket waits for */ void *socketp; /* settable by users with curl_multi_assign() */ unsigned int users; /* number of transfers using this */ unsigned int readers; /* this many transfers want to read */ unsigned int writers; /* this many transfers want to write */ }; /* bits for 'action' having no bits means this socket is not expecting any action */ #define SH_READ 1 #define SH_WRITE 2 /* look up a given socket in the socket hash, skip invalid sockets */ static struct Curl_sh_entry *sh_getentry(struct curl_hash *sh, curl_socket_t s) { if(s != CURL_SOCKET_BAD) { /* only look for proper sockets */ return Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t)); } return NULL; } #define TRHASH_SIZE 13 static size_t trhash(void *key, size_t key_length, size_t slots_num) { size_t keyval = (size_t)*(struct Curl_easy **)key; (void) key_length; return (keyval % slots_num); } static size_t trhash_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void)k1_len; (void)k2_len; return *(struct Curl_easy **)k1 == *(struct Curl_easy **)k2; } static void trhash_dtor(void *nada) { (void)nada; } /* make sure this socket is present in the hash for this handle */ static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh, curl_socket_t s) { struct Curl_sh_entry *there = sh_getentry(sh, s); struct Curl_sh_entry *check; if(there) { /* it is present, return fine */ return there; } /* not present, add it */ check = calloc(1, sizeof(struct Curl_sh_entry)); if(!check) return NULL; /* major failure */ if(Curl_hash_init(&check->transfers, TRHASH_SIZE, trhash, trhash_compare, trhash_dtor)) { free(check); return NULL; } /* make/add new hash entry */ if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) { free(check); return NULL; /* major failure */ } return check; /* things are good in sockhash land */ } /* delete the given socket + handle from the hash */ static void sh_delentry(struct Curl_sh_entry *entry, struct curl_hash *sh, curl_socket_t s) { Curl_hash_destroy(&entry->transfers); /* We remove the hash entry. This will end up in a call to sh_freeentry(). */ Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t)); } /* * free a sockhash entry */ static void sh_freeentry(void *freethis) { struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis; free(p); } static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len) { (void) k1_len; (void) k2_len; return (*((curl_socket_t *) k1)) == (*((curl_socket_t *) k2)); } static size_t hash_fd(void *key, size_t key_length, size_t slots_num) { curl_socket_t fd = *((curl_socket_t *) key); (void) key_length; return (fd % slots_num); } /* * sh_init() creates a new socket hash and returns the handle for it. * * Quote from README.multi_socket: * * "Some tests at 7000 and 9000 connections showed that the socket hash lookup * is somewhat of a bottle neck. Its current implementation may be a bit too * limiting. It simply has a fixed-size array, and on each entry in the array * it has a linked list with entries. So the hash only checks which list to * scan through. The code I had used so for used a list with merely 7 slots * (as that is what the DNS hash uses) but with 7000 connections that would * make an average of 1000 nodes in each list to run through. I upped that to * 97 slots (I believe a prime is suitable) and noticed a significant speed * increase. I need to reconsider the hash implementation or use a rather * large default value like this. At 9000 connections I was still below 10us * per call." * */ static int sh_init(struct curl_hash *hash, int hashsize) { return Curl_hash_init(hash, hashsize, hash_fd, fd_key_compare, sh_freeentry); } /* * multi_addmsg() * * Called when a transfer is completed. Adds the given msg pointer to * the list kept in the multi handle. */ static CURLMcode multi_addmsg(struct Curl_multi *multi, struct Curl_message *msg) { Curl_llist_insert_next(&multi->msglist, multi->msglist.tail, msg, &msg->list); return CURLM_OK; } struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */ int chashsize) /* connection hash */ { struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi)); if(!multi) return NULL; multi->type = CURL_MULTI_HANDLE; if(Curl_mk_dnscache(&multi->hostcache)) goto error; if(sh_init(&multi->sockhash, hashsize)) goto error; if(Curl_conncache_init(&multi->conn_cache, chashsize)) goto error; Curl_llist_init(&multi->msglist, NULL); Curl_llist_init(&multi->pending, NULL); multi->multiplexing = CURLPIPE_MULTIPLEX; /* -1 means it not set by user, use the default value */ multi->maxconnects = -1; return multi; error: Curl_hash_destroy(&multi->sockhash); Curl_hash_destroy(&multi->hostcache); Curl_conncache_destroy(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); free(multi); return NULL; } struct Curl_multi *curl_multi_init(void) { return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE, CURL_CONNECTION_HASH_SIZE); } CURLMcode curl_multi_add_handle(struct Curl_multi *multi, struct Curl_easy *data) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from adding same easy handle more than once and prevent adding to more than one multi stack */ if(data->multi) return CURLM_ADDED_ALREADY; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; /* Initialize timeout list for this handle */ Curl_llist_init(&data->state.timeoutlist, NULL); /* * No failure allowed in this function beyond this point. And no * modification of easy nor multi handle allowed before this except for * potential multi's connection cache growing which won't be undone in this * function no matter what. */ if(data->set.errorbuffer) data->set.errorbuffer[0] = 0; /* set the easy handle */ multistate(data, CURLM_STATE_INIT); /* for multi interface connections, we share DNS cache automatically if the easy handle's one is currently not set. */ if(!data->dns.hostcache || (data->dns.hostcachetype == HCACHE_NONE)) { data->dns.hostcache = &multi->hostcache; data->dns.hostcachetype = HCACHE_MULTI; } /* Point to the shared or multi handle connection cache */ if(data->share && (data->share->specifier & (1<< CURL_LOCK_DATA_CONNECT))) data->state.conn_cache = &data->share->conn_cache; else data->state.conn_cache = &multi->conn_cache; #ifdef USE_LIBPSL /* Do the same for PSL. */ if(data->share && (data->share->specifier & (1 << CURL_LOCK_DATA_PSL))) data->psl = &data->share->psl; else data->psl = &multi->psl; #endif /* We add the new entry last in the list. */ data->next = NULL; /* end of the line */ if(multi->easyp) { struct Curl_easy *last = multi->easylp; last->next = data; data->prev = last; multi->easylp = data; /* the new last node */ } else { /* first node, make prev NULL! */ data->prev = NULL; multi->easylp = multi->easyp = data; /* both first and last */ } /* make the Curl_easy refer back to this multi handle */ data->multi = multi; /* Set the timeout for this handle to expire really soon so that it will be taken care of even when this handle is added in the midst of operation when only the curl_multi_socket() API is used. During that flow, only sockets that time-out or have actions will be dealt with. Since this handle has no action yet, we make sure it times out to get things to happen. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* increase the node-counter */ multi->num_easy++; /* increase the alive-counter */ multi->num_alive++; /* A somewhat crude work-around for a little glitch in Curl_update_timer() that happens if the lastcall time is set to the same time when the handle is removed as when the next handle is added, as then the check in Curl_update_timer() that prevents calling the application multiple times with the same timer info will not trigger and then the new handle's timeout will not be notified to the app. The work-around is thus simply to clear the 'lastcall' variable to force Curl_update_timer() to always trigger a callback to the app when a new easy handle is added */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); /* The closure handle only ever has default timeouts set. To improve the state somewhat we clone the timeouts from each added handle so that the closure handle always has the same timeouts as the most recently added easy handle. */ data->state.conn_cache->closure_handle->set.timeout = data->set.timeout; data->state.conn_cache->closure_handle->set.server_response_timeout = data->set.server_response_timeout; data->state.conn_cache->closure_handle->set.no_signal = data->set.no_signal; Curl_update_timer(multi); return CURLM_OK; } #if 0 /* Debug-function, used like this: * * Curl_hash_print(multi->sockhash, debug_print_sock_hash); * * Enable the hash print function first by editing hash.c */ static void debug_print_sock_hash(void *p) { struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p; fprintf(stderr, " [easy %p/magic %x/socket %d]", (void *)sh->data, sh->data->magic, (int)sh->socket); } #endif static CURLcode multi_done(struct Curl_easy *data, CURLcode status, /* an error if this is called after an error was detected */ bool premature) { CURLcode result; struct connectdata *conn = data->conn; unsigned int i; DEBUGF(infof(data, "multi_done\n")); if(data->state.done) /* Stop if multi_done() has already been called */ return CURLE_OK; /* Stop the resolver and free its own resources (but not dns_entry yet). */ Curl_resolver_kill(conn); /* Cleanup possible redirect junk */ Curl_safefree(data->req.newurl); Curl_safefree(data->req.location); switch(status) { case CURLE_ABORTED_BY_CALLBACK: case CURLE_READ_ERROR: case CURLE_WRITE_ERROR: /* When we're aborted due to a callback return code it basically have to be counted as premature as there is trouble ahead if we don't. We have many callbacks and protocols work differently, we could potentially do this more fine-grained in the future. */ premature = TRUE; default: break; } /* this calls the protocol-specific function pointer previously set */ if(conn->handler->done) result = conn->handler->done(conn, status, premature); else result = status; if(CURLE_ABORTED_BY_CALLBACK != result) { /* avoid this if we already aborted by callback to avoid this calling another callback */ CURLcode rc = Curl_pgrsDone(conn); if(!result && rc) result = CURLE_ABORTED_BY_CALLBACK; } process_pending_handles(data->multi); /* connection / multiplex */ detach_connnection(data); if(CONN_INUSE(conn)) { /* Stop if still used. */ DEBUGF(infof(data, "Connection still in use %zu, " "no more multi_done now!\n", conn->easyq.size)); return CURLE_OK; } data->state.done = TRUE; /* called just now! */ if(conn->dns_entry) { Curl_resolv_unlock(data, conn->dns_entry); /* done with this */ conn->dns_entry = NULL; } Curl_hostcache_prune(data); Curl_safefree(data->state.ulbuf); /* if the transfer was completed in a paused state there can be buffered data left to free */ for(i = 0; i < data->state.tempcount; i++) { free(data->state.tempwrite[i].buf); } data->state.tempcount = 0; /* if data->set.reuse_forbid is TRUE, it means the libcurl client has forced us to close this connection. This is ignored for requests taking place in a NTLM/NEGOTIATE authentication handshake if conn->bits.close is TRUE, it means that the connection should be closed in spite of all our efforts to be nice, due to protocol restrictions in our or the server's end if premature is TRUE, it means this connection was said to be DONE before the entire request operation is complete and thus we can't know in what state it is for re-using, so we're forced to close it. In a perfect world we can add code that keep track of if we really must close it here or not, but currently we have no such detail knowledge. */ if((data->set.reuse_forbid #if defined(USE_NTLM) && !(conn->http_ntlm_state == NTLMSTATE_TYPE2 || conn->proxy_ntlm_state == NTLMSTATE_TYPE2) #endif #if defined(USE_SPNEGO) && !(conn->http_negotiate_state == GSS_AUTHRECV || conn->proxy_negotiate_state == GSS_AUTHRECV) #endif ) || conn->bits.close || (premature && !(conn->handler->flags & PROTOPT_STREAM))) { CURLcode res2 = Curl_disconnect(data, conn, premature); /* If we had an error already, make sure we return that one. But if we got a new error, return that. */ if(!result && res2) result = res2; } else { char buffer[256]; /* create string before returning the connection */ msnprintf(buffer, sizeof(buffer), "Connection #%ld to host %s left intact", conn->connection_id, conn->bits.socksproxy ? conn->socks_proxy.host.dispname : conn->bits.httpproxy ? conn->http_proxy.host.dispname : conn->bits.conn_to_host ? conn->conn_to_host.dispname : conn->host.dispname); /* the connection is no longer in use by this transfer */ if(Curl_conncache_return_conn(conn)) { /* remember the most recently used connection */ data->state.lastconnect = conn; infof(data, "%s\n", buffer); } else data->state.lastconnect = NULL; } Curl_free_request_state(data); return result; } CURLMcode curl_multi_remove_handle(struct Curl_multi *multi, struct Curl_easy *data) { struct Curl_easy *easy = data; bool premature; bool easy_owns_conn; struct curl_llist_element *e; /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; /* Verify that we got a somewhat good easy handle too */ if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; /* Prevent users from trying to remove same easy handle more than once */ if(!data->multi) return CURLM_OK; /* it is already removed so let's say it is fine! */ if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE; easy_owns_conn = (data->conn && (data->conn->data == easy)) ? TRUE : FALSE; /* If the 'state' is not INIT or COMPLETED, we might need to do something nice to put the easy_handle in a good known state when this returns. */ if(premature) { /* this handle is "alive" so we need to count down the total number of alive connections when this is removed */ multi->num_alive--; } if(data->conn && data->mstate > CURLM_STATE_DO && data->mstate < CURLM_STATE_COMPLETED) { /* Set connection owner so that the DONE function closes it. We can safely do this here since connection is killed. */ data->conn->data = easy; streamclose(data->conn, "Removed with partial response"); easy_owns_conn = TRUE; } /* The timer must be shut down before data->multi is set to NULL, else the timenode will remain in the splay tree after curl_easy_cleanup is called. */ Curl_expire_clear(data); if(data->conn) { /* we must call multi_done() here (if we still own the connection) so that we don't leave a half-baked one around */ if(easy_owns_conn) { /* multi_done() clears the conn->data field to lose the association between the easy handle and the connection Note that this ignores the return code simply because there's nothing really useful to do with it anyway! */ (void)multi_done(data, data->result, premature); } } if(data->connect_queue.ptr) /* the handle was in the pending list waiting for an available connection, so go ahead and remove it */ Curl_llist_remove(&multi->pending, &data->connect_queue, NULL); if(data->dns.hostcachetype == HCACHE_MULTI) { /* stop using the multi handle's DNS cache, *after* the possible multi_done() call above */ data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } Curl_wildcard_dtor(&data->wildcard); /* destroy the timeout list that is held in the easy handle, do this *after* multi_done() as that may actually call Curl_expire that uses this */ Curl_llist_destroy(&data->state.timeoutlist, NULL); /* as this was using a shared connection cache we clear the pointer to that since we're not part of that multi handle anymore */ data->state.conn_cache = NULL; /* change state without using multistate(), only to make singlesocket() do what we want */ data->mstate = CURLM_STATE_COMPLETED; singlesocket(multi, easy); /* to let the application know what sockets that vanish with this handle */ /* Remove the association between the connection and the handle */ if(data->conn) { data->conn->data = NULL; detach_connnection(data); } #ifdef USE_LIBPSL /* Remove the PSL association. */ if(data->psl == &multi->psl) data->psl = NULL; #endif data->multi = NULL; /* clear the association to this multi handle */ /* make sure there's no pending message in the queue sent from this easy handle */ for(e = multi->msglist.head; e; e = e->next) { struct Curl_message *msg = e->ptr; if(msg->extmsg.easy_handle == easy) { Curl_llist_remove(&multi->msglist, e, NULL); /* there can only be one from this specific handle */ break; } } /* make the previous node point to our next */ if(data->prev) data->prev->next = data->next; else multi->easyp = data->next; /* point to first node */ /* make our next point to our previous node */ if(data->next) data->next->prev = data->prev; else multi->easylp = data->prev; /* point to last node */ /* NOTE NOTE NOTE We do not touch the easy handle here! */ multi->num_easy--; /* one less to care about now */ Curl_update_timer(multi); return CURLM_OK; } /* Return TRUE if the application asked for multiplexing */ bool Curl_multiplex_wanted(const struct Curl_multi *multi) { return (multi && (multi->multiplexing)); } /* This is the only function that should clear data->conn. This will occasionally be called with the pointer already cleared. */ static void detach_connnection(struct Curl_easy *data) { struct connectdata *conn = data->conn; if(conn) Curl_llist_remove(&conn->easyq, &data->conn_queue, NULL); data->conn = NULL; } /* This is the only function that should assign data->conn */ void Curl_attach_connnection(struct Curl_easy *data, struct connectdata *conn) { DEBUGASSERT(!data->conn); DEBUGASSERT(conn); data->conn = conn; Curl_llist_insert_next(&conn->easyq, conn->easyq.tail, data, &data->conn_queue); } static int waitconnect_getsock(struct connectdata *conn, curl_socket_t *sock) { int i; int s = 0; int rc = 0; #ifdef USE_SSL if(CONNECT_FIRSTSOCKET_PROXY_SSL()) return Curl_ssl_getsock(conn, sock); #endif for(i = 0; i<2; i++) { if(conn->tempsock[i] != CURL_SOCKET_BAD) { sock[s] = conn->tempsock[i]; rc |= GETSOCK_WRITESOCK(s); #ifdef ENABLE_QUIC if(conn->transport == TRNSPRT_QUIC) /* when connecting QUIC, we want to read the socket too */ rc |= GETSOCK_READSOCK(s); #endif s++; } } return rc; } static int waitproxyconnect_getsock(struct connectdata *conn, curl_socket_t *sock) { sock[0] = conn->sock[FIRSTSOCKET]; /* when we've sent a CONNECT to a proxy, we should rather wait for the socket to become readable to be able to get the response headers */ if(conn->connect_state) return GETSOCK_READSOCK(0); return GETSOCK_WRITESOCK(0); } static int domore_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn && conn->handler->domore_getsock) return conn->handler->domore_getsock(conn, socks); return GETSOCK_BLANK; } static int doing_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn && conn->handler->doing_getsock) return conn->handler->doing_getsock(conn, socks); return GETSOCK_BLANK; } static int protocol_getsock(struct connectdata *conn, curl_socket_t *socks) { if(conn->handler->proto_getsock) return conn->handler->proto_getsock(conn, socks); /* Backup getsock logic. Since there is a live socket in use, we must wait for it or it will be removed from watching when the multi_socket API is used. */ socks[0] = conn->sock[FIRSTSOCKET]; return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0); } /* returns bitmapped flags for this handle and its sockets. The 'socks[]' array contains MAX_SOCKSPEREASYHANDLE entries. */ static int multi_getsock(struct Curl_easy *data, curl_socket_t *socks) { /* The no connection case can happen when this is called from curl_multi_remove_handle() => singlesocket() => multi_getsock(). */ if(!data->conn) return 0; if(data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_COMPLETED) { /* Set up ownership correctly */ data->conn->data = data; } switch(data->mstate) { default: #if 0 /* switch back on these cases to get the compiler to check for all enums to be present */ case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */ case CURLM_STATE_COMPLETED: case CURLM_STATE_MSGSENT: case CURLM_STATE_INIT: case CURLM_STATE_CONNECT: case CURLM_STATE_WAITDO: case CURLM_STATE_DONE: case CURLM_STATE_LAST: /* this will get called with CURLM_STATE_COMPLETED when a handle is removed */ #endif return 0; case CURLM_STATE_WAITRESOLVE: return Curl_resolv_getsock(data->conn, socks); case CURLM_STATE_PROTOCONNECT: case CURLM_STATE_SENDPROTOCONNECT: return protocol_getsock(data->conn, socks); case CURLM_STATE_DO: case CURLM_STATE_DOING: return doing_getsock(data->conn, socks); case CURLM_STATE_WAITPROXYCONNECT: return waitproxyconnect_getsock(data->conn, socks); case CURLM_STATE_WAITCONNECT: return waitconnect_getsock(data->conn, socks); case CURLM_STATE_DO_MORE: return domore_getsock(data->conn, socks); case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch to waiting for the same as the *PERFORM states */ case CURLM_STATE_PERFORM: return Curl_single_getsock(data->conn, socks); } } CURLMcode curl_multi_fdset(struct Curl_multi *multi, fd_set *read_fd_set, fd_set *write_fd_set, fd_set *exc_fd_set, int *max_fd) { /* Scan through all the easy handles to get the file descriptors set. Some easy handles may not have connected to the remote host yet, and then we must make sure that is done. */ struct Curl_easy *data; int this_max_fd = -1; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int i; (void)exc_fd_set; /* not used */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; data = multi->easyp; while(data) { int bitmap = multi_getsock(data, sockbunch); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], read_fd_set); s = sockbunch[i]; } if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) { FD_SET(sockbunch[i], write_fd_set); s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) /* this socket is unused, break out of loop */ break; if((int)s > this_max_fd) this_max_fd = (int)s; } data = data->next; /* check next handle */ } *max_fd = this_max_fd; return CURLM_OK; } #define NUM_POLLS_ON_STACK 10 static CURLMcode Curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret, bool extrawait) /* when no socket, wait */ { struct Curl_easy *data; curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE]; int bitmap; unsigned int i; unsigned int nfds = 0; unsigned int curlfds; bool ufds_malloc = FALSE; long timeout_internal; int retcode = 0; struct pollfd a_few_on_stack[NUM_POLLS_ON_STACK]; struct pollfd *ufds = &a_few_on_stack[0]; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; /* Count up how many fds we have from the multi handle */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } /* If the internally desired timeout is actually shorter than requested from the outside, then use the shorter time! But only if the internal timer is actually larger than -1! */ (void)multi_timeout(multi, &timeout_internal); if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms)) timeout_ms = (int)timeout_internal; curlfds = nfds; /* number of internal file descriptors */ nfds += extra_nfds; /* add the externally provided ones */ if(nfds > NUM_POLLS_ON_STACK) { /* 'nfds' is a 32 bit value and 'struct pollfd' is typically 8 bytes big, so at 2^29 sockets this value might wrap. When a process gets the capability to actually handle over 500 million sockets this calculation needs a integer overflow check. */ ufds = malloc(nfds * sizeof(struct pollfd)); if(!ufds) return CURLM_OUT_OF_MEMORY; ufds_malloc = TRUE; } nfds = 0; /* only do the second loop if we found descriptors in the first stage run above */ if(curlfds) { /* Add the curl handles to our pollfds first */ data = multi->easyp; while(data) { bitmap = multi_getsock(data, sockbunch); for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) { curl_socket_t s = CURL_SOCKET_BAD; if(bitmap & GETSOCK_READSOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLIN; ++nfds; s = sockbunch[i]; } if(bitmap & GETSOCK_WRITESOCK(i)) { ufds[nfds].fd = sockbunch[i]; ufds[nfds].events = POLLOUT; ++nfds; s = sockbunch[i]; } if(s == CURL_SOCKET_BAD) { break; } } data = data->next; /* check next handle */ } } /* Add external file descriptions from poll-like struct curl_waitfd */ for(i = 0; i < extra_nfds; i++) { ufds[nfds].fd = extra_fds[i].fd; ufds[nfds].events = 0; if(extra_fds[i].events & CURL_WAIT_POLLIN) ufds[nfds].events |= POLLIN; if(extra_fds[i].events & CURL_WAIT_POLLPRI) ufds[nfds].events |= POLLPRI; if(extra_fds[i].events & CURL_WAIT_POLLOUT) ufds[nfds].events |= POLLOUT; ++nfds; } if(nfds) { int pollrc; /* wait... */ pollrc = Curl_poll(ufds, nfds, timeout_ms); if(pollrc > 0) { retcode = pollrc; /* copy revents results from the poll to the curl_multi_wait poll struct, the bit values of the actual underlying poll() implementation may not be the same as the ones in the public libcurl API! */ for(i = 0; i < extra_nfds; i++) { unsigned short mask = 0; unsigned r = ufds[curlfds + i].revents; if(r & POLLIN) mask |= CURL_WAIT_POLLIN; if(r & POLLOUT) mask |= CURL_WAIT_POLLOUT; if(r & POLLPRI) mask |= CURL_WAIT_POLLPRI; extra_fds[i].revents = mask; } } } if(ufds_malloc) free(ufds); if(ret) *ret = retcode; if(!extrawait || extra_fds || curlfds) /* if any socket was checked */ ; else { long sleep_ms = 0; /* Avoid busy-looping when there's nothing particular to wait for */ if(!curl_multi_timeout(multi, &sleep_ms) && sleep_ms) { if(sleep_ms > timeout_ms) sleep_ms = timeout_ms; Curl_wait_ms((int)sleep_ms); } } return CURLM_OK; } CURLMcode curl_multi_wait(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, FALSE); } CURLMcode curl_multi_poll(struct Curl_multi *multi, struct curl_waitfd extra_fds[], unsigned int extra_nfds, int timeout_ms, int *ret) { return Curl_multi_wait(multi, extra_fds, extra_nfds, timeout_ms, ret, TRUE); } /* * multi_ischanged() is called * * Returns TRUE/FALSE whether the state is changed to trigger a CONNECT_PEND * => CONNECT action. * * Set 'clear' to TRUE to have it also clear the state variable. */ static bool multi_ischanged(struct Curl_multi *multi, bool clear) { bool retval = multi->recheckstate; if(clear) multi->recheckstate = FALSE; return retval; } CURLMcode Curl_multi_add_perform(struct Curl_multi *multi, struct Curl_easy *data, struct connectdata *conn) { CURLMcode rc; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; rc = curl_multi_add_handle(multi, data); if(!rc) { struct SingleRequest *k = &data->req; /* pass in NULL for 'conn' here since we don't want to init the connection, only this transfer */ Curl_init_do(data, NULL); /* take this handle to the perform state right away */ multistate(data, CURLM_STATE_PERFORM); Curl_attach_connnection(data, conn); k->keepon |= KEEP_RECV; /* setup to receive! */ } return rc; } /* * do_complete is called when the DO actions are complete. * * We init chunking and trailer bits to their default values here immediately * before receiving any header data for the current request. */ static void do_complete(struct connectdata *conn) { conn->data->req.chunk = FALSE; Curl_pgrsTime(conn->data, TIMER_PRETRANSFER); } static CURLcode multi_do(struct Curl_easy *data, bool *done) { CURLcode result = CURLE_OK; struct connectdata *conn = data->conn; DEBUGASSERT(conn); DEBUGASSERT(conn->handler); if(conn->handler->do_it) { /* generic protocol-specific function pointer set in curl_connect() */ result = conn->handler->do_it(conn, done); if(!result && *done) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); } return result; } /* * multi_do_more() is called during the DO_MORE multi state. It is basically a * second stage DO state which (wrongly) was introduced to support FTP's * second connection. * * 'complete' can return 0 for incomplete, 1 for done and -1 for go back to * DOING state there's more work to do! */ static CURLcode multi_do_more(struct connectdata *conn, int *complete) { CURLcode result = CURLE_OK; *complete = 0; if(conn->handler->do_more) result = conn->handler->do_more(conn, complete); if(!result && (*complete == 1)) /* do_complete must be called after the protocol-specific DO function */ do_complete(conn); return result; } /* * We are doing protocol-specific connecting and this is being called over and * over from the multi interface until the connection phase is done on * protocol layer. */ static CURLcode protocol_connecting(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->connecting) { *done = FALSE; result = conn->handler->connecting(conn, done); } else *done = TRUE; return result; } /* * We are DOING this is being called over and over from the multi interface * until the DOING phase is done on protocol layer. */ static CURLcode protocol_doing(struct connectdata *conn, bool *done) { CURLcode result = CURLE_OK; if(conn && conn->handler->doing) { *done = FALSE; result = conn->handler->doing(conn, done); } else *done = TRUE; return result; } /* * We have discovered that the TCP connection has been successful, we can now * proceed with some action. * */ static CURLcode protocol_connect(struct connectdata *conn, bool *protocol_done) { CURLcode result = CURLE_OK; DEBUGASSERT(conn); DEBUGASSERT(protocol_done); *protocol_done = FALSE; if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) { /* We already are connected, get back. This may happen when the connect worked fine in the first call, like when we connect to a local server or proxy. Note that we don't know if the protocol is actually done. Unless this protocol doesn't have any protocol-connect callback, as then we know we're done. */ if(!conn->handler->connecting) *protocol_done = TRUE; return CURLE_OK; } if(!conn->bits.protoconnstart) { result = Curl_proxy_connect(conn, FIRSTSOCKET); if(result) return result; if(CONNECT_FIRSTSOCKET_PROXY_SSL()) /* wait for HTTPS proxy SSL initialization to complete */ return CURLE_OK; if(conn->bits.tunnel_proxy && conn->bits.httpproxy && Curl_connect_ongoing(conn)) /* when using an HTTP tunnel proxy, await complete tunnel establishment before proceeding further. Return CURLE_OK so we'll be called again */ return CURLE_OK; if(conn->handler->connect_it) { /* is there a protocol-specific connect() procedure? */ /* Call the protocol-specific connect function */ result = conn->handler->connect_it(conn, protocol_done); } else *protocol_done = TRUE; /* it has started, possibly even completed but that knowledge isn't stored in this bit! */ if(!result) conn->bits.protoconnstart = TRUE; } return result; /* pass back status */ } static CURLMcode multi_runsingle(struct Curl_multi *multi, struct curltime now, struct Curl_easy *data) { struct Curl_message *msg = NULL; bool connected; bool async; bool protocol_connected = FALSE; bool dophase_done = FALSE; bool done = FALSE; CURLMcode rc; CURLcode result = CURLE_OK; timediff_t timeout_ms; timediff_t recv_timeout_ms; timediff_t send_timeout_ms; int control; if(!GOOD_EASY_HANDLE(data)) return CURLM_BAD_EASY_HANDLE; do { /* A "stream" here is a logical stream if the protocol can handle that (HTTP/2), or the full connection for older protocols */ bool stream_error = FALSE; rc = CURLM_OK; DEBUGASSERT((data->mstate <= CURLM_STATE_CONNECT) || (data->mstate >= CURLM_STATE_DONE) || data->conn); if(!data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_DONE) { /* In all these states, the code will blindly access 'data->conn' so this is precaution that it isn't NULL. And it silences static analyzers. */ failf(data, "In state %d with no conn, bail out!\n", data->mstate); return CURLM_INTERNAL_ERROR; } if(multi_ischanged(multi, TRUE)) { DEBUGF(infof(data, "multi changed, check CONNECT_PEND queue!\n")); process_pending_handles(multi); /* multiplexed */ } if(data->conn && data->mstate > CURLM_STATE_CONNECT && data->mstate < CURLM_STATE_COMPLETED) { /* Make sure we set the connection's current owner */ data->conn->data = data; } if(data->conn && (data->mstate >= CURLM_STATE_CONNECT) && (data->mstate < CURLM_STATE_COMPLETED)) { /* we need to wait for the connect state as only then is the start time stored, but we must not check already completed handles */ timeout_ms = Curl_timeleft(data, &now, (data->mstate <= CURLM_STATE_DO)? TRUE:FALSE); if(timeout_ms < 0) { /* Handle timed out */ if(data->mstate == CURLM_STATE_WAITRESOLVE) failf(data, "Resolving timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else if(data->mstate == CURLM_STATE_WAITCONNECT) failf(data, "Connection timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds", Curl_timediff(now, data->progress.t_startsingle)); else { struct SingleRequest *k = &data->req; if(k->size != -1) { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " out of %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount, k->size); } else { failf(data, "Operation timed out after %" CURL_FORMAT_TIMEDIFF_T " milliseconds with %" CURL_FORMAT_CURL_OFF_T " bytes received", Curl_timediff(now, data->progress.t_startsingle), k->bytecount); } } /* Force connection closed if the connection has indeed been used */ if(data->mstate > CURLM_STATE_DO) { streamclose(data->conn, "Disconnected with pending data"); stream_error = TRUE; } result = CURLE_OPERATION_TIMEDOUT; (void)multi_done(data, result, TRUE); /* Skip the statemachine and go directly to error handling section. */ goto statemachine_end; } } switch(data->mstate) { case CURLM_STATE_INIT: /* init this transfer. */ result = Curl_pretransfer(data); if(!result) { /* after init, go CONNECT */ multistate(data, CURLM_STATE_CONNECT); Curl_pgrsTime(data, TIMER_STARTOP); rc = CURLM_CALL_MULTI_PERFORM; } break; case CURLM_STATE_CONNECT_PEND: /* We will stay here until there is a connection available. Then we try again in the CURLM_STATE_CONNECT state. */ break; case CURLM_STATE_CONNECT: /* Connect. We want to get a connection identifier filled in. */ Curl_pgrsTime(data, TIMER_STARTSINGLE); if(data->set.timeout) Curl_expire(data, data->set.timeout, EXPIRE_TIMEOUT); if(data->set.connecttimeout) Curl_expire(data, data->set.connecttimeout, EXPIRE_CONNECTTIMEOUT); result = Curl_connect(data, &async, &protocol_connected); if(CURLE_NO_CONNECTION_AVAILABLE == result) { /* There was no connection available. We will go to the pending state and wait for an available connection. */ multistate(data, CURLM_STATE_CONNECT_PEND); /* add this handle to the list of connect-pending handles */ Curl_llist_insert_next(&multi->pending, multi->pending.tail, data, &data->connect_queue); result = CURLE_OK; break; } else if(data->state.previouslypending) { /* this transfer comes from the pending queue so try move another */ infof(data, "Transfer was pending, now try another\n"); process_pending_handles(data->multi); } if(!result) { if(async) /* We're now waiting for an asynchronous name lookup */ multistate(data, CURLM_STATE_WAITRESOLVE); else { /* after the connect has been sent off, go WAITCONNECT unless the protocol connect is already done and we can go directly to WAITDO or DO! */ rc = CURLM_CALL_MULTI_PERFORM; if(protocol_connected) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(Curl_connect_ongoing(data->conn)) multistate(data, CURLM_STATE_WAITPROXYCONNECT); else #endif multistate(data, CURLM_STATE_WAITCONNECT); } } } break; case CURLM_STATE_WAITRESOLVE: /* awaiting an asynch name resolve to complete */ { struct Curl_dns_entry *dns = NULL; struct connectdata *conn = data->conn; const char *hostname; DEBUGASSERT(conn); if(conn->bits.httpproxy) hostname = conn->http_proxy.host.name; else if(conn->bits.conn_to_host) hostname = conn->conn_to_host.name; else hostname = conn->host.name; /* check if we have the name resolved by now */ dns = Curl_fetch_addr(conn, hostname, (int)conn->port); if(dns) { #ifdef CURLRES_ASYNCH conn->async.dns = dns; conn->async.done = TRUE; #endif result = CURLE_OK; infof(data, "Hostname '%s' was found in DNS cache\n", hostname); } if(!dns) result = Curl_resolv_check(data->conn, &dns); /* Update sockets here, because the socket(s) may have been closed and the application thus needs to be told, even if it is likely that the same socket(s) will again be used further down. If the name has not yet been resolved, it is likely that new sockets have been opened in an attempt to contact another resolver. */ singlesocket(multi, data); if(dns) { /* Perform the next step in the connection phase, and then move on to the WAITCONNECT state */ result = Curl_once_resolved(data->conn, &protocol_connected); if(result) /* if Curl_once_resolved() returns failure, the connection struct is already freed and gone */ data->conn = NULL; /* no more connection */ else { /* call again please so that we get the next socket setup */ rc = CURLM_CALL_MULTI_PERFORM; if(protocol_connected) multistate(data, CURLM_STATE_DO); else { #ifndef CURL_DISABLE_HTTP if(Curl_connect_ongoing(data->conn)) multistate(data, CURLM_STATE_WAITPROXYCONNECT); else #endif multistate(data, CURLM_STATE_WAITCONNECT); } } } if(result) { /* failure detected */ stream_error = TRUE; break; } } break; #ifndef CURL_DISABLE_HTTP case CURLM_STATE_WAITPROXYCONNECT: /* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */ DEBUGASSERT(data->conn); result = Curl_http_connect(data->conn, &protocol_connected); if(data->conn->bits.proxy_connect_closed) { rc = CURLM_CALL_MULTI_PERFORM; /* connect back to proxy again */ result = CURLE_OK; multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_CONNECT); } else if(!result) { if((data->conn->http_proxy.proxytype != CURLPROXY_HTTPS || data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) && Curl_connect_complete(data->conn)) { rc = CURLM_CALL_MULTI_PERFORM; /* initiate protocol connect phase */ multistate(data, CURLM_STATE_SENDPROTOCONNECT); } } else if(result) stream_error = TRUE; break; #endif case CURLM_STATE_WAITCONNECT: /* awaiting a completion of an asynch TCP connect */ DEBUGASSERT(data->conn); result = Curl_is_connected(data->conn, FIRSTSOCKET, &connected); if(connected && !result) { #ifndef CURL_DISABLE_HTTP if((data->conn->http_proxy.proxytype == CURLPROXY_HTTPS && !data->conn->bits.proxy_ssl_connected[FIRSTSOCKET]) || Curl_connect_ongoing(data->conn)) { multistate(data, CURLM_STATE_WAITPROXYCONNECT); break; } #endif rc = CURLM_CALL_MULTI_PERFORM; multistate(data, data->conn->bits.tunnel_proxy? CURLM_STATE_WAITPROXYCONNECT: CURLM_STATE_SENDPROTOCONNECT); } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; break; } break; case CURLM_STATE_SENDPROTOCONNECT: result = protocol_connect(data->conn, &protocol_connected); if(!result && !protocol_connected) /* switch to waiting state */ multistate(data, CURLM_STATE_PROTOCONNECT); else if(!result) { /* protocol connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = CURLM_CALL_MULTI_PERFORM; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_PROTOCONNECT: /* protocol-specific connect phase */ result = protocol_connecting(data->conn, &protocol_connected); if(!result && protocol_connected) { /* after the connect has completed, go WAITDO or DO */ multistate(data, CURLM_STATE_DO); rc = CURLM_CALL_MULTI_PERFORM; } else if(result) { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, TRUE); stream_error = TRUE; } break; case CURLM_STATE_DO: if(data->set.connect_only) { /* keep connection open for application to use the socket */ connkeep(data->conn, "CONNECT_ONLY"); multistate(data, CURLM_STATE_DONE); result = CURLE_OK; rc = CURLM_CALL_MULTI_PERFORM; } else { /* Perform the protocol's DO action */ result = multi_do(data, &dophase_done); /* When multi_do() returns failure, data->conn might be NULL! */ if(!result) { if(!dophase_done) { #ifndef CURL_DISABLE_FTP /* some steps needed for wildcard matching */ if(data->state.wildcardmatch) { struct WildcardData *wc = &data->wildcard; if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) { /* skip some states if it is important */ multi_done(data, CURLE_OK, FALSE); multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; break; } } #endif /* DO was not completed in one function call, we must continue DOING... */ multistate(data, CURLM_STATE_DOING); rc = CURLM_OK; } /* after DO, go DO_DONE... or DO_MORE */ else if(data->conn->bits.do_more) { /* we're supposed to do more, but we need to sit down, relax and wait a little while first */ multistate(data, CURLM_STATE_DO_MORE); rc = CURLM_OK; } else { /* we're done with the DO, now DO_DONE */ multistate(data, CURLM_STATE_DO_DONE); rc = CURLM_CALL_MULTI_PERFORM; } } else if((CURLE_SEND_ERROR == result) && data->conn->bits.reuse) { /* * In this situation, a connection that we were trying to use * may have unexpectedly died. If possible, send the connection * back to the CONNECT phase so we can try again. */ char *newurl = NULL; followtype follow = FOLLOW_NONE; CURLcode drc; drc = Curl_retry_request(data->conn, &newurl); if(drc) { /* a failure here pretty much implies an out of memory */ result = drc; stream_error = TRUE; } Curl_posttransfer(data); drc = multi_done(data, result, FALSE); /* When set to retry the connection, we must to go back to * the CONNECT state */ if(newurl) { if(!drc || (drc == CURLE_SEND_ERROR)) { follow = FOLLOW_RETRY; drc = Curl_follow(data, newurl, follow); if(!drc) { multistate(data, CURLM_STATE_CONNECT); rc = CURLM_CALL_MULTI_PERFORM; result = CURLE_OK; } else { /* Follow failed */ result = drc; } } else { /* done didn't return OK or SEND_ERROR */ result = drc; } } else { /* Have error handler disconnect conn if we can't retry */ stream_error = TRUE; } free(newurl); } else { /* failure detected */ Curl_posttransfer(data); if(data->conn) multi_done(data, result, FALSE); stream_error = TRUE; } } break; case CURLM_STATE_DOING: /* we continue DOING until the DO phase is complete */ DEBUGASSERT(data->conn); result = protocol_doing(data->conn, &dophase_done); if(!result) { if(dophase_done) { /* after DO, go DO_DONE or DO_MORE */ multistate(data, data->conn->bits.do_more? CURLM_STATE_DO_MORE: CURLM_STATE_DO_DONE); rc = CURLM_CALL_MULTI_PERFORM; } /* dophase_done */ } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_MORE: /* * When we are connected, DO MORE and then go DO_DONE */ DEBUGASSERT(data->conn); result = multi_do_more(data->conn, &control); if(!result) { if(control) { /* if positive, advance to DO_DONE if negative, go back to DOING */ multistate(data, control == 1? CURLM_STATE_DO_DONE: CURLM_STATE_DOING); rc = CURLM_CALL_MULTI_PERFORM; } else /* stay in DO_MORE */ rc = CURLM_OK; } else { /* failure detected */ Curl_posttransfer(data); multi_done(data, result, FALSE); stream_error = TRUE; } break; case CURLM_STATE_DO_DONE: DEBUGASSERT(data->conn); if(data->conn->bits.multiplex) /* Check if we can move pending requests to send pipe */ process_pending_handles(multi); /* multiplexed */ /* Only perform the transfer if there's a good socket to work with. Having both BAD is a signal to skip immediately to DONE */ if((data->conn->sockfd != CURL_SOCKET_BAD) || (data->conn->writesockfd != CURL_SOCKET_BAD)) multistate(data, CURLM_STATE_PERFORM); else { #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch && ((data->conn->handler->flags & PROTOPT_WILDCARD) == 0)) { data->wildcard.state = CURLWC_DONE; } #endif multistate(data, CURLM_STATE_DONE); } rc = CURLM_CALL_MULTI_PERFORM; break; case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */ DEBUGASSERT(data->conn); /* if both rates are within spec, resume transfer */ if(Curl_pgrsUpdate(data->conn)) result = CURLE_ABORTED_BY_CALLBACK; else result = Curl_speedcheck(data, now); if(!result) { send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(!send_timeout_ms && !recv_timeout_ms) { multistate(data, CURLM_STATE_PERFORM); Curl_ratelimit(data, now); } else if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); } break; case CURLM_STATE_PERFORM: { char *newurl = NULL; bool retry = FALSE; bool comeback = FALSE; /* check if over send speed */ send_timeout_ms = 0; if(data->set.max_send_speed > 0) send_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.uploaded, data->progress.ul_limit_size, data->set.max_send_speed, data->progress.ul_limit_start, now); /* check if over recv speed */ recv_timeout_ms = 0; if(data->set.max_recv_speed > 0) recv_timeout_ms = Curl_pgrsLimitWaitTime(data->progress.downloaded, data->progress.dl_limit_size, data->set.max_recv_speed, data->progress.dl_limit_start, now); if(send_timeout_ms || recv_timeout_ms) { Curl_ratelimit(data, now); multistate(data, CURLM_STATE_TOOFAST); if(send_timeout_ms >= recv_timeout_ms) Curl_expire(data, send_timeout_ms, EXPIRE_TOOFAST); else Curl_expire(data, recv_timeout_ms, EXPIRE_TOOFAST); break; } /* read/write data if it is ready to do so */ result = Curl_readwrite(data->conn, data, &done, &comeback); if(done || (result == CURLE_RECV_ERROR)) { /* If CURLE_RECV_ERROR happens early enough, we assume it was a race * condition and the server closed the re-used connection exactly when * we wanted to use it, so figure out if that is indeed the case. */ CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) retry = (newurl)?TRUE:FALSE; else if(!result) result = ret; if(retry) { /* if we are to retry, set the result to OK and consider the request as done */ result = CURLE_OK; done = TRUE; } } else if((CURLE_HTTP2_STREAM == result) && Curl_h2_http_1_1_error(data->conn)) { CURLcode ret = Curl_retry_request(data->conn, &newurl); if(!ret) { infof(data, "Downgrades to HTTP/1.1!\n"); data->set.httpversion = CURL_HTTP_VERSION_1_1; /* clear the error message bit too as we ignore the one we got */ data->state.errorbuf = FALSE; if(!newurl) /* typically for HTTP_1_1_REQUIRED error on first flight */ newurl = strdup(data->change.url); /* if we are to retry, set the result to OK and consider the request as done */ retry = TRUE; result = CURLE_OK; done = TRUE; } else result = ret; } if(result) { /* * The transfer phase returned error, we mark the connection to get * closed to prevent being re-used. This is because we can't possibly * know if the connection is in a good shape or not now. Unless it is * a protocol which uses two "channels" like FTP, as then the error * happened in the data connection. */ if(!(data->conn->handler->flags & PROTOPT_DUAL) && result != CURLE_HTTP2_STREAM) streamclose(data->conn, "Transfer returned error"); Curl_posttransfer(data); multi_done(data, result, TRUE); } else if(done) { followtype follow = FOLLOW_NONE; /* call this even if the readwrite function returned error */ Curl_posttransfer(data); /* When we follow redirects or is set to retry the connection, we must to go back to the CONNECT state */ if(data->req.newurl || retry) { if(!retry) { /* if the URL is a follow-location and not just a retried request then figure out the URL here */ free(newurl); newurl = data->req.newurl; data->req.newurl = NULL; follow = FOLLOW_REDIR; } else follow = FOLLOW_RETRY; (void)multi_done(data, CURLE_OK, FALSE); /* multi_done() might return CURLE_GOT_NOTHING */ result = Curl_follow(data, newurl, follow); if(!result) { multistate(data, CURLM_STATE_CONNECT); rc = CURLM_CALL_MULTI_PERFORM; } free(newurl); } else { /* after the transfer is done, go DONE */ /* but first check to see if we got a location info even though we're not following redirects */ if(data->req.location) { free(newurl); newurl = data->req.location; data->req.location = NULL; result = Curl_follow(data, newurl, FOLLOW_FAKE); free(newurl); if(result) { stream_error = TRUE; result = multi_done(data, result, TRUE); } } if(!result) { multistate(data, CURLM_STATE_DONE); rc = CURLM_CALL_MULTI_PERFORM; } } } else if(comeback) rc = CURLM_CALL_MULTI_PERFORM; break; } case CURLM_STATE_DONE: /* this state is highly transient, so run another loop after this */ rc = CURLM_CALL_MULTI_PERFORM; if(data->conn) { CURLcode res; if(data->conn->bits.multiplex) /* Check if we can move pending requests to connection */ process_pending_handles(multi); /* multiplexing */ /* post-transfer command */ res = multi_done(data, result, FALSE); /* allow a previously set error code take precedence */ if(!result) result = res; /* * If there are other handles on the connection, multi_done won't set * conn to NULL. In such a case, curl_multi_remove_handle() can * access free'd data, if the connection is free'd and the handle * removed before we perform the processing in CURLM_STATE_COMPLETED */ if(data->conn) detach_connnection(data); } #ifndef CURL_DISABLE_FTP if(data->state.wildcardmatch) { if(data->wildcard.state != CURLWC_DONE) { /* if a wildcard is set and we are not ending -> lets start again with CURLM_STATE_INIT */ multistate(data, CURLM_STATE_INIT); break; } } #endif /* after we have DONE what we're supposed to do, go COMPLETED, and it doesn't matter what the multi_done() returned! */ multistate(data, CURLM_STATE_COMPLETED); break; case CURLM_STATE_COMPLETED: break; case CURLM_STATE_MSGSENT: data->result = result; return CURLM_OK; /* do nothing */ default: return CURLM_INTERNAL_ERROR; } statemachine_end: if(data->mstate < CURLM_STATE_COMPLETED) { if(result) { /* * If an error was returned, and we aren't in completed state now, * then we go to completed and consider this transfer aborted. */ /* NOTE: no attempt to disconnect connections must be made in the case blocks above - cleanup happens only here */ /* Check if we can move pending requests to send pipe */ process_pending_handles(multi); /* connection */ if(data->conn) { if(stream_error) { /* Don't attempt to send data over a connection that timed out */ bool dead_connection = result == CURLE_OPERATION_TIMEDOUT; struct connectdata *conn = data->conn; /* This is where we make sure that the conn pointer is reset. We don't have to do this in every case block above where a failure is detected */ detach_connnection(data); /* disconnect properly */ Curl_disconnect(data, conn, dead_connection); } } else if(data->mstate == CURLM_STATE_CONNECT) { /* Curl_connect() failed */ (void)Curl_posttransfer(data); } multistate(data, CURLM_STATE_COMPLETED); rc = CURLM_CALL_MULTI_PERFORM; } /* if there's still a connection to use, call the progress function */ else if(data->conn && Curl_pgrsUpdate(data->conn)) { /* aborted due to progress callback return code must close the connection */ result = CURLE_ABORTED_BY_CALLBACK; streamclose(data->conn, "Aborted by callback"); /* if not yet in DONE state, go there, otherwise COMPLETED */ multistate(data, (data->mstate < CURLM_STATE_DONE)? CURLM_STATE_DONE: CURLM_STATE_COMPLETED); rc = CURLM_CALL_MULTI_PERFORM; } } if(CURLM_STATE_COMPLETED == data->mstate) { if(data->set.fmultidone) { /* signal via callback instead */ data->set.fmultidone(data, result); } else { /* now fill in the Curl_message with this info */ msg = &data->msg; msg->extmsg.msg = CURLMSG_DONE; msg->extmsg.easy_handle = data; msg->extmsg.data.result = result; rc = multi_addmsg(multi, msg); DEBUGASSERT(!data->conn); } multistate(data, CURLM_STATE_MSGSENT); } } while((rc == CURLM_CALL_MULTI_PERFORM) || multi_ischanged(multi, FALSE)); data->result = result; return rc; } CURLMcode curl_multi_perform(struct Curl_multi *multi, int *running_handles) { struct Curl_easy *data; CURLMcode returncode = CURLM_OK; struct Curl_tree *t; struct curltime now = Curl_now(); if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; data = multi->easyp; while(data) { CURLMcode result; SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(result) returncode = result; data = data->next; /* operate on next handle */ } /* * Simply remove all expired timers from the splay since handles are dealt * with unconditionally by this function and curl_multi_timeout() requires * that already passed/handled expire times are removed from the splay. * * It is important that the 'now' value is set at the entry of this function * and not for the current time as it may have ticked a little while since * then and then we risk this loop to remove timers that actually have not * been handled! */ do { multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) /* the removed may have another timeout in queue */ (void)add_next_timeout(now, multi, t->payload); } while(t); *running_handles = multi->num_alive; if(CURLM_OK >= returncode) Curl_update_timer(multi); return returncode; } CURLMcode curl_multi_cleanup(struct Curl_multi *multi) { struct Curl_easy *data; struct Curl_easy *nextdata; if(GOOD_MULTI_HANDLE(multi)) { if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; multi->type = 0; /* not good anymore */ /* Firsrt remove all remaining easy handles */ data = multi->easyp; while(data) { nextdata = data->next; if(!data->state.done && data->conn) /* if DONE was never called for this handle */ (void)multi_done(data, CURLE_OK, TRUE); if(data->dns.hostcachetype == HCACHE_MULTI) { /* clear out the usage of the shared DNS cache */ Curl_hostcache_clean(data, data->dns.hostcache); data->dns.hostcache = NULL; data->dns.hostcachetype = HCACHE_NONE; } /* Clear the pointer to the connection cache */ data->state.conn_cache = NULL; data->multi = NULL; /* clear the association */ #ifdef USE_LIBPSL if(data->psl == &multi->psl) data->psl = NULL; #endif data = nextdata; } /* Close all the connections in the connection cache */ Curl_conncache_close_all_connections(&multi->conn_cache); Curl_hash_destroy(&multi->sockhash); Curl_conncache_destroy(&multi->conn_cache); Curl_llist_destroy(&multi->msglist, NULL); Curl_llist_destroy(&multi->pending, NULL); Curl_hash_destroy(&multi->hostcache); Curl_psl_destroy(&multi->psl); free(multi); return CURLM_OK; } return CURLM_BAD_HANDLE; } /* * curl_multi_info_read() * * This function is the primary way for a multi/multi_socket application to * figure out if a transfer has ended. We MUST make this function as fast as * possible as it will be polled frequently and we MUST NOT scan any lists in * here to figure out things. We must scale fine to thousands of handles and * beyond. The current design is fully O(1). */ CURLMsg *curl_multi_info_read(struct Curl_multi *multi, int *msgs_in_queue) { struct Curl_message *msg; *msgs_in_queue = 0; /* default to none */ if(GOOD_MULTI_HANDLE(multi) && !multi->in_callback && Curl_llist_count(&multi->msglist)) { /* there is one or more messages in the list */ struct curl_llist_element *e; /* extract the head of the list to return */ e = multi->msglist.head; msg = e->ptr; /* remove the extracted entry */ Curl_llist_remove(&multi->msglist, e, NULL); *msgs_in_queue = curlx_uztosi(Curl_llist_count(&multi->msglist)); return &msg->extmsg; } return NULL; } /* * singlesocket() checks what sockets we deal with and their "action state" * and if we have a different state in any of those sockets from last time we * call the callback accordingly. */ static CURLMcode singlesocket(struct Curl_multi *multi, struct Curl_easy *data) { curl_socket_t socks[MAX_SOCKSPEREASYHANDLE]; int i; struct Curl_sh_entry *entry; curl_socket_t s; int num; unsigned int curraction; int actions[MAX_SOCKSPEREASYHANDLE]; for(i = 0; i< MAX_SOCKSPEREASYHANDLE; i++) socks[i] = CURL_SOCKET_BAD; /* Fill in the 'current' struct with the state as it is now: what sockets to supervise and for what actions */ curraction = multi_getsock(data, socks); /* We have 0 .. N sockets already and we get to know about the 0 .. M sockets we should have from now on. Detect the differences, remove no longer supervised ones and add new ones */ /* walk over the sockets we got right now */ for(i = 0; (i< MAX_SOCKSPEREASYHANDLE) && (curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i))); i++) { unsigned int action = CURL_POLL_NONE; unsigned int prevaction = 0; unsigned int comboaction; bool sincebefore = FALSE; s = socks[i]; /* get it from the hash */ entry = sh_getentry(&multi->sockhash, s); if(curraction & GETSOCK_READSOCK(i)) action |= CURL_POLL_IN; if(curraction & GETSOCK_WRITESOCK(i)) action |= CURL_POLL_OUT; actions[i] = action; if(entry) { /* check if new for this transfer */ int j; for(j = 0; j< data->numsocks; j++) { if(s == data->sockets[j]) { prevaction = data->actions[j]; sincebefore = TRUE; break; } } } else { /* this is a socket we didn't have before, add it to the hash! */ entry = sh_addentry(&multi->sockhash, s); if(!entry) /* fatal */ return CURLM_OUT_OF_MEMORY; } if(sincebefore && (prevaction != action)) { /* Socket was used already, but different action now */ if(prevaction & CURL_POLL_IN) entry->readers--; if(prevaction & CURL_POLL_OUT) entry->writers--; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; } else if(!sincebefore) { /* a new user */ entry->users++; if(action & CURL_POLL_IN) entry->readers++; if(action & CURL_POLL_OUT) entry->writers++; /* add 'data' to the transfer hash on this socket! */ if(!Curl_hash_add(&entry->transfers, (char *)&data, /* hash key */ sizeof(struct Curl_easy *), data)) return CURLM_OUT_OF_MEMORY; } comboaction = (entry->writers? CURL_POLL_OUT : 0) | (entry->readers ? CURL_POLL_IN : 0); /* socket existed before and has the same action set as before */ if(sincebefore && (entry->action == comboaction)) /* same, continue */ continue; if(multi->socket_cb) multi->socket_cb(data, s, comboaction, multi->socket_userp, entry->socketp); entry->action = comboaction; /* store the current action state */ } num = i; /* number of sockets */ /* when we've walked over all the sockets we should have right now, we must make sure to detect sockets that are removed */ for(i = 0; i< data->numsocks; i++) { int j; bool stillused = FALSE; s = data->sockets[i]; for(j = 0; j < num; j++) { if(s == socks[j]) { /* this is still supervised */ stillused = TRUE; break; } } if(stillused) continue; entry = sh_getentry(&multi->sockhash, s); /* if this is NULL here, the socket has been closed and notified so already by Curl_multi_closed() */ if(entry) { int oldactions = data->actions[i]; /* this socket has been removed. Decrease user count */ entry->users--; if(oldactions & CURL_POLL_OUT) entry->writers--; if(oldactions & CURL_POLL_IN) entry->readers--; if(!entry->users) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); sh_delentry(entry, &multi->sockhash, s); } else { /* still users, but remove this handle as a user of this socket */ if(Curl_hash_delete(&entry->transfers, (char *)&data, sizeof(struct Curl_easy *))) { DEBUGASSERT(NULL); } } } } /* for loop over numsocks */ memcpy(data->sockets, socks, num*sizeof(curl_socket_t)); memcpy(data->actions, actions, num*sizeof(int)); data->numsocks = num; return CURLM_OK; } void Curl_updatesocket(struct Curl_easy *data) { singlesocket(data->multi, data); } /* * Curl_multi_closed() * * Used by the connect code to tell the multi_socket code that one of the * sockets we were using is about to be closed. This function will then * remove it from the sockethash for this handle to make the multi_socket API * behave properly, especially for the case when libcurl will create another * socket again and it gets the same file descriptor number. */ void Curl_multi_closed(struct Curl_easy *data, curl_socket_t s) { if(data) { /* if there's still an easy handle associated with this connection */ struct Curl_multi *multi = data->multi; if(multi) { /* this is set if this connection is part of a handle that is added to a multi handle, and only then this is necessary */ struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(entry) { if(multi->socket_cb) multi->socket_cb(data, s, CURL_POLL_REMOVE, multi->socket_userp, entry->socketp); /* now remove it from the socket hash */ sh_delentry(entry, &multi->sockhash, s); } } } } /* * add_next_timeout() * * Each Curl_easy has a list of timeouts. The add_next_timeout() is called * when it has just been removed from the splay tree because the timeout has * expired. This function is then to advance in the list to pick the next * timeout to use (skip the already expired ones) and add this node back to * the splay tree again. * * The splay tree only has each sessionhandle as a single node and the nearest * timeout is used to sort it on. */ static CURLMcode add_next_timeout(struct curltime now, struct Curl_multi *multi, struct Curl_easy *d) { struct curltime *tv = &d->state.expiretime; struct curl_llist *list = &d->state.timeoutlist; struct curl_llist_element *e; struct time_node *node = NULL; /* move over the timeout list for this specific handle and remove all timeouts that are now passed tense and store the next pending timeout in *tv */ for(e = list->head; e;) { struct curl_llist_element *n = e->next; timediff_t diff; node = (struct time_node *)e->ptr; diff = Curl_timediff(node->time, now); if(diff <= 0) /* remove outdated entry */ Curl_llist_remove(list, e, NULL); else /* the list is sorted so get out on the first mismatch */ break; e = n; } e = list->head; if(!e) { /* clear the expire times within the handles that we remove from the splay tree */ tv->tv_sec = 0; tv->tv_usec = 0; } else { /* copy the first entry to 'tv' */ memcpy(tv, &node->time, sizeof(*tv)); /* Insert this node again into the splay. Keep the timer in the list in case we need to recompute future timers. */ multi->timetree = Curl_splayinsert(*tv, multi->timetree, &d->state.timenode); } return CURLM_OK; } static CURLMcode multi_socket(struct Curl_multi *multi, bool checkall, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result = CURLM_OK; struct Curl_easy *data = NULL; struct Curl_tree *t; struct curltime now = Curl_now(); if(checkall) { /* *perform() deals with running_handles on its own */ result = curl_multi_perform(multi, running_handles); /* walk through each easy handle and do the socket state change magic and callbacks */ if(result != CURLM_BAD_HANDLE) { data = multi->easyp; while(data && !result) { result = singlesocket(multi, data); data = data->next; } } /* or should we fall-through and do the timer-based stuff? */ return result; } if(s != CURL_SOCKET_TIMEOUT) { struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); if(!entry) /* Unmatched socket, we can't act on it but we ignore this fact. In real-world tests it has been proved that libevent can in fact give the application actions even though the socket was just previously asked to get removed, so thus we better survive stray socket actions and just move on. */ ; else { struct curl_hash_iterator iter; struct curl_hash_element *he; /* the socket can be shared by many transfers, iterate */ Curl_hash_start_iterate(&entry->transfers, &iter); for(he = Curl_hash_next_element(&iter); he; he = Curl_hash_next_element(&iter)) { data = (struct Curl_easy *)he->ptr; DEBUGASSERT(data); DEBUGASSERT(data->magic == CURLEASY_MAGIC_NUMBER); if(data->conn && !(data->conn->handler->flags & PROTOPT_DIRLOCK)) /* set socket event bitmask if they're not locked */ data->conn->cselect_bits = ev_bitmask; Curl_expire(data, 0, EXPIRE_RUN_NOW); } /* Now we fall-through and do the timer-based stuff, since we don't want to force the user to have to deal with timeouts as long as at least one connection in fact has traffic. */ data = NULL; /* set data to NULL again to avoid calling multi_runsingle() in case there's no need to */ now = Curl_now(); /* get a newer time since the multi_runsingle() loop may have taken some time */ } } else { /* Asked to run due to time-out. Clear the 'lastcall' variable to force Curl_update_timer() to trigger a callback to the app again even if the same timeout is still the one to run after this call. That handles the case when the application asks libcurl to run the timeout prematurely. */ memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall)); } /* * The loop following here will go on as long as there are expire-times left * to process in the splay and 'data' will be re-assigned for every expired * handle we deal with. */ do { /* the first loop lap 'data' can be NULL */ if(data) { SIGPIPE_VARIABLE(pipe_st); sigpipe_ignore(data, &pipe_st); result = multi_runsingle(multi, now, data); sigpipe_restore(&pipe_st); if(CURLM_OK >= result) { /* get the socket(s) and check if the state has been changed since last */ result = singlesocket(multi, data); if(result) return result; } } /* Check if there's one (more) expired timer to deal with! This function extracts a matching node if there is one */ multi->timetree = Curl_splaygetbest(now, multi->timetree, &t); if(t) { data = t->payload; /* assign this for next loop */ (void)add_next_timeout(now, multi, t->payload); } } while(t); *running_handles = multi->num_alive; return result; } #undef curl_multi_setopt CURLMcode curl_multi_setopt(struct Curl_multi *multi, CURLMoption option, ...) { CURLMcode res = CURLM_OK; va_list param; if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; va_start(param, option); switch(option) { case CURLMOPT_SOCKETFUNCTION: multi->socket_cb = va_arg(param, curl_socket_callback); break; case CURLMOPT_SOCKETDATA: multi->socket_userp = va_arg(param, void *); break; case CURLMOPT_PUSHFUNCTION: multi->push_cb = va_arg(param, curl_push_callback); break; case CURLMOPT_PUSHDATA: multi->push_userp = va_arg(param, void *); break; case CURLMOPT_PIPELINING: multi->multiplexing = va_arg(param, long) & CURLPIPE_MULTIPLEX; break; case CURLMOPT_TIMERFUNCTION: multi->timer_cb = va_arg(param, curl_multi_timer_callback); break; case CURLMOPT_TIMERDATA: multi->timer_userp = va_arg(param, void *); break; case CURLMOPT_MAXCONNECTS: multi->maxconnects = va_arg(param, long); break; case CURLMOPT_MAX_HOST_CONNECTIONS: multi->max_host_connections = va_arg(param, long); break; case CURLMOPT_MAX_TOTAL_CONNECTIONS: multi->max_total_connections = va_arg(param, long); break; /* options formerly used for pipelining */ case CURLMOPT_MAX_PIPELINE_LENGTH: break; case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE: break; case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE: break; case CURLMOPT_PIPELINING_SITE_BL: break; case CURLMOPT_PIPELINING_SERVER_BL: break; default: res = CURLM_UNKNOWN_OPTION; break; } va_end(param); return res; } /* we define curl_multi_socket() in the public multi.h header */ #undef curl_multi_socket CURLMcode curl_multi_socket(struct Curl_multi *multi, curl_socket_t s, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, FALSE, s, 0, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } CURLMcode curl_multi_socket_action(struct Curl_multi *multi, curl_socket_t s, int ev_bitmask, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, FALSE, s, ev_bitmask, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } CURLMcode curl_multi_socket_all(struct Curl_multi *multi, int *running_handles) { CURLMcode result; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; result = multi_socket(multi, TRUE, CURL_SOCKET_BAD, 0, running_handles); if(CURLM_OK >= result) Curl_update_timer(multi); return result; } static CURLMcode multi_timeout(struct Curl_multi *multi, long *timeout_ms) { static struct curltime tv_zero = {0, 0}; if(multi->timetree) { /* we have a tree of expire times */ struct curltime now = Curl_now(); /* splay the lowest to the bottom */ multi->timetree = Curl_splay(tv_zero, multi->timetree); if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) { /* some time left before expiration */ timediff_t diff = Curl_timediff(multi->timetree->key, now); if(diff <= 0) /* * Since we only provide millisecond resolution on the returned value * and the diff might be less than one millisecond here, we don't * return zero as that may cause short bursts of busyloops on fast * processors while the diff is still present but less than one * millisecond! instead we return 1 until the time is ripe. */ *timeout_ms = 1; else /* this should be safe even on 64 bit archs, as we don't use that overly long timeouts */ *timeout_ms = (long)diff; } else /* 0 means immediately */ *timeout_ms = 0; } else *timeout_ms = -1; return CURLM_OK; } CURLMcode curl_multi_timeout(struct Curl_multi *multi, long *timeout_ms) { /* First, make some basic checks that the CURLM handle is a good handle */ if(!GOOD_MULTI_HANDLE(multi)) return CURLM_BAD_HANDLE; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; return multi_timeout(multi, timeout_ms); } /* * Tell the application it should update its timers, if it subscribes to the * update timer callback. */ void Curl_update_timer(struct Curl_multi *multi) { long timeout_ms; if(!multi->timer_cb) return; if(multi_timeout(multi, &timeout_ms)) { return; } if(timeout_ms < 0) { static const struct curltime none = {0, 0}; if(Curl_splaycomparekeys(none, multi->timer_lastcall)) { multi->timer_lastcall = none; /* there's no timeout now but there was one previously, tell the app to disable it */ multi->timer_cb(multi, -1, multi->timer_userp); return; } return; } /* When multi_timeout() is done, multi->timetree points to the node with the * timeout we got the (relative) time-out time for. We can thus easily check * if this is the same (fixed) time as we got in a previous call and then * avoid calling the callback again. */ if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0) return; multi->timer_lastcall = multi->timetree->key; multi->timer_cb(multi, timeout_ms, multi->timer_userp); } /* * multi_deltimeout() * * Remove a given timestamp from the list of timeouts. */ static void multi_deltimeout(struct Curl_easy *data, expire_id eid) { struct curl_llist_element *e; struct curl_llist *timeoutlist = &data->state.timeoutlist; /* find and remove the specific node from the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *n = (struct time_node *)e->ptr; if(n->eid == eid) { Curl_llist_remove(timeoutlist, e, NULL); return; } } } /* * multi_addtimeout() * * Add a timestamp to the list of timeouts. Keep the list sorted so that head * of list is always the timeout nearest in time. * */ static CURLMcode multi_addtimeout(struct Curl_easy *data, struct curltime *stamp, expire_id eid) { struct curl_llist_element *e; struct time_node *node; struct curl_llist_element *prev = NULL; size_t n; struct curl_llist *timeoutlist = &data->state.timeoutlist; node = &data->state.expires[eid]; /* copy the timestamp and id */ memcpy(&node->time, stamp, sizeof(*stamp)); node->eid = eid; /* also marks it as in use */ n = Curl_llist_count(timeoutlist); if(n) { /* find the correct spot in the list */ for(e = timeoutlist->head; e; e = e->next) { struct time_node *check = (struct time_node *)e->ptr; timediff_t diff = Curl_timediff(check->time, node->time); if(diff > 0) break; prev = e; } } /* else this is the first timeout on the list */ Curl_llist_insert_next(timeoutlist, prev, node, &node->list); return CURLM_OK; } /* * Curl_expire() * * given a number of milliseconds from now to use to set the 'act before * this'-time for the transfer, to be extracted by curl_multi_timeout() * * The timeout will be added to a queue of timeouts if it defines a moment in * time that is later than the current head of queue. * * Expire replaces a former timeout using the same id if already set. */ void Curl_expire(struct Curl_easy *data, timediff_t milli, expire_id id) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; struct curltime set; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; DEBUGASSERT(id < EXPIRE_LAST); set = Curl_now(); set.tv_sec += (time_t)(milli/1000); /* might be a 64 to 32 bit conversion */ set.tv_usec += (unsigned int)(milli%1000)*1000; if(set.tv_usec >= 1000000) { set.tv_sec++; set.tv_usec -= 1000000; } /* Remove any timer with the same id just in case. */ multi_deltimeout(data, id); /* Add it to the timer list. It must stay in the list until it has expired in case we need to recompute the minimum timer later. */ multi_addtimeout(data, &set, id); if(nowp->tv_sec || nowp->tv_usec) { /* This means that the struct is added as a node in the splay tree. Compare if the new time is earlier, and only remove-old/add-new if it is. */ timediff_t diff = Curl_timediff(set, *nowp); int rc; if(diff > 0) { /* The current splay tree entry is sooner than this new expiry time. We don't need to update our splay tree entry. */ return; } /* Since this is an updated time, we must remove the previous entry from the splay tree first and then re-add the new value */ rc = Curl_splayremovebyaddr(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error removing splay node = %d\n", rc); } /* Indicate that we are in the splay tree and insert the new timer expiry value since it is our local minimum. */ *nowp = set; data->state.timenode.payload = data; multi->timetree = Curl_splayinsert(*nowp, multi->timetree, &data->state.timenode); } /* * Curl_expire_done() * * Removes the expire timer. Marks it as done. * */ void Curl_expire_done(struct Curl_easy *data, expire_id id) { /* remove the timer, if there */ multi_deltimeout(data, id); } /* * Curl_expire_clear() * * Clear ALL timeout values for this handle. */ void Curl_expire_clear(struct Curl_easy *data) { struct Curl_multi *multi = data->multi; struct curltime *nowp = &data->state.expiretime; /* this is only interesting while there is still an associated multi struct remaining! */ if(!multi) return; if(nowp->tv_sec || nowp->tv_usec) { /* Since this is an cleared time, we must remove the previous entry from the splay tree */ struct curl_llist *list = &data->state.timeoutlist; int rc; rc = Curl_splayremovebyaddr(multi->timetree, &data->state.timenode, &multi->timetree); if(rc) infof(data, "Internal error clearing splay node = %d\n", rc); /* flush the timeout list too */ while(list->size > 0) { Curl_llist_remove(list, list->tail, NULL); } #ifdef DEBUGBUILD infof(data, "Expire cleared (transfer %p)\n", data); #endif nowp->tv_sec = 0; nowp->tv_usec = 0; } } CURLMcode curl_multi_assign(struct Curl_multi *multi, curl_socket_t s, void *hashp) { struct Curl_sh_entry *there = NULL; if(multi->in_callback) return CURLM_RECURSIVE_API_CALL; there = sh_getentry(&multi->sockhash, s); if(!there) return CURLM_BAD_SOCKET; there->socketp = hashp; return CURLM_OK; } size_t Curl_multi_max_host_connections(struct Curl_multi *multi) { return multi ? multi->max_host_connections : 0; } size_t Curl_multi_max_total_connections(struct Curl_multi *multi) { return multi ? multi->max_total_connections : 0; } /* * When information about a connection has appeared, call this! */ void Curl_multiuse_state(struct connectdata *conn, int bundlestate) /* use BUNDLE_* defines */ { DEBUGASSERT(conn); DEBUGASSERT(conn->bundle); DEBUGASSERT(conn->data); DEBUGASSERT(conn->data->multi); conn->bundle->multiuse = bundlestate; process_pending_handles(conn->data->multi); } static void process_pending_handles(struct Curl_multi *multi) { struct curl_llist_element *e = multi->pending.head; if(e) { struct Curl_easy *data = e->ptr; DEBUGASSERT(data->mstate == CURLM_STATE_CONNECT_PEND); multistate(data, CURLM_STATE_CONNECT); /* Remove this node from the list */ Curl_llist_remove(&multi->pending, e, NULL); /* Make sure that the handle will be processed soonish. */ Curl_expire(data, 0, EXPIRE_RUN_NOW); /* mark this as having been in the pending queue */ data->state.previouslypending = TRUE; } } void Curl_set_in_callback(struct Curl_easy *data, bool value) { /* might get called when there is no data pointer! */ if(data) { if(data->multi_easy) data->multi_easy->in_callback = value; else if(data->multi) data->multi->in_callback = value; } } bool Curl_is_in_callback(struct Curl_easy *easy) { return ((easy->multi && easy->multi->in_callback) || (easy->multi_easy && easy->multi_easy->in_callback)); } #ifdef DEBUGBUILD void Curl_multi_dump(struct Curl_multi *multi) { struct Curl_easy *data; int i; fprintf(stderr, "* Multi status: %d handles, %d alive\n", multi->num_easy, multi->num_alive); for(data = multi->easyp; data; data = data->next) { if(data->mstate < CURLM_STATE_COMPLETED) { /* only display handles that are not completed */ fprintf(stderr, "handle %p, state %s, %d sockets\n", (void *)data, statename[data->mstate], data->numsocks); for(i = 0; i < data->numsocks; i++) { curl_socket_t s = data->sockets[i]; struct Curl_sh_entry *entry = sh_getentry(&multi->sockhash, s); fprintf(stderr, "%d ", (int)s); if(!entry) { fprintf(stderr, "INTERNAL CONFUSION\n"); continue; } fprintf(stderr, "[%s %s] ", (entry->action&CURL_POLL_IN)?"RECVING":"", (entry->action&CURL_POLL_OUT)?"SENDING":""); } if(data->numsocks) fprintf(stderr, "\n"); } } } #endif
PooyaEimandar/WolfEngine
engine/src/wolf.system/curl/src/multi.c
C
mit
99,453
///\file /****************************************************************************** The MIT License(MIT) Embedded Template Library. https://github.com/ETLCPP/etl Copyright(c) 2014 jwellbelove Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #ifndef __ETL_POOL__ #define __ETL_POOL__ #include "alignment.h" #include "array.h" #include "bitset.h" #include "ipool.h" #include <iterator> //***************************************************************************** ///\defgroup pool pool /// A fixed capacity pool. ///\ingroup containers //***************************************************************************** namespace etl { //************************************************************************* /// A templated pool implementation that uses a fixed size pool. ///\ingroup pool //************************************************************************* template <typename T, const size_t SIZE_> class pool : public ipool<T> { public: static const size_t SIZE = SIZE_; //************************************************************************* /// Constructor //************************************************************************* pool() : ipool<T>(reinterpret_cast<T*>(&buffer[0]), in_use, SIZE) { } //************************************************************************* /// Destructor //************************************************************************* ~pool() { ipool<T>::release_all(); } private: ///< The memory for the pool of objects. typename etl::aligned_storage<sizeof(T), etl::alignment_of<T>::value>::type buffer[SIZE]; ///< The set of flags that indicate which items are free in the pool. bitset<SIZE> in_use; }; } #endif
GatorQue/etl
pool.h
C
mit
2,844
// This is a manifest file that'll be compiled into including all the files listed below. // Add new JavaScript/Coffee code in separate files in this directory and they'll automatically // be included in the compiled file accessible from http://example.com/assets/application.js // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // the compiled file. // //= require jquery //= require jquery_ujs //= require_tree .
astjohn/cornerstone
app/assets/javascripts/cornerstone.js
JavaScript
mit
465
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcGloballyUniqueId.h" #include "ifcpp/IFC4/include/IfcIdentifier.h" #include "ifcpp/IFC4/include/IfcLabel.h" #include "ifcpp/IFC4/include/IfcMember.h" #include "ifcpp/IFC4/include/IfcMemberTypeEnum.h" #include "ifcpp/IFC4/include/IfcObjectPlacement.h" #include "ifcpp/IFC4/include/IfcOwnerHistory.h" #include "ifcpp/IFC4/include/IfcProductRepresentation.h" #include "ifcpp/IFC4/include/IfcRelAggregates.h" #include "ifcpp/IFC4/include/IfcRelAssigns.h" #include "ifcpp/IFC4/include/IfcRelAssignsToProduct.h" #include "ifcpp/IFC4/include/IfcRelAssociates.h" #include "ifcpp/IFC4/include/IfcRelConnectsElements.h" #include "ifcpp/IFC4/include/IfcRelConnectsWithRealizingElements.h" #include "ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelCoversBldgElements.h" #include "ifcpp/IFC4/include/IfcRelDeclares.h" #include "ifcpp/IFC4/include/IfcRelDefinesByObject.h" #include "ifcpp/IFC4/include/IfcRelDefinesByProperties.h" #include "ifcpp/IFC4/include/IfcRelDefinesByType.h" #include "ifcpp/IFC4/include/IfcRelFillsElement.h" #include "ifcpp/IFC4/include/IfcRelInterferesElements.h" #include "ifcpp/IFC4/include/IfcRelNests.h" #include "ifcpp/IFC4/include/IfcRelProjectsElement.h" #include "ifcpp/IFC4/include/IfcRelReferencedInSpatialStructure.h" #include "ifcpp/IFC4/include/IfcRelSpaceBoundary.h" #include "ifcpp/IFC4/include/IfcRelVoidsElement.h" #include "ifcpp/IFC4/include/IfcText.h" // ENTITY IfcMember IfcMember::IfcMember( int id ) { m_entity_id = id; } shared_ptr<BuildingObject> IfcMember::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcMember> copy_self( new IfcMember() ); if( m_GlobalId ) { if( options.create_new_IfcGloballyUniqueId ) { copy_self->m_GlobalId = make_shared<IfcGloballyUniqueId>( createBase64Uuid_wstr().data() ); } else { copy_self->m_GlobalId = dynamic_pointer_cast<IfcGloballyUniqueId>( m_GlobalId->getDeepCopy(options) ); } } if( m_OwnerHistory ) { if( options.shallow_copy_IfcOwnerHistory ) { copy_self->m_OwnerHistory = m_OwnerHistory; } else { copy_self->m_OwnerHistory = dynamic_pointer_cast<IfcOwnerHistory>( m_OwnerHistory->getDeepCopy(options) ); } } if( m_Name ) { copy_self->m_Name = dynamic_pointer_cast<IfcLabel>( m_Name->getDeepCopy(options) ); } if( m_Description ) { copy_self->m_Description = dynamic_pointer_cast<IfcText>( m_Description->getDeepCopy(options) ); } if( m_ObjectType ) { copy_self->m_ObjectType = dynamic_pointer_cast<IfcLabel>( m_ObjectType->getDeepCopy(options) ); } if( m_ObjectPlacement ) { copy_self->m_ObjectPlacement = dynamic_pointer_cast<IfcObjectPlacement>( m_ObjectPlacement->getDeepCopy(options) ); } if( m_Representation ) { copy_self->m_Representation = dynamic_pointer_cast<IfcProductRepresentation>( m_Representation->getDeepCopy(options) ); } if( m_Tag ) { copy_self->m_Tag = dynamic_pointer_cast<IfcIdentifier>( m_Tag->getDeepCopy(options) ); } if( m_PredefinedType ) { copy_self->m_PredefinedType = dynamic_pointer_cast<IfcMemberTypeEnum>( m_PredefinedType->getDeepCopy(options) ); } return copy_self; } void IfcMember::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCMEMBER" << "("; if( m_GlobalId ) { m_GlobalId->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_OwnerHistory ) { stream << "#" << m_OwnerHistory->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Name ) { m_Name->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectType ) { m_ObjectType->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_ObjectPlacement ) { stream << "#" << m_ObjectPlacement->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Representation ) { stream << "#" << m_Representation->m_entity_id; } else { stream << "$"; } stream << ","; if( m_Tag ) { m_Tag->getStepParameter( stream ); } else { stream << "$"; } stream << ","; if( m_PredefinedType ) { m_PredefinedType->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcMember::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; } const std::wstring IfcMember::toString() const { return L"IfcMember"; } void IfcMember::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 9 ){ std::stringstream err; err << "Wrong parameter count for entity IfcMember, expecting 9, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } m_GlobalId = IfcGloballyUniqueId::createObjectFromSTEP( args[0], map ); readEntityReference( args[1], m_OwnerHistory, map ); m_Name = IfcLabel::createObjectFromSTEP( args[2], map ); m_Description = IfcText::createObjectFromSTEP( args[3], map ); m_ObjectType = IfcLabel::createObjectFromSTEP( args[4], map ); readEntityReference( args[5], m_ObjectPlacement, map ); readEntityReference( args[6], m_Representation, map ); m_Tag = IfcIdentifier::createObjectFromSTEP( args[7], map ); m_PredefinedType = IfcMemberTypeEnum::createObjectFromSTEP( args[8], map ); } void IfcMember::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcBuildingElement::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "PredefinedType", m_PredefinedType ) ); } void IfcMember::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcBuildingElement::getAttributesInverse( vec_attributes_inverse ); } void IfcMember::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcBuildingElement::setInverseCounterparts( ptr_self_entity ); } void IfcMember::unlinkFromInverseCounterparts() { IfcBuildingElement::unlinkFromInverseCounterparts(); }
ifcquery/ifcplusplus
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcMember.cpp
C++
mit
6,494
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="apple-mobile-web-app-capable" content="no"> <meta name="viewport" content="width=1000"> <meta name="keywords" content="attrs.ui"> <meta name="author" content="[email protected]"> <meta name="description" content="Examples"> <title>Style System Basic</title> <script type="text/javascript" src="../ui.debug.js"></script> <script type="text/javascript"> // define style var style = new Appbus.Style({ 'background': 'white', 'color': 'black', 'font-size': 10, '.hierachy': { 'color': 'grey', 'background': 'yellow', 'test': { 'font-size': 9 } } }); console.log('style', style); style.on('*', function(e) { console.log('[' + e.type + '] event occured'); console.log('src', e.src); console.log('values', e.values); console.log('\n\n'); }); // append style.set('..newcls', { 'background': 'lightorange', '.hierachy': { '': { 'color': 'red' } } }); // replace style.set('color', 'grey'); // remove style.remove('font-size'); // merge element style.merge('..cls', { 'display': 'box', 'background-image': 'url("http://localhost/image.png")', 'transition': 'aa', 'p': { 'color': 'blue' } }); // sub style replace style.get('..cls').set('color', 'grey'); // sub style remove style.get('..cls').remove('color'); </script> </head> <body> </body> </html>
attrs/ui-aliens
src/deprecated/examples/core/stylesystem/style.events.html
HTML
mit
1,721
/** * Copyright 2014 Pacific Controls Software Services LLC (PCSS). All Rights Reserved. * * This software is the property of Pacific Controls Software Services LLC and its * suppliers. The intellectual and technical concepts contained herein are proprietary * to PCSS. Dissemination of this information or reproduction of this material is * strictly forbidden unless prior written permission is obtained from Pacific * Controls Software Services. * * PCSS MAKES NO REPRESENTATION OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTANILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGMENT. PCSS SHALL * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * Version : 1.0 * User : pcseg306 * Function : Service for Super/client Admin Notification Functions */ gxMainApp.factory("adminFunctionsService", function($http,$rootScope,gxAPIServiceWrapper){ var _notificationArray = []; var _resultPromise; var _getNotificationArray = function() { _resultPromise = gxAPIServiceWrapper.get("models/superAdmin/dummySuperAdminNotification.json"); console.log(_resultPromise); return _resultPromise; } return{ notificationArray: _notificationArray, getNotificationArray: _getNotificationArray, resultPromise : _resultPromise }; });
dddomin3/angular-galaxy
services/adminNotification/adminNotificationDataService.js
JavaScript
mit
1,524
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/thumbor/thumbor/wiki # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 globo.com [email protected] from thumbor.loaders import http_loader from tornado.concurrent import return_future from urllib import unquote def _normalize_url(url): url = http_loader.quote_url(unquote(url)) if url.startswith('http:'): url = url.replace('http:', 'https:', 1) return url if url.startswith('https://') else 'https://%s' % url def validate(context, url): if url.startswith('http://'): return False return http_loader.validate(context, url, normalize_url_func=_normalize_url) def return_contents(response, url, callback, context): return http_loader.return_contents(response, url, callback, context) @return_future def load(context, url, callback): return http_loader.load_sync(context, url, callback, normalize_url_func=_normalize_url) def encode(string): return http_loader.encode(string)
jdunaravich/thumbor
thumbor/loaders/strict_https_loader.py
Python
mit
1,086
<?php class device extends CI_Controller{ public function add_device(){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id'); //later stages will take users key $passcode = rand($key,$key+10000); $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key, 'passcode' => $passcode ); $this->device_model->add_device($data); $this->session->set_userdata('passcode', $passcode); redirect('user/device'); } public function edit_device($id){ $this->load->model('device_model'); $device_name = $this->input->post('device_name'); $device_id = $this->input->post('device_id'); $about_device = $this->input->post('about_device'); $key = $this->session->userdata('id');; //later stages will take users key $data = array( 'device_name' => $device_name, 'device_id' => $device_id, 'about_device' => $about_device, 'key' => $key ); $this->device_model->edit_device($id,$data); redirect('user/device'); } public function delete_device($id){ $this->load->model('device_model'); $this->device_model->delete_device($id); redirect('user/device'); } public function add_parameters($device_id){ $parameters = $this->input->post("parameter_name[]"); $this->load->model('device_model'); foreach ($parameters as $parameter_name) { $data = [ 'parameter_name' => $parameter_name, 'device_id' => $device_id ]; $this->device_model->add_parameter($data); } redirect("user/device"); } public function update_parameter(){ $this->load->model('device_model'); $parameter_names = $this->input->post('parameter_name[]'); $parameter_ids = $this->input->post('parameter_id[]'); $count = 0; foreach ($parameter_names as $parameter_name){ $id = $parameter_ids[$count]; $data = array('parameter_name' => $parameter_name); $this->device_model->edit_parameter($id,$data); $count = $count + 1; } redirect('user/device'); } } ?>
Chaitya62/IOT-Bridge-Final-name-not-comfirmed
application/controllers/device.php
PHP
mit
2,164
define(function(require) { var test = require('../../../test') var count = 0 require.async('./a', function(a) { test.assert(a.name === 'a', 'load CMD module file') done() }) require.async('./b.js', function() { test.assert(global.SPECS_MODULES_ASYNC === true, 'load normal script file') global.SPECS_MODULES_ASYNC = undefined done() }) require.async(['./c1', './c2'], function(c1, c2) { test.assert(c1.name === 'c1', c1.name) test.assert(c2.name === 'c2', c2.name) done() }) function done() { if (++count === 3) { test.next() } } });
007slm/seajs
tests/specs/module/require-async/main.js
JavaScript
mit
609
namespace AbpKendoDemo.Migrations { using System; using System.Data.Entity.Migrations; public partial class Upgrade_Abp_And_Module_Zero_To_0_8_1 : DbMigration { public override void Up() { CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 128), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 256), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 128), EntityTypeName = c.String(maxLength: 256), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 128), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); } public override void Down() { DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserNotifications"); DropTable("dbo.AbpNotificationSubscriptions"); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpBackgroundJobs"); } } }
s-takatsu/aspnetboilerplate-samples
KendoUiDemo/src/AbpKendoDemo.EntityFramework/Migrations/201602161446590_Upgrade_Abp_And_Module_Zero_To_0_8_1.cs
C#
mit
4,104
using System.Web; using System.Web.Optimization; namespace TwitterFeed { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css","~/Content/site.css")); bundles.Add(new ScriptBundle("~/Scripts/js").Include("~/Scripts/jquery-2.1.1.min.js", "~/Scripts/bootstrap.min.js", "~/Scripts/knockout-3.3.0.js", "~/Scripts/sammy-0.7.5.min.js", "~/Scripts/main.js")); } } }
jakeholland/TwitterFeed
TwitterFeed/App_Start/BundleConfig.cs
C#
mit
553
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.advisor.v2017_04_19; import com.microsoft.azure.arm.collection.SupportsCreating; import rx.Completable; import rx.Observable; import com.microsoft.azure.management.advisor.v2017_04_19.implementation.SuppressionsInner; import com.microsoft.azure.arm.model.HasInner; /** * Type representing Suppressions. */ public interface Suppressions extends SupportsCreating<SuppressionContract.DefinitionStages.Blank>, HasInner<SuppressionsInner> { /** * Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> listAsync(); /** * Obtains the details of a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Observable<SuppressionContract> getAsync(String resourceUri, String recommendationId, String name); /** * Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression. * * @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies. * @param recommendationId The recommendation ID. * @param name The name of the suppression. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ Completable deleteAsync(String resourceUri, String recommendationId, String name); }
selvasingh/azure-sdk-for-java
sdk/advisor/mgmt-v2017_04_19/src/main/java/com/microsoft/azure/management/advisor/v2017_04_19/Suppressions.java
Java
mit
2,252
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/item/shared_armor_composite_helmet.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
anhstudios/swganh
data/scripts/templates/object/static/item/shared_armor_composite_helmet.py
Python
mit
447
const fs = require('fs'); const path = require('path'); const cleanCss = require('../../index.js'); module.exports = { name : 'basic test', this : function () { const str = fs.readFileSync(path.resolve('test/styles/basic.dirty.scss'), 'utf8'); const clean = cleanCss({ css : str }); return clean; }, isEqual : function () { return fs.readFileSync(path.resolve('test/styles/basic.clean.scss'), 'utf8'); } };
SeanJM/css-clean-npm
test/tests/basic.js
JavaScript
mit
445
<script src="/socket.io/socket.io.js"></script> <script src="bower_components/virtualjoystick.js/virtualjoystick.js"></script> <script src="../threex.cloudcontroller.js"></script> <script src="../threex.cloudcontrollerscreenupdater.js"></script> <script src="../threex.cloudcontrollervirtualjoystick.js"></script> <body style='width:100%;margin: 0px; background-color: #bbbbbb; overflow: hidden;'> <!-- <img id='remoteImage' src=''/> --> <script> window.addEventListener('load', function(event){ ////////////////////////////////////////////////////////////////////////////////// // CloudController itself // ////////////////////////////////////////////////////////////////////////////////// var cloudController = new THREEx.CloudController() cloudController.socket.on('connect', function(){ console.log('connected to server') }) cloudController.socket.on('disconnect', function(){ console.warn('disconnected from server') }) ////////////////////////////////////////////////////////////////////////////////// // screenUpdater // ////////////////////////////////////////////////////////////////////////////////// var screenUpdater = new THREEx.CloudControllerScreenUpdater(cloudController) document.body.appendChild(screenUpdater.domElement) screenUpdater.sendResolution() setTimeout(function(){ screenUpdater.sendResolution() }, 1000*0.5) ////////////////////////////////////////////////////////////////////////////////// // virtualjoystick // ////////////////////////////////////////////////////////////////////////////////// var cloudVirtualJoystick = new THREEx.CloudControllerVirtualJoystick(cloudController) setInterval(function(){ cloudVirtualJoystick.sendIfChanged() }, 1000*1/60) }) </script></body>
Zekom/threex.cloudgaming
examples/remotecontroller.html
HTML
mit
1,773
<a href="/learning-programming.html" class="lgi">Learning Programming</a> <a href="/serverless.html" class="lgi">Serverless Architectures</a> <a href="/aws-lambda.html" class="lgi">AWS Lambda</a> <a href="/monitoring.html" class="lgi">Monitoring</a> <a href="/deployment.html" class="lgi">Deployment</a> <a href="/rollbar.html" class="lgi">Rollbar</a> <a href="https://rollbar.com" class="lgi">Rollbar homepage {% include "blog/external-link.html" %}</a> <a href="https://docs.rollbar.com/docs/python/#aws-lambda" class="lgi">Rollbar AWS Lambda docs {% include "blog/external-link.html" %}</a>
mattmakai/fullstackpython.com
theme/templates/blog/monitor-python-3-6-example-code-aws-lambda-rollbar.html
HTML
mit
594
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112) on Sat May 13 03:02:10 PDT 2017 --> <title>ConsoleUI</title> <meta name="date" content="2017-05-13"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <script type="text/javascript" src="../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ConsoleUI"; } } catch(err) { } //--> var methods = {"i0":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-all.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../ui/Environment.html" title="class in ui"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?ui/ConsoleUI.html" target="_top">Frames</a></li> <li><a href="ConsoleUI.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">ui</div> <h2 title="Class ConsoleUI" class="title">Class ConsoleUI</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>ui.ConsoleUI</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.util.Observer</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">ConsoleUI</span> extends java.lang.Object implements java.util.Observer</pre> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>0.1 A console logger</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../ui/ConsoleUI.html#ConsoleUI--">ConsoleUI</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../ui/ConsoleUI.html#update-java.util.Observable-java.lang.Object-">update</a></span>(java.util.Observable&nbsp;o, java.lang.Object&nbsp;arg)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ConsoleUI--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ConsoleUI</h4> <pre>public&nbsp;ConsoleUI()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="update-java.util.Observable-java.lang.Object-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>update</h4> <pre>public&nbsp;void&nbsp;update(java.util.Observable&nbsp;o, java.lang.Object&nbsp;arg)</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>update</code>&nbsp;in interface&nbsp;<code>java.util.Observer</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li><a href="../index-all.html">Index</a></li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../ui/Environment.html" title="class in ui"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?ui/ConsoleUI.html" target="_top">Frames</a></li> <li><a href="ConsoleUI.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
slemonide/sasuga
docs/ui/ConsoleUI.html
HTML
mit
8,809
## 快捷键 ## {% highlight json %} { "去色" : "C-S-u", "反相" : "C-i", } {% endhighlight %}
openefit/openefit.github.io
_drafts/photoshop.md
Markdown
mit
106
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Test setting the $P4COMSTR variable. """ import os.path import TestSCons _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.subdir('Perforce', ['Perforce', 'sub'], 'sub') sub_Perforce = os.path.join('sub', 'Perforce') sub_SConscript = os.path.join('sub', 'SConscript') sub_all = os.path.join('sub', 'all') sub_ddd_in = os.path.join('sub', 'ddd.in') sub_ddd_out = os.path.join('sub', 'ddd.out') sub_eee_in = os.path.join('sub', 'eee.in') sub_eee_out = os.path.join('sub', 'eee.out') sub_fff_in = os.path.join('sub', 'fff.in') sub_fff_out = os.path.join('sub', 'fff.out') test.write('my-p4.py', """ import shutil import sys for f in sys.argv[1:]: shutil.copy('Perforce/'+f, f) """) test.write('SConstruct', """ def cat(env, source, target): target = str(target[0]) source = map(str, source) f = open(target, "wb") for src in source: f.write(open(src, "rb").read()) f.close() env = Environment(TOOLS = ['default', 'Perforce'], BUILDERS={'Cat':Builder(action=cat)}, P4COM='%(_python_)s my-p4.py $TARGET', P4COMSTR='Checking out $TARGET from our fake Perforce') env.Cat('aaa.out', 'aaa.in') env.Cat('bbb.out', 'bbb.in') env.Cat('ccc.out', 'ccc.in') env.Cat('all', ['aaa.out', 'bbb.out', 'ccc.out']) env.SourceCode('.', env.Perforce()) SConscript('sub/SConscript', "env") """ % locals()) test.write(['Perforce', 'sub', 'SConscript'], """\ Import("env") env.Cat('ddd.out', 'ddd.in') env.Cat('eee.out', 'eee.in') env.Cat('fff.out', 'fff.in') env.Cat('all', ['ddd.out', 'eee.out', 'fff.out']) """) test.write(['Perforce', 'aaa.in'], "Perforce/aaa.in\n") test.write('bbb.in', "checked-out bbb.in\n") test.write(['Perforce', 'ccc.in'], "Perforce/ccc.in\n") test.write(['Perforce', 'sub', 'ddd.in'], "Perforce/sub/ddd.in\n") test.write(['sub', 'eee.in'], "checked-out sub/eee.in\n") test.write(['Perforce', 'sub', 'fff.in'], "Perforce/sub/fff.in\n") test.run(arguments = '.', stdout = test.wrap_stdout(read_str = """\ Checking out %(sub_SConscript)s from our fake Perforce """ % locals(), build_str = """\ Checking out aaa.in from our fake Perforce cat(["aaa.out"], ["aaa.in"]) cat(["bbb.out"], ["bbb.in"]) Checking out ccc.in from our fake Perforce cat(["ccc.out"], ["ccc.in"]) cat(["all"], ["aaa.out", "bbb.out", "ccc.out"]) Checking out %(sub_ddd_in)s from our fake Perforce cat(["%(sub_ddd_out)s"], ["%(sub_ddd_in)s"]) cat(["%(sub_eee_out)s"], ["%(sub_eee_in)s"]) Checking out %(sub_fff_in)s from our fake Perforce cat(["%(sub_fff_out)s"], ["%(sub_fff_in)s"]) cat(["%(sub_all)s"], ["%(sub_ddd_out)s", "%(sub_eee_out)s", "%(sub_fff_out)s"]) """ % locals())) test.must_match('all', "Perforce/aaa.in\nchecked-out bbb.in\nPerforce/ccc.in\n") test.must_match(['sub', 'all'], "Perforce/sub/ddd.in\nchecked-out sub/eee.in\nPerforce/sub/fff.in\n") # test.pass_test()
datalogics/scons
test/Perforce/P4COMSTR.py
Python
mit
4,112
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Serialization; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Fungus { /** * Visual scripting controller for the Flowchart programming language. * Flowchart objects may be edited visually using the Flowchart editor window. */ [ExecuteInEditMode] public class Flowchart : MonoBehaviour { /** * Current version used to compare with the previous version so older versions can be custom-updated from previous versions. */ public const string CURRENT_VERSION = "1.0"; /** * The name of the initial block in a new flowchart. */ public const string DEFAULT_BLOCK_NAME = "New Block"; /** * Variable to track flowchart's version and if initial set up has completed. */ [HideInInspector] public string version; /** * Scroll position of Flowchart editor window. */ [HideInInspector] public Vector2 scrollPos; /** * Scroll position of Flowchart variables window. */ [HideInInspector] public Vector2 variablesScrollPos; /** * Show the variables pane. */ [HideInInspector] public bool variablesExpanded = true; /** * Height of command block view in inspector. */ [HideInInspector] public float blockViewHeight = 400; /** * Zoom level of Flowchart editor window */ [HideInInspector] public float zoom = 1f; /** * Scrollable area for Flowchart editor window. */ [HideInInspector] public Rect scrollViewRect; /** * Currently selected block in the Flowchart editor. */ [HideInInspector] [FormerlySerializedAs("selectedSequence")] public Block selectedBlock; /** * Currently selected command in the Flowchart editor. */ [HideInInspector] public List<Command> selectedCommands = new List<Command>(); /** * The list of variables that can be accessed by the Flowchart. */ [HideInInspector] public List<Variable> variables = new List<Variable>(); [TextArea(3, 5)] [Tooltip("Description text displayed in the Flowchart editor window")] public string description = ""; /** * Slow down execution in the editor to make it easier to visualise program flow. */ [Range(0f, 5f)] [Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")] public float stepPause = 0f; /** * Use command color when displaying the command list in the inspector. */ [Tooltip("Use command color when displaying the command list in the Fungus Editor window")] public bool colorCommands = true; /** * Hides the Flowchart block and command components in the inspector. * Deselect to inspect the block and command components that make up the Flowchart. */ [Tooltip("Hides the Flowchart block and command components in the inspector")] public bool hideComponents = true; /** * Saves the selected block and commands when saving the scene. * Helps avoid version control conflicts if you've only changed the active selection. */ [Tooltip("Saves the selected block and commands when saving the scene.")] public bool saveSelection = true; /** * Unique identifier for identifying this flowchart in localized string keys. */ [Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")] public string localizationId = ""; /** * Cached list of flowchart objects in the scene for fast lookup */ public static List<Flowchart> cachedFlowcharts = new List<Flowchart>(); protected static bool eventSystemPresent; /** * Returns the next id to assign to a new flowchart item. * Item ids increase monotically so they are guaranteed to * be unique within a Flowchart. */ public int NextItemId() { int maxId = -1; Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { maxId = Math.Max(maxId, block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { maxId = Math.Max(maxId, command.itemId); } return maxId + 1; } protected virtual void OnLevelWasLoaded(int level) { // Reset the flag for checking for an event system as there may not be one in the newly loaded scene. eventSystemPresent = false; } protected virtual void Start() { CheckEventSystem(); } // There must be an Event System in the scene for Say and Menu input to work. // This method will automatically instantiate one if none exists. protected virtual void CheckEventSystem() { if (eventSystemPresent) { return; } EventSystem eventSystem = GameObject.FindObjectOfType<EventSystem>(); if (eventSystem == null) { // Auto spawn an Event System from the prefab GameObject prefab = Resources.Load<GameObject>("EventSystem"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.name = "EventSystem"; } } eventSystemPresent = true; } public virtual void OnEnable() { if (!cachedFlowcharts.Contains(this)) { cachedFlowcharts.Add(this); } CheckItemIds(); CleanupComponents(); UpdateVersion(); } public virtual void OnDisable() { cachedFlowcharts.Remove(this); } protected virtual void CheckItemIds() { // Make sure item ids are unique and monotonically increasing. // This should always be the case, but some legacy Flowcharts may have issues. List<int> usedIds = new List<int>(); Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.itemId == -1 || usedIds.Contains(block.itemId)) { block.itemId = NextItemId(); } usedIds.Add(block.itemId); } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { if (command.itemId == -1 || usedIds.Contains(command.itemId)) { command.itemId = NextItemId(); } usedIds.Add(command.itemId); } } protected virtual void CleanupComponents() { // Delete any unreferenced components which shouldn't exist any more // Unreferenced components don't have any effect on the flowchart behavior, but // they waste memory so should be cleared out periodically. Block[] blocks = GetComponentsInChildren<Block>(); foreach (Variable variable in GetComponents<Variable>()) { if (!variables.Contains(variable)) { DestroyImmediate(variable); } } foreach (Command command in GetComponents<Command>()) { bool found = false; foreach (Block block in blocks) { if (block.commandList.Contains(command)) { found = true; break; } } if (!found) { DestroyImmediate(command); } } foreach (EventHandler eventHandler in GetComponents<EventHandler>()) { bool found = false; foreach (Block block in blocks) { if (block.eventHandler == eventHandler) { found = true; break; } } if (!found) { DestroyImmediate(eventHandler); } } } private void UpdateVersion() { // If versions match, then we are already using the latest. if (version == CURRENT_VERSION) return; switch (version) { // Version never set, so we are initializing on first creation or this flowchart is pre-versioning. case null: case "": Initialize(); break; } version = CURRENT_VERSION; } protected virtual void Initialize() { // If there are other flowcharts in the scene and the selected block has the default name, then this is probably a new block. // Reset the event handler of the new flowchart's default block to avoid crashes. if (selectedBlock && cachedFlowcharts.Count > 1 && selectedBlock.blockName == DEFAULT_BLOCK_NAME) { selectedBlock.eventHandler = null; } } protected virtual Block CreateBlockComponent(GameObject parent) { Block block = parent.AddComponent<Block>(); return block; } /** * Create a new block node which you can then add commands to. */ public virtual Block CreateBlock(Vector2 position) { Block b = CreateBlockComponent(gameObject); b.nodeRect.x = position.x; b.nodeRect.y = position.y; b.blockName = GetUniqueBlockKey(b.blockName, b); b.itemId = NextItemId(); return b; } /** * Returns the named Block in the flowchart, or null if not found. */ public virtual Block FindBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { return block; } } return null; } /** * Start running another Flowchart by executing a specific child block. * The block must be in an idle state to be executed. * You can use this method in a UI event. e.g. to handle a button click. */ public virtual void ExecuteBlock(string blockName) { Block [] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { if (block.blockName == blockName) { ExecuteBlock(block); } } } /** * Sends a message to this Flowchart only. * Any block with a matching MessageReceived event handler will start executing. */ public virtual void SendFungusMessage(string messageName) { MessageReceived[] eventHandlers = GetComponentsInChildren<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Sends a message to all Flowchart objects in the current scene. * Any block with a matching MessageReceived event handler will start executing. */ public static void BroadcastFungusMessage(string messageName) { MessageReceived[] eventHandlers = GameObject.FindObjectsOfType<MessageReceived>(); foreach (MessageReceived eventHandler in eventHandlers) { eventHandler.OnSendFungusMessage(messageName); } } /** * Start executing a specific child block in the flowchart. * The block must be in an idle state to be executed. * Returns true if the Block started execution. */ public virtual bool ExecuteBlock(Block block, Action onComplete = null) { // Block must be a component of the Flowchart game object if (block == null || block.gameObject != gameObject) { return false; } // Can't restart a running block, have to wait until it's idle again if (block.IsExecuting()) { return false; } // Execute the first command in the command list block.Execute(onComplete); return true; } /** * Returns a new variable key that is guaranteed not to clash with any existing variable in the list. */ public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null) { int suffix = 0; string baseKey = originalKey; // Only letters and digits allowed char[] arr = baseKey.Where(c => (char.IsLetterOrDigit(c) || c == '_')).ToArray(); baseKey = new string(arr); // No leading digits allowed baseKey = baseKey.TrimStart('0','1','2','3','4','5','6','7','8','9'); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "Var"; } string key = baseKey; while (true) { bool collision = false; foreach(Variable variable in variables) { if (variable == null || variable == ignoreVariable || variable.key == null) { continue; } if (variable.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart. */ public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Block"; } Block[] blocks = GetComponentsInChildren<Block>(); string key = baseKey; while (true) { bool collision = false; foreach(Block block in blocks) { if (block == ignoreBlock || block.blockName == null) { continue; } if (block.blockName.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns a new Label key that is guaranteed not to clash with any existing Label in the Block. */ public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel) { int suffix = 0; string baseKey = originalKey.Trim(); // No empty keys allowed if (baseKey.Length == 0) { baseKey = "New Label"; } Block block = ignoreLabel.parentBlock; string key = baseKey; while (true) { bool collision = false; foreach(Command command in block.commandList) { Label label = command as Label; if (label == null || label == ignoreLabel) { continue; } if (label.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) { collision = true; suffix++; key = baseKey + suffix; } } if (!collision) { return key; } } } /** * Returns the variable with the specified key, or null if the key is not found. * You can then access the variable's value using the Value property. e.g. * BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool"); * boolVar.Value = false; */ public T GetVariable<T>(string key) where T : Variable { foreach (Variable variable in variables) { if (variable.key == key) { return variable as T; } } return null; } /** * Gets a list of all variables with public scope in this Flowchart. */ public virtual List<Variable> GetPublicVariables() { List<Variable> publicVariables = new List<Variable>(); foreach (Variable v in variables) { if (v.scope == VariableScope.Public) { publicVariables.Add(v); } } return publicVariables; } /** * Gets the value of a boolean variable. * Returns false if the variable key does not exist. */ public virtual bool GetBooleanVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Boolean variable " + key + " not found."); return false; } /** * Sets the value of a boolean variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetBooleanVariable(string key, bool value) { foreach (Variable v in variables) { if (v.key == key) { BooleanVariable variable = v as BooleanVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Boolean variable " + key + " not found."); } /** * Gets the value of an integer variable. * Returns 0 if the variable key does not exist. */ public virtual int GetIntegerVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Integer variable " + key + " not found."); return 0; } /** * Sets the value of an integer variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetIntegerVariable(string key, int value) { foreach (Variable v in variables) { if (v.key == key) { IntegerVariable variable = v as IntegerVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Integer variable " + key + " not found."); } /** * Gets the value of a float variable. * Returns 0 if the variable key does not exist. */ public virtual float GetFloatVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("Float variable " + key + " not found."); return 0f; } /** * Sets the value of a float variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetFloatVariable(string key, float value) { foreach (Variable v in variables) { if (v.key == key) { FloatVariable variable = v as FloatVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("Float variable " + key + " not found."); } /** * Gets the value of a string variable. * Returns the empty string if the variable key does not exist. */ public virtual string GetStringVariable(string key) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { return variable.value; } } } Debug.LogWarning("String variable " + key + " not found."); return ""; } /** * Sets the value of a string variable. * The variable must already be added to the list of variables for this Flowchart. */ public virtual void SetStringVariable(string key, string value) { foreach (Variable v in variables) { if (v.key == key) { StringVariable variable = v as StringVariable; if (variable != null) { variable.value = value; return; } } } Debug.LogWarning("String variable " + key + " not found."); } /** * Set the block objects to be hidden or visible depending on the hideComponents property. */ public virtual void UpdateHideFlags() { if (hideComponents) { Block[] blocks = GetComponentsInChildren<Block>(); foreach (Block block in blocks) { block.hideFlags = HideFlags.HideInInspector; if (block.gameObject != gameObject) { block.gameObject.hideFlags = HideFlags.HideInHierarchy; } } Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.hideFlags = HideFlags.HideInInspector; } EventHandler[] eventHandlers = GetComponentsInChildren<EventHandler>(); foreach (EventHandler eventHandler in eventHandlers) { eventHandler.hideFlags = HideFlags.HideInInspector; } } else { MonoBehaviour[] monoBehaviours = GetComponentsInChildren<MonoBehaviour>(); foreach (MonoBehaviour monoBehaviour in monoBehaviours) { if (monoBehaviour == null) { continue; } monoBehaviour.hideFlags = HideFlags.None; monoBehaviour.gameObject.hideFlags = HideFlags.None; } } } public virtual void ClearSelectedCommands() { selectedCommands.Clear(); } public virtual void AddSelectedCommand(Command command) { if (!selectedCommands.Contains(command)) { selectedCommands.Add(command); } } public virtual void Reset(bool resetCommands, bool resetVariables) { if (resetCommands) { Command[] commands = GetComponentsInChildren<Command>(); foreach (Command command in commands) { command.OnReset(); } } if (resetVariables) { foreach (Variable variable in variables) { variable.OnReset(); } } } public virtual string SubstituteVariables(string text) { string subbedText = text; // Instantiate the regular expression object. Regex r = new Regex("{\\$.*?}"); // Match the regular expression pattern against a text string. var results = r.Matches(text); foreach (Match match in results) { string key = match.Value.Substring(2, match.Value.Length - 3); // Look for any matching variables in this Flowchart first (public or private) foreach (Variable variable in variables) { if (variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } // Now search all public variables in all scene Flowcharts in the scene foreach (Flowchart flowchart in cachedFlowcharts) { if (flowchart == this) { // We've already searched this flowchart continue; } foreach (Variable variable in flowchart.variables) { if (variable.scope == VariableScope.Public && variable.key == key) { string value = variable.ToString(); subbedText = subbedText.Replace(match.Value, value); } } } // Next look for matching localized string string localizedString = Localization.GetLocalizedString(key); if (localizedString != null) { subbedText = subbedText.Replace(match.Value, localizedString); } } return subbedText; } } }
tapiralec/Fungus
Assets/Fungus/Flowchart/Scripts/Flowchart.cs
C#
mit
21,856
/// \file /// \brief SocketLayer class implementation /// /// This file is part of RakNet Copyright 2003 Kevin Jenkins. /// /// Usage of RakNet is subject to the appropriate license agreement. /// Creative Commons Licensees are subject to the /// license found at /// http://creativecommons.org/licenses/by-nc/2.5/ /// Single application licensees are subject to the license found at /// http://www.jenkinssoftware.com/SingleApplicationLicense.html /// Custom license users are subject to the terms therein. /// GPL license users are subject to the GNU General Public /// License as published by the Free /// Software Foundation; either version 2 of the License, or (at your /// option) any later version. #ifndef __SOCKET_LAYER_H #define __SOCKET_LAYER_H #include "RakMemoryOverride.h" #ifdef _XBOX360 #include "Console1Includes.h" #elif defined(_PS3) #include "Console2Includes.h" typedef int SOCKET; #elif defined(_WIN32) // IP_DONTFRAGMENT is different between winsock 1 and winsock 2. Therefore, Winsock2.h must be linked againt Ws2_32.lib // winsock.h must be linked against WSock32.lib. If these two are mixed up the flag won't work correctly #include <winsock2.h> #include <ws2tcpip.h> //#include "RakMemoryOverride.h" #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> //#include "RakMemoryOverride.h" /// Unix/Linux uses ints for sockets typedef int SOCKET; #endif //#include "ClientContextStruct.h" class RakPeer; // A platform independent implementation of Berkeley sockets, with settings used by RakNet class SocketLayer : public RakNet::RakMemoryOverride { public: /// Default Constructor SocketLayer(); /// Destructor ~SocketLayer(); // Get the singleton instance of the Socket Layer. /// \return unique instance static inline SocketLayer* Instance() { return & I; } // Connect a socket to a remote host. /// \param[in] writeSocket The local socket. /// \param[in] binaryAddress The address of the remote host. /// \param[in] port the remote port. /// \return A new socket used for communication. SOCKET Connect( SOCKET writeSocket, unsigned int binaryAddress, unsigned short port ); /// Creates a bound socket to listen for incoming connections on the specified port /// \param[in] port the port number /// \param[in] blockingSocket /// \return A new socket used for accepting clients SOCKET CreateBoundSocket( unsigned short port, bool blockingSocket, const char *forceHostAddress ); /// Returns if this specified port is in use, for UDP /// \param[in] port the port number /// \return If this port is already in use static bool IsPortInUse(unsigned short port); #if !defined(_XBOX360) const char* DomainNameToIP( const char *domainName ); #endif /// Start an asynchronous read using the specified socket. The callback will use the specified SystemAddress (associated with this socket) and call either the client or the server callback (one or /// the other should be 0) /// \note Was used for depreciated IO completion ports. bool AssociateSocketWithCompletionPortAndRead( SOCKET readSocket, unsigned int binaryAddress, unsigned short port, RakPeer* rakPeer ); /// Write \a data of length \a length to \a writeSocket /// \param[in] writeSocket The socket to write to /// \param[in] data The data to write /// \param[in] length The length of \a data void Write( const SOCKET writeSocket, const char* data, const int length ); /// Read data from a socket /// \param[in] s the socket /// \param[in] rakPeer The instance of rakPeer containing the recvFrom C callback /// \param[in] errorCode An error code if an error occured . /// \param[in] connectionSocketIndex Which of the sockets in RakPeer we are using /// \return Returns true if you successfully read data, false on error. int RecvFrom( const SOCKET s, RakPeer *rakPeer, int *errorCode, unsigned connectionSocketIndex ); #if !defined(_XBOX360) /// Retrieve all local IP address in a string format. /// \param[in] s The socket whose port we are referring to /// \param[in] ipList An array of ip address in dotted notation. void GetMyIP( char ipList[ 10 ][ 16 ] ); #endif /// Call sendto (UDP obviously) /// \param[in] s the socket /// \param[in] data The byte buffer to send /// \param[in] length The length of the \a data in bytes /// \param[in] ip The address of the remote host in dotted notation. /// \param[in] port The port number to send to. /// \return 0 on success, nonzero on failure. int SendTo( SOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port ); /// Call sendto (UDP obviously) /// It won't reach the recipient, except on a LAN /// However, this is good for opening routers / firewalls /// \param[in] s the socket /// \param[in] data The byte buffer to send /// \param[in] length The length of the \a data in bytes /// \param[in] ip The address of the remote host in dotted notation. /// \param[in] port The port number to send to. /// \param[in] ttl Max hops of datagram /// \return 0 on success, nonzero on failure. int SendToTTL( SOCKET s, const char *data, int length, const char ip[ 16 ], unsigned short port, int ttl ); /// Call sendto (UDP obviously) /// \param[in] s the socket /// \param[in] data The byte buffer to send /// \param[in] length The length of the \a data in bytes /// \param[in] binaryAddress The address of the remote host in binary format. /// \param[in] port The port number to send to. /// \return 0 on success, nonzero on failure. int SendTo( SOCKET s, const char *data, int length, unsigned int binaryAddress, unsigned short port ); /// Returns the local port, useful when passing 0 as the startup port. /// \param[in] s The socket whose port we are referring to /// \return The local port unsigned short GetLocalPort ( SOCKET s ); private: static bool socketLayerStarted; #ifdef _WIN32 static WSADATA winsockInfo; #endif static SocketLayer I; }; #endif
Miclebrick/Imagination-Server
RakNet/Headers/SocketLayer.h
C
mit
6,024
{%= author.name %}
lucasconstantino/gulp-verb
test/fixtures/README.tmpl.md
Markdown
mit
19
<div class="comment-view mb-6"> {% if not comment_list %} <div class="no-comment"> <p class="text-muted small">{{ _("No comments yet. ") }} <span class="hidden login-required"> <a href="/login?redirect-to={{ pathname }}">{{ _("Login to start a new discussion") }}</a> </span> <span class="hidden start-discussion">{{ _("Start a new discussion") }}</span> </p> </div> {% endif %} {% if not is_communication %} <div class="add-comment-section mb-5"> <div class="comment-form-wrapper"> <div id="comment-form"> <form class="new-comment"> <fieldset class="new-comment-fields"> <div class="user-details row" style="margin-bottom: 15px; display:none;"> <div class="comment-by col-sm-6 pb-4"> <div class="form-label mb-1">{{ _("Your Name") }}</div> <input class="form-control comment_by" name="comment_by" type="text"> </div> <div class="col-sm-6"> <div class="form-label mb-1">{{ _("Email") }}</div> <input class="form-control comment_email" name="comment_email" type="email"> </div> </div> <div class="comment-text-area"> <div class="form-label mb-1">{{ _("Add a comment") }}</div> <textarea class="form-control" name="comment" rows=5 ></textarea> <div class="text-muted small mt-1 mb-4">{{ _("Ctrl+Enter to add comment") }}</div> </div> <button class="btn btn-sm small" id="submit-comment">{{ _("Comment") }}</button> </fieldset> </form> </div> </div> </div> {% endif %} <hr class="add-comment-hr my-5"> <div itemscope itemtype="http://schema.org/UserComments" id="comment-list"> <div class="add-comment mb-5"> <div class="timeline-dot"></div> <button class="btn btn-sm small add-comment-button">{{ _("Add a comment") }}</button> </div> <div class="comment-list"> {% for comment in comment_list %} {% include "templates/includes/comments/comment.html" %} {% endfor %} </div> </div> </div> <script> frappe.ready(function() { let guest_allowed = parseInt("{{ guest_allowed or 0}}"); let comment_count = "{{ comment_text }}"; let full_name = "" let user_id = ""; let update_timeline_line_length = function(direction, size) { if (direction == 'top') { $('.blog-container')[0].style.setProperty('--comment-timeline-top', size); } else { let comment_timeline_bottom = $('.comment-list .comment-row:last-child').height() - 10; $('.blog-container')[0].style.setProperty('--comment-timeline-bottom', comment_timeline_bottom +'px'); } } let show_comment_box = function() { $('.comment-form-wrapper').show(); update_timeline_line_length('top', '-20px'); $('.add-comment-hr').hide(); $('.add-comment').hide(); } let hide_comment_box = function() { $('.comment-form-wrapper').hide(); update_timeline_line_length('top', '8px'); update_timeline_line_length('bottom'); $('.add-comment-hr').show(); $('.add-comment').show(); } let $comment_count = $(` <div class="feedback-item"> <span class="comment-icon">${frappe.utils.icon('small-message', 'md')}</span> <span class="comment-count"></span> </div> `); $('form').keydown(function(event) { if (event.ctrlKey && event.keyCode === 13) { $(this).find('#submit-comment').trigger('click'); } }) if (!frappe.is_user_logged_in()) { $(".user-details").toggle('hide'); if (guest_allowed) { $('.start-discussion').removeClass('hidden'); } else { $(".login-required, .comment-form-wrapper").toggleClass("hidden"); $('.add-comment-button').text('{{ _("Login to comment") }}'); $('.add-comment-button').click(() => { window.location.href = '/login?redirect-to={{ pathname }}'; }); } } else { $('input.comment_by').prop("disabled", true); $('input.comment_email').prop("disabled", true); full_name = frappe.get_cookie("full_name"); user_id = frappe.get_cookie("user_id"); if(user_id != "Guest") { $("[name='comment_email']").val(user_id); $("[name='comment_by']").val(full_name); } $('.start-discussion').removeClass('hidden'); } $('.blog-feedback').append($comment_count); $('.comment-count').text(comment_count); $("#comment-form textarea").val(""); update_timeline_line_length('bottom'); let n_comments = $(".comment-row").length; n_comments ? $(".no_comment").toggle(false) : show_comment_box(); if(n_comments > 50) { $(".add-comment").toggle(false) .parent().append("<div class='text-muted'>Comments are closed.</div>") } $('.add-comment-button').click(() => { show_comment_box(); }); $("#submit-comment").click(function() { var args = { comment_by: $("[name='comment_by']").val(), comment_email: $("[name='comment_email']").val(), comment: $("[name='comment']").val(), reference_doctype: "{{ reference_doctype or doctype }}", reference_name: "{{ reference_name or name }}", comment_type: "Comment", route: "{{ pathname }}", } if(!args.comment_by || !args.comment_email || !args.comment) { frappe.msgprint('{{ _("All fields are necessary to submit the comment.") }}'); return false; } if (args.comment_email!=='Administrator' && !validate_email(args.comment_email)) { frappe.msgprint('{{ _("Please enter a valid email address.") }}'); return false; } if(!args.comment || !args.comment.trim()) { frappe.msgprint('{{ _("Please add a valid comment.") }}'); return false; } frappe.call({ btn: this, type: "POST", method: "frappe.templates.includes.comments.comments.add_comment", args: args, callback: function(r) { if(r.exc) { if(r._server_messages) frappe.msgprint(r._server_messages); } else { if (r.message) { $(r.message).prependTo(".comment-list"); comment_count = cint(comment_count) + 1; $('.comment-count').text(comment_count); } $(".no-comment").toggle(false); $("#comment-form textarea").val(""); hide_comment_box(); } } }) return false; }); }); </script>
frappe/frappe
frappe/templates/includes/comments/comments.html
HTML
mit
6,128
// // RHCoreDataTableViewController.h // // Copyright (C) 2013 by Christopher Meyer // http://schwiiz.org/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <CoreData/CoreData.h> @import UIKit; @interface RHCoreDataTableViewController : UITableViewController<NSFetchedResultsControllerDelegate, UISearchDisplayDelegate, UISearchBarDelegate> { NSFetchedResultsController *fetchedResultsController; } @property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController; @property (nonatomic, strong) UISearchDisplayController *searchController; @property (nonatomic, strong) NSString *searchString; @property (nonatomic, assign) BOOL massUpdate; @property (nonatomic, assign) BOOL enableSectionIndex; -(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath; -(void)addSearchBarWithPlaceHolder:(NSString *)placeholder; // -(void)removeSearchBar; -(void)resetMassUpdate; -(void)refreshVisibleCells; -(UITableView *)currentTableView; @end
appy-tw/1129ios
ios/model/RHManagedObject/RHCoreDataTableViewController.h
C
mit
2,031
// Copyright 2016 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package gitutil import ( "html/template" "testing" dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" "github.com/gogs/git-module" ) func Test_diffsToHTML(t *testing.T) { tests := []struct { diffs []dmp.Diff lineType git.DiffLineType expHTML template.HTML }{ { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffInsert, Text: "bar"}, {Type: dmp.DiffDelete, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineAdd, expHTML: template.HTML(`+foo <span class="added-code">bar</span> biz`), }, { diffs: []dmp.Diff{ {Type: dmp.DiffEqual, Text: "foo "}, {Type: dmp.DiffDelete, Text: "bar"}, {Type: dmp.DiffInsert, Text: " baz"}, {Type: dmp.DiffEqual, Text: " biz"}, }, lineType: git.DiffLineDelete, expHTML: template.HTML(`-foo <span class="removed-code">bar</span> biz`), }, } for _, test := range tests { t.Run("", func(t *testing.T) { assert.Equal(t, test.expHTML, diffsToHTML(test.diffs, test.lineType)) }) } }
gogits/gogs
internal/gitutil/diff_test.go
GO
mit
1,244
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/ReactiveObjC/ReactiveObjC.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/ReactiveObjC/ReactiveObjC.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
lionsom/LXReactiveCocoa_Demo
RAC_GatherClass/Pods/Target Support Files/Pods-RAC_GatherClass/Pods-RAC_GatherClass-frameworks.sh
Shell
mit
3,723
<?php include 'Vehicle.php'; include 'Car.php'; $car = new Car(4, 'Red', 'Audi', 'A4', 2016); print_r($car); echo "<br>"; $car->setColor('Green'); print_r($car);
stoyantodorovbg/PHP-Web-Development-Basics
Lab OOP Encapsulation and Inheritance/problem6/index.php
PHP
mit
166
--- title: لمزيد من الدرس date: 25/06/2021 --- لِمَزِيد مِنْ الدَّرس: حول التطهير الأخير للأرض من الْخَطِيَّة اقرأ من كتاب الصراع العظيم صفحة ٧١٥-٧٣٢. «وإذ تمر سنو الأبدية فستأتي بإعلانات أغنى وأمجد عن الله والمسيح. وكما تتجدّد المعرفة فكذلك ستتجدّد المحبة والوقار والسعادة وتزيد أَيْضًا. وكلما عرف الناس أشياء أكثر عن الله زاد إعجابهم بصفاته. وإذ يكشف يسوع أَمَامهم غنى الفداء والأعمال العظيمة المدهشة في الصراع الهائل مع الشيطان فإن قلوب المفتدين تختلج بتعبّد حار عميق، وبفرح مذهل للعقل يضربون على قيثاراتهم الذهبية فتتحد ربوات ربوات وألوف ألوف من الأصوات في إنشاد أغنية الحمد العظيمة. « ‹وَكُلُّ خَلِيقَةٍ مِمَّا فِي السَّمَاءِ وَعَلَى الأَرْض وَتَحْتَ الأَرْض، وَمَا عَلَى الْبَحْرِ، كُلُّ مَا فِيهَا، سَمِعْتُهَا قَائِلَةً: لِلْجَالِسِ عَلَى الْعَرْشِ وَلِلْخَرُوفِ الْبَرَكَةُ وَالْكَرَامَةُ وَالْمَجْدُ وَالسُّلْطَانُ إلى الأبدين.› (رؤيا ٥: ١٣). «لقد انتهى الصّراع العظيم. وما عاد للخطيئة أو للخطاة وجود. وقد صارت المسكونة كلها طاهرة. وفي عاطفة واحدة مِن الوفاق والفرح يشترك كل الخلائق. ومَن ذاك الذي قد خَلق الجميع تفيض الحياة والنور والبهجة في كل الأقاليم في الفضاء الذي لا حدود له. فمن أصغر ذرة إلى أعظم كوكب، مِن حي إلى جماد، بجمالها وكمالها – كلّها تشهد شهادة واحدة قائلة: الله محبة» (روح النُّبُوَّة، الصراع العظيم، صفحة ٧٣٢). **أسئلة للنقاش** `١. قال الكاتب فرانسيسكو غوزي مورينو، «إننا نرى ذواتنا في ضوء ومنظور الكون ذات النظام المتناغم، فندرك جهلنا وعجزنا النهائي، وبالتالي شعورنا بعدم الأمان. ونتيجة لذلك نخاف» [بين الإيمان العقل: الخوف الأساسي والحالة الإنسانية، (مطبعة نيويورك هاربر، ١٩٧٧، صفحة ٦]. قارن هذه العبارة مع ما درسته هذا الأسبوع من أفسس ٣: ١٧-١٩. ناقش الاختلافات بين العبارتين.` `٢. يَعِدنَا الله بالفرح كمؤمنين بالمسيح. هل الفرح هو ذاته مثل السعادة؟ وهل يتوجَّب علينا أنْ نكون دائمًا فرحين؟ وإذا لم يكن الأمر كذلك، فهل يوجد شيء ما ليس على ما يرام في اختبارنا المسيحي؟ ماذا يمكن لحياة المسيح أن تُظهِره لنا ممَّا يساعدنا على فهم الأجوبة لهذه الأسئلة؟` `٣. ناقش وتعمّق أكثر في فكرة كوننا ممتلئين «إِلَى كُلِّ مِلْءِ اللهِ» (أفسس ٣: ١٩). ماذا يعني ذلك؟ وكيف لنا أن نختبر ذلك في حياتنا؟` **مُلَخَّص الدَّرس**: ليس العَهْد مجرد أفكار لاهوتية عميقة، بل هو بالأحرى يُعَرِّف عُمق علاقتنا الخلاصية مع المسيح، وتلك العلاقة تنيلنا حصادًا وفيرًا من الفوائد العجيبة الآن، وبخاصة في وقت عودة المسيح.
imasaru/sabbath-school-lessons
src/ar/2021-02/13/07.md
Markdown
mit
4,006
<script type="text/javascript"> var _d = DialogManager.get('config_dialog'); _d.setWidth(350); _d.setPosition('center'); $("select[ectype='bgcolor_selector']").change(function(){ $("input[ectype='bgcolor']").val(this.value); }); $("select[name='img_recom_id']").change(function(){ switchRecommend(this.value, 'img_cate_id'); }); $("select[name='txt_recom_id']").change(function(){ switchRecommend(this.value, 'txt_cate_id'); }); switchRecommend($("select[name='img_recom_id']").val(), 'img_cate_id'); switchRecommend($("select[name='txt_recom_id']").val(), 'txt_cate_id'); function switchRecommend(recomId, selectName) { if (recomId >= 0) { $("select[name='" + selectName + "']").hide(); } else { $("select[name='" + selectName + "']").show(); } } </script> <div class="field_item"> <label>模块名称:</label> <p><input type="text" name="module_name" value="{$options.module_name}" /></p> </div> <div class="field_item"> <label>背景色:(<span>格式:#332211</span>)</label> <p><input type="text" name="bgcolor" ectype="bgcolor" value="{$options.bgcolor}" /> <select ectype="bgcolor_selector" style="width:100px"> <option value="">请选择...</option> <option value="#bbc5d6" style="background:#bbc5d6"></option> <option value="#a7d8c8" style="background:#a7d8c8"></option> <option value="#a3c9ee" style="background:#a3c9ee"></option> <option value="#9fd9dd" style="background:#9fd9dd"></option> <option value="#b9afd4" style="background:#b9afd4"></option> <option value="#dcad7f" style="background:#dcad7f"></option> <option value="#c4d568" style="background:#c4d568"></option> <option value="#dcc972" style="background:#dcc972"></option> <option value="#e8b5e5" style="background:#e8b5e5"></option> <option value="#ecb8bc" style="background:#ecb8bc"></option> </select></p> </div> <div class="field_item"> <label>热门关键字:(<span>多个关键字之间用空格隔开</span>)</label> <p><input type="text" name="keyword_list" value="{$options.keyword_list}" /></p> </div> <div class="field_item"> <label>上传广告图片:(<span>图片尺寸:210*280,支持 gif|jpg|jpeg|png 格式</span>)</label> <p><input type="file" name="ad_image_file" /><input type="hidden" name="ad_image_url" value="{$options.ad_image_url}" /></p> <!-- {if $options.ad_image_url} --><p><img src="{$options.ad_image_url}" height="20" /></p><!-- {/if} --> </div> <div class="field_item"> <label>广告链接地址:</label> <p><input type="text" name="ad_link_url" value="{$options.ad_link_url}" /></p> </div> <div class="field_item"> <label>图片推荐类型:</label> <p><select name="img_recom_id"> <option value="0">请选择...</option> <!-- {foreach from=$recommends key=recom_id item=recom_name} --> <option value="{$recom_id}"{if $options.img_recom_id eq $recom_id} selected="selected"{/if}>{$recom_name|escape}</option> <!-- {/foreach} --> </select> <select name="img_cate_id"> <option value="0">请选择分类...</option> <!-- {html_options options=$gcategories selected=$options.img_cate_id} --> </select></p> </div> <div class="field_item"> <label>文字推荐类型:</label> <p><select name="txt_recom_id"> <option value="0">请选择...</option> <!-- {foreach from=$recommends key=recom_id item=recom_name} --> <option value="{$recom_id}"{if $options.txt_recom_id eq $recom_id} selected="selected"{/if}>{$recom_name|escape}</option> <!-- {/foreach} --> </select> <select name="txt_cate_id"> <option value="0">请选择分类...</option> <!-- {html_options options=$gcategories selected=$options.txt_cate_id} --> </select></p> </div>
lotosbin/ecmall-docker-compose
upload/external/widgets/goods_module_1/config.html
HTML
mit
4,008
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!-- NewPage --> <html lang="sv"> <head> <!-- Generated by javadoc on Fri Mar 18 12:42:22 CET 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>IV1201 1.0-SNAPSHOT API</title> <script type="text/javascript"> targetPage = "" + window.location.search; if (targetPage != "" && targetPage != "undefined") targetPage = targetPage.substring(1); if (targetPage.indexOf(":") != -1 || (targetPage != "" && !validURL(targetPage))) targetPage = "undefined"; function validURL(url) { try { url = decodeURIComponent(url); } catch (error) { return false; } var pos = url.indexOf(".html"); if (pos == -1 || pos != url.length - 5) return false; var allowNumber = false; var allowSep = false; var seenDot = false; for (var i = 0; i < url.length - 5; i++) { var ch = url.charAt(i); if ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '$' || ch == '_' || ch.charCodeAt(0) > 127) { allowNumber = true; allowSep = true; } else if ('0' <= ch && ch <= '9' || ch == '-') { if (!allowNumber) return false; } else if (ch == '/' || ch == '.') { if (!allowSep) return false; allowNumber = false; allowSep = false; if (ch == '.') seenDot = true; if (ch == '/' && seenDot) return false; } else { return false; } } return true; } function loadFrames() { if (targetPage != "" && targetPage != "undefined") top.classFrame.location = top.targetPage; } </script> </head> <frameset cols="20%,80%" title="Documentation frame" onload="top.loadFrames()"> <frameset rows="30%,70%" title="Left frames" onload="top.loadFrames()"> <frame src="overview-frame.html" name="packageListFrame" title="All Packages"> <frame src="allclasses-frame.html" name="packageFrame" title="All classes and interfaces (except non-static nested types)"> </frameset> <frame src="overview-summary.html" name="classFrame" title="Package, class and interface descriptions" scrolling="yes"> <noframes> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <h2>Frame Alert</h2> <p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="overview-summary.html">Non-frame version</a>.</p> </noframes> </frameset> </html>
Limmen/IV1201
target/site/apidocs/index.html
HTML
mit
2,909
# meteor-intro Intro to Meteor
BenDiuguid/meteor-intro
README.md
Markdown
mit
31