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
Template.postSubmit.onCreated(function() { Session.set('postSubmitErrors', {}); }); Template.postSubmit.helpers({ errorMessage: function(field) { return Session.get('postSubmitErrors')[field]; }, errorClass: function (field) { return !!Session.get('postSubmitErrors')[field] ? 'has-error' : ''; } }); Template.postSubmit.onRendered(function(){ // AutoForm.hooks({ // postSubmitForm: hooksObject // }); }); // Template.postSubmit.events({ // 'submit form': function(e) { // e.preventDefault(); // var post = { // url: $(e.target).find('[name=url]').val(), // title: $(e.target).find('[name=title]').val() // }; // var errors = validatePost(post); // if (errors.title || errors.url) // return Session.set('postSubmitErrors', errors); // Meteor.call('postInsert', post, function(error, result) { // // display the error to the user and abort // if (error) // return throwError(error.reason); // // show this result but route anyway // if (result.postExists) // throwError('This link has already been posted'); // Router.go('postPage', {_id: result._id}); // }); // } // });
fuzzybabybunny/microscope-orionjs
client/templates/posts/post_submit.js
JavaScript
mit
1,228
<?php // Text $_['text_sizechart'] = 'Größentabelle';
trydalcoholic/opencart-materialize
source/opencart_3.0.x/upload/catalog/language/de-de/extension/module/sizechart.php
PHP
mit
56
package ru.mephi.interpreter; import org.antlr.v4.runtime.tree.ParseTree; import java.math.BigInteger; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Anton_Chkadua */ public class Scope { static Scope GLOBAL = new Scope(null); private Scope parent; private Map<BigInteger, Variable> variables = new HashMap<>(); private Map<Function, ParseTree> functions = new HashMap<>(); private BigInteger memoryCounter = BigInteger.ZERO; Scope(Scope parent) { this.parent = parent; if (parent != null) { memoryCounter = parent.getMemoryCounter(); } } private BigInteger getMemoryCounter() { return memoryCounter; } void add(Variable variable) throws RuntimeLangException { if (variables.values().contains(variable)) { throw new RuntimeLangException(RuntimeLangException.Type.DUPLICATE_IDENTIFIER); } if (variable instanceof Array) { ((Array) variable).setScope(this); for (int i = 0; i < ((Array) variable).memoryLength; i++) { variables.put(memoryCounter, variable); memoryCounter = memoryCounter.add(BigInteger.ONE); } } else { variables.put(memoryCounter, variable); memoryCounter = memoryCounter.add(BigInteger.ONE); } } public void remove(String name) throws RuntimeLangException { Variable toBeRemoved = get(name); BigInteger address = variables.keySet().stream().filter(key -> variables.get(key).equals(toBeRemoved)).findFirst().orElseThrow(() -> new RuntimeLangException( RuntimeLangException.Type.NO_SUCH_VARIABLE)); variables.remove(address); } Scope getParent() { return parent; } Variable get(String name) throws RuntimeLangException { Variable candidate = variables.values().stream().filter(variable -> variable.getName().equals(name)).findAny() .orElse(null); if (candidate == null) { if (parent != null) { candidate = parent.get(name); } else { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_VARIABLE); } } return candidate; } Variable getByAddress(Pointer pointer) throws RuntimeLangException { Variable variable = variables.get(pointer.getValue()); System.out.println(variable); if (variable instanceof Array) { int address = getVariableAddress(variable).intValue(); int index = pointer.getValue().intValue() - address; return variable.getElement(index); } else { return variable; } } void setValueByAddress(Pointer pointer, BigInteger value) throws RuntimeLangException { if (pointer.constantValue) throw new RuntimeLangException(RuntimeLangException.Type.ILLEGAL_MODIFICATION); variables.get(pointer.getValue()).setValue(value); } BigInteger getVariableAddress(Variable variable) throws RuntimeLangException { if (!variables.values().contains(variable)) { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_VARIABLE); } for (Map.Entry<BigInteger, Variable> entry : variables.entrySet()) { if (entry.getValue().name.equals(variable.name)) return entry.getKey(); } return null; } void addFunction(Function function, ParseTree functionTree) throws RuntimeLangException { if (functions.containsKey(function)) { throw new RuntimeLangException(RuntimeLangException.Type.DUPLICATE_IDENTIFIER); } functions.put(function, functionTree); } ParseTree getFunctionTree(String name, List<Class> types) throws RuntimeLangException { ParseTree tree = functions.get(getFunction(name, types)); if (tree == null) { if (parent != null) { tree = parent.getFunctionTree(name, types); } else { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } } return tree; } Function getFunction(String name, List<Class> types) throws RuntimeLangException { Map.Entry<Function, ParseTree> entryCandidate = functions.entrySet().stream().filter(entry -> entry.getKey().name.equals(name)).findAny() .orElse(null); Function candidate = null; if (entryCandidate == null) { if (parent != null) { candidate = parent.getFunction(name, types); } } else { candidate = entryCandidate.getKey(); } if (candidate == null) { if (name.equals("main")) { throw new RuntimeLangException(RuntimeLangException.Type.NO_MAIN_FUNCTION); } else { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } } if (candidate.args.size() != types.size()) { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } for (int i = 0; i < candidate.args.size(); i++) { if (!candidate.args.get(i).getType().equals(types.get(i))) { throw new RuntimeLangException(RuntimeLangException.Type.NO_SUCH_FUNCTION); } } return candidate; } @Override public String toString() { String parent = this.parent != null ? this.parent.toString() : ""; StringBuilder builder = new StringBuilder(); for (Variable variable : variables.values()) { builder.append(variable.getName()).append("-").append(variable.getType()).append("-length-") .append(variable.getLength()); try { builder.append("-value-").append(variable.getValue()).append('-').append(variable.constantValue) .append("\r\n"); } catch (RuntimeLangException e) { System.out.println(e.getType()); } } return builder.insert(0, parent).toString(); } }
AVChkadua/interpreter
src/ru/mephi/interpreter/Scope.java
Java
mit
6,273
# ServiceInfo.TryExcludeTag method Attempts to exclude a tag from service. ```csharp public bool TryExcludeTag(string tagName, out ServiceInfo service, out IReadOnlyList<ServiceDefinitionError> errors) ``` ## See Also * class [ServiceDefinitionError](../ServiceDefinitionError.md) * class [ServiceInfo](../ServiceInfo.md) * namespace [Facility.Definition](../../Facility.Definition.md) <!-- DO NOT EDIT: generated by xmldocmd for Facility.Definition.dll -->
FacilityApi/Facility
docs/Facility.Definition/ServiceInfo/TryExcludeTag.md
Markdown
mit
471
<?php return array ( 'id' => 'sec_e900_ver1_sub10', 'fallback' => 'sec_e900_ver1', 'capabilities' => array ( 'accept_third_party_cookie' => 'false', 'j2me_max_jar_size' => '700000', 'ajax_support_getelementbyid' => 'true', 'ajax_support_events' => 'true', ), );
cuckata23/wurfl-data
data/sec_e900_ver1_sub10.php
PHP
mit
289
<?php return array ( 'id' => 'dell_streak_7_ver1_suban32', 'fallback' => 'dell_streak_7_ver1', 'capabilities' => array ( 'device_os_version' => '3.2', ), );
cuckata23/wurfl-data
data/dell_streak_7_ver1_suban32.php
PHP
mit
172
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="author" content="Open Knowledge"> <meta name="description" content="The Global Open Data Index assesses the state of open government data around the world. "> <meta name="keywords" content="Open Government, Open Data, Government Transparency, Open Knowledge "> <meta property="og:type" content="website"/> <meta property="og:title" content="Open Data Index - Open Knowledge"/> <meta property="og:site_name" content="Open Data Index"/> <meta property="og:description" content="The Global Open Data Index assesses the state of open government data around the world."/> <meta property="og:image" content="/static/images/favicon.ico"/> <title>Ghana / Health performance (2013) | Global Open Data Index by Open Knowledge</title> <base href="/"> <!--[if lt IE 9]> <script src="/static/vendor/html5shiv.min.js"></script> <![endif]--> <link rel="stylesheet" href="/static/css/site.css"> <link rel="icon" href="/static/images/favicon.ico"> <script> var siteUrl = ''; </script> </head> <body class="na"> <div class="fixed-ok-panel"> <div id="ok-panel" class="closed"> <iframe src="http://assets.okfn.org/themes/okfn/okf-panel.html" scrolling="no"></iframe> </div> <a class="ok-ribbon"><img src="http://okfnlabs.org/ok-panel/assets/images/ok-ribbon.png" alt="Open Knowledge"></a> </div> <header id="header"> <nav class="navbar navbar-default" role="navigation"> <div class="container"> <div> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="logo"> <a href="/"> <img src="/static/images/logo2.png"> <span>Global<br/>Open Data Index</span> </a> </div> </div> <div class="collapse navbar-collapse" id="navbar-collapse"> <ul class="nav navbar-nav" style="margin-right: 132px;"> <li> <a href="/place/" title="About the Open Data Index project"> Places </a> </li> <li> <a href="/dataset/" title="About the Open Data Index project"> Datasets </a> </li> <li> <a href="/download/" title="Download Open Data Index data"> Download </a> </li> <li> <a href="/insights/" title="Insights"> Insights </a> </li> <li> <a href="/methodology/" title="The methodology behind the Open Data Index"> Methodology </a> </li> <li> <a href="/about/" title="About the Open Data Index project"> About </a> </li> <li> <a href="/press/" title="Press information for the Open Data Index"> Press </a> </li> </ul> </div> </div> </div> </nav> </header> <div class="container"> <div class="content"> <div class="row"> <div class="col-md-12"> <ol class="breadcrumb"> <li> <a href="/">Home</a> </li> <li class="active">Ghana / Health performance (2013)</li> </ol> <header class="page-header"> <h1>Ghana / Health performance (2013)</h1> </header> <h3>Sorry</h3> <p> There is no data available for Ghana / Health performance (2013) in the Index. </p> </div> </div> </div> </div> <footer id="footer"> <div class="container"> <div class="row"> <div class="footer-main col-md-8"> <div class="footer-attribution"> <p> <a href="http://opendefinition.org/ossd/" title="Open Online Software Service"> <img src="http://assets.okfn.org/images/ok_buttons/os_80x15_orange_grey.png" alt="" border=""/> </a> <a href="http://opendefinition.org/okd/" title="Open Online Software Service"> <img src="http://assets.okfn.org/images/ok_buttons/od_80x15_blue.png" alt="" border=""/> </a> <a href="http://opendefinition.org/okd/" title="Open Content"> <img src="http://assets.okfn.org/images/ok_buttons/oc_80x15_blue.png" alt="" border=""/> </a> &ndash; <a href="http://creativecommons.org/licenses/by/3.0/" title="Content Licensed under a CC Attribution"></a> <a href="http://opendatacommons.org/licenses/pddl/1.0" title="Data License (Public Domain)">Data License (Public Domain)</a> </p> </div> <div class="footer-meta"> <p> This service is run by <a href="https://okfn.org/" title="Open Knowledge">Open Knowledge</a> </p> <a class="naked" href="http://okfn.org/" title="Open Knowledge"><img src="http://assets.okfn.org/p/okfn/img/okfn-logo-landscape-black-s.png" alt="" height="28"></a> </div> </div> <div class="footer-links col-md-2"> <li><a href="http://okfn.org/" title="Open Knowledge">Open Knowledge</a></li> <li><a href="http://okfn.org/opendata/" title="What is Open Data?">What is Open Data?</a></li> <li><a href="http://census.okfn.org/" title="Run your own Index">Run your own Index</a></li> <li><a href="https://github.com/okfn/opendataindex" title="The source code for Open Data Index">Source Code</a></li> </div> <div class="footer-links col-md-2"> <li><a href="/" title="Open Data Index home">Home</a></li> <li><a href="/download/" title="Download data">Download</a></li> <li><a href="/methodology/" title="The methodology behind the Open Data Index">Methodology</a></li> <li><a href="/faq/" title=" Open Data Index FAQ">FAQ</a></li> <li><a href="/about/" title="About the Open Data Index">About</a></li> <li><a href="/about/" title="Contact us">Contact</a></li> <li><a href="/press/" title="Press">Press</a></li> </div> </div> </div> </footer> <script data-main="/static/scripts/site" src="/static/scripts/require.js"></script> </body> </html>
okfn/opendataindex-2015
place/ghana/health/2013/index.html
HTML
mit
8,142
#include <cstring> #include <iostream> #include <algorithm> #include "matcher.h" #include "edit.h" #include "char.h" #include "instrumentation.h" #define INIT_POS -1 #define __DEBUG__ false // the node represented by a given point #define node(p) (distances[(p)->j][(p)->i]) // the edit distance at a given point, from the distance matrix #define dist(p) (node(p).distance) using namespace std; // simply reverses a string in place void strrev(char *str, int len) { for(int i = 0; i < len / 2; i++) { std::swap(str[i], str[len - i - 1]); } } // empty constructor EditTable::EditTable() { } // destructor EditTable::~EditTable() { // free the rows of the table free_rows(); // free the table itself delete[] distances; // get rid of the best match if(best_match != NULL) { delete best_match; } } // compares the 3 given points based on their given distances, and // returns the point with the lowest distance Point *min3(Point *p1, int d1, Point *p2, int d2, Point *p3, int d3) { if(d1 < d2) { return d1 < d3 ? p1 : p3; } else { return d2 < d3 ? p2 : p3; } } // get the point surrounding (j,i) with the minimum distance Point *EditTable::min_neighbour(int j, int i) { // the only valid surrounding for the top-corner is (0,0) if(j == 1 && i == 1) { return new Point(0, 0); // if we're in the top row, we can't go up any higher } else if(j == 1) { return new Point(j, i - 1); // if we're in the leftmost column, we CAN go more left // (since it just means we're starting the match from there) } else if(i == 1) { return new Point(j, 0); // otherwise, } else { // 3 comparisons here inc_comparisons(3); return min3( // just above it new Point(j - 1, i), distances[j - 1][i].distance, // just to its left new Point(j, i - 1), distances[j][i - 1].distance, // top-left corner new Point(j - 1, i - 1), distances[j - 1][i - 1].distance + // add 1 if we need a replacement (text[j - 1] == query->query_str[i - 1] ? 0 : 1) ); } } // j is the index into the text, // i is the index into the query // assuming j != 0 and i != 0 int EditTable::set_distance(int j, int i) { Node &node = distances[j][i]; // get the valid neighbour with the minimum edit distance node.from = min_neighbour(j, i); node.distance = dist(node.from); // if the two characters at this node are different, if( query->query_str[i - 1] != text[j - 1] ) { // add 1 to the edit distance (replacement) node.distance++; } // return the edit distance of this node return node.distance; } // dump the whole table void EditTable::dump() { // print the query characters cerr << '\t'; for(int i = 0; i < query->query_len; i++) { cerr << '\t'; pc(cerr, query->query_str[i]); } cerr << endl; for(int j = 0; j <= text_len; j++) { for(int i = 0; i <= query->query_len; i++) { // print the text characters if(i == 0 && j != 0) { pc(cerr, text[j - 1]); } cerr << '\t'; // print the actual distance cerr << distances[j][i].distance; } cerr << endl; } } // traceback the best match SearchResult *EditTable::get_match() { SearchResult *result; // if there is no match, return an empty search result if(best_match->j == INIT_POS) { return new SearchResult(0); } // if the match has too high a distance, return an empty search result if(dist(best_match) > query->errors_allowed) { return new SearchResult(0); } // allocate memory for the result result = new SearchResult(query->query_len + query->errors_allowed); // the easy stuff first result->errors = dist(best_match); result->match_len = 0; // start off at the node with the best match Point *current = best_match; while(current != NULL) { // add the next char to the result result->match[result->match_len++] = text[current->j - 1]; // advance to the next node current = node(current).from; } // we don't really want to include the \0 char result->match_len--; // reverse the string in place strrev(result->match, result->match_len); /*// print the result if(__DEBUG__) { pc(cerr, result->match, result->match_len); cerr << endl; }*/ return result; } void EditTable::free_rows() { // free the rows of the table for(int j = 0; j <= text_len; j++) { if(query != NULL) { delete[] distances[j]; } } } void EditTable::fill_table() { // there are going to be the same amount of creates/accesses here inc_comparisons((text_len + 1) * (query->query_len + 1)); inc_ds((text_len + 1) * (query->query_len + 1)); // reset the best match best_match = new Point(INIT_POS, INIT_POS); // the first row and column have a distance 0 for(int j = 0; j <= text_len; j++) { // allocate memory for each row distances[j] = new Node[text_len + 1]; // set the first column to 0 distances[j][0].distance = 0; } for(int i = 0; i <= query->query_len; i++) { // set the first row to 0 distances[0][i].distance = 0; } // first go through the text (rows) for(int j = 1; j <= text_len; j++) { // then go through the query (columns) for(int i = 1; i <= query->query_len; i++) { // work out the edit distance set_distance(j, i); // if we're in the last column (the end of the query string), // [remember matches only happen at the end of the query string] if(i == query->query_len) { // if this is the first time we get to the end of the query, // or if it's got a lower edit distance than the current // best match, if( best_match->j == INIT_POS || distances[j][i].distance < dist(best_match) ) { // then update the best match to be this point best_match->j = j; best_match->i = i; } } } } } SearchResult *EditTable::execute_query(SearchQuery *query) { SearchResult *result; // save the query this->query = query; // fill the table this->fill_table(); // dump it if(__DEBUG__) { this->dump(); } // get the best match result = get_match(); // finally, return the match return result; } void EditTable::load_text(char *text, int len) { // save these values this->text = new char[len]; strncpy(this->text, text, len); this->text_len = len; // build an empty array this->distances = new Node *[text_len + 1]; } // used by main which doesn't know about the EditTable Matcher *create_matcher() { return new EditTable(); }
pmansour/algorithms
string-matching/edittable-and-tries/edit.cpp
C++
mit
6,604
/*! * # Semantic UI 2.1.6 - Message * http://github.com/semantic-org/semantic-ui/ * * * Copyright 2015 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ /******************************* Message *******************************/ .ui.message { position: relative; min-height: 1em; margin: 1em 0em; background: #F8F8F9; padding: 1em 1.5em; line-height: 1.4285em; color: rgba(0, 0, 0, 0.87); -webkit-transition: opacity 0.1s ease, color 0.1s ease, background 0.1s ease, box-shadow 0.1s ease; transition: opacity 0.1s ease, color 0.1s ease, background 0.1s ease, box-shadow 0.1s ease; border-radius: 0.30769em; box-shadow: 0px 0px 0px 1px rgba(34, 36, 38, 0.22) inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.message:first-child { margin-top: 0em; } .ui.message:last-child { margin-bottom: 0em; } /*-------------- Content ---------------*/ /* Header */ .ui.message .header { display: block; font-family: 'Arial', 'Helvetica Neue', Arial, Helvetica, sans-serif; font-weight: bold; margin: -0.14285em 0em 0rem 0em; } /* Default font size */ .ui.message .header:not(.ui) { font-size: 1.15384615em; } /* Paragraph */ .ui.message p { opacity: 0.85; margin: 0.75em 0em; } .ui.message p:first-child { margin-top: 0em; } .ui.message p:last-child { margin-bottom: 0em; } .ui.message .header + p { margin-top: 0.25em; } /* List */ .ui.message .list:not(.ui) { text-align: left; padding: 0em; opacity: 0.85; list-style-position: inside; margin: 0.5em 0em 0em; } .ui.message .list:not(.ui):first-child { margin-top: 0em; } .ui.message .list:not(.ui):last-child { margin-bottom: 0em; } .ui.message .list:not(.ui) li { position: relative; list-style-type: none; margin: 0em 0em 0.3em 1em; padding: 0em; } .ui.message .list:not(.ui) li:before { position: absolute; content: '•'; left: -1em; height: 100%; vertical-align: baseline; } .ui.message .list:not(.ui) li:last-child { margin-bottom: 0em; } /* Icon */ .ui.message > .icon { margin-right: 0.6em; } /* Close Icon */ .ui.message > .close.icon { cursor: pointer; position: absolute; margin: 0em; top: 0.78575em; right: 0.5em; opacity: 0.7; -webkit-transition: opacity 0.1s ease; transition: opacity 0.1s ease; } .ui.message > .close.icon:hover { opacity: 1; } /* First / Last Element */ .ui.message > :first-child { margin-top: 0em; } .ui.message > :last-child { margin-bottom: 0em; } /******************************* Coupling *******************************/ .ui.dropdown .menu > .message { margin: 0px -1px; } /******************************* States *******************************/ /*-------------- Visible ---------------*/ .ui.visible.visible.visible.visible.message { display: block; } .ui.icon.visible.visible.visible.visible.message { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } /*-------------- Hidden ---------------*/ .ui.hidden.hidden.hidden.hidden.message { display: none; } /******************************* Variations *******************************/ /*-------------- Compact ---------------*/ .ui.compact.message { display: inline-block; } /*-------------- Attached ---------------*/ .ui.attached.message { margin-bottom: -1px; border-radius: 0.30769em 0.30769em 0em 0em; box-shadow: 0em 0em 0em 1px rgba(0, 0, 0, 0.13) inset; margin-left: -1px; margin-right: -1px; } .ui.attached + .ui.attached.message:not(.top):not(.bottom) { margin-top: -1px; border-radius: 0em; } .ui.bottom.attached.message { margin-top: -1px; border-radius: 0em 0em 0.30769em 0.30769em; box-shadow: 0em 0em 0em 1px rgba(0, 0, 0, 0.13) inset, 0px 1px 2px 0 rgba(0, 0, 0, 0.13); } .ui.bottom.attached.message:not(:last-child) { margin-bottom: 1em; } .ui.attached.icon.message { width: auto; } /*-------------- Icon ---------------*/ .ui.icon.message { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; width: 100%; -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; } .ui.icon.message > .icon:not(.close) { display: block; -webkit-box-flex: 0; -webkit-flex: 0 0 auto; -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; line-height: 1; vertical-align: middle; font-size: 3em; opacity: 0.8; } .ui.icon.message > .content { display: block; -webkit-box-flex: 1; -webkit-flex: 1 1 auto; -ms-flex: 1 1 auto; flex: 1 1 auto; vertical-align: middle; } .ui.icon.message .icon:not(.close) + .content { padding-left: 0rem; } .ui.icon.message .circular.icon { width: 1em; } /*-------------- Floating ---------------*/ .ui.floating.message { box-shadow: 0px 0px 0px 1px rgba(34, 36, 38, 0.22) inset, 0px 2px 4px 0px rgba(34, 36, 38, 0.12), 0px 2px 10px 0px rgba(34, 36, 38, 0.08); } /*-------------- Colors ---------------*/ .ui.black.message { background-color: #444C55; color: rgba(255, 255, 255, 0.9); } /*-------------- Types ---------------*/ /* Positive */ .ui.positive.message { background-color: #FCFFF5; color: #2C662D; } .ui.positive.message, .ui.attached.positive.message { box-shadow: 0px 0px 0px 1px #A3C293 inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.positive.message .header { color: #1A531B; } /* Negative */ .ui.negative.message { background-color: #FFF6F6; color: #9F3A38; } .ui.negative.message, .ui.attached.negative.message { box-shadow: 0px 0px 0px 1px #E0B4B4 inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.negative.message .header { color: #912D2B; } /* Info */ .ui.info.message { background-color: #E6F1F6; color: #4E575B; } .ui.info.message, .ui.attached.info.message { box-shadow: 0px 0px 0px 1px #A9D5DE inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.info.message .header { color: #0E566C; } /* Warning */ .ui.warning.message { background-color: #FFFAF3; color: #573A08; } .ui.warning.message, .ui.attached.warning.message { box-shadow: 0px 0px 0px 1px #C9BA9B inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.warning.message .header { color: #794B02; } /* Error */ .ui.error.message { background-color: #FFF6F6; color: #9F3A38; } .ui.error.message, .ui.attached.error.message { box-shadow: 0px 0px 0px 1px #E0B4B4 inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.error.message .header { color: #912D2B; } /* Success */ .ui.success.message { background-color: #FCFFF5; color: #2C662D; } .ui.success.message, .ui.attached.success.message { box-shadow: 0px 0px 0px 1px #A3C293 inset, 0px 0px 0px 0px rgba(0, 0, 0, 0); } .ui.success.message .header { color: #1A531B; } /* Colors */ .ui.inverted.message, .ui.black.message { background-color: #444C55; color: rgba(255, 255, 255, 0.9); } .ui.red.message { background-color: #FFE8E6; color: #E03131; } .ui.red.message .header { color: #d72020; } .ui.orange.message { background-color: #FFEDDE; color: #D26911; } .ui.orange.message .header { color: #ba5d0f; } .ui.yellow.message { background-color: #FFF8DB; color: #B58105; } .ui.yellow.message .header { color: #9c6f04; } .ui.olive.message { background-color: #FBFDEF; color: #8ABC1E; } .ui.olive.message .header { color: #7aa61a; } .ui.green.message { background-color: #E5F9E7; color: #1EBC30; } .ui.green.message .header { color: #1aa62a; } .ui.teal.message { background-color: #E1F7F7; color: #10A3A3; } .ui.teal.message .header { color: #0e8c8c; } .ui.blue.message { background-color: #DFF0FF; color: #80A6CD; } .ui.blue.message .header { color: #6e99c6; } .ui.violet.message { background-color: #EAE7FF; color: #6435C9; } .ui.violet.message .header { color: #5a30b5; } .ui.purple.message { background-color: #F6E7FF; color: #A333C8; } .ui.purple.message .header { color: #922eb4; } .ui.pink.message { background-color: #FFE3FB; color: #E03997; } .ui.pink.message .header { color: #dd238b; } .ui.brown.message { background-color: #F1E2D3; color: #A5673F; } .ui.brown.message .header { color: #935b38; } /*-------------- Sizes ---------------*/ .ui.small.message { font-size: 0.92307692em; } .ui.message { font-size: 1em; } .ui.large.message { font-size: 1.15384615em; } .ui.huge.message { font-size: 1.46153846em; } .ui.massive.message { font-size: 1.69230769em; } /******************************* Theme Overrides *******************************/ /******************************* Site Overrides *******************************/
arpitbbhayani/penny
app/static/semantic/dist/components/message.css
CSS
mit
8,661
<?php /* * This file is part of the Beloop package. * * Copyright (c) 2016 AHDO Studio B.V. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Feel free to edit as you please, and have fun. * * @author Arkaitz Garro <[email protected]> */ namespace Beloop\Bundle\InstagramBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\KernelInterface; use Beloop\Bundle\CoreBundle\Abstracts\AbstractBundle; use Beloop\Bundle\InstagramBundle\CompilerPass\MappingCompilerPass; use Beloop\Bundle\InstagramBundle\DependencyInjection\BeloopInstagramExtension; /** * BeloopInstagramBundle Bundle. */ class BeloopInstagramBundle extends AbstractBundle { /** * @param ContainerBuilder $container */ public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new MappingCompilerPass()); } /** * Returns the bundle's container extension. * * @return ExtensionInterface The container extension */ public function getContainerExtension() { return new BeloopInstagramExtension(); } /** * Create instance of current bundle, and return dependent bundle namespaces. * * @param KernelInterface $kernel * @return array Bundle instances */ public static function getBundleDependencies(KernelInterface $kernel) { return [ 'Beloop\Bundle\CoreBundle\BeloopCoreBundle', 'Beloop\Bundle\CoreBundle\BeloopUserBundle', ]; } }
beloop/components
src/Beloop/Bundle/InstagramBundle/BeloopInstagramBundle.php
PHP
mit
1,660
6650 #include "types.h" 6651 #include "x86.h" 6652 6653 void* 6654 memset(void *dst, int c, uint n) 6655 { 6656 if ((int)dst%4 == 0 && n%4 == 0){ 6657 c &= 0xFF; 6658 stosl(dst, (c<<24)|(c<<16)|(c<<8)|c, n/4); 6659 } else 6660 stosb(dst, c, n); 6661 return dst; 6662 } 6663 6664 int 6665 memcmp(const void *v1, const void *v2, uint n) 6666 { 6667 const uchar *s1, *s2; 6668 6669 s1 = v1; 6670 s2 = v2; 6671 while(n-- > 0){ 6672 if(*s1 != *s2) 6673 return *s1 - *s2; 6674 s1++, s2++; 6675 } 6676 6677 return 0; 6678 } 6679 6680 void* 6681 memmove(void *dst, const void *src, uint n) 6682 { 6683 const char *s; 6684 char *d; 6685 6686 s = src; 6687 d = dst; 6688 if(s < d && s + n > d){ 6689 s += n; 6690 d += n; 6691 while(n-- > 0) 6692 *--d = *--s; 6693 } else 6694 while(n-- > 0) 6695 *d++ = *s++; 6696 6697 return dst; 6698 } 6699 6700 // memcpy exists to placate GCC. Use memmove. 6701 void* 6702 memcpy(void *dst, const void *src, uint n) 6703 { 6704 return memmove(dst, src, n); 6705 } 6706 6707 int 6708 strncmp(const char *p, const char *q, uint n) 6709 { 6710 while(n > 0 && *p && *p == *q) 6711 n--, p++, q++; 6712 if(n == 0) 6713 return 0; 6714 return (uchar)*p - (uchar)*q; 6715 } 6716 6717 char* 6718 strncpy(char *s, const char *t, int n) 6719 { 6720 char *os; 6721 6722 os = s; 6723 while(n-- > 0 && (*s++ = *t++) != 0) 6724 ; 6725 while(n-- > 0) 6726 *s++ = 0; 6727 return os; 6728 } 6729 6730 // Like strncpy but guaranteed to NUL-terminate. 6731 char* 6732 safestrcpy(char *s, const char *t, int n) 6733 { 6734 char *os; 6735 6736 os = s; 6737 if(n <= 0) 6738 return os; 6739 while(--n > 0 && (*s++ = *t++) != 0) 6740 ; 6741 *s = 0; 6742 return os; 6743 } 6744 6745 6746 6747 6748 6749 6750 int 6751 strlen(const char *s) 6752 { 6753 int n; 6754 6755 for(n = 0; s[n]; n++) 6756 ; 6757 return n; 6758 } 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799
animesh2049/xv6
fmt/string.c
C
mit
2,236
import { IQuotation } from '../../model/QuotationService/IQuotation'; export interface IQuoteDisplayProps { quote: IQuotation; }
BobGerman/SPFx
quotes/src/webparts/quoteDisplay/components/QuoteDisplay/IQuoteDisplayProps.ts
TypeScript
mit
132
# Laravel 5.1 Generators Some generators for Laravel 5.1 ## Install Require the package: ```sh composer require bvw/laravel-generators dev-master ``` Add the service provider to **config/app.php** in Providers section: ```sh BVW\Providers\GeneratorServiceProvider::class, ``` Run the generators: ```sh php artisan make:database ``` ### Available Commands ```sh make:database -- creates a database based on your environment variables (.env file) ``` ### Notes For the *make:database* command you should configure your .env and add DB_CONNECTION to override default *mysql* in **config/database.php** config file
brunowerneck/Generators
README.md
Markdown
mit
623
--=========== Copyright © 2019, Planimeter, All rights reserved. ===========-- -- -- Purpose: Payload class -- --==========================================================================-- require( "engine.shared.typelenvalues" ) class "payload" ( "typelenvalues" ) payload._handlers = payload._handlers or {} -- Generate ids for packet structures do local payloads = "engine.shared.network.payloads" if ( package.loaded[ payloads ] ) then unrequire( payloads ) end require( payloads ) typelenvalues.generateIds( payload.structs ) end function payload.initializeFromData( data ) local payload = payload() payload.data = data payload:deserialize() return payload end function payload.setHandler( func, struct ) payload._handlers[ struct ] = func end function payload:payload( struct ) typelenvalues.typelenvalues( self, payload.structs, struct ) end function payload:dispatchToHandler() local name = self:getStructName() if ( name == nil ) then return end local handler = payload._handlers[ name ] if ( handler ) then handler( self ) end end accessor( payload, "peer" ) function payload:getPlayer() return player.getByPeer( self.peer ) end function payload:sendToServer() if ( _CLIENT ) then local network = engine.client.network network.sendToServer( self ) end end function payload:broadcast() if ( _SERVER ) then local network = engine.server.network network.broadcast( self ) end end
Planimeter/grid-sdk
engine/shared/network/payload.lua
Lua
mit
1,441
version https://git-lfs.github.com/spec/v1 oid sha256:c4d5490597798effaf63d11e546f0b200f196f28e17c69d39ce236de0c6683f0 size 64139
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.17.2/scrollview-paginator/scrollview-paginator-coverage.js
JavaScript
mit
130
### 2019-03-10 diff between today and yesterday #### python * [pirate/ArchiveBox](https://github.com/pirate/ArchiveBox): The open source self-hosted web archive. Takes browser history/bookmarks/Pocket/Pinboard/etc., saves HTML, JS, PDFs, media, and more... * [0xAX/linux-insides](https://github.com/0xAX/linux-insides): A little bit about a linux kernel * [ageitgey/face_recognition](https://github.com/ageitgey/face_recognition): The world's simplest facial recognition api for Python and the command line * [ArchiveTeam/grab-site](https://github.com/ArchiveTeam/grab-site): The archivist's web crawler: WARC output, dashboard for all crawls, dynamic ignore patterns * [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning): A curated list of awesome Machine Learning frameworks, libraries and software. * [pallets/flask](https://github.com/pallets/flask): The Python micro framework for building web applications. * [smacke/subsync](https://github.com/smacke/subsync): Automagically synchronize subtitles with video. #### go * [gotify/server](https://github.com/gotify/server): A simple server for sending and receiving messages in real-time per web socket. (Includes a sleek web-ui) * [gotify/cli](https://github.com/gotify/cli): A command line interface for pushing messages to gotify/server. * [ma6254/FictionDown](https://github.com/ma6254/FictionDown): ||||Markdown|txt|epub|| * [etcd-io/etcd](https://github.com/etcd-io/etcd): Distributed reliable key-value store for the most critical data of a distributed system * [restic/restic](https://github.com/restic/restic): Fast, secure, efficient backup program * [snail007/goproxy](https://github.com/snail007/goproxy): Proxy is a high performance HTTP(S), websocket, TCP, UDP,Secure DNS, Socks5 proxy server implemented by golang. Now, it supports chain-style proxies,nat forwarding in different lan,TCP/UDP port forwarding, SSH forwarding.Proxygolanghttp,https,websocket,tcp,DNS,socks5,,,,HTTP,SOCKS5,,,KCP,API * [google/gvisor](https://github.com/google/gvisor): Container Runtime Sandbox * [dgraph-io/dgraph](https://github.com/dgraph-io/dgraph): Fast, Distributed Graph DB #### cpp * [olive-editor/olive](https://github.com/olive-editor/olive): Professional open-source NLE video editor * [DeanRoddey/CIDLib](https://github.com/DeanRoddey/CIDLib): The CIDLib general purpose C++ development environment * [musescore/MuseScore](https://github.com/musescore/MuseScore): MuseScore is an open source and free music notation software. For support, contribution, bug reports, visit MuseScore.org. Fork and make pull requests! * [REDasmOrg/REDasm](https://github.com/REDasmOrg/REDasm): The OpenSource Disassembler * [google/flutter-desktop-embedding](https://github.com/google/flutter-desktop-embedding): Desktop implementations of the Flutter embedding API * [DiligentGraphics/DiligentEngine](https://github.com/DiligentGraphics/DiligentEngine): A modern cross-platform low-level graphics library * [cmderdev/cmder](https://github.com/cmderdev/cmder): Lovely console emulator package for Windows #### javascript * [bvaughn/react-window](https://github.com/bvaughn/react-window): React components for efficiently rendering large lists and tabular data * [NervJS/taro](https://github.com/NervJS/taro): React ///H5React Native https://taro.js.org/ * [facebook/react-native](https://github.com/facebook/react-native): A framework for building native apps with React. * [nodejs/node](https://github.com/nodejs/node): Node.js JavaScript runtime * [facebook/jest](https://github.com/facebook/jest): Delightful JavaScript Testing. * [twbs/bootstrap](https://github.com/twbs/bootstrap): The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web. * [frankmcsherry/blog](https://github.com/frankmcsherry/blog): Some notes on things I find interesting and important. #### coffeescript * [unpoly/unpoly](https://github.com/unpoly/unpoly): Unobtrusive Javascript Framework for server-side applications * [boennemann/badges](https://github.com/boennemann/badges): Readme Badges Gotta catch 'em all * [atom/language-json](https://github.com/atom/language-json): JSON package for Atom
larsbijl/trending_archive
2019-03/2019-03-10_short.md
Markdown
mit
4,230
import { Component, DebugElement } from '@angular/core'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By, DOCUMENT } from '@angular/platform-browser'; import { TocComponent } from './toc.component'; import { TocItem, TocService } from 'app/shared/toc.service'; describe('TocComponent', () => { let tocComponentDe: DebugElement; let tocComponent: TocComponent; let tocService: TestTocService; let page: { listItems: DebugElement[]; tocHeading: DebugElement; tocHeadingButton: DebugElement; tocMoreButton: DebugElement; }; function setPage(): typeof page { return { listItems: tocComponentDe.queryAll(By.css('ul.toc-list>li')), tocHeading: tocComponentDe.query(By.css('.toc-heading')), tocHeadingButton: tocComponentDe.query(By.css('.toc-heading button')), tocMoreButton: tocComponentDe.query(By.css('button.toc-more-items')), }; } beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ HostEmbeddedTocComponent, HostNotEmbeddedTocComponent, TocComponent ], providers: [ { provide: TocService, useClass: TestTocService } ] }) .compileComponents(); })); describe('when embedded in doc body', () => { let fixture: ComponentFixture<HostEmbeddedTocComponent>; beforeEach(() => { fixture = TestBed.createComponent(HostEmbeddedTocComponent); tocComponentDe = fixture.debugElement.children[0]; tocComponent = tocComponentDe.componentInstance; tocService = TestBed.get(TocService); }); it('should create tocComponent', () => { expect(tocComponent).toBeTruthy(); }); it('should be in embedded state', () => { expect(tocComponent.isEmbedded).toEqual(true); }); it('should not display anything when no TocItems', () => { tocService.tocList = []; fixture.detectChanges(); expect(tocComponentDe.children.length).toEqual(0); }); describe('when four TocItems', () => { beforeEach(() => { tocService.tocList.length = 4; fixture.detectChanges(); page = setPage(); }); it('should have four displayed items', () => { expect(page.listItems.length).toEqual(4); }); it('should not have secondary items', () => { expect(tocComponent.hasSecondary).toEqual(false, 'hasSecondary flag'); const aSecond = page.listItems.find(item => item.classes.secondary); expect(aSecond).toBeFalsy('should not find a secondary'); }); it('should not display expando buttons', () => { expect(page.tocHeadingButton).toBeFalsy('top expand/collapse button'); expect(page.tocMoreButton).toBeFalsy('bottom more button'); }); }); describe('when many TocItems', () => { beforeEach(() => { fixture.detectChanges(); page = setPage(); }); it('should have more than 4 displayed items', () => { expect(page.listItems.length).toBeGreaterThan(4); expect(page.listItems.length).toEqual(tocService.tocList.length); }); it('should be in "closed" (not expanded) state at the start', () => { expect(tocComponent.isClosed).toBeTruthy(); }); it('should have "closed" class at the start', () => { expect(tocComponentDe.children[0].classes.closed).toEqual(true); }); it('should display expando buttons', () => { expect(page.tocHeadingButton).toBeTruthy('top expand/collapse button'); expect(page.tocMoreButton).toBeTruthy('bottom more button'); }); it('should have secondary items', () => { expect(tocComponent.hasSecondary).toEqual(true, 'hasSecondary flag'); }); // CSS should hide items with the secondary class when closed it('should have secondary item with a secondary class', () => { const aSecondary = page.listItems.find(item => item.classes.secondary); expect(aSecondary).toBeTruthy('should find a secondary'); expect(aSecondary.classes.secondary).toEqual(true, 'has secondary class'); }); describe('after click expando button', () => { beforeEach(() => { page.tocHeadingButton.nativeElement.click(); fixture.detectChanges(); }); it('should not be "closed"', () => { expect(tocComponent.isClosed).toEqual(false); }); it('should not have "closed" class', () => { expect(tocComponentDe.children[0].classes.closed).toBeFalsy(); }); }); }); }); describe('when in side panel (not embedded))', () => { let fixture: ComponentFixture<HostNotEmbeddedTocComponent>; beforeEach(() => { fixture = TestBed.createComponent(HostNotEmbeddedTocComponent); tocComponentDe = fixture.debugElement.children[0]; tocComponent = tocComponentDe.componentInstance; fixture.detectChanges(); page = setPage(); }); it('should not be in embedded state', () => { expect(tocComponent.isEmbedded).toEqual(false); }); it('should display all items', () => { expect(page.listItems.length).toEqual(tocService.tocList.length); }); it('should not have secondary items', () => { expect(tocComponent.hasSecondary).toEqual(false, 'hasSecondary flag'); const aSecond = page.listItems.find(item => item.classes.secondary); expect(aSecond).toBeFalsy('should not find a secondary'); }); it('should not display expando buttons', () => { expect(page.tocHeadingButton).toBeFalsy('top expand/collapse button'); expect(page.tocMoreButton).toBeFalsy('bottom more button'); }); }); }); //// helpers //// @Component({ selector: 'aio-embedded-host', template: '<aio-toc class="embedded"></aio-toc>' }) class HostEmbeddedTocComponent {} @Component({ selector: 'aio-not-embedded-host', template: '<aio-toc></aio-toc>' }) class HostNotEmbeddedTocComponent {} class TestTocService { tocList: TocItem[] = getTestTocList(); } // tslint:disable:quotemark function getTestTocList() { return [ { "content": "Heading one", "href": "fizz/buzz#heading-one-special-id", "level": "h2", "title": "Heading one" }, { "content": "H2 Two", "href": "fizz/buzz#h2-two", "level": "h2", "title": "H2 Two" }, { "content": "H2 <b>Three</b>", "href": "fizz/buzz#h2-three", "level": "h2", "title": "H2 Three" }, { "content": "H3 3a", "href": "fizz/buzz#h3-3a", "level": "h3", "title": "H3 3a" }, { "content": "H3 3b", "href": "fizz/buzz#h3-3b", "level": "h3", "title": "H3 3b" }, { "content": "<i>H2 <b>four</b></i>", "href": "fizz/buzz#h2-four", "level": "h2", "title": "H2 4" } ]; }
diestrin/angular
aio/src/app/embedded/toc/toc.component.spec.ts
TypeScript
mit
6,886
<style> body { padding: 0; margin: 0; } #viewer { background-color: #000; color: #fff; margin: 0px; padding: 0; overflow: hidden; } </style> <div id="viewer"></div>
emgeee/webvr-camera-viewer
src/templates/view.tpl.html
HTML
mit
181
/* omega - node.js server http://code.google.com/p/theomega/ Copyright 2011, Jonathon Fillmore Licensed under the MIT license. See LICENSE file. http://www.opensource.org/licenses/mit-license.php */ var http=require("http");var om=require("./omlib"); var Omega={Request:function(req){var req;req={api:null};req._sock=req;req._answer=function(){return"foo!"};return req},Response:function(res){var resp;resp={_sock:res,data:null,result:false,encoding:"json",headers:{"Content-Type":"text/plain","Cache-Control":"no-cache"},return_code:"200"};resp.set_result=function(result){resp.result=result?true:false};resp.encode=function(){var answer={result:resp.result};if(resp.result)answer.data=resp.data;else{answer.reason=resp.data;answer.data=null}return om.json.encode(answer)}; return resp},Server:function(conf){var omega;omega={_session_id:null,_session:null,_conf:conf,config:null,request:null,response:null,service:null,service_name:""};omega.answer=function(req,res){var answer;omega.request=Omega.Request(req);omega.response=Omega.Response(res);try{omega.response.data=omega.request._answer();omega.response.result=true}catch(e){omega.response.data=e;omega.response.return_code="500"}res.writeHead(omega.response.return_code,omega.response.headers);res.end(omega.response.encode())}; omega._server=http.createServer(omega.answer);omega._server.listen(conf.port,conf.iface);if(omega._conf.verbose)console.log(om.sprintf("Server running at http://%s:%d/",conf.iface,conf.port));return omega}};exports.Server=Omega.Server;
jfillmore/Omega-API-Engine
servers/js/omega.js
JavaScript
mit
1,539
module Souschef # Loads Souschef configuration YAML class Config # Public - Reads the configuration file # # Returns Hash def self.read verify_file YAML.load_file(File.expand_path('~/.souschef.yml')) end # Private - Checks if we have a configuraiton file # # Returns nil def self.verify_file conf = File.expand_path('~/.souschef.yml') fail "'~/.souschef.yml' missing!" unless File.exist?(conf) end end end
akrasic/souschef
lib/souschef/config.rb
Ruby
mit
477
package main import ( "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/url" "os" "os/user" "path/filepath" "strings" "crypto/tls" "net/http" ) type configCommand struct { config *ClientConfig } // skipVerifyHTTPClient returns an *http.Client with InsecureSkipVerify set // to true for its TLS config. This allows self-signed SSL certificates. func skipVerifyHTTPClient(skipVerify bool) *http.Client { if skipVerify { tlsConfig := &tls.Config{InsecureSkipVerify: true} transport := &http.Transport{TLSClientConfig: tlsConfig} return &http.Client{Transport: transport} } return http.DefaultClient } func (cmd *configCommand) Run(args []string) error { if len(args) < 1 { cmd.Usage() os.Exit(1) } var config *ClientConfig if cfg, err := LoadClientConfig(); err == nil { config = cfg } else { config = new(ClientConfig) } var run func(*ClientConfig, []string) error switch strings.ToLower(args[0]) { case "set": run = setCmd case "print": printConfig() return nil default: cmd.Usage() os.Exit(1) } return run(config, args[1:]) } func printConfig() { path, err := clientConfigPath() if err != nil { log.Fatal(err) } cfgData, err := ioutil.ReadFile(path) if err != nil { log.Fatal(err) } fmt.Println(string(cfgData)) } func (cmd *configCommand) Usage() error { const help = ` mdmctl config print mdmctl config set -h ` fmt.Println(help) return nil } func setCmd(cfg *ClientConfig, args []string) error { flagset := flag.NewFlagSet("set", flag.ExitOnError) var ( flToken = flagset.String("api-token", "", "api token to connect to micromdm server") flServerURL = flagset.String("server-url", "", "server url of micromdm server") flSkipVerify = flagset.Bool("skip-verify", false, "skip verification of server certificate (insecure)") ) flagset.Usage = usageFor(flagset, "mdmctl config set [flags]") if err := flagset.Parse(args); err != nil { return err } if *flToken != "" { cfg.APIToken = *flToken } if *flServerURL != "" { if !strings.HasPrefix(*flServerURL, "http") || !strings.HasPrefix(*flServerURL, "https") { *flServerURL = "https://" + *flServerURL } u, err := url.Parse(*flServerURL) if err != nil { return err } u.Scheme = "https" u.Path = "/" cfg.ServerURL = u.String() } cfg.SkipVerify = *flSkipVerify return SaveClientConfig(cfg) } func clientConfigPath() (string, error) { usr, err := user.Current() if err != nil { return "", err } return filepath.Join(usr.HomeDir, ".micromdm", "default.json"), err } func SaveClientConfig(cfg *ClientConfig) error { configPath, err := clientConfigPath() if err != nil { return err } if _, err := os.Stat(filepath.Dir(configPath)); os.IsNotExist(err) { if err := os.MkdirAll(filepath.Dir(configPath), 0777); err != nil { return err } } f, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return err } defer f.Close() if cfg == nil { cfg = new(ClientConfig) } enc := json.NewEncoder(f) enc.SetIndent("", " ") return enc.Encode(cfg) } func LoadClientConfig() (*ClientConfig, error) { path, err := clientConfigPath() if err != nil { return nil, err } cfgData, err := ioutil.ReadFile(path) if err != nil { return nil, fmt.Errorf("unable to load default config file: %s", err) } var cfg ClientConfig err = json.Unmarshal(cfgData, &cfg) if err != nil { return nil, fmt.Errorf("failed to unmarshal %s : %s", path, err) } return &cfg, nil } type ClientConfig struct { APIToken string `json:"api_token"` ServerURL string `json:"server_url"` SkipVerify bool `json:"skip_verify"` }
natewalck/micromdm
cmd/mdmctl/config.go
GO
mit
3,654
module PlazrStore VERSION = "0.0.1" end
Plazr/plazr_store
lib/plazr_store/version.rb
Ruby
mit
42
# This is needed to render the menu properly, according to user's actions. # The first menu option has an index of 0. The lower option is, the higher index it has. selectable-update-current-index() { # In case Arrow Down was pressed. if [ "$1" == $SELECTABLE_ARROW_DOWN ]; then # If there are no more options to choose from, do nothing: the current index will NOT # be reset to 0 (zero). if (($(($SELECTABLE_CURRENT_INDEX+1)) < $SELECTABLE_OPTIONS_AMOUNT)); then # Increment the value. SELECTABLE_CURRENT_INDEX=$(($SELECTABLE_CURRENT_INDEX+1)) fi fi # In case Arrow Up was pressed. if [ "$1" == $SELECTABLE_ARROW_UP ]; then # See the condition above. The current index will NOT be set to the latest element # (option). if (($(($SELECTABLE_CURRENT_INDEX-1)) >= 0)); then # Decrement the value. SELECTABLE_CURRENT_INDEX=$(($SELECTABLE_CURRENT_INDEX-1)) fi fi }
bound1ess/selectable
pieces/update-current-index.sh
Shell
mit
1,010
/* * TestProxy.cpp * * Created on: Sep 6, 2013 * Author: penrique */ #include "InvocationManager.h" #include <bb/system/CardDoneMessage> #include <bb/system/InvokeRequest> // to send number data while invoking phone application #include <bb/PpsObject> // Map #include <bb/platform/LocationMapInvoker> #include <bb/platform/RouteMapInvoker> // contacts #include <bb/cascades/pickers/ContactPicker> using namespace bb::system; using namespace bb::platform; using namespace bb::cascades::pickers; InvocationManager::InvocationManager(const char* name) : Ti::TiProxy(name) { // Create a method, it also has to start with `_` createPropertyFunction("openURL", _openURLMethod); createPropertyFunction("callPhoneNumber", _callPhoneNumberMethod); createPropertyFunction("facebookShare", _facebookShareMethod); createPropertyFunction("openSettings", _openSettingsMethod); createPropertyFunction("openPdf", _openPdfMethod); createPropertyFunction("openMap", _openMapMethod); createPropertyFunction("openContacts", _openContactsMethod); } InvocationManager::~InvocationManager() { // delete instatiated pointers } Ti::TiValue InvocationManager::openURLMethod(Ti::TiValue url) { Ti::TiValue returnValue; returnValue.toBool(); if (invokeReply_ && !invokeReply_->isFinished()) { // Don't send another invoke request if one is already pending. return returnValue; } // convert variable to QString QString myUrl = url.toString(); InvokeRequest request; request.setTarget("sys.browser"); request.setAction("bb.action.OPEN"); request.setUri(myUrl); invokeReply_ = invokeManager_.invoke(request); if (!invokeReply_) { fprintf(stderr, "Failed to invoke this card\n"); return returnValue; } returnValue.setBool(true); return returnValue; } Ti::TiValue InvocationManager::callPhoneNumberMethod(Ti::TiValue number) { Ti::TiValue returnValue; returnValue.toBool(); if (invokeReply_ && !invokeReply_->isFinished()) { // Don't send another invoke request if one is already pending. return returnValue; } // convert variable to QString QString myNumber = number.toString(); QVariantMap map; map.insert("number", myNumber); QByteArray requestData = bb::PpsObject::encode(map, NULL); InvokeRequest request; request.setAction("bb.action.DIAL"); request.setMimeType("application/vnd.blackberry.phone.startcall"); request.setData(requestData); invokeReply_ = invokeManager_.invoke(request); if (!invokeReply_) { fprintf(stderr, "Failed to invoke this card\n"); return returnValue; } returnValue.setBool(true); return returnValue; } Ti::TiValue InvocationManager::facebookShareMethod(Ti::TiValue text) { //TODO: support image & url Ti::TiValue returnValue; returnValue.toBool(); if (invokeReply_ && !invokeReply_->isFinished()) { // Don't send another invoke request if one is already pending. return returnValue; } // convert variable to QString QString myText = text.toString(); InvokeRequest request; request.setTarget("Facebook"); request.setAction("bb.action.SHARE"); request.setMimeType("text/plain"); //request.setUri(myUrl); request.setData(myText.toLocal8Bit()); invokeReply_ = invokeManager_.invoke(request); if (!invokeReply_) { fprintf(stderr, "Failed to invoke this card\n"); return returnValue; } returnValue.setBool(true); return returnValue; } Ti::TiValue InvocationManager::openSettingsMethod(Ti::TiValue page) { Ti::TiValue returnValue; returnValue.toBool(); if (invokeReply_ && !invokeReply_->isFinished()) { // Don't send another invoke request if one is already pending. return returnValue; } // convert variable to QString QString myPage = page.toString(); InvokeRequest request; request.setTarget("sys.settings.card"); request.setAction("bb.action.OPEN"); request.setMimeType("settings/view"); request.setUri(myPage); invokeReply_ = invokeManager_.invoke(request); if (!invokeReply_) { fprintf(stderr, "Failed to invoke this card\n"); return returnValue; } returnValue.setBool(true); return returnValue; } Ti::TiValue InvocationManager::openPdfMethod(Ti::TiValue url) { Ti::TiValue returnValue; returnValue.toBool(); if (invokeReply_ && !invokeReply_->isFinished()) { // Don't send another invoke request if one is already pending. return returnValue; } // convert variable to QString QString myUrl = url.toString(); InvokeRequest request; request.setTarget("com.rim.bb.app.adobeReader.viewer"); request.setAction("bb.action.VIEW"); request.setMimeType("application/pdf"); request.setUri( "file:" + QDir::currentPath() + "/app/native/assets/" + myUrl); invokeReply_ = invokeManager_.invoke(request); if (!invokeReply_) { fprintf(stderr, "Failed to invoke this card\n"); return returnValue; } returnValue.setBool(true); return returnValue; } Ti::TiValue InvocationManager::openMapMethod(Ti::TiValue type) { Ti::TiValue returnValue; returnValue.toBool(); // convert variable to QString QString myType = type.toString(); if (myType == "pin") { LocationMapInvoker lmi; // Sample location set as Toronto // Latitude and Longitude values are expressed // in WGS 84 datum standard lmi.setLocationLatitude(25.1980730); lmi.setLocationLongitude(55.2728830); lmi.setLocationName("Burj Khalifa"); lmi.setLocationDescription("The tallest building in the world."); //set "geocode" : false lmi.setGeocodeLocationEnabled(true); //set "geolocation" : false lmi.setCurrentLocationEnabled(true); lmi.go(); } else { RouteMapInvoker rmi; // Latitude and Longitude values are expressed // in WGS 84 datum standard rmi.setEndLatitude(25.1412000); rmi.setEndLongitude(55.1854000); rmi.setEndName("Burj Al-Arab"); rmi.setEndDescription("The royal suite"); rmi.setEndAddress("Burj Al-Arab, Dubai"); rmi.setNavigationMode(bb::platform::MapNavigationMode::FastestRoute); rmi.setTransportationMode(bb::platform::MapTransportationMode::Car); rmi.go(); } returnValue.setBool(true); return returnValue; } Ti::TiValue InvocationManager::openContactsMethod(Ti::TiValue text) { Ti::TiValue returnValue; returnValue.toBool(); ContactPicker *contactPicker = new ContactPicker(); contactPicker->setMode(ContactSelectionMode::Single); contactPicker->setKindFilters( QSet<bb::pim::contacts::AttributeKind::Type>() << bb::pim::contacts::AttributeKind::Phone); contactPicker->open(); returnValue.setBool(true); return returnValue; }
HazemKhaled/TiCardInvocation
module/InvocationManager.cpp
C++
mit
6,446
<?php namespace Lonquan\TaobaoSDK\Top\Request; use Lonquan\TaobaoSDK\Top\RequestCheckUtil; use Lonquan\TaobaoSDK\Top\RequestInterface; /** * TOP API: taobao.product.img.delete request * * @author auto create * @since 1.0, 2016.03.05 */ class ProductImgDeleteRequest implements RequestInterface { /** * 非主图ID **/ private $id; /** * 产品ID.Product的id,通过taobao.product.add接口新增产品的时候会返回id. **/ private $productId; private $apiParas = [ ]; public function setId($id) { $this->id = $id; $this->apiParas["id"] = $id; } public function getId() { return $this->id; } public function setProductId($productId) { $this->productId = $productId; $this->apiParas["product_id"] = $productId; } public function getProductId() { return $this->productId; } public function getApiMethodName() { return "taobao.product.img.delete"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkNotNull($this->id, "id"); RequestCheckUtil::checkNotNull($this->productId, "productId"); } public function putOtherTextParam($key, $value) { $this->apiParas[ $key ] = $value; $this->$key = $value; } }
lonquan/taobao-sdk
src/Top/Request/ProductImgDeleteRequest.php
PHP
mit
1,480
require "point/version" module Point autoload :Point, 'point/point' def self.sum(*args) x = y = 0 args.each do |point| x += point.x y += point.y end self::Point.new(x, y) end end
login73ul/point
lib/point.rb
Ruby
mit
219
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="de"> <head> <!-- Generated by javadoc (1.8.0_121) on Sat Apr 01 23:01:20 CEST 2017 --> <title>Uses of Class algorithms.InitStrategy</title> <meta name="date" content="2017-04-01"> <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="Uses of Class algorithms.InitStrategy"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../algorithms/InitStrategy.html" title="enum in algorithms">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?algorithms/class-use/InitStrategy.html" target="_top">Frames</a></li> <li><a href="InitStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class algorithms.InitStrategy" class="title">Uses of Class<br>algorithms.InitStrategy</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#algorithms">algorithms</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="algorithms"> <!-- --> </a> <h3>Uses of <a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a> in <a href="../../algorithms/package-summary.html">algorithms</a></h3> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../algorithms/package-summary.html">algorithms</a> that return <a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a></code></td> <td class="colLast"><span class="typeNameLabel">InitStrategy.</span><code><span class="memberNameLink"><a href="../../algorithms/InitStrategy.html#valueOf-java.lang.String-">valueOf</a></span>(java.lang.String&nbsp;name)</code> <div class="block">Returns the enum constant of this type with the specified name.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a>[]</code></td> <td class="colLast"><span class="typeNameLabel">InitStrategy.</span><code><span class="memberNameLink"><a href="../../algorithms/InitStrategy.html#values--">values</a></span>()</code> <div class="block">Returns an array containing the constants of this enum type, in the order they are declared.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../algorithms/package-summary.html">algorithms</a> with parameters of type <a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../data/Cluster.html" title="class in data">Cluster</a>&gt;</code></td> <td class="colLast"><span class="typeNameLabel">Kmeans.</span><code><span class="memberNameLink"><a href="../../algorithms/Kmeans.html#calculateClusters-algorithms.InitStrategy-algorithms.UpdateStrategy-">calculateClusters</a></span>(<a href="../../algorithms/InitStrategy.html" title="enum in algorithms">InitStrategy</a>&nbsp;initStrat, <a href="../../algorithms/UpdateStrategy.html" title="enum in algorithms">UpdateStrategy</a>&nbsp;updateStrat)</code> <div class="block">calculateClusters(initStrat, updateStrat) startet das Clustering-Verfahren</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../algorithms/InitStrategy.html" title="enum in algorithms">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?algorithms/class-use/InitStrategy.html" target="_top">Frames</a></li> <li><a href="InitStrategy.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
markhun/univie-SDM_K-means
doc/algorithms/class-use/InitStrategy.html
HTML
mit
7,718
<?php namespace MvMidia\Factory; use MvMidia\Service\AudioService; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; class AudioServiceFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $entityManager = $serviceLocator->get('Doctrine\ORM\EntityManager'); return new AudioService($entityManager); } }
marcusvy/mv-orion
_server/module/MvMidia/src/MvMidia/Factory/AudioServiceFactory.php
PHP
mit
420
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10.CatalanNumbers { class Program { static void Main(string[] args) { // 10. Write a program to calculate the Nth Catalan number by given N. Console.Write("Insert N = "); string input = Console.ReadLine(); int num; int catalanNumber; int factN = 1; int factM = 1; int factK = 1; if (int.TryParse(input, out num)) { if (num > -1) { if (num == 0) { Console.WriteLine("Catalan number given by '0' is: 1"); } else if (num >= 1) { int n = num; while (n > 1) { factN = factN * n; // for (n!) n = n - 1; } n = num + 1; while (n > 1) { factM = factM * n; // for (n + 1) n = n - 1; } n = 2 * num; while (n > 1) { factK = factK * n; // for (2 * n) n = n - 1; } catalanNumber = factK / (factM * factN); Console.WriteLine("Catalan number given by 'N' is: " + catalanNumber); } } else { Console.WriteLine("N < 0"); } } else { Console.WriteLine("Incorect input!"); } } } }
bstaykov/Telerik-CSharp-Part-1
Loops/10.CatalanNumbers/Program.cs
C#
mit
1,982
<?php /* TwigBundle:Exception:traces.txt.twig */ class __TwigTemplate_c3e3230b69c4964c8a557e1f2f357b5c8020737511aeeb0ff45cb50924b53015 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 if (twig_length_filter($this->env, $this->getAttribute($this->getContext($context, "exception"), "trace"))) { // line 2 $context['_parent'] = (array) $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute($this->getContext($context, "exception"), "trace")); foreach ($context['_seq'] as $context["_key"] => $context["trace"]) { // line 3 $this->env->loadTemplate("TwigBundle:Exception:trace.txt.twig")->display(array("trace" => $this->getContext($context, "trace"))); // line 4 echo " "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['trace'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; } } public function getTemplateName() { return "TwigBundle:Exception:traces.txt.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 42 => 14, 38 => 13, 35 => 4, 26 => 5, 87 => 20, 80 => 19, 55 => 13, 46 => 7, 44 => 10, 36 => 7, 31 => 5, 25 => 3, 21 => 2, 94 => 22, 92 => 21, 89 => 20, 85 => 19, 79 => 18, 75 => 17, 72 => 16, 68 => 14, 64 => 12, 56 => 9, 50 => 8, 41 => 9, 27 => 4, 24 => 4, 22 => 2, 201 => 92, 199 => 91, 196 => 90, 187 => 84, 183 => 82, 173 => 74, 171 => 73, 168 => 72, 166 => 71, 163 => 70, 158 => 67, 156 => 66, 151 => 63, 142 => 59, 138 => 57, 136 => 56, 133 => 55, 123 => 47, 121 => 46, 117 => 44, 115 => 43, 112 => 42, 105 => 40, 101 => 24, 91 => 31, 86 => 28, 69 => 25, 66 => 15, 62 => 23, 51 => 15, 49 => 19, 39 => 6, 32 => 12, 19 => 1, 57 => 16, 54 => 21, 43 => 8, 40 => 7, 33 => 10, 30 => 3,); } }
lrodriguezcabrales/Tutorial
app/cache/dev/twig/c3/e3/230b69c4964c8a557e1f2f357b5c8020737511aeeb0ff45cb50924b53015.php
PHP
mit
2,351
<section *ngIf="blogItems"> <div class="background"></div> <div class="wrapper" *ngFor="let item of blogItems"> <div class="text" [innerHtml]="texts[blogItems.indexOf(item)]"></div> <div class="item"> <aae-blog-item [blogItem]="item" [alias]="alias"></aae-blog-item> </div> </div> </section>
KeJSaR/artezian-info-web
src/app/content/about/about.component.html
HTML
mit
322
(function() { var $, expect, fruits; $ = require('../'); expect = require('expect.js'); /* Examples */ fruits = '<ul id = "fruits">\n <li class = "apple">Apple</li>\n <li class = "orange">Orange</li>\n <li class = "pear">Pear</li>\n</ul>'.replace(/(\n|\s{2})/g, ''); /* Tests */ describe('$(...)', function() { describe('.find', function() { it('() : should return this', function() { return expect($('ul', fruits).find()[0].name).to.equal('ul'); }); it('(single) : should find one descendant', function() { return expect($('#fruits', fruits).find('.apple')[0].attribs["class"]).to.equal('apple'); }); it('(many) : should find all matching descendant', function() { return expect($('#fruits', fruits).find('li')).to.have.length(3); }); it('(many) : should merge all selected elems with matching descendants'); it('(invalid single) : should return empty if cant find', function() { return expect($('ul', fruits).find('blah')).to.have.length(0); }); return it('should return empty if search already empty result', function() { return expect($('#fruits').find('li')).to.have.length(0); }); }); describe('.children', function() { it('() : should get all children', function() { return expect($('ul', fruits).children()).to.have.length(3); }); it('(selector) : should return children matching selector', function() { return expect($('ul', fruits).children('.orange').hasClass('orange')).to.be.ok; }); it('(invalid selector) : should return empty', function() { return expect($('ul', fruits).children('.lulz')).to.have.length(0); }); return it('should only match immediate children, not ancestors'); }); describe('.next', function() { it('() : should return next element', function() { return expect($('.orange', fruits).next().hasClass('pear')).to.be.ok; }); return it('(no next) : should return null (?)'); }); describe('.prev', function() { it('() : should return previous element', function() { return expect($('.orange', fruits).prev().hasClass('apple')).to.be.ok; }); return it('(no prev) : should return null (?)'); }); describe('.siblings', function() { it('() : should get all the siblings', function() { return expect($('.orange', fruits).siblings()).to.have.length(2); }); return it('(selector) : should get all siblings that match the selector', function() { return expect($('.orange', fruits).siblings('li')).to.have.length(2); }); }); describe('.each', function() { return it('( (i, elem) -> ) : should loop selected returning fn with (i, elem)', function() { var items; items = []; $('li', fruits).each(function(i, elem) { return items[i] = elem; }); expect(items[0].attribs["class"]).to.equal('apple'); expect(items[1].attribs["class"]).to.equal('orange'); return expect(items[2].attribs["class"]).to.equal('pear'); }); }); describe('.first', function() { it('() : should return the first item', function() { var elem, src; src = $("<span>foo</span><span>bar</span><span>baz</span>"); elem = src.first(); expect(elem.length).to.equal(1); return expect(elem.html()).to.equal('foo'); }); return it('() : should return an empty object for an empty object', function() { var first, src; src = $(); first = src.first(); expect(first.length).to.equal(0); return expect(first.html()).to.be(null); }); }); describe('.last', function() { it('() : should return the last element', function() { var elem, src; src = $("<span>foo</span><span>bar</span><span>baz</span>"); elem = src.last(); expect(elem.length).to.equal(1); return expect(elem.html()).to.equal('baz'); }); return it('() : should return an empty object for an empty object', function() { var last, src; src = $(); last = src.last(); expect(last.length).to.equal(0); return expect(last.html()).to.be(null); }); }); describe('.first & .last', function() { return it('() : should return same object if only one object', function() { var first, last, src; src = $("<span>bar</span>"); first = src.first(); last = src.last(); expect(first.html()).to.equal(last.html()); expect(first.length).to.equal(1); expect(first.html()).to.equal('bar'); expect(last.length).to.equal(1); return expect(last.html()).to.equal('bar'); }); }); return describe('.eq', function() { return it('(i) : should return the element at the specified index', function() { expect($('li', fruits).eq(0).text()).to.equal('Apple'); expect($('li', fruits).eq(1).text()).to.equal('Orange'); expect($('li', fruits).eq(2).text()).to.equal('Pear'); expect($('li', fruits).eq(3).text()).to.equal(''); return expect($('li', fruits).eq(-1).text()).to.equal('Pear'); }); }); }); }).call(this);
wheeyls/meetingVis
node_modules/facile/test/public/javascripts/node_modules/cheerio/test/api.traversing.js
JavaScript
mit
5,315
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form; use Symfony\Component\Form\Exception\InvalidArgumentException; use Symfony\Component\Form\Exception\UnexpectedTypeException; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\OptionsResolver\OptionsResolver; /** * A wrapper for a form type and its extensions. * * @author Bernhard Schussek <[email protected]> */ class ResolvedFormType implements ResolvedFormTypeInterface { /** * @var FormTypeInterface */ private $innerType; /** * @var FormTypeExtensionInterface[] */ private $typeExtensions; /** * @var ResolvedFormTypeInterface|null */ private $parent; /** * @var OptionsResolver */ private $optionsResolver; public function __construct(FormTypeInterface $innerType, array $typeExtensions = array(), ResolvedFormTypeInterface $parent = null) { if (!preg_match('/^[a-z0-9_]*$/i', $innerType->getName())) { throw new InvalidArgumentException(sprintf( 'The "%s" form type name ("%s") is not valid. Names must only contain letters, numbers, and "_".', get_class($innerType), $innerType->getName() )); } foreach ($typeExtensions as $extension) { if (!$extension instanceof FormTypeExtensionInterface) { throw new UnexpectedTypeException($extension, 'Symfony\Component\Form\FormTypeExtensionInterface'); } } $this->innerType = $innerType; $this->typeExtensions = $typeExtensions; $this->parent = $parent; } /** * {@inheritdoc} */ public function getName() { return $this->innerType->getName(); } /** * {@inheritdoc} */ public function getParent() { return $this->parent; } /** * {@inheritdoc} */ public function getInnerType() { return $this->innerType; } /** * {@inheritdoc} */ public function getTypeExtensions() { return $this->typeExtensions; } /** * {@inheritdoc} */ public function createBuilder(FormFactoryInterface $factory, $name, array $options = array()) { $options = $this->getOptionsResolver()->resolve($options); // Should be decoupled from the specific option at some point $dataClass = isset($options['data_class']) ? $options['data_class'] : null; $builder = $this->newBuilder($name, $dataClass, $factory, $options); $builder->setType($this); return $builder; } /** * {@inheritdoc} */ public function createView(FormInterface $form, FormView $parent = null) { return $this->newView($parent); } /** * Configures a form builder for the type hierarchy. * * @param FormBuilderInterface $builder The builder to configure * @param array $options The options used for the configuration */ public function buildForm(FormBuilderInterface $builder, array $options) { if (null !== $this->parent) { $this->parent->buildForm($builder, $options); } $this->innerType->buildForm($builder, $options); foreach ($this->typeExtensions as $extension) { $extension->buildForm($builder, $options); } } /** * Configures a form view for the type hierarchy. * * This method is called before the children of the view are built. * * @param FormView $view The form view to configure * @param FormInterface $form The form corresponding to the view * @param array $options The options used for the configuration */ public function buildView(FormView $view, FormInterface $form, array $options) { if (null !== $this->parent) { $this->parent->buildView($view, $form, $options); } $this->innerType->buildView($view, $form, $options); foreach ($this->typeExtensions as $extension) { $extension->buildView($view, $form, $options); } } /** * Finishes a form view for the type hierarchy. * * This method is called after the children of the view have been built. * * @param FormView $view The form view to configure * @param FormInterface $form The form corresponding to the view * @param array $options The options used for the configuration */ public function finishView(FormView $view, FormInterface $form, array $options) { if (null !== $this->parent) { $this->parent->finishView($view, $form, $options); } $this->innerType->finishView($view, $form, $options); foreach ($this->typeExtensions as $extension) { /* @var FormTypeExtensionInterface $extension */ $extension->finishView($view, $form, $options); } } /** * Returns the configured options resolver used for this type. * * @return \Symfony\Component\OptionsResolver\OptionsResolverInterface The options resolver */ public function getOptionsResolver() { if (null === $this->optionsResolver) { if (null !== $this->parent) { $this->optionsResolver = clone $this->parent->getOptionsResolver(); } else { $this->optionsResolver = new OptionsResolver(); } $this->innerType->setDefaultOptions($this->optionsResolver); if (method_exists($this->innerType, 'configureOptions')) { $reflector = new \ReflectionMethod($this->innerType, 'setDefaultOptions'); $isOldOverwritten = 'Symfony\Component\Form\AbstractType' !== $reflector->getDeclaringClass()->getName(); $reflector = new \ReflectionMethod($this->innerType, 'configureOptions'); $isNewOverwritten = 'Symfony\Component\Form\AbstractType' !== $reflector->getDeclaringClass()->getName(); if ($isOldOverwritten && !$isNewOverwritten) { @trigger_error(get_class($this->innerType).': The FormTypeInterface::setDefaultOptions() method is deprecated since version 2.7 and will be removed in 3.0. Use configureOptions() instead. This method will be added to the FormTypeInterface with Symfony 3.0.', E_USER_DEPRECATED); } } else { @trigger_error(get_class($this->innerType).': The FormTypeInterface::configureOptions() method will be added in Symfony 3.0. You should extend AbstractType or implement it in your classes.', E_USER_DEPRECATED); } foreach ($this->typeExtensions as $extension) { $extension->setDefaultOptions($this->optionsResolver); if (method_exists($extension, 'configureOptions')) { $reflector = new \ReflectionMethod($extension, 'setDefaultOptions'); $isOldOverwritten = 'Symfony\Component\Form\AbstractTypeExtension' !== $reflector->getDeclaringClass()->getName(); $reflector = new \ReflectionMethod($extension, 'configureOptions'); $isNewOverwritten = 'Symfony\Component\Form\AbstractTypeExtension' !== $reflector->getDeclaringClass()->getName(); if ($isOldOverwritten && !$isNewOverwritten) { @trigger_error(get_class($extension).': The FormTypeExtensionInterface::setDefaultOptions() method is deprecated since version 2.7 and will be removed in 3.0. Use configureOptions() instead. This method will be added to the FormTypeExtensionInterface with Symfony 3.0.', E_USER_DEPRECATED); } } else { @trigger_error(get_class($this->innerType).': The FormTypeExtensionInterface::configureOptions() method will be added in Symfony 3.0. You should extend AbstractTypeExtension or implement it in your classes.', E_USER_DEPRECATED); } } } return $this->optionsResolver; } /** * Creates a new builder instance. * * Override this method if you want to customize the builder class. * * @param string $name The name of the builder * @param string $dataClass The data class * @param FormFactoryInterface $factory The current form factory * @param array $options The builder options * * @return FormBuilderInterface The new builder instance */ protected function newBuilder($name, $dataClass, FormFactoryInterface $factory, array $options) { if ($this->innerType instanceof ButtonTypeInterface) { return new ButtonBuilder($name, $options); } if ($this->innerType instanceof SubmitButtonTypeInterface) { return new SubmitButtonBuilder($name, $options); } return new FormBuilder($name, $dataClass, new EventDispatcher(), $factory, $options); } /** * Creates a new view instance. * * Override this method if you want to customize the view class. * * @param FormView|null $parent The parent view, if available * * @return FormView A new view instance */ protected function newView(FormView $parent = null) { return new FormView($parent); } }
inso/symfony
src/Symfony/Component/Form/ResolvedFormType.php
PHP
mit
9,680
<!DOCTYPE html> <html lang = "en"> <head> <title> Cultural Blog</title> <link href='http://fonts.googleapis.com/css?family=Italianno' rel='stylesheet' type='text/css'> </head> <style type="text/css"> h1 { text-align: center; margin-top: 3% } p { } body { background: url("http://www.hdwallpapers.in/walls/hd_sky_blue_beach-HD.jpg"); background-size: cover; font-family: 'Italianno', serif; font-size: 32px } .question { color: #4D4D4D; margin-top: 3% } .answer { } </style> <body> <h1>Here are my answers to Q&A:</h1> <p class="question">Q: When you think of the times in your life where you've been the happiest, the proudest, or the most satisfied, which of the following values come to mind?</p> <p class="answer">A: Accomplishment, Achievement, Adventure, Autonomy, Relationships, Commitment, Courage, Creativity, Competence, Confidence, Credibility, Decisiveness, Effectiveness, Excitement, Faith, Freedom, Fiendships, Growth, Having a family, Health, Helping other people, Independence, Inner harmony, Insight, Justice, Knowledge, Peace, Personal development, Pleasure, Romance, Security, Serenity, Sophistication, Spirituality, Tranquility, Truth, Vibrancy, Wisdom</p> <p class="question">Q: Pick one value and write a couple of sentences about why one of the values you chose is important to you</p> <p class="answer">A: Having faith is the source of everything you need in life. Faith in god and yourself. It brings all other qualities and values you need in life. It brings peace, Inner harmony, Serenity, Courage, Confidence, and all other values I mentioned above.</p> <p class="question">Q: Answer the following for the values you chose in Exercise 1: In general, I try to live up to these values: Disagree 1 ----- 2 ----- 3 ----- 4 ----- 5 Agree</p> <p class="answer">A: I have to say 5. I try my best to live up to those values because they do make me happy and satisfied.</p> <p class="question">Q: What was the last topic that someone asked for your advice on?</p> <p class="answer">A: A close friend of mine got accepted in couple of universities for p.h.d and he asked for my advice about the cities and which university he should attend.</p> </body>
Parjam/parjam.github.io
week2_cultural_blog.html
HTML
mit
2,212
# nepali-wordlist Nepali wordlist for wpa2 cracking. Includes password with length of 8 character or more and mostly contains nepali words including other common words. ## Files * __nepali-name-suffix-8+.txt.gz:__ `Nepali names passwords with numbered suffix. Contains 80,00,000 words with up to 3 number suffixa. Level 9 compression used to compress. Original size is around 50 MB. ` * __nepali-name.txt:__ `8000+ nepali names which might be helpful to create your own wordlist or in some other projects.` * __wlist.py:__ `This is a wordlist manager script which can strip down larg wordlist to a smaller one according to your need. Codes are all messed up wtihout proper documentation but it works perfectly.. :)` *__Install:__* 1. Copy this script to your path. 2. Make it execuitable by `chmod +x wlist.py` 3. Execuite command by wlist.py from terminal.
prabinzz/nepali-wordlist
README.md
Markdown
mit
897
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: diplomacy_tensorflow/core/example/feature.proto #include "diplomacy_tensorflow/core/example/feature.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_BytesList; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_FloatList; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Int64List; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureList; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureLists_FeatureListEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_Features_FeatureEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_Feature; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto namespace diplomacy { namespace tensorflow { class BytesListDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BytesList> _instance; } _BytesList_default_instance_; class FloatListDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FloatList> _instance; } _FloatList_default_instance_; class Int64ListDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Int64List> _instance; } _Int64List_default_instance_; class FeatureDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Feature> _instance; const ::diplomacy::tensorflow::BytesList* bytes_list_; const ::diplomacy::tensorflow::FloatList* float_list_; const ::diplomacy::tensorflow::Int64List* int64_list_; } _Feature_default_instance_; class Features_FeatureEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Features_FeatureEntry_DoNotUse> _instance; } _Features_FeatureEntry_DoNotUse_default_instance_; class FeaturesDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Features> _instance; } _Features_default_instance_; class FeatureListDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FeatureList> _instance; } _FeatureList_default_instance_; class FeatureLists_FeatureListEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FeatureLists_FeatureListEntry_DoNotUse> _instance; } _FeatureLists_FeatureListEntry_DoNotUse_default_instance_; class FeatureListsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FeatureLists> _instance; } _FeatureLists_default_instance_; } // namespace tensorflow } // namespace diplomacy namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto { static void InitDefaultsBytesList() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_BytesList_default_instance_; new (ptr) ::diplomacy::tensorflow::BytesList(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::BytesList::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_BytesList = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBytesList}, {}}; static void InitDefaultsFloatList() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_FloatList_default_instance_; new (ptr) ::diplomacy::tensorflow::FloatList(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::FloatList::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_FloatList = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFloatList}, {}}; static void InitDefaultsInt64List() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_Int64List_default_instance_; new (ptr) ::diplomacy::tensorflow::Int64List(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::Int64List::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_Int64List = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInt64List}, {}}; static void InitDefaultsFeature() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_Feature_default_instance_; new (ptr) ::diplomacy::tensorflow::Feature(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::Feature::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<3> scc_info_Feature = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsFeature}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base, &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base, &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base,}}; static void InitDefaultsFeatures_FeatureEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_Features_FeatureEntry_DoNotUse_default_instance_; new (ptr) ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse(); } ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_Features_FeatureEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatures_FeatureEntry_DoNotUse}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base,}}; static void InitDefaultsFeatures() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_Features_default_instance_; new (ptr) ::diplomacy::tensorflow::Features(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::Features::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_Features = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatures}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features_FeatureEntry_DoNotUse.base,}}; static void InitDefaultsFeatureList() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_FeatureList_default_instance_; new (ptr) ::diplomacy::tensorflow::FeatureList(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::FeatureList::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureList = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatureList}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base,}}; static void InitDefaultsFeatureLists_FeatureListEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_FeatureLists_FeatureListEntry_DoNotUse_default_instance_; new (ptr) ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse(); } ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureLists_FeatureListEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatureLists_FeatureListEntry_DoNotUse}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base,}}; static void InitDefaultsFeatureLists() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::_FeatureLists_default_instance_; new (ptr) ::diplomacy::tensorflow::FeatureLists(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::FeatureLists::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_FeatureLists = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsFeatureLists}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists_FeatureListEntry_DoNotUse.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_BytesList.base); ::google::protobuf::internal::InitSCC(&scc_info_FloatList.base); ::google::protobuf::internal::InitSCC(&scc_info_Int64List.base); ::google::protobuf::internal::InitSCC(&scc_info_Feature.base); ::google::protobuf::internal::InitSCC(&scc_info_Features_FeatureEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_Features.base); ::google::protobuf::internal::InitSCC(&scc_info_FeatureList.base); ::google::protobuf::internal::InitSCC(&scc_info_FeatureLists_FeatureListEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_FeatureLists.base); } ::google::protobuf::Metadata file_level_metadata[9]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::BytesList, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::BytesList, value_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FloatList, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FloatList, value_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Int64List, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Int64List, value_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Feature, _internal_metadata_), ~0u, // no _extensions_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Feature, _oneof_case_[0]), ~0u, // no _weak_field_map_ offsetof(::diplomacy::tensorflow::FeatureDefaultTypeInternal, bytes_list_), offsetof(::diplomacy::tensorflow::FeatureDefaultTypeInternal, float_list_), offsetof(::diplomacy::tensorflow::FeatureDefaultTypeInternal, int64_list_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Feature, kind_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::Features, feature_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureList, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureList, feature_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::FeatureLists, feature_list_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::diplomacy::tensorflow::BytesList)}, { 6, -1, sizeof(::diplomacy::tensorflow::FloatList)}, { 12, -1, sizeof(::diplomacy::tensorflow::Int64List)}, { 18, -1, sizeof(::diplomacy::tensorflow::Feature)}, { 27, 34, sizeof(::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse)}, { 36, -1, sizeof(::diplomacy::tensorflow::Features)}, { 42, -1, sizeof(::diplomacy::tensorflow::FeatureList)}, { 48, 55, sizeof(::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse)}, { 57, -1, sizeof(::diplomacy::tensorflow::FeatureLists)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_BytesList_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FloatList_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Int64List_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Feature_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Features_FeatureEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_Features_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FeatureList_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FeatureLists_FeatureListEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::_FeatureLists_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "diplomacy_tensorflow/core/example/feature.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 9); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n/diplomacy_tensorflow/core/example/feat" "ure.proto\022\024diplomacy.tensorflow\"\032\n\tBytes" "List\022\r\n\005value\030\001 \003(\014\"\036\n\tFloatList\022\021\n\005valu" "e\030\001 \003(\002B\002\020\001\"\036\n\tInt64List\022\021\n\005value\030\001 \003(\003B" "\002\020\001\"\266\001\n\007Feature\0225\n\nbytes_list\030\001 \001(\0132\037.di" "plomacy.tensorflow.BytesListH\000\0225\n\nfloat_" "list\030\002 \001(\0132\037.diplomacy.tensorflow.FloatL" "istH\000\0225\n\nint64_list\030\003 \001(\0132\037.diplomacy.te" "nsorflow.Int64ListH\000B\006\n\004kind\"\227\001\n\010Feature" "s\022<\n\007feature\030\001 \003(\0132+.diplomacy.tensorflo" "w.Features.FeatureEntry\032M\n\014FeatureEntry\022" "\013\n\003key\030\001 \001(\t\022,\n\005value\030\002 \001(\0132\035.diplomacy." "tensorflow.Feature:\0028\001\"=\n\013FeatureList\022.\n" "\007feature\030\001 \003(\0132\035.diplomacy.tensorflow.Fe" "ature\"\260\001\n\014FeatureLists\022I\n\014feature_list\030\001" " \003(\01323.diplomacy.tensorflow.FeatureLists" ".FeatureListEntry\032U\n\020FeatureListEntry\022\013\n" "\003key\030\001 \001(\t\0220\n\005value\030\002 \001(\0132!.diplomacy.te" "nsorflow.FeatureList:\0028\001Bi\n\026org.tensorfl" "ow.exampleB\rFeatureProtosP\001Z;github.com/" "tensorflow/tensorflow/tensorflow/go/core" "/example\370\001\001b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 859); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "diplomacy_tensorflow/core/example/feature.proto", &protobuf_RegisterTypes); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto namespace diplomacy { namespace tensorflow { // =================================================================== void BytesList::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BytesList::kValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BytesList::BytesList() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.BytesList) } BytesList::BytesList(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), value_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.BytesList) } BytesList::BytesList(const BytesList& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), value_(from.value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.BytesList) } void BytesList::SharedCtor() { } BytesList::~BytesList() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.BytesList) SharedDtor(); } void BytesList::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void BytesList::ArenaDtor(void* object) { BytesList* _this = reinterpret_cast< BytesList* >(object); (void)_this; } void BytesList::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void BytesList::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* BytesList::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const BytesList& BytesList::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_BytesList.base); return *internal_default_instance(); } void BytesList::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.BytesList) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; value_.Clear(); _internal_metadata_.Clear(); } bool BytesList::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.BytesList) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated bytes value = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( input, this->add_value())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.BytesList) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.BytesList) return false; #undef DO_ } void BytesList::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.BytesList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated bytes value = 1; for (int i = 0, n = this->value_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteBytes( 1, this->value(i), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.BytesList) } ::google::protobuf::uint8* BytesList::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.BytesList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated bytes value = 1; for (int i = 0, n = this->value_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteBytesToArray(1, this->value(i), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.BytesList) return target; } size_t BytesList::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.BytesList) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated bytes value = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->value_size()); for (int i = 0, n = this->value_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::BytesSize( this->value(i)); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BytesList::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.BytesList) GOOGLE_DCHECK_NE(&from, this); const BytesList* source = ::google::protobuf::internal::DynamicCastToGenerated<const BytesList>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.BytesList) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.BytesList) MergeFrom(*source); } } void BytesList::MergeFrom(const BytesList& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.BytesList) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; value_.MergeFrom(from.value_); } void BytesList::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.BytesList) if (&from == this) return; Clear(); MergeFrom(from); } void BytesList::CopyFrom(const BytesList& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.BytesList) if (&from == this) return; Clear(); MergeFrom(from); } bool BytesList::IsInitialized() const { return true; } void BytesList::Swap(BytesList* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { BytesList* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void BytesList::UnsafeArenaSwap(BytesList* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void BytesList::InternalSwap(BytesList* other) { using std::swap; value_.InternalSwap(CastToBase(&other->value_)); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata BytesList::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void FloatList::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FloatList::kValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FloatList::FloatList() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.FloatList) } FloatList::FloatList(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), value_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.FloatList) } FloatList::FloatList(const FloatList& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), value_(from.value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.FloatList) } void FloatList::SharedCtor() { } FloatList::~FloatList() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.FloatList) SharedDtor(); } void FloatList::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void FloatList::ArenaDtor(void* object) { FloatList* _this = reinterpret_cast< FloatList* >(object); (void)_this; } void FloatList::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FloatList::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FloatList::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const FloatList& FloatList::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FloatList.base); return *internal_default_instance(); } void FloatList::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.FloatList) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; value_.Clear(); _internal_metadata_.Clear(); } bool FloatList::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.FloatList) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated float value = 1 [packed = true]; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_value()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(13u /* 13 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>( 1, 10u, input, this->mutable_value()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.FloatList) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.FloatList) return false; #undef DO_ } void FloatList::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.FloatList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float value = 1 [packed = true]; if (this->value_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _value_cached_byte_size_)); ::google::protobuf::internal::WireFormatLite::WriteFloatArray( this->value().data(), this->value_size(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.FloatList) } ::google::protobuf::uint8* FloatList::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.FloatList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float value = 1 [packed = true]; if (this->value_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _value_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteFloatNoTagToArray(this->value_, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.FloatList) return target; } size_t FloatList::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.FloatList) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated float value = 1 [packed = true]; { unsigned int count = static_cast<unsigned int>(this->value_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _value_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void FloatList::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.FloatList) GOOGLE_DCHECK_NE(&from, this); const FloatList* source = ::google::protobuf::internal::DynamicCastToGenerated<const FloatList>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.FloatList) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.FloatList) MergeFrom(*source); } } void FloatList::MergeFrom(const FloatList& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.FloatList) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; value_.MergeFrom(from.value_); } void FloatList::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.FloatList) if (&from == this) return; Clear(); MergeFrom(from); } void FloatList::CopyFrom(const FloatList& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.FloatList) if (&from == this) return; Clear(); MergeFrom(from); } bool FloatList::IsInitialized() const { return true; } void FloatList::Swap(FloatList* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { FloatList* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void FloatList::UnsafeArenaSwap(FloatList* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void FloatList::InternalSwap(FloatList* other) { using std::swap; value_.InternalSwap(&other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata FloatList::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void Int64List::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Int64List::kValueFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Int64List::Int64List() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.Int64List) } Int64List::Int64List(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), value_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.Int64List) } Int64List::Int64List(const Int64List& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), value_(from.value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.Int64List) } void Int64List::SharedCtor() { } Int64List::~Int64List() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.Int64List) SharedDtor(); } void Int64List::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void Int64List::ArenaDtor(void* object) { Int64List* _this = reinterpret_cast< Int64List* >(object); (void)_this; } void Int64List::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Int64List::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Int64List::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Int64List& Int64List::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Int64List.base); return *internal_default_instance(); } void Int64List::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.Int64List) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; value_.Clear(); _internal_metadata_.Clear(); } bool Int64List::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.Int64List) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated int64 value = 1 [packed = true]; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, this->mutable_value()))); } else if ( static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( 1, 10u, input, this->mutable_value()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.Int64List) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.Int64List) return false; #undef DO_ } void Int64List::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.Int64List) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int64 value = 1 [packed = true]; if (this->value_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(static_cast< ::google::protobuf::uint32>( _value_cached_byte_size_)); } for (int i = 0, n = this->value_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt64NoTag( this->value(i), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.Int64List) } ::google::protobuf::uint8* Int64List::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.Int64List) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated int64 value = 1 [packed = true]; if (this->value_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( static_cast< ::google::protobuf::int32>( _value_cached_byte_size_), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt64NoTagToArray(this->value_, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.Int64List) return target; } size_t Int64List::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.Int64List) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated int64 value = 1 [packed = true]; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int64Size(this->value_); if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( static_cast< ::google::protobuf::int32>(data_size)); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _value_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Int64List::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.Int64List) GOOGLE_DCHECK_NE(&from, this); const Int64List* source = ::google::protobuf::internal::DynamicCastToGenerated<const Int64List>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.Int64List) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.Int64List) MergeFrom(*source); } } void Int64List::MergeFrom(const Int64List& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.Int64List) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; value_.MergeFrom(from.value_); } void Int64List::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.Int64List) if (&from == this) return; Clear(); MergeFrom(from); } void Int64List::CopyFrom(const Int64List& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.Int64List) if (&from == this) return; Clear(); MergeFrom(from); } bool Int64List::IsInitialized() const { return true; } void Int64List::Swap(Int64List* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { Int64List* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void Int64List::UnsafeArenaSwap(Int64List* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void Int64List::InternalSwap(Int64List* other) { using std::swap; value_.InternalSwap(&other->value_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata Int64List::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void Feature::InitAsDefaultInstance() { ::diplomacy::tensorflow::_Feature_default_instance_.bytes_list_ = const_cast< ::diplomacy::tensorflow::BytesList*>( ::diplomacy::tensorflow::BytesList::internal_default_instance()); ::diplomacy::tensorflow::_Feature_default_instance_.float_list_ = const_cast< ::diplomacy::tensorflow::FloatList*>( ::diplomacy::tensorflow::FloatList::internal_default_instance()); ::diplomacy::tensorflow::_Feature_default_instance_.int64_list_ = const_cast< ::diplomacy::tensorflow::Int64List*>( ::diplomacy::tensorflow::Int64List::internal_default_instance()); } void Feature::set_allocated_bytes_list(::diplomacy::tensorflow::BytesList* bytes_list) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_kind(); if (bytes_list) { ::google::protobuf::Arena* submessage_arena = ::google::protobuf::Arena::GetArena(bytes_list); if (message_arena != submessage_arena) { bytes_list = ::google::protobuf::internal::GetOwnedMessage( message_arena, bytes_list, submessage_arena); } set_has_bytes_list(); kind_.bytes_list_ = bytes_list; } // @@protoc_insertion_point(field_set_allocated:diplomacy.tensorflow.Feature.bytes_list) } void Feature::set_allocated_float_list(::diplomacy::tensorflow::FloatList* float_list) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_kind(); if (float_list) { ::google::protobuf::Arena* submessage_arena = ::google::protobuf::Arena::GetArena(float_list); if (message_arena != submessage_arena) { float_list = ::google::protobuf::internal::GetOwnedMessage( message_arena, float_list, submessage_arena); } set_has_float_list(); kind_.float_list_ = float_list; } // @@protoc_insertion_point(field_set_allocated:diplomacy.tensorflow.Feature.float_list) } void Feature::set_allocated_int64_list(::diplomacy::tensorflow::Int64List* int64_list) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_kind(); if (int64_list) { ::google::protobuf::Arena* submessage_arena = ::google::protobuf::Arena::GetArena(int64_list); if (message_arena != submessage_arena) { int64_list = ::google::protobuf::internal::GetOwnedMessage( message_arena, int64_list, submessage_arena); } set_has_int64_list(); kind_.int64_list_ = int64_list; } // @@protoc_insertion_point(field_set_allocated:diplomacy.tensorflow.Feature.int64_list) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Feature::kBytesListFieldNumber; const int Feature::kFloatListFieldNumber; const int Feature::kInt64ListFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Feature::Feature() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.Feature) } Feature::Feature(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.Feature) } Feature::Feature(const Feature& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_kind(); switch (from.kind_case()) { case kBytesList: { mutable_bytes_list()->::diplomacy::tensorflow::BytesList::MergeFrom(from.bytes_list()); break; } case kFloatList: { mutable_float_list()->::diplomacy::tensorflow::FloatList::MergeFrom(from.float_list()); break; } case kInt64List: { mutable_int64_list()->::diplomacy::tensorflow::Int64List::MergeFrom(from.int64_list()); break; } case KIND_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.Feature) } void Feature::SharedCtor() { clear_has_kind(); } Feature::~Feature() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.Feature) SharedDtor(); } void Feature::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); if (has_kind()) { clear_kind(); } } void Feature::ArenaDtor(void* object) { Feature* _this = reinterpret_cast< Feature* >(object); (void)_this; } void Feature::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Feature::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Feature::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Feature& Feature::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Feature.base); return *internal_default_instance(); } void Feature::clear_kind() { // @@protoc_insertion_point(one_of_clear_start:diplomacy.tensorflow.Feature) switch (kind_case()) { case kBytesList: { if (GetArenaNoVirtual() == NULL) { delete kind_.bytes_list_; } break; } case kFloatList: { if (GetArenaNoVirtual() == NULL) { delete kind_.float_list_; } break; } case kInt64List: { if (GetArenaNoVirtual() == NULL) { delete kind_.int64_list_; } break; } case KIND_NOT_SET: { break; } } _oneof_case_[0] = KIND_NOT_SET; } void Feature::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.Feature) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; clear_kind(); _internal_metadata_.Clear(); } bool Feature::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.Feature) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // .diplomacy.tensorflow.BytesList bytes_list = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_bytes_list())); } else { goto handle_unusual; } break; } // .diplomacy.tensorflow.FloatList float_list = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u /* 18 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_float_list())); } else { goto handle_unusual; } break; } // .diplomacy.tensorflow.Int64List int64_list = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u /* 26 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_int64_list())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.Feature) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.Feature) return false; #undef DO_ } void Feature::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.Feature) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .diplomacy.tensorflow.BytesList bytes_list = 1; if (has_bytes_list()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->_internal_bytes_list(), output); } // .diplomacy.tensorflow.FloatList float_list = 2; if (has_float_list()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->_internal_float_list(), output); } // .diplomacy.tensorflow.Int64List int64_list = 3; if (has_int64_list()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->_internal_int64_list(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.Feature) } ::google::protobuf::uint8* Feature::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.Feature) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .diplomacy.tensorflow.BytesList bytes_list = 1; if (has_bytes_list()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->_internal_bytes_list(), deterministic, target); } // .diplomacy.tensorflow.FloatList float_list = 2; if (has_float_list()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->_internal_float_list(), deterministic, target); } // .diplomacy.tensorflow.Int64List int64_list = 3; if (has_int64_list()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->_internal_int64_list(), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.Feature) return target; } size_t Feature::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.Feature) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } switch (kind_case()) { // .diplomacy.tensorflow.BytesList bytes_list = 1; case kBytesList: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *kind_.bytes_list_); break; } // .diplomacy.tensorflow.FloatList float_list = 2; case kFloatList: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *kind_.float_list_); break; } // .diplomacy.tensorflow.Int64List int64_list = 3; case kInt64List: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *kind_.int64_list_); break; } case KIND_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Feature::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.Feature) GOOGLE_DCHECK_NE(&from, this); const Feature* source = ::google::protobuf::internal::DynamicCastToGenerated<const Feature>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.Feature) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.Feature) MergeFrom(*source); } } void Feature::MergeFrom(const Feature& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.Feature) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; switch (from.kind_case()) { case kBytesList: { mutable_bytes_list()->::diplomacy::tensorflow::BytesList::MergeFrom(from.bytes_list()); break; } case kFloatList: { mutable_float_list()->::diplomacy::tensorflow::FloatList::MergeFrom(from.float_list()); break; } case kInt64List: { mutable_int64_list()->::diplomacy::tensorflow::Int64List::MergeFrom(from.int64_list()); break; } case KIND_NOT_SET: { break; } } } void Feature::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.Feature) if (&from == this) return; Clear(); MergeFrom(from); } void Feature::CopyFrom(const Feature& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.Feature) if (&from == this) return; Clear(); MergeFrom(from); } bool Feature::IsInitialized() const { return true; } void Feature::Swap(Feature* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { Feature* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void Feature::UnsafeArenaSwap(Feature* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void Feature::InternalSwap(Feature* other) { using std::swap; swap(kind_, other->kind_); swap(_oneof_case_[0], other->_oneof_case_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata Feature::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== Features_FeatureEntry_DoNotUse::Features_FeatureEntry_DoNotUse() {} Features_FeatureEntry_DoNotUse::Features_FeatureEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void Features_FeatureEntry_DoNotUse::MergeFrom(const Features_FeatureEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata Features_FeatureEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[4]; } void Features_FeatureEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void Features::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Features::kFeatureFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Features::Features() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.Features) } Features::Features(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), feature_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.Features) } Features::Features(const Features& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); feature_.MergeFrom(from.feature_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.Features) } void Features::SharedCtor() { } Features::~Features() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.Features) SharedDtor(); } void Features::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void Features::ArenaDtor(void* object) { Features* _this = reinterpret_cast< Features* >(object); (void)_this; } void Features::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void Features::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* Features::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Features& Features::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_Features.base); return *internal_default_instance(); } void Features::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.Features) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; feature_.Clear(); _internal_metadata_.Clear(); } bool Features::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.Features) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<string, .diplomacy.tensorflow.Feature> feature = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { Features_FeatureEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< Features_FeatureEntry_DoNotUse, ::std::string, ::diplomacy::tensorflow::Feature, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 >, ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature > > parser(&feature_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.Features.FeatureEntry.key")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.Features) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.Features) return false; #undef DO_ } void Features::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.Features) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.Feature> feature = 1; if (!this->feature().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.Features.FeatureEntry.key"); } }; if (output->IsSerializationDeterministic() && this->feature().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->feature().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator it = this->feature().begin(); it != this->feature().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(feature_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator it = this->feature().begin(); it != this->feature().end(); ++it) { entry.reset(feature_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.Features) } ::google::protobuf::uint8* Features::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.Features) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.Feature> feature = 1; if (!this->feature().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.Features.FeatureEntry.key"); } }; if (deterministic && this->feature().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->feature().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator it = this->feature().begin(); it != this->feature().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(feature_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator it = this->feature().begin(); it != this->feature().end(); ++it) { entry.reset(feature_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.Features) return target; } size_t Features::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.Features) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, .diplomacy.tensorflow.Feature> feature = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->feature_size()); { ::std::unique_ptr<Features_FeatureEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::Feature >::const_iterator it = this->feature().begin(); it != this->feature().end(); ++it) { if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } entry.reset(feature_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Features::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.Features) GOOGLE_DCHECK_NE(&from, this); const Features* source = ::google::protobuf::internal::DynamicCastToGenerated<const Features>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.Features) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.Features) MergeFrom(*source); } } void Features::MergeFrom(const Features& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.Features) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; feature_.MergeFrom(from.feature_); } void Features::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.Features) if (&from == this) return; Clear(); MergeFrom(from); } void Features::CopyFrom(const Features& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.Features) if (&from == this) return; Clear(); MergeFrom(from); } bool Features::IsInitialized() const { return true; } void Features::Swap(Features* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { Features* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void Features::UnsafeArenaSwap(Features* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void Features::InternalSwap(Features* other) { using std::swap; feature_.Swap(&other->feature_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata Features::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void FeatureList::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FeatureList::kFeatureFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FeatureList::FeatureList() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.FeatureList) } FeatureList::FeatureList(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), feature_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.FeatureList) } FeatureList::FeatureList(const FeatureList& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), feature_(from.feature_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.FeatureList) } void FeatureList::SharedCtor() { } FeatureList::~FeatureList() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.FeatureList) SharedDtor(); } void FeatureList::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void FeatureList::ArenaDtor(void* object) { FeatureList* _this = reinterpret_cast< FeatureList* >(object); (void)_this; } void FeatureList::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FeatureList::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FeatureList::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const FeatureList& FeatureList::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureList.base); return *internal_default_instance(); } void FeatureList::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.FeatureList) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; feature_.Clear(); _internal_metadata_.Clear(); } bool FeatureList::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.FeatureList) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .diplomacy.tensorflow.Feature feature = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_feature())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.FeatureList) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.FeatureList) return false; #undef DO_ } void FeatureList::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.FeatureList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .diplomacy.tensorflow.Feature feature = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->feature_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->feature(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.FeatureList) } ::google::protobuf::uint8* FeatureList::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.FeatureList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .diplomacy.tensorflow.Feature feature = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->feature_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->feature(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.FeatureList) return target; } size_t FeatureList::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.FeatureList) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .diplomacy.tensorflow.Feature feature = 1; { unsigned int count = static_cast<unsigned int>(this->feature_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->feature(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void FeatureList::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.FeatureList) GOOGLE_DCHECK_NE(&from, this); const FeatureList* source = ::google::protobuf::internal::DynamicCastToGenerated<const FeatureList>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.FeatureList) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.FeatureList) MergeFrom(*source); } } void FeatureList::MergeFrom(const FeatureList& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.FeatureList) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; feature_.MergeFrom(from.feature_); } void FeatureList::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.FeatureList) if (&from == this) return; Clear(); MergeFrom(from); } void FeatureList::CopyFrom(const FeatureList& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.FeatureList) if (&from == this) return; Clear(); MergeFrom(from); } bool FeatureList::IsInitialized() const { return true; } void FeatureList::Swap(FeatureList* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { FeatureList* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void FeatureList::UnsafeArenaSwap(FeatureList* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void FeatureList::InternalSwap(FeatureList* other) { using std::swap; CastToBase(&feature_)->InternalSwap(CastToBase(&other->feature_)); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata FeatureList::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== FeatureLists_FeatureListEntry_DoNotUse::FeatureLists_FeatureListEntry_DoNotUse() {} FeatureLists_FeatureListEntry_DoNotUse::FeatureLists_FeatureListEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void FeatureLists_FeatureListEntry_DoNotUse::MergeFrom(const FeatureLists_FeatureListEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata FeatureLists_FeatureListEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[7]; } void FeatureLists_FeatureListEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void FeatureLists::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FeatureLists::kFeatureListFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FeatureLists::FeatureLists() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.FeatureLists) } FeatureLists::FeatureLists(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), feature_list_(arena) { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists.base); SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:diplomacy.tensorflow.FeatureLists) } FeatureLists::FeatureLists(const FeatureLists& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); feature_list_.MergeFrom(from.feature_list_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.FeatureLists) } void FeatureLists::SharedCtor() { } FeatureLists::~FeatureLists() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.FeatureLists) SharedDtor(); } void FeatureLists::SharedDtor() { GOOGLE_DCHECK(GetArenaNoVirtual() == NULL); } void FeatureLists::ArenaDtor(void* object) { FeatureLists* _this = reinterpret_cast< FeatureLists* >(object); (void)_this; } void FeatureLists::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void FeatureLists::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* FeatureLists::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const FeatureLists& FeatureLists::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::scc_info_FeatureLists.base); return *internal_default_instance(); } void FeatureLists::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.FeatureLists) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; feature_list_.Clear(); _internal_metadata_.Clear(); } bool FeatureLists::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.FeatureLists) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { FeatureLists_FeatureListEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< FeatureLists_FeatureListEntry_DoNotUse, ::std::string, ::diplomacy::tensorflow::FeatureList, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 >, ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList > > parser(&feature_list_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.FeatureLists.FeatureListEntry.key")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.FeatureLists) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.FeatureLists) return false; #undef DO_ } void FeatureLists::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.FeatureLists) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1; if (!this->feature_list().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.FeatureLists.FeatureListEntry.key"); } }; if (output->IsSerializationDeterministic() && this->feature_list().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->feature_list().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator it = this->feature_list().begin(); it != this->feature_list().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(feature_list_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator it = this->feature_list().begin(); it != this->feature_list().end(); ++it) { entry.reset(feature_list_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.FeatureLists) } ::google::protobuf::uint8* FeatureLists::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.FeatureLists) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1; if (!this->feature_list().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.FeatureLists.FeatureListEntry.key"); } }; if (deterministic && this->feature_list().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->feature_list().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator it = this->feature_list().begin(); it != this->feature_list().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(feature_list_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator it = this->feature_list().begin(); it != this->feature_list().end(); ++it) { entry.reset(feature_list_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.FeatureLists) return target; } size_t FeatureLists::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.FeatureLists) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, .diplomacy.tensorflow.FeatureList> feature_list = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->feature_list_size()); { ::std::unique_ptr<FeatureLists_FeatureListEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::FeatureList >::const_iterator it = this->feature_list().begin(); it != this->feature_list().end(); ++it) { if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } entry.reset(feature_list_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void FeatureLists::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.FeatureLists) GOOGLE_DCHECK_NE(&from, this); const FeatureLists* source = ::google::protobuf::internal::DynamicCastToGenerated<const FeatureLists>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.FeatureLists) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.FeatureLists) MergeFrom(*source); } } void FeatureLists::MergeFrom(const FeatureLists& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.FeatureLists) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; feature_list_.MergeFrom(from.feature_list_); } void FeatureLists::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.FeatureLists) if (&from == this) return; Clear(); MergeFrom(from); } void FeatureLists::CopyFrom(const FeatureLists& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.FeatureLists) if (&from == this) return; Clear(); MergeFrom(from); } bool FeatureLists::IsInitialized() const { return true; } void FeatureLists::Swap(FeatureLists* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { FeatureLists* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void FeatureLists::UnsafeArenaSwap(FeatureLists* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void FeatureLists::InternalSwap(FeatureLists* other) { using std::swap; feature_list_.Swap(&other->feature_list_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata FeatureLists::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fexample_2ffeature_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace tensorflow } // namespace diplomacy namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::BytesList* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::BytesList >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::BytesList >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FloatList* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FloatList >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FloatList >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Int64List* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Int64List >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Int64List >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Feature* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Feature >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Feature >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Features_FeatureEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::Features* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::Features >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::Features >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FeatureList* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FeatureList >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FeatureList >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FeatureLists_FeatureListEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::FeatureLists* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::FeatureLists >(Arena* arena) { return Arena::CreateMessageInternal< ::diplomacy::tensorflow::FeatureLists >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
diplomacy/research
diplomacy_research/proto/diplomacy_tensorflow/core/example/feature.pb.cc
C++
mit
110,384
require 'spec_helper' require 'gitnesse/cli' module Gitnesse describe Cli, type: :cli do let(:help) do <<-EOS USAGE: gitnesse push Pushes local features to remote git-based wiki Pushes the local features files to the remote git-based wiki, creating/updating wiki pages as necessary. Examples: gitnesse push # will push local features to remote wiki EOS end it "has help info" do expect(gitnesse("help push")).to eq help end end end
hybridgroup/gitnesse
spec/lib/cli/task/push_spec.rb
Ruby
mit
478
// // This file is auto-generated. Please don't modify it! // package org.opencv.objdetect; import org.opencv.core.Mat; import org.opencv.core.MatOfDouble; import org.opencv.core.MatOfInt; import org.opencv.core.MatOfRect; import org.opencv.core.Size; // C++: class CascadeClassifier //javadoc: CascadeClassifier public class CascadeClassifier { protected final long nativeObj; protected CascadeClassifier(long addr) { nativeObj = addr; } // // C++: CascadeClassifier() // //javadoc: CascadeClassifier::CascadeClassifier() public CascadeClassifier() { nativeObj = CascadeClassifier_0(); return; } // // C++: CascadeClassifier(String filename) // //javadoc: CascadeClassifier::CascadeClassifier(filename) public CascadeClassifier(String filename) { nativeObj = CascadeClassifier_1(filename); return; } // // C++: bool load(String filename) // //javadoc: CascadeClassifier::convert(oldcascade, newcascade) public static boolean convert(String oldcascade, String newcascade) { boolean retVal = convert_0(oldcascade, newcascade); return retVal; } // // C++: bool empty() // // C++: CascadeClassifier() private static native long CascadeClassifier_0(); // // C++: bool read(FileNode node) // // Unknown type 'FileNode' (I), skipping the function // // C++: void detectMultiScale(Mat image, vector_Rect& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) // // C++: CascadeClassifier(String filename) private static native long CascadeClassifier_1(String filename); // C++: bool load(String filename) private static native boolean load_0(long nativeObj, String filename); // // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& numDetections, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) // // C++: bool empty() private static native boolean empty_0(long nativeObj); // C++: void detectMultiScale(Mat image, vector_Rect& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) private static native void detectMultiScale_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height); // // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& rejectLevels, vector_double& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false) // private static native void detectMultiScale_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj); // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& numDetections, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size()) private static native void detectMultiScale2_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long numDetections_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height); // // C++: bool isOldFormatCascade() // private static native void detectMultiScale2_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long numDetections_mat_nativeObj); // // C++: Size getOriginalWindowSize() // // C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& rejectLevels, vector_double& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false) private static native void detectMultiScale3_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long rejectLevels_mat_nativeObj, long levelWeights_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height, boolean outputRejectLevels); // // C++: int getFeatureType() // private static native void detectMultiScale3_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long rejectLevels_mat_nativeObj, long levelWeights_mat_nativeObj); // // C++: static bool convert(String oldcascade, String newcascade) // // C++: bool isOldFormatCascade() private static native boolean isOldFormatCascade_0(long nativeObj); // C++: Size getOriginalWindowSize() private static native double[] getOriginalWindowSize_0(long nativeObj); // C++: int getFeatureType() private static native int getFeatureType_0(long nativeObj); // C++: static bool convert(String oldcascade, String newcascade) private static native boolean convert_0(String oldcascade, String newcascade); // native support for java finalize() private static native void delete(long nativeObj); //javadoc: CascadeClassifier::load(filename) public boolean load(String filename) { boolean retVal = load_0(nativeObj, filename); return retVal; } //javadoc: CascadeClassifier::empty() public boolean empty() { boolean retVal = empty_0(nativeObj); return retVal; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, scaleFactor, minNeighbors, flags, minSize, maxSize) public void detectMultiScale(Mat image, MatOfRect objects, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize) { Mat objects_mat = objects; detectMultiScale_0(nativeObj, image.nativeObj, objects_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects) public void detectMultiScale(Mat image, MatOfRect objects) { Mat objects_mat = objects; detectMultiScale_1(nativeObj, image.nativeObj, objects_mat.nativeObj); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, numDetections, scaleFactor, minNeighbors, flags, minSize, maxSize) public void detectMultiScale2(Mat image, MatOfRect objects, MatOfInt numDetections, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize) { Mat objects_mat = objects; Mat numDetections_mat = numDetections; detectMultiScale2_0(nativeObj, image.nativeObj, objects_mat.nativeObj, numDetections_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, numDetections) public void detectMultiScale2(Mat image, MatOfRect objects, MatOfInt numDetections) { Mat objects_mat = objects; Mat numDetections_mat = numDetections; detectMultiScale2_1(nativeObj, image.nativeObj, objects_mat.nativeObj, numDetections_mat.nativeObj); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, rejectLevels, levelWeights, scaleFactor, minNeighbors, flags, minSize, maxSize, outputRejectLevels) public void detectMultiScale3(Mat image, MatOfRect objects, MatOfInt rejectLevels, MatOfDouble levelWeights, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize, boolean outputRejectLevels) { Mat objects_mat = objects; Mat rejectLevels_mat = rejectLevels; Mat levelWeights_mat = levelWeights; detectMultiScale3_0(nativeObj, image.nativeObj, objects_mat.nativeObj, rejectLevels_mat.nativeObj, levelWeights_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height, outputRejectLevels); return; } //javadoc: CascadeClassifier::detectMultiScale(image, objects, rejectLevels, levelWeights) public void detectMultiScale3(Mat image, MatOfRect objects, MatOfInt rejectLevels, MatOfDouble levelWeights) { Mat objects_mat = objects; Mat rejectLevels_mat = rejectLevels; Mat levelWeights_mat = levelWeights; detectMultiScale3_1(nativeObj, image.nativeObj, objects_mat.nativeObj, rejectLevels_mat.nativeObj, levelWeights_mat.nativeObj); return; } //javadoc: CascadeClassifier::isOldFormatCascade() public boolean isOldFormatCascade() { boolean retVal = isOldFormatCascade_0(nativeObj); return retVal; } //javadoc: CascadeClassifier::getOriginalWindowSize() public Size getOriginalWindowSize() { Size retVal = new Size(getOriginalWindowSize_0(nativeObj)); return retVal; } //javadoc: CascadeClassifier::getFeatureType() public int getFeatureType() { int retVal = getFeatureType_0(nativeObj); return retVal; } @Override protected void finalize() throws Throwable { delete(nativeObj); } }
MHS-FIRSTrobotics/TeamClutch-FTC2016
OpenCV/src/main/java/org/opencv/objdetect/CascadeClassifier.java
Java
mit
9,327
package GlidersGrid; import java.util.Iterator; import repast.simphony.context.Context; import repast.simphony.engine.schedule.ScheduledMethod; import repast.simphony.query.space.grid.MooreQuery; import repast.simphony.space.grid.Grid; import repast.simphony.space.grid.GridPoint; import repast.simphony.util.ContextUtils; public class Dead { private Grid<Object> grid; private int state; public Dead(Grid<Object> grid) { this.grid = grid; } // calculate the state for the next time tick for dead cells @ScheduledMethod(start = 1, interval = 1, priority = 4) public void step1() { MooreQuery<Dead> query = new MooreQuery(grid, this); int neighbours = 0; for (Object o : query.query()) { if (o instanceof Living) { neighbours++; if (neighbours ==3) { } } } if (neighbours == 3) { state = 1; } else { state = 0; } } // visualise the change into the underlay and grid @ScheduledMethod(start = 1, interval = 1, priority = 1) public void step2() { if (state == 1) { GridPoint gpt = grid.getLocation(this); Context<Object> context = ContextUtils.getContext(this); context.remove(this); Living livingCell = new Living(grid); context.add(livingCell); grid.moveTo(livingCell, gpt.getX(), gpt.getY()); context.add(livingCell); } } }
ZawilecxD/Social-Network-Simulator
GlidersGrid/src/GlidersGrid/Dead.java
Java
mit
1,307
#ifndef LM75_H_ #define LM75_H_ /******************************************************************************/ /** \file Lm75.h ******************************************************************************* * * \brief This module allows to read the temperature of an attached lm75 * device. * <p> * The LM75A is an industry-standard digital temperature sensor * with an integrated Sigma-Delta analog-to-digital converter and * I2C interface. The LM75A provides 9-bit digital temperature * readings with an accuracy of +/-2°C from -25°C to 100°C and * +/-3°C over -55°C to 125°C. The temperature data output of the * LM75 is available at all times via the I2C bus. * * \author wht4 * ******************************************************************************/ /* * function readTempLm75 * ******************************************************************************/ //----- Header-Files ----------------------------------------------------------- #include <stdint.h> #include "BBBTypes.h" //----- Macros ----------------------------------------------------------------- #define LM75_DEVICE "/dev/i2c-1" #define LM75_ADDR ( 0x48 ) //----- Data types ------------------------------------------------------------- //----- Function prototypes ---------------------------------------------------- extern BBBError readTempLm75(int32_t *ps32Temp); //----- Data ------------------------------------------------------------------- #endif /* LM75_H_ */
stocyr/Webhuesli
Server/hw/Lm75.h
C
mit
1,624
#region Copyright (c) 2009 S. van Deursen /* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent * manner. * * To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/ * * Copyright (c) 2009 S. van Deursen * * 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. */ #endregion using System; using System.ComponentModel; namespace CuttingEdge.Conditions { /// <summary> /// The RequiresValidator can be used for precondition checks. /// </summary> /// <typeparam name="T">The type of the argument to be validated</typeparam> internal class RequiresValidator<T> : ConditionValidator<T> { internal RequiresValidator(string argumentName, T value) : base(argumentName, value) { } internal virtual Exception BuildExceptionBasedOnViolationType(ConstraintViolationType type, string message) { switch (type) { case ConstraintViolationType.OutOfRangeViolation: return new ArgumentOutOfRangeException(this.ArgumentName, message); case ConstraintViolationType.InvalidEnumViolation: string enumMessage = this.BuildInvalidEnumArgumentExceptionMessage(message); return new InvalidEnumArgumentException(enumMessage); default: if (this.Value != null) { return new ArgumentException(message, this.ArgumentName); } else { return new ArgumentNullException(this.ArgumentName, message); } } } /// <summary>Throws an exception.</summary> /// <param name="condition">Describes the condition that doesn't hold, e.g., "Value should not be /// null".</param> /// <param name="additionalMessage">An additional message that will be appended to the exception /// message, e.g. "The actual value is 3.". This value may be null or empty.</param> /// <param name="type">Gives extra information on the exception type that must be build. The actual /// implementation of the validator may ignore some or all values.</param> protected override void ThrowExceptionCore(string condition, string additionalMessage, ConstraintViolationType type) { string message = BuildExceptionMessage(condition, additionalMessage); Exception exceptionToThrow = this.BuildExceptionBasedOnViolationType(type, message); throw exceptionToThrow; } private static string BuildExceptionMessage(string condition, string additionalMessage) { if (!String.IsNullOrEmpty(additionalMessage)) { return condition + ". " + additionalMessage; } else { return condition + "."; } } private string BuildInvalidEnumArgumentExceptionMessage(string message) { ArgumentException argumentException = new ArgumentException(message, this.ArgumentName); // Returns the message formatted according to the current culture. // Note that the 'Parameter name' part of the message is culture sensitive. return argumentException.Message; } } }
conditions/conditions
CuttingEdge.Conditions/RequiresValidator.cs
C#
mit
4,490
(function(){ 'use strict'; function ListService($http){ this.getList = function(list_id){ return $http.get('/lists/' + list_id + ".json") } } ListService.$inject = ['$http'] angular .module('app') .service('ListService', ListService) }())
jd2rogers2/presently
old-code/ListService.js
JavaScript
mit
273
angular.module('movieApp') .directive('movieResult', function () { var directive = { restrict: 'E', replace: true, scope: { result: '=result' }, template: [ '<div class="row">', '<div class="col-sm-4">', '<img ng-src="{{result.Poster}}" alt="{{result.Title}}" width="220px">', '</div>', '<div class="col-sm-8">', '<h3>{{result.Title}}</h3>', '<p>{{result.Plot}}</p>', '<p><strong>Director:</strong> {{result.Director}}</p>', '<p><strong>Actors:</strong> {{result.Actors}}</p>', '<p><strong>Released:</strong> {{result.Released}} ({{result.Released | fromNow}})</p>', '<p><strong>Genre:</strong> {{result.Genre}}</p>', '</div>', '</div>' ].join('') }; return directive; });
cjp666/MovieApp
src/movie-app/movie-result.directive.js
JavaScript
mit
751
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目&nbsp;</b></th><td class="std2">博學洽聞</td></tr> <tr><th class="std1"><b>注音&nbsp;</b></th><td class="std2">ㄅㄛ<sup class="subfont">ˊ</sup> ㄒㄩㄝ<sup class="subfont">ˊ</sup> ㄑ|ㄚ<sup class="subfont">ˋ</sup> ㄨㄣ<sup class="subfont">ˊ</sup> (又音)ㄅㄛ<sup class="subfont">ˊ</sup> ㄒㄩㄝ<sup class="subfont">ˊ</sup> ㄒ|ㄚ<sup class="subfont">ˊ</sup> ㄨㄣ</td></tr> <tr><th class="std1"><b>漢語拼音&nbsp;</b></th><td class="std2"><font class="english_word">bó xué qià wén bó xué xiá wēn</font></td></tr> <tr><th class="std1"><b>釋義&nbsp;</b></th><td class="std2">學問廣博,見識豐富。晉書˙卷三十九˙荀顗傳:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>性至孝,總角知名,博學洽聞,理思周密。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>亦作<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>博學多聞<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>。</td></tr> <tr><th class="std1"><b><font class="fltypefont">附錄</font>&nbsp;</b></th><td class="std2">修訂本參考資料</td></tr> </td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
BuzzAcademy/idioms-moe-unformatted-data
all-data/24000-24999/24914-22.html
HTML
mit
1,712
#include<stdio.h> #include<math.h> #include<conio.h> #include<ctype.h> int i,j,cash=100; void wheel(); void game(int r); void game_over(); int suit_bet(); int cash_bet(); int roll_wheel(); int roll_dice(); void wheel_count(int c,int h,int s); void dice_count(int d,int h); int w[9][9]={ {32,32,32,32,2,32,32,32,32}, {32,32,32,3,5,4,32,32,32}, {32,32,5,4,3,6,5,32,32}, {32,4,3,6,5,3,4,6,32}, {2,6,5,4,15,5,3,6,2}, {32,3,6,3,4,5,4,3,32}, {32,32,5,6,3,4,5,32,32}, {32,32,32,4,6,6,32,32,32}, {32,32,32,32,2,32,32,32,32} }; void main(){ int round; char e; //game intro printf("\t\t\tWelcome to Roullette\n\n"); //game instruction printf("Game Instructions:\n\n"); printf("Diamond(d)=%c Hearts(h)=%c Clubs(c)=%c Spades(s)=%c Jack(j)=%c Bull's Eye=%c \n",4,3,5,6,2,15); printf("\n-The game starts with $100 \n-You chooses how many rounds to play \n-Then bet with cash on Suits,Jack and Null spaces of the wheel on which the dice will hit \n-A dice is thrown \n-If the dice hits the betting suit then you earn the betting cash.\n"); printf("-If the dice hits suits other than the betting one then you lose $10\n"); printf("-If it hits any of the Null spaces which is not bet then you lose bet cash \n"); printf("-If it hits the Jack which is bet then you earn the beting cash + $100 otherwise you earn only the bet cash \n"); printf("-Your cash is doubled if you hit the Bull's Eye \n"); printf("\n\n"); printf("Press Enter to Start Game"); scanf("%c",&e); if(e=='\n'){ printf("\nThe Roullette Wheel: \n\n"); wheel(); printf("\n\nYour Cash: $%d",cash); printf("\n\nHow many rounds you want to play: "); scanf("%d",&round); printf("\n\nYour Cash : $%d \n",cash); game(round); printf("\n\n"); printf("\t %d rounds completed!! \n\n\tYou Earned Total $%d !!\n\n",round,cash); } else{ printf("\nSorry!!\nYou Entered The Wrong Key!!\n"); } } //game on void game(int r){ int count; for(count=1;count<=r;count++){ int suit,ca,hit,dice; fflush(stdin); suit=suit_bet(); ca=cash_bet(); hit=roll_wheel(); dice=roll_dice(); wheel_count(ca,hit,suit); dice_count(dice,hit); printf("\n"); wheel(); printf("\n\nCash: $%d \nSuit Bet: %c \nCash Bet: $%d \nWheel Hit: %c \nDice: %d\n\n\n",cash,suit,ca,hit,dice); } } //show wheel void wheel(){ for(i=0;i<9;i++){ for(j=0;j<9;j++){ printf("%c ",w[i][j]); } printf("\n"); } } //betting on suit int suit_bet(){ char s; int k; printf("Suit Bet: "); s=getchar(); s=tolower(s); switch(s){ case 'h': k=3; break; case 'd': k=4; break; case 'c': k=5; break; case 's': k=6; break; case 'j': k=2; break; case 'n': k=32; break; default: k=0; } return k; } //betting on cash int cash_bet(){ int c; printf("Cash Bet: $"); scanf("%d",&c); return c; } //rolling the wheel int roll_wheel(){ float m,n; int wh1,wh2,res; m=rand()/32768.0; n=rand()/32768.0; wh1=(int) (m*9); wh2=(int) (n*9); res=w[wh1][wh2]; w[wh1][wh2]=249; return res; } //rolling the dice int roll_dice(){ float d; int res; d=rand()/32768.0; res=(int) (d*6)+1; return res; } //cash update form wheel hit void wheel_count(int c,int h,int s){ if(h==s){ if(h==2){ cash=cash+c+100; }else{ cash=cash+c; } } else if(h==3 || h==4 || h==5 || h==6){ cash=cash-10; } else if(h==32){ cash=cash-c; } else if(h==2){ cash=cash+c; } if(s==2 && h!=2){ cash=cash-50; } } //cash update from dice throw void dice_count(int d,int h){ if(h==3 || h==4 || h==5 || h==6){ if(d==6){ cash=cash+20; } } else if(h==15){ cash=2*cash; } else if(h==249){ if(d==6){ cash=cash+20; } } } //game end/over
abrarShariar/Roll-the-dice
final.c
C
mit
4,262
/* eslint-env mocha */ const { expect } = chai; import React from './React'; import TestUtils from './TestUtils'; describe('React components', () => { it('should find valid xpath in react component', () => { const component = TestUtils.renderIntoDocument(<blink>hi</blink>); expect(component).to.have.xpath('//blink'); }); it('should find valid xpath in react component twice', () => { const component = TestUtils.renderIntoDocument(<blink>hi</blink>); expect(component).to.have.xpath('//blink'); expect(component).to.have.xpath('//blink'); }); describe('when it does not find valid xpath in react component', () => { it('should throw', () => { const component = TestUtils.renderIntoDocument(<blink>hi</blink>); expect(() => { expect(component).to.have.xpath('//h1'); }).to.throw('to have xpath \'//h1\''); }); it('should throw with outerHTML of the component', () => { const component = TestUtils.renderIntoDocument(<blink>hi</blink>); expect(() => { expect(component).to.have.xpath('//h1'); }).to.throw('hi</blink>'); }); }); });
relekang/chai-have-xpath
test/react-tests.js
JavaScript
mit
1,136
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Sandsound</title> <link rel="stylesheet" href="/css/reset.css"> <link rel="stylesheet" href="/css/style.css"> </head> <body> <canvas id="canvas" class="background"></canvas> <!-- Ne s'affiche que si sur mobile :) --> <div class="mobile"> <a href="/"><img class="logo" src="/css/img/logo.png" alt="SandSound"></a> <p>Pour profiter de l'expérience SandSound, rendez-vous sur une tablette ou desktop !</p> </div> <div class="sidebar"> <a href="/"><img class="logo" src="/css/img/logo.png" alt="SandSound"></a> <nav> <ul> <li class="active"><a href="{{ route('profile', ['name' => $user->name]) }}">Profil</a></li> <li>{{ link_to_route('room', 'Rejoindre un salon') }}</li> <li>{{ link_to_route('form-private', 'Nouveau salon') }}</li> <li>{{ link_to_route('rank', 'Classement') }}</li> </ul> </nav> </div> <div class="content"> <div class="content__infos"> <ul> <li class="content__infos--pseudo">{{ $user->name }}</li> <li class="content__infos--pts">{{ $user->score->xp }}<span> pts </span></li> <li class="content__infos--niv"><span>Niv :</span> {{ $user->score->lvl_total }}</li> </ul> </div> <div class="content__title"> <h1>| {{ $user->name }}</h1> <div class="content__title--intro"> <p>{{ $user->name }} est niveau <span>{{ $user->score->lvl_total }}</span>.</p> </div> <div class="content__title--explain"> <p> Découvrez les dernières musiques de <span>{{ $user->name }}</span>. </p> </div> <div class="content__experiencepre"> <ul> <li class="content__experiencepre--bass">| Bass : <span>{{ $user->score->lvl_bass }}</span></li> <li class="content__experiencepre--pads">| Ambiance : <span>{{ $user->score->lvl_ambiance }}</span></li> <li class="content__experiencepre--drum">| Drum : <span>{{ $user->score->lvl_drum }}</span></li> <li class="content__experiencepre--lead">| Lead : <span>{{ $user->score->lvl_lead }}</span></li> </ul> </div> <div class="content__experience"> <ul> <li class="content__experience--bass"></li> <li class="content__experience--pads"></li> <li class="content__experience--drum"></li> <li class="content__experience--lead"></li> </ul> </div> @if (count($songs)) <div class="content__title--score"> <table> <thead> <tr> <th scope="col">Nom de la chanson :</th> <th scope="col">Score :</th> </tr> <tbody> @foreach ($songs as $song) <tr> <td> {{ $song->name }}</td> <td>{{ $song->score }}</td> </tr> @endforeach </tbody> </table> </div> @endif </div> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src="/js/index.js"></script> </body> </html>
vbillardm/Projet_Fin_ann-e
resources/views/profile/detail.blade.php
PHP
mit
3,476
require 'lapine/test/exchange' module Lapine module Test module RSpecHelper def self.setup(_example = nil) RSpec::Mocks::AllowanceTarget.new(Lapine::Exchange).to( RSpec::Mocks::Matchers::Receive.new(:new, ->(name, properties) { Lapine::Test::Exchange.new(name, properties) }) ) end def self.teardown Lapine.close_connections! end end end end
wanelo/lapine
lib/lapine/test/rspec_helper.rb
Ruby
mit
436
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/animation/UnitBezier.h" #include <gtest/gtest.h> using namespace WebCore; namespace { TEST(UnitBezierTest, BasicUse) { UnitBezier bezier(0.5, 1.0, 0.5, 1.0); EXPECT_EQ(0.875, bezier.solve(0.5, 0.005)); } TEST(UnitBezierTest, Overshoot) { UnitBezier bezier(0.5, 2.0, 0.5, 2.0); EXPECT_EQ(1.625, bezier.solve(0.5, 0.005)); } TEST(UnitBezierTest, Undershoot) { UnitBezier bezier(0.5, -1.0, 0.5, -1.0); EXPECT_EQ(-0.625, bezier.solve(0.5, 0.005)); } TEST(UnitBezierTest, InputAtEdgeOfRange) { UnitBezier bezier(0.5, 1.0, 0.5, 1.0); EXPECT_EQ(0.0, bezier.solve(0.0, 0.005)); EXPECT_EQ(1.0, bezier.solve(1.0, 0.005)); } TEST(UnitBezierTest, InputOutOfRange) { UnitBezier bezier(0.5, 1.0, 0.5, 1.0); EXPECT_EQ(0.0, bezier.solve(-1.0, 0.005)); EXPECT_EQ(1.0, bezier.solve(2.0, 0.005)); } TEST(UnitBezierTest, InputOutOfRangeLargeEpsilon) { UnitBezier bezier(0.5, 1.0, 0.5, 1.0); EXPECT_EQ(0.0, bezier.solve(-1.0, 1.0)); EXPECT_EQ(1.0, bezier.solve(2.0, 1.0)); } } // namespace
lordmos/blink
Source/platform/animation/UnitBezierTest.cpp
C++
mit
2,438
using Brandbank.Xml.Logging; using System; namespace Brandbank.Api.Clients { public sealed class FeedbackClientLogger : IFeedbackClient { private readonly ILogger<IFeedbackClient> _logger; private readonly IFeedbackClient _feedbackClient; public FeedbackClientLogger(ILogger<IFeedbackClient> logger, IFeedbackClient feedbackClient) { _logger = logger; _feedbackClient = feedbackClient; } public int UploadCompressedFeedback(byte[] compressedFeedback) { _logger.LogDebug("Uploading compressed feedback to Brandbank"); try { var response = _feedbackClient.UploadCompressedFeedback(compressedFeedback); _logger.LogDebug(response == 0 ? "Uploaded compressed feedback to Brandbank" : $"Upload compressed feedback to Brandbank failed, response code {response}"); return response; } catch (Exception e) { _logger.LogError($"Upload compressed feedback to Brandbank failed: {e}"); throw; } } public void Dispose() { _logger.LogDebug("Disposing feedback client"); try { _feedbackClient.Dispose(); _logger.LogDebug("Disposed feedback client"); } catch (Exception e) { _logger.LogError($"Disposing feedback client failed: {e}"); throw; } } } }
Brandbank/Brandbank-Xml-And-Api-Helpers
Brandbank.Api/Clients/FeedbackClientLogger.cs
C#
mit
1,649
<?php namespace Zodream\Infrastructure\Http\Input; /** * Created by PhpStorm. * User: zx648 * Date: 2016/4/3 * Time: 9:23 */ use Zodream\Infrastructure\Base\MagicObject; abstract class BaseInput extends MagicObject { /** * 格式化 * @param array|string $data * @return array|string */ protected function _clean($data) { if (is_array($data)) { foreach ($data as $key => $value) { unset($data[$key]); $data[strtolower($this->_clean($key))] = $this->_clean($value); } } else if (defined('APP_SAFE') && APP_SAFE){ $data = htmlspecialchars($data, ENT_COMPAT); } return $data; } protected function setValues(array $data) { $this->set($this->_clean($data)); } public function get($name = null, $default = null) { return parent::get(strtolower($name), $default); } }
zx648383079/zodream
src/Infrastructure/Http/Input/BaseInput.php
PHP
mit
932
--- home: true heroImage: /sofa128.png actionText: Get Started → features: - title: Schema definition details: Strict modeling based on schema with automatic and custom type validation. - title: Database operations details: Insert, upsert and remove documents. - title: Middleware details: Support for pre and post middleware hooks. - title: Embedded documents details: Embedded documents with automatic or manual population. - title: Indexing details: Automatic indexing for performant queries using reference lookup documents. - title: Flexible API details: Use either callback or promise based API. actionLink: /guide/ footer: MIT Licensed | Copyright © 2018 - present Bojan D. --- ```js var lounge = require('lounge') lounge.connect({ connectionString: 'couchbase://127.0.0.1', bucket: 'lounge_test' }) var schema = lounge.schema({ name: String }) var Cat = lounge.model('Cat', schema) var kitty = new Cat({ name: 'Zildjian' }) kitty.save(function (err) { if (err) // ... console.log('meow') }) ```
bojand/lounge
docs/README.md
Markdown
mit
1,030
<?php /* * This file is part of the Grosona. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Grosona; use Grosona\PhpProcess\Utils\Logger; use Grosona\PhpProcess\TrobuleHandler; /** * Read configurations from the file. * * @author hchsiao */ class TroubleHandler implements TrobuleHandler { protected $logger = null; public function activate(Logger $logger) { $this->logger = $logger; } public function handle(\Exception $err) { if( is_int(stripos($err->getMessage(), "Error validating access token: Session has expired")) || is_int(stripos($err->getMessage(), "Invalid appsecret_proof")) ) { $msg = "token died\n"; echo $msg; } else if(is_int(stripos($err->getMessage(), "Access token mismatch"))) { $msg = "token confilict\n"; echo $msg; } else { $msg = (string) $err; } $this->logger->log("<Exception> $msg", Logger::LEVEL_ERROR); } public function shutdown() { $logger = $this->logger; if(!$logger instanceof Logger) { die(); } $err = error_get_last(); $errMsg = $err['message']; if(is_int(stripos($errMsg, "FacebookSDKException' with message 'Connection timed out"))) { $logger->log("facebook server down", Logger::LEVEL_WARN); } else if( is_int(stripos($errMsg, "operation failed")) || is_int(stripos($errMsg, "Gateway Time-out")) || is_int(stripos($errMsg, "HTTP request failed")) || is_int(stripos($errMsg, "Connection timed out")) || // faild to download image, will retry so it's OK is_int(stripos($errMsg, "Undefined variable: http_response_header")) || is_int(stripos($errMsg, "Stream returned an empty response")) // facebook http request failed, retry too ) { $logger->log("HTTP request failed", Logger::LEVEL_INFO); } else if($errMsg) { $type = $err['type']; $place = $err['file'] . '(' . $err['line'] . ')'; $logger->log("<Shutdown Type=$type> $errMsg at $place", Logger::LEVEL_ERROR); } } }
hchsiao/grosona
src/Grosona/TroubleHandler.php
PHP
mit
2,474
class DashboardController < ApplicationController def index end end # vim: fo=tcq
MaxMEllon/udon-dou
app/controllers/dashboard_controller.rb
Ruby
mit
87
-- 创建T_Good表 CREATE TABLE IF NOT EXISTS T_Good ( goodId INTEGER PRIMARY KEY NOT NULL, good TEXT, "createAt" TEXT DEFAULT (datetime('now', 'localtime')) );
DreamCatcherJ/shopping-cart-demo
购物车/shoppingcart-demo/tables.sql
SQL
mit
162
const getAllMatchers = require("./getAllMatchers"); describe("unit: getAllMatchers", () => { let handler; let matcherStore; beforeEach(() => { matcherStore = [{}, {}, {}]; handler = getAllMatchers(matcherStore); }); test("it should return all matchers", () => { expect(handler()).toHaveProperty("body", matcherStore); }); test("it should return a status of 200", () => { expect(handler()).toHaveProperty("status", 200); }); });
dos-j/sham-it
server/internal/getAllMatchers.test.js
JavaScript
mit
465
table { font-family: Consolas, Monaco, monospace; font-size: 1em; line-height: 1.44em; } table th, table td { padding: 0.4em 0.8em; }
spiralx/userstyle-sources
css/unpkg.com.css
CSS
mit
142
--- layout: post title: "Welcome to Jekyll!" tags: [web, jekyll] --- Vestibulum vulputate ac sem dapibus sagittis. Phasellus vestibulum ligula quam, vitae porta risus posuere sit amet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lobortis nisl ut semper suscipit. Aenean eget sem nisl. Sed gravida suscipit mauris et pellentesque. Sed eget euismod sem. Vivamus volutpat sem odio, ut hendrerit arcu tempor non. Sed at sodales nisl. Mauris dui sem, bibendum vel tortor ac, vulputate sollicitudin massa. Proin mattis rhoncus tempus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed eget metus purus. Vestibulum sagittis non velit id tempus. ![My helpful screenshot](http://trentwalton.com/assets/uploads/2013/12/work-values.jpg) ```js const options = { size: 45 }; ``` Mauris posuere arcu eu erat ullamcorper, a auctor elit semper. In quis consectetur leo. In et dictum justo. Fusce at urna ultrices, sodales lacus eget, molestie ex. In eleifend orci et ipsum lacinia, vitae fermentum augue laoreet. Sed a ultricies lorem. Pellentesque varius nisi ac neque aliquam porta. Nunc viverra imperdiet augue, quis vulputate odio pellentesque sit amet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam tristique ante et tristique euismod. Proin rutrum interdum nisl id elementum. Pellentesque lacinia velit orci, a tincidunt tortor porta id. Donec mauris urna, rhoncus nec mauris eget, suscipit feugiat risus. Maecenas in viverra metus. Nulla facilisi. Aliquam porta venenatis enim in congue. Phasellus ut suscipit libero. Vestibulum urna magna, pretium eu lorem vel, dapibus sollicitudin ligula. Maecenas varius aliquam malesuada. Donec consectetur ultricies turpis ultrices gravida. Praesent efficitur nulla ac vehicula consequat. Praesent feugiat, magna dignissim varius eleifend, ligula sapien accumsan nisi, eu tincidunt magna neque a neque. Donec interdum, magna id vestibulum suscipit, neque quam dignissim nibh, ut molestie felis purus vitae sem. Phasellus imperdiet eleifend erat ac posuere. Donec id vehicula enim. Maecenas vel blandit nisl. Sed porta convallis lacinia. Phasellus sit amet aliquet velit. Proin consectetur malesuada tortor sed consequat. Morbi arcu odio, dictum eget nibh eget, tempor gravida risus. Nulla at tortor id libero rutrum luctus et id leo. Nam dolor urna, congue eu dapibus et, ultrices eget magna. Fusce dignissim lacinia elementum. Aenean condimentum nulla iaculis velit dictum gravida. Pellentesque eleifend dignissim est, volutpat consectetur est ornare a. Vestibulum ut nulla commodo, iaculis augue sit amet, volutpat orci. Nullam sit amet lacinia justo. Mauris eu elit quam. Aliquam erat volutpat. Ut pulvinar quis enim ut placerat. Duis dictum varius iaculis. Suspendisse potenti. Nam tellus magna, consequat a dictum a, elementum a nisl. Pellentesque posuere nulla eu gravida rhoncus. Maecenas non ipsum ut felis vulputate consequat ac quis lectus. Nulla in porttitor elit. Nam at metus consectetur, sollicitudin augue ut, vulputate mi. Donec lobortis bibendum mauris vel vehicula. Fusce scelerisque id sapien sed bibendum.
maplemap/maplemap.github.io
_posts/2017/2017-7-4-Hello-World1.md
Markdown
mit
3,187
# [parser](https://github.com/yanhaijing/template.js/blob/master/packages/parser) [![](https://img.shields.io/badge/Powered%20by-jslib%20base-brightgreen.svg)](https://github.com/yanhaijing/jslib-base) [template.js](https://github.com/yanhaijing/template.js)的模板编译器 ## 兼容性 单元测试保证支持如下环境: | IE | CH | FF | SF | OP | IOS | Android | Node | | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | | 6+ | 29+ | 55+ | 9+ | 50+ | 9+ | 4+ | 0.10+ | **注意:编译代码依赖ES5环境,对于ie6-8需要引入[es5-shim](http://github.com/es-shims/es5-shim/)才可以兼容,可以查看[demo/demo-global.html](./demo/demo-global.html)中的例子** ## 使用者指南 通过npm下载安装代码 ```bash $ npm install --save @templatejs/parser ``` 如果你是node环境 ```js const parser = require('@templatejs/parser'); const tpl = ` <div><%=a%></div> `; parser.parse(tpl); // return a render string like '<div>' + a + '</div>' ``` 支持的参数 ```js // sTag 开始标签 // eTag 结束标签 // escape 是否默认转移输出变量 parser.parse(tpl, {sTag: '<#', eTag: '#>', escape: true}); ``` ## 文档 [API](https://github.com/yanhaijing/template.js/blob/master/./doc/api.md) ## 贡献者列表 [contributors](https://github.com/yanhaijing/template.js/graphs/contributors) ## 更新日志 [CHANGELOG.md](https://github.com/yanhaijing/template.js/blob/master/TODO.md/CHANGELOG.md) ## 计划列表 [TODO.md](https://github.com/yanhaijing/template.js/blob/master/TODO.md)
yanhaijing/template.js
packages/parser/README.md
Markdown
mit
1,564
# coding=utf-8 # -------------------------------------------------------------------------- # 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. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import functools from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.mgmt.core.exceptions import ARMErrorFormat from msrest import Serializer from .. import models as _models from .._vendor import _convert_request, _format_url_section T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False def build_get_request( resource_group_name: str, managed_instance_name: str, database_name: str, query_id: str, subscription_id: str, **kwargs: Any ) -> HttpRequest: api_version = "2020-11-01-preview" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'), "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), "queryId": _SERIALIZER.url("query_id", query_id, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) def build_list_by_query_request( resource_group_name: str, managed_instance_name: str, database_name: str, query_id: str, subscription_id: str, *, start_time: Optional[str] = None, end_time: Optional[str] = None, interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None, **kwargs: Any ) -> HttpRequest: api_version = "2020-11-01-preview" accept = "application/json" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics') path_format_arguments = { "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str'), "managedInstanceName": _SERIALIZER.url("managed_instance_name", managed_instance_name, 'str'), "databaseName": _SERIALIZER.url("database_name", database_name, 'str'), "queryId": _SERIALIZER.url("query_id", query_id, 'str'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if start_time is not None: query_parameters['startTime'] = _SERIALIZER.query("start_time", start_time, 'str') if end_time is not None: query_parameters['endTime'] = _SERIALIZER.query("end_time", end_time, 'str') if interval is not None: query_parameters['interval'] = _SERIALIZER.query("interval", interval, 'str') query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') return HttpRequest( method="GET", url=url, params=query_parameters, headers=header_parameters, **kwargs ) class ManagedDatabaseQueriesOperations(object): """ManagedDatabaseQueriesOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.sql.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config @distributed_trace def get( self, resource_group_name: str, managed_instance_name: str, database_name: str, query_id: str, **kwargs: Any ) -> "_models.ManagedInstanceQuery": """Get query by query id. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the database. :type database_name: str :param query_id: :type query_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ManagedInstanceQuery, or the result of cls(response) :rtype: ~azure.mgmt.sql.models.ManagedInstanceQuery :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQuery"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) request = build_get_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, database_name=database_name, query_id=query_id, subscription_id=self._config.subscription_id, template_url=self.get.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ManagedInstanceQuery', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}'} # type: ignore @distributed_trace def list_by_query( self, resource_group_name: str, managed_instance_name: str, database_name: str, query_id: str, start_time: Optional[str] = None, end_time: Optional[str] = None, interval: Optional[Union[str, "_models.QueryTimeGrainType"]] = None, **kwargs: Any ) -> Iterable["_models.ManagedInstanceQueryStatistics"]: """Get query execution statistics by query id. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. :type resource_group_name: str :param managed_instance_name: The name of the managed instance. :type managed_instance_name: str :param database_name: The name of the database. :type database_name: str :param query_id: :type query_id: str :param start_time: Start time for observed period. :type start_time: str :param end_time: End time for observed period. :type end_time: str :param interval: The time step to be used to summarize the metric values. :type interval: str or ~azure.mgmt.sql.models.QueryTimeGrainType :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ManagedInstanceQueryStatistics or the result of cls(response) :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.sql.models.ManagedInstanceQueryStatistics] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ManagedInstanceQueryStatistics"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) def prepare_request(next_link=None): if not next_link: request = build_list_by_query_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, database_name=database_name, query_id=query_id, subscription_id=self._config.subscription_id, start_time=start_time, end_time=end_time, interval=interval, template_url=self.list_by_query.metadata['url'], ) request = _convert_request(request) request.url = self._client.format_url(request.url) else: request = build_list_by_query_request( resource_group_name=resource_group_name, managed_instance_name=managed_instance_name, database_name=database_name, query_id=query_id, subscription_id=self._config.subscription_id, start_time=start_time, end_time=end_time, interval=interval, template_url=next_link, ) request = _convert_request(request) request.url = self._client.format_url(request.url) request.method = "GET" return request def extract_data(pipeline_response): deserialized = self._deserialize("ManagedInstanceQueryStatistics", pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, iter(list_of_elem) def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return ItemPaged( get_next, extract_data ) list_by_query.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}/queries/{queryId}/statistics'} # type: ignore
Azure/azure-sdk-for-python
sdk/sql/azure-mgmt-sql/azure/mgmt/sql/operations/_managed_database_queries_operations.py
Python
mit
12,909
Unicode.sublime-package ======================= Disclaimer ---------- This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Installation ------------ Install package to: * __OSX:__ `~/Library/Application Support/Sublime Text 2/Installed Packages` * __Windows:__ `%APPDATA%\Sublime Text 2\Installed Packages` * __Linux:__ `~/.config/sublime-text-2/Installed Packages` Usage ----- * __Main Menu:__ `Edit` | `Convert Unicode` * __Context Menu:__ `Convert Unicode` * __Command Palette:__ `Convert ...` * __Keymap:__ (Windows, Linux) * Unicode characters to escape sequences: <kbd>alt+shift+w</kbd> * Unicode escape sequences to characters: <kbd>alt+shift+e</kbd> * __Keymap:__ (OSX) * Unicode characters to escape sequences: <kbd>⌥⇧⌘w</kbd> * Unicode escape sequences to characters: <kbd>⌥⇧⌘e</kbd> LICENSE ------- See file [__LICENSE__](../master/LICENSE) for details.
caffee/Unicode.sublime-package
README.md
Markdown
mit
1,041
<?php namespace Koalamon\IntegrationBundle\Integration; class Integration { private $name; private $image; private $description; private $url; private $activeElements; private $totalElements; /** * Integration constructor. * * @param $name * @param $image * @param $description * @param $url */ public function __construct($name, $image, $description, $url = null, $activeElements = null, $totalElements = null) { $this->name = $name; $this->image = $image; $this->description = $description; $this->url = $url; $this->activeElements = $activeElements; $this->totalElements = $totalElements; } /** * @return mixed */ public function getName() { return $this->name; } /** * @return mixed */ public function getImage() { return $this->image; } /** * @return mixed */ public function getDescription() { return $this->description; } /** * @return mixed */ public function getUrl() { return $this->url; } /** * @return null */ public function getActiveElements() { return $this->activeElements; } /** * @return null */ public function getTotalElements() { return $this->totalElements; } /** * @param null $activeElements */ public function setActiveElements($activeElements) { $this->activeElements = $activeElements; } public function setUrl($url) { $this->url = $url; } }
koalamon/KoalamomPlatform
src/Koalamon/IntegrationBundle/Integration/Integration.php
PHP
mit
1,660
--- layout: page title: Roger Mercado's 91st Birthday date: 2016-05-24 author: Juan Rodgers tags: weekly links, java status: published summary: In molestie nec mauris a pretium. Pellentesque massa. banner: images/banner/meeting-01.jpg booking: startDate: 06/25/2016 endDate: 06/27/2016 ctyhocn: SCOINHX groupCode: RM9B published: true --- Praesent rhoncus neque at tincidunt dictum. Aenean sagittis pretium pulvinar. Integer a lectus at lectus pulvinar rutrum in fermentum ante. Duis tincidunt id nunc tincidunt porttitor. Fusce ultrices, ligula sit amet malesuada hendrerit, augue ante viverra est, vel viverra quam tortor vel ligula. Nam justo enim, interdum vel vestibulum ac, lacinia nec velit. Suspendisse efficitur magna sit amet arcu pretium porta. Mauris accumsan venenatis nulla, quis vulputate libero imperdiet porta. In mi justo, malesuada quis eleifend eu, tincidunt vitae enim. Aliquam erat volutpat. Suspendisse scelerisque urna eu accumsan suscipit. Suspendisse non enim nulla. Ut a sapien vel nisi porttitor iaculis vitae at orci. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin nec commodo erat. Pellentesque sed vehicula nisi, a maximus massa. Nam aliquam nisi metus, in tincidunt diam consequat eu. Donec sit amet diam feugiat, mollis ante sit amet, vehicula risus. Curabitur in lobortis eros. 1 Aliquam vel dui a enim rhoncus venenatis 1 Morbi varius est quis mauris efficitur, vel mattis ante molestie. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Proin euismod hendrerit pulvinar. Mauris ac tortor consectetur, tincidunt eros at, luctus dolor. Aliquam vel diam vitae quam aliquet aliquet. In sed ante massa. Donec orci arcu, consectetur nec placerat eget, dapibus vitae neque. Pellentesque in urna arcu. Nulla pharetra aliquam malesuada. Proin accumsan dolor ac tortor aliquet, eget tempor enim efficitur. Nulla blandit dignissim mattis. Duis at erat tellus. In hac habitasse platea dictumst. Duis elit nibh, consectetur vel mi non, interdum consectetur augue. Donec malesuada congue sagittis. Vestibulum rhoncus leo non velit malesuada feugiat. Praesent faucibus nibh non tempor tempor. In posuere magna eu gravida pulvinar. Proin vel orci diam. Ut at accumsan augue. Proin tincidunt, lacus vitae egestas finibus, sem mi ultricies enim, nec blandit massa mauris eu diam. Aenean ac ipsum eget leo finibus consequat. Praesent id varius leo.
KlishGroup/prose-pogs
pogs/S/SCOINHX/RM9B/index.md
Markdown
mit
2,469
import redis import logging import simplejson as json import sys from msgpack import Unpacker from flask import Flask, request, render_template from daemon import runner from os.path import dirname, abspath # add the shared settings file to namespace sys.path.insert(0, dirname(dirname(abspath(__file__)))) import settings REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH) app = Flask(__name__) app.config['PROPAGATE_EXCEPTIONS'] = True @app.route("/") def index(): return render_template('index.html'), 200 @app.route("/app_settings") def app_settings(): app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST, 'OCULUS_HOST': settings.OCULUS_HOST, 'FULL_NAMESPACE': settings.FULL_NAMESPACE, } resp = json.dumps(app_settings) return resp, 200 @app.route("/api", methods=['GET']) def data(): metric = request.args.get('metric', None) try: raw_series = REDIS_CONN.get(metric) if not raw_series: resp = json.dumps({'results': 'Error: No metric by that name'}) return resp, 404 else: unpacker = Unpacker(use_list = False) unpacker.feed(raw_series) timeseries = [item[:2] for item in unpacker] resp = json.dumps({'results': timeseries}) return resp, 200 except Exception as e: error = "Error: " + e resp = json.dumps({'results': error}) return resp, 500 class App(): def __init__(self): self.stdin_path = '/dev/null' self.stdout_path = settings.LOG_PATH + '/webapp.log' self.stderr_path = settings.LOG_PATH + '/webapp.log' self.pidfile_path = settings.PID_PATH + '/webapp.pid' self.pidfile_timeout = 5 def run(self): logger.info('starting webapp') logger.info('hosted at %s' % settings.WEBAPP_IP) logger.info('running on port %d' % settings.WEBAPP_PORT) app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT) if __name__ == "__main__": """ Start the server """ webapp = App() logger = logging.getLogger("AppLog") logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S") handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log') handler.setFormatter(formatter) logger.addHandler(handler) if len(sys.argv) > 1 and sys.argv[1] == 'run': webapp.run() else: daemon_runner = runner.DaemonRunner(webapp) daemon_runner.daemon_context.files_preserve = [handler.stream] daemon_runner.do_action()
MyNameIsMeerkat/skyline
src/webapp/webapp.py
Python
mit
2,673
/******************************************************************************* * * * Author : Angus Johnson * * Version : 6.4.2 * * Date : 27 February 2017 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2010-2017 * * * * License: * * Use, modification & distribution is subject to Boost Software License Ver 1. * * http://www.boost.org/LICENSE_1_0.txt * * * * Attributions: * * The code in this library is an extension of Bala Vatti's clipping algorithm: * * "A generic solution to polygon clipping" * * Communications of the ACM, Vol 35, Issue 7 (July 1992) pp 56-63. * * http://portal.acm.org/citation.cfm?id=129906 * * * * Computer graphics and geometric modeling: implementation and algorithms * * By Max K. Agoston * * Springer; 1 edition (January 4, 2005) * * http://books.google.com/books?q=vatti+clipping+agoston * * * * See also: * * "Polygon Offsetting by Computing Winding Numbers" * * Paper no. DETC2005-85513 pp. 565-575 * * ASME 2005 International Design Engineering Technical Conferences * * and Computers and Information in Engineering Conference (IDETC/CIE2005) * * September 24-28, 2005 , Long Beach, California, USA * * http://www.me.berkeley.edu/~mcmains/pubs/DAC05OffsetPolygon.pdf * * * *******************************************************************************/ /******************************************************************************* * * * This is a translation of the Delphi Clipper library and the naming style * * used has retained a Delphi flavour. * * * *******************************************************************************/ #include "clipper.hpp" #include <cmath> #include <vector> #include <algorithm> #include <stdexcept> #include <cstring> #include <cstdlib> #include <ostream> #include <functional> namespace ClipperLib { static double const pi = 3.141592653589793238; static double const two_pi = pi *2; static double const def_arc_tolerance = 0.25; enum Direction { dRightToLeft, dLeftToRight }; static int const Unassigned = -1; //edge not currently 'owning' a solution static int const Skip = -2; //edge that would otherwise close a path #define HORIZONTAL (-1.0E+40) #define TOLERANCE (1.0e-20) #define NEAR_ZERO(val) (((val) > -TOLERANCE) && ((val) < TOLERANCE)) struct TEdge { IntPoint Bot; IntPoint Curr; //current (updated for every new scanbeam) IntPoint Top; double Dx; PolyType PolyTyp; EdgeSide Side; //side only refers to current side of solution poly int WindDelta; //1 or -1 depending on winding direction int WindCnt; int WindCnt2; //winding count of the opposite polytype int OutIdx; TEdge *Next; TEdge *Prev; TEdge *NextInLML; TEdge *NextInAEL; TEdge *PrevInAEL; TEdge *NextInSEL; TEdge *PrevInSEL; }; struct IntersectNode { TEdge *Edge1; TEdge *Edge2; IntPoint Pt; }; struct LocalMinimum { cInt Y; TEdge *LeftBound; TEdge *RightBound; }; struct OutPt; //OutRec: contains a path in the clipping solution. Edges in the AEL will //carry a pointer to an OutRec when they are part of the clipping solution. struct OutRec { int Idx; bool IsHole; bool IsOpen; OutRec *FirstLeft; //see comments in clipper.pas PolyNode *PolyNd; OutPt *Pts; OutPt *BottomPt; }; struct OutPt { int Idx; IntPoint Pt; OutPt *Next; OutPt *Prev; }; struct Join { OutPt *OutPt1; OutPt *OutPt2; IntPoint OffPt; }; struct LocMinSorter { inline bool operator()(const LocalMinimum& locMin1, const LocalMinimum& locMin2) { return locMin2.Y < locMin1.Y; } }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ inline cInt Round(double val) { if ((val < 0)) return static_cast<cInt>(val - 0.5); else return static_cast<cInt>(val + 0.5); } //------------------------------------------------------------------------------ inline cInt Abs(cInt val) { return val < 0 ? -val : val; } //------------------------------------------------------------------------------ // PolyTree methods ... //------------------------------------------------------------------------------ void PolyTree::Clear() { for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i) delete AllNodes[i]; AllNodes.resize(0); Childs.resize(0); } //------------------------------------------------------------------------------ PolyNode* PolyTree::GetFirst() const { if (!Childs.empty()) return Childs[0]; else return 0; } //------------------------------------------------------------------------------ int PolyTree::Total() const { int result = (int)AllNodes.size(); //with negative offsets, ignore the hidden outer polygon ... if (result > 0 && Childs[0] != AllNodes[0]) result--; return result; } //------------------------------------------------------------------------------ // PolyNode methods ... //------------------------------------------------------------------------------ PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false) { } //------------------------------------------------------------------------------ int PolyNode::ChildCount() const { return (int)Childs.size(); } //------------------------------------------------------------------------------ void PolyNode::AddChild(PolyNode& child) { unsigned cnt = (unsigned)Childs.size(); Childs.push_back(&child); child.Parent = this; child.Index = cnt; } //------------------------------------------------------------------------------ PolyNode* PolyNode::GetNext() const { if (!Childs.empty()) return Childs[0]; else return GetNextSiblingUp(); } //------------------------------------------------------------------------------ PolyNode* PolyNode::GetNextSiblingUp() const { if (!Parent) //protects against PolyTree.GetNextSiblingUp() return 0; else if (Index == Parent->Childs.size() - 1) return Parent->GetNextSiblingUp(); else return Parent->Childs[Index + 1]; } //------------------------------------------------------------------------------ bool PolyNode::IsHole() const { bool result = true; PolyNode* node = Parent; while (node) { result = !result; node = node->Parent; } return result; } //------------------------------------------------------------------------------ bool PolyNode::IsOpen() const { return m_IsOpen; } //------------------------------------------------------------------------------ #ifndef use_int32 //------------------------------------------------------------------------------ // Int128 class (enables safe math on signed 64bit integers) // eg Int128 val1((long64)9223372036854775807); //ie 2^63 -1 // Int128 val2((long64)9223372036854775807); // Int128 val3 = val1 * val2; // val3.AsString => "85070591730234615847396907784232501249" (8.5e+37) //------------------------------------------------------------------------------ class Int128 { public: ulong64 lo; long64 hi; Int128(long64 _lo = 0) { lo = (ulong64)_lo; if (_lo < 0) hi = -1; else hi = 0; } Int128(const Int128 &val): lo(val.lo), hi(val.hi){} Int128(const long64& _hi, const ulong64& _lo): lo(_lo), hi(_hi){} Int128& operator = (const long64 &val) { lo = (ulong64)val; if (val < 0) hi = -1; else hi = 0; return *this; } bool operator == (const Int128 &val) const {return (hi == val.hi && lo == val.lo);} bool operator != (const Int128 &val) const { return !(*this == val);} bool operator > (const Int128 &val) const { if (hi != val.hi) return hi > val.hi; else return lo > val.lo; } bool operator < (const Int128 &val) const { if (hi != val.hi) return hi < val.hi; else return lo < val.lo; } bool operator >= (const Int128 &val) const { return !(*this < val);} bool operator <= (const Int128 &val) const { return !(*this > val);} Int128& operator += (const Int128 &rhs) { hi += rhs.hi; lo += rhs.lo; if (lo < rhs.lo) hi++; return *this; } Int128 operator + (const Int128 &rhs) const { Int128 result(*this); result+= rhs; return result; } Int128& operator -= (const Int128 &rhs) { *this += -rhs; return *this; } Int128 operator - (const Int128 &rhs) const { Int128 result(*this); result -= rhs; return result; } Int128 operator-() const //unary negation { if (lo == 0) return Int128(-hi, 0); else return Int128(~hi, ~lo + 1); } operator double() const { const double shift64 = 18446744073709551616.0; //2^64 if (hi < 0) { if (lo == 0) return (double)hi * shift64; else return -(double)(~lo + ~hi * shift64); } else return (double)(lo + hi * shift64); } }; //------------------------------------------------------------------------------ Int128 Int128Mul (long64 lhs, long64 rhs) { bool negate = (lhs < 0) != (rhs < 0); if (lhs < 0) lhs = -lhs; ulong64 int1Hi = ulong64(lhs) >> 32; ulong64 int1Lo = ulong64(lhs & 0xFFFFFFFF); if (rhs < 0) rhs = -rhs; ulong64 int2Hi = ulong64(rhs) >> 32; ulong64 int2Lo = ulong64(rhs & 0xFFFFFFFF); //nb: see comments in clipper.pas ulong64 a = int1Hi * int2Hi; ulong64 b = int1Lo * int2Lo; ulong64 c = int1Hi * int2Lo + int1Lo * int2Hi; Int128 tmp; tmp.hi = long64(a + (c >> 32)); tmp.lo = long64(c << 32); tmp.lo += long64(b); if (tmp.lo < b) tmp.hi++; if (negate) tmp = -tmp; return tmp; }; #endif //------------------------------------------------------------------------------ // Miscellaneous global functions //------------------------------------------------------------------------------ bool Orientation(const Path &poly) { return Area(poly) >= 0; } //------------------------------------------------------------------------------ double Area(const Path &poly) { int size = (int)poly.size(); if (size < 3) return 0; double a = 0; for (int i = 0, j = size -1; i < size; ++i) { a += ((double)poly[j].X + poly[i].X) * ((double)poly[j].Y - poly[i].Y); j = i; } return -a * 0.5; } //------------------------------------------------------------------------------ double Area(const OutPt *op) { const OutPt *startOp = op; if (!op) return 0; double a = 0; do { a += (double)(op->Prev->Pt.X + op->Pt.X) * (double)(op->Prev->Pt.Y - op->Pt.Y); op = op->Next; } while (op != startOp); return a * 0.5; } //------------------------------------------------------------------------------ double Area(const OutRec &outRec) { return Area(outRec.Pts); } //------------------------------------------------------------------------------ bool PointIsVertex(const IntPoint &Pt, OutPt *pp) { OutPt *pp2 = pp; do { if (pp2->Pt == Pt) return true; pp2 = pp2->Next; } while (pp2 != pp); return false; } //------------------------------------------------------------------------------ //See "The Point in Polygon Problem for Arbitrary Polygons" by Hormann & Agathos //http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.88.5498&rep=rep1&type=pdf int PointInPolygon(const IntPoint &pt, const Path &path) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary int result = 0; size_t cnt = path.size(); if (cnt < 3) return 0; IntPoint ip = path[0]; for(size_t i = 1; i <= cnt; ++i) { IntPoint ipNext = (i == cnt ? path[0] : path[i]); if (ipNext.Y == pt.Y) { if ((ipNext.X == pt.X) || (ip.Y == pt.Y && ((ipNext.X > pt.X) == (ip.X < pt.X)))) return -1; } if ((ip.Y < pt.Y) != (ipNext.Y < pt.Y)) { if (ip.X >= pt.X) { if (ipNext.X > pt.X) result = 1 - result; else { double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); if (!d) return -1; if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; } } else { if (ipNext.X > pt.X) { double d = (double)(ip.X - pt.X) * (ipNext.Y - pt.Y) - (double)(ipNext.X - pt.X) * (ip.Y - pt.Y); if (!d) return -1; if ((d > 0) == (ipNext.Y > ip.Y)) result = 1 - result; } } } ip = ipNext; } return result; } //------------------------------------------------------------------------------ int PointInPolygon (const IntPoint &pt, OutPt *op) { //returns 0 if false, +1 if true, -1 if pt ON polygon boundary int result = 0; OutPt* startOp = op; for(;;) { if (op->Next->Pt.Y == pt.Y) { if ((op->Next->Pt.X == pt.X) || (op->Pt.Y == pt.Y && ((op->Next->Pt.X > pt.X) == (op->Pt.X < pt.X)))) return -1; } if ((op->Pt.Y < pt.Y) != (op->Next->Pt.Y < pt.Y)) { if (op->Pt.X >= pt.X) { if (op->Next->Pt.X > pt.X) result = 1 - result; else { double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y); if (!d) return -1; if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result; } } else { if (op->Next->Pt.X > pt.X) { double d = (double)(op->Pt.X - pt.X) * (op->Next->Pt.Y - pt.Y) - (double)(op->Next->Pt.X - pt.X) * (op->Pt.Y - pt.Y); if (!d) return -1; if ((d > 0) == (op->Next->Pt.Y > op->Pt.Y)) result = 1 - result; } } } op = op->Next; if (startOp == op) break; } return result; } //------------------------------------------------------------------------------ bool Poly2ContainsPoly1(OutPt *OutPt1, OutPt *OutPt2) { OutPt* op = OutPt1; do { //nb: PointInPolygon returns 0 if false, +1 if true, -1 if pt on polygon int res = PointInPolygon(op->Pt, OutPt2); if (res >= 0) return res > 0; op = op->Next; } while (op != OutPt1); return true; } //---------------------------------------------------------------------- bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range) { #ifndef use_int32 if (UseFullInt64Range) return Int128Mul(e1.Top.Y - e1.Bot.Y, e2.Top.X - e2.Bot.X) == Int128Mul(e1.Top.X - e1.Bot.X, e2.Top.Y - e2.Bot.Y); else #endif return (e1.Top.Y - e1.Bot.Y) * (e2.Top.X - e2.Bot.X) == (e1.Top.X - e1.Bot.X) * (e2.Top.Y - e2.Bot.Y); } //------------------------------------------------------------------------------ bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3, bool UseFullInt64Range) { #ifndef use_int32 if (UseFullInt64Range) return Int128Mul(pt1.Y-pt2.Y, pt2.X-pt3.X) == Int128Mul(pt1.X-pt2.X, pt2.Y-pt3.Y); else #endif return (pt1.Y-pt2.Y)*(pt2.X-pt3.X) == (pt1.X-pt2.X)*(pt2.Y-pt3.Y); } //------------------------------------------------------------------------------ bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range) { #ifndef use_int32 if (UseFullInt64Range) return Int128Mul(pt1.Y-pt2.Y, pt3.X-pt4.X) == Int128Mul(pt1.X-pt2.X, pt3.Y-pt4.Y); else #endif return (pt1.Y-pt2.Y)*(pt3.X-pt4.X) == (pt1.X-pt2.X)*(pt3.Y-pt4.Y); } //------------------------------------------------------------------------------ inline bool IsHorizontal(TEdge &e) { return e.Dx == HORIZONTAL; } //------------------------------------------------------------------------------ inline double GetDx(const IntPoint pt1, const IntPoint pt2) { return (pt1.Y == pt2.Y) ? HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y); } //--------------------------------------------------------------------------- inline void SetDx(TEdge &e) { cInt dy = (e.Top.Y - e.Bot.Y); if (dy == 0) e.Dx = HORIZONTAL; else e.Dx = (double)(e.Top.X - e.Bot.X) / dy; } //--------------------------------------------------------------------------- inline void SwapSides(TEdge &Edge1, TEdge &Edge2) { EdgeSide Side = Edge1.Side; Edge1.Side = Edge2.Side; Edge2.Side = Side; } //------------------------------------------------------------------------------ inline void SwapPolyIndexes(TEdge &Edge1, TEdge &Edge2) { int OutIdx = Edge1.OutIdx; Edge1.OutIdx = Edge2.OutIdx; Edge2.OutIdx = OutIdx; } //------------------------------------------------------------------------------ inline cInt TopX(TEdge &edge, const cInt currentY) { return ( currentY == edge.Top.Y ) ? edge.Top.X : edge.Bot.X + Round(edge.Dx *(currentY - edge.Bot.Y)); } //------------------------------------------------------------------------------ void IntersectPoint(TEdge &Edge1, TEdge &Edge2, IntPoint &ip) { #ifdef use_xyz ip.Z = 0; #endif double b1, b2; if (Edge1.Dx == Edge2.Dx) { ip.Y = Edge1.Curr.Y; ip.X = TopX(Edge1, ip.Y); return; } else if (Edge1.Dx == 0) { ip.X = Edge1.Bot.X; if (IsHorizontal(Edge2)) ip.Y = Edge2.Bot.Y; else { b2 = Edge2.Bot.Y - (Edge2.Bot.X / Edge2.Dx); ip.Y = Round(ip.X / Edge2.Dx + b2); } } else if (Edge2.Dx == 0) { ip.X = Edge2.Bot.X; if (IsHorizontal(Edge1)) ip.Y = Edge1.Bot.Y; else { b1 = Edge1.Bot.Y - (Edge1.Bot.X / Edge1.Dx); ip.Y = Round(ip.X / Edge1.Dx + b1); } } else { b1 = Edge1.Bot.X - Edge1.Bot.Y * Edge1.Dx; b2 = Edge2.Bot.X - Edge2.Bot.Y * Edge2.Dx; double q = (b2-b1) / (Edge1.Dx - Edge2.Dx); ip.Y = Round(q); if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) ip.X = Round(Edge1.Dx * q + b1); else ip.X = Round(Edge2.Dx * q + b2); } if (ip.Y < Edge1.Top.Y || ip.Y < Edge2.Top.Y) { if (Edge1.Top.Y > Edge2.Top.Y) ip.Y = Edge1.Top.Y; else ip.Y = Edge2.Top.Y; if (std::fabs(Edge1.Dx) < std::fabs(Edge2.Dx)) ip.X = TopX(Edge1, ip.Y); else ip.X = TopX(Edge2, ip.Y); } //finally, don't allow 'ip' to be BELOW curr.Y (ie bottom of scanbeam) ... if (ip.Y > Edge1.Curr.Y) { ip.Y = Edge1.Curr.Y; //use the more vertical edge to derive X ... if (std::fabs(Edge1.Dx) > std::fabs(Edge2.Dx)) ip.X = TopX(Edge2, ip.Y); else ip.X = TopX(Edge1, ip.Y); } } //------------------------------------------------------------------------------ void ReversePolyPtLinks(OutPt *pp) { if (!pp) return; OutPt *pp1, *pp2; pp1 = pp; do { pp2 = pp1->Next; pp1->Next = pp1->Prev; pp1->Prev = pp2; pp1 = pp2; } while( pp1 != pp ); } //------------------------------------------------------------------------------ void DisposeOutPts(OutPt*& pp) { if (pp == 0) return; pp->Prev->Next = 0; while( pp ) { OutPt *tmpPp = pp; pp = pp->Next; delete tmpPp; } } //------------------------------------------------------------------------------ inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt) { std::memset(e, 0, sizeof(TEdge)); e->Next = eNext; e->Prev = ePrev; e->Curr = Pt; e->OutIdx = Unassigned; } //------------------------------------------------------------------------------ void InitEdge2(TEdge& e, PolyType Pt) { if (e.Curr.Y >= e.Next->Curr.Y) { e.Bot = e.Curr; e.Top = e.Next->Curr; } else { e.Top = e.Curr; e.Bot = e.Next->Curr; } SetDx(e); e.PolyTyp = Pt; } //------------------------------------------------------------------------------ TEdge* RemoveEdge(TEdge* e) { //removes e from double_linked_list (but without removing from memory) e->Prev->Next = e->Next; e->Next->Prev = e->Prev; TEdge* result = e->Next; e->Prev = 0; //flag as removed (see ClipperBase.Clear) return result; } //------------------------------------------------------------------------------ inline void ReverseHorizontal(TEdge &e) { //swap horizontal edges' Top and Bottom x's so they follow the natural //progression of the bounds - ie so their xbots will align with the //adjoining lower edge. [Helpful in the ProcessHorizontal() method.] std::swap(e.Top.X, e.Bot.X); #ifdef use_xyz std::swap(e.Top.Z, e.Bot.Z); #endif } //------------------------------------------------------------------------------ void SwapPoints(IntPoint &pt1, IntPoint &pt2) { IntPoint tmp = pt1; pt1 = pt2; pt2 = tmp; } //------------------------------------------------------------------------------ bool GetOverlapSegment(IntPoint pt1a, IntPoint pt1b, IntPoint pt2a, IntPoint pt2b, IntPoint &pt1, IntPoint &pt2) { //precondition: segments are Collinear. if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y)) { if (pt1a.X > pt1b.X) SwapPoints(pt1a, pt1b); if (pt2a.X > pt2b.X) SwapPoints(pt2a, pt2b); if (pt1a.X > pt2a.X) pt1 = pt1a; else pt1 = pt2a; if (pt1b.X < pt2b.X) pt2 = pt1b; else pt2 = pt2b; return pt1.X < pt2.X; } else { if (pt1a.Y < pt1b.Y) SwapPoints(pt1a, pt1b); if (pt2a.Y < pt2b.Y) SwapPoints(pt2a, pt2b); if (pt1a.Y < pt2a.Y) pt1 = pt1a; else pt1 = pt2a; if (pt1b.Y > pt2b.Y) pt2 = pt1b; else pt2 = pt2b; return pt1.Y > pt2.Y; } } //------------------------------------------------------------------------------ bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2) { OutPt *p = btmPt1->Prev; while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Prev; double dx1p = std::fabs(GetDx(btmPt1->Pt, p->Pt)); p = btmPt1->Next; while ((p->Pt == btmPt1->Pt) && (p != btmPt1)) p = p->Next; double dx1n = std::fabs(GetDx(btmPt1->Pt, p->Pt)); p = btmPt2->Prev; while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Prev; double dx2p = std::fabs(GetDx(btmPt2->Pt, p->Pt)); p = btmPt2->Next; while ((p->Pt == btmPt2->Pt) && (p != btmPt2)) p = p->Next; double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt)); if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) && std::min(dx1p, dx1n) == std::min(dx2p, dx2n)) return Area(btmPt1) > 0; //if otherwise identical use orientation else return (dx1p >= dx2p && dx1p >= dx2n) || (dx1n >= dx2p && dx1n >= dx2n); } //------------------------------------------------------------------------------ OutPt* GetBottomPt(OutPt *pp) { OutPt* dups = 0; OutPt* p = pp->Next; while (p != pp) { if (p->Pt.Y > pp->Pt.Y) { pp = p; dups = 0; } else if (p->Pt.Y == pp->Pt.Y && p->Pt.X <= pp->Pt.X) { if (p->Pt.X < pp->Pt.X) { dups = 0; pp = p; } else { if (p->Next != pp && p->Prev != pp) dups = p; } } p = p->Next; } if (dups) { //there appears to be at least 2 vertices at BottomPt so ... while (dups != p) { if (!FirstIsBottomPt(p, dups)) pp = dups; dups = dups->Next; while (dups->Pt != pp->Pt) dups = dups->Next; } } return pp; } //------------------------------------------------------------------------------ bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3) { if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2)) return false; else if (pt1.X != pt3.X) return (pt2.X > pt1.X) == (pt2.X < pt3.X); else return (pt2.Y > pt1.Y) == (pt2.Y < pt3.Y); } //------------------------------------------------------------------------------ bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b) { if (seg1a > seg1b) std::swap(seg1a, seg1b); if (seg2a > seg2b) std::swap(seg2a, seg2b); return (seg1a < seg2b) && (seg2a < seg1b); } //------------------------------------------------------------------------------ // ClipperBase class methods ... //------------------------------------------------------------------------------ ClipperBase::ClipperBase() //constructor { m_CurrentLM = m_MinimaList.begin(); //begin() == end() here m_UseFullRange = false; } //------------------------------------------------------------------------------ ClipperBase::~ClipperBase() //destructor { Clear(); } //------------------------------------------------------------------------------ void RangeTest(const IntPoint& Pt, bool& useFullRange) { if (useFullRange) { if (Pt.X > hiRange || Pt.Y > hiRange || -Pt.X > hiRange || -Pt.Y > hiRange) throw clipperException("Coordinate outside allowed range"); } else if (Pt.X > loRange|| Pt.Y > loRange || -Pt.X > loRange || -Pt.Y > loRange) { useFullRange = true; RangeTest(Pt, useFullRange); } } //------------------------------------------------------------------------------ TEdge* FindNextLocMin(TEdge* E) { for (;;) { while (E->Bot != E->Prev->Bot || E->Curr == E->Top) E = E->Next; if (!IsHorizontal(*E) && !IsHorizontal(*E->Prev)) break; while (IsHorizontal(*E->Prev)) E = E->Prev; TEdge* E2 = E; while (IsHorizontal(*E)) E = E->Next; if (E->Top.Y == E->Prev->Bot.Y) continue; //ie just an intermediate horz. if (E2->Prev->Bot.X < E->Bot.X) E = E2; break; } return E; } //------------------------------------------------------------------------------ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) { TEdge *Result = E; TEdge *Horz = 0; if (E->OutIdx == Skip) { //if edges still remain in the current bound beyond the skip edge then //create another LocMin and call ProcessBound once more if (NextIsForward) { while (E->Top.Y == E->Next->Bot.Y) E = E->Next; //don't include top horizontals when parsing a bound a second time, //they will be contained in the opposite bound ... while (E != Result && IsHorizontal(*E)) E = E->Prev; } else { while (E->Top.Y == E->Prev->Bot.Y) E = E->Prev; while (E != Result && IsHorizontal(*E)) E = E->Next; } if (E == Result) { if (NextIsForward) Result = E->Next; else Result = E->Prev; } else { //there are more edges in the bound beyond result starting with E if (NextIsForward) E = Result->Next; else E = Result->Prev; MinimaList::value_type locMin; locMin.Y = E->Bot.Y; locMin.LeftBound = 0; locMin.RightBound = E; E->WindDelta = 0; Result = ProcessBound(E, NextIsForward); m_MinimaList.push_back(locMin); } return Result; } TEdge *EStart; if (IsHorizontal(*E)) { //We need to be careful with open paths because this may not be a //true local minima (ie E may be following a skip edge). //Also, consecutive horz. edges may start heading left before going right. if (NextIsForward) EStart = E->Prev; else EStart = E->Next; if (IsHorizontal(*EStart)) //ie an adjoining horizontal skip edge { if (EStart->Bot.X != E->Bot.X && EStart->Top.X != E->Bot.X) ReverseHorizontal(*E); } else if (EStart->Bot.X != E->Bot.X) ReverseHorizontal(*E); } EStart = E; if (NextIsForward) { while (Result->Top.Y == Result->Next->Bot.Y && Result->Next->OutIdx != Skip) Result = Result->Next; if (IsHorizontal(*Result) && Result->Next->OutIdx != Skip) { //nb: at the top of a bound, horizontals are added to the bound //only when the preceding edge attaches to the horizontal's left vertex //unless a Skip edge is encountered when that becomes the top divide Horz = Result; while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev; if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev; } while (E != Result) { E->NextInLML = E->Next; if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); E = E->Next; } if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); Result = Result->Next; //move to the edge just beyond current bound } else { while (Result->Top.Y == Result->Prev->Bot.Y && Result->Prev->OutIdx != Skip) Result = Result->Prev; if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip) { Horz = Result; while (IsHorizontal(*Horz->Next)) Horz = Horz->Next; if (Horz->Next->Top.X == Result->Prev->Top.X || Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next; } while (E != Result) { E->NextInLML = E->Prev; if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) ReverseHorizontal(*E); E = E->Prev; } if (IsHorizontal(*E) && E != EStart && E->Bot.X != E->Next->Top.X) ReverseHorizontal(*E); Result = Result->Prev; //move to the edge just beyond current bound } return Result; } //------------------------------------------------------------------------------ bool ClipperBase::AddPath(const Path &pg, PolyType PolyTyp, bool Closed) { #ifdef use_lines if (!Closed && PolyTyp == ptClip) throw clipperException("AddPath: Open paths must be subject."); #else if (!Closed) throw clipperException("AddPath: Open paths have been disabled."); #endif int highI = (int)pg.size() -1; if (Closed) while (highI > 0 && (pg[highI] == pg[0])) --highI; while (highI > 0 && (pg[highI] == pg[highI -1])) --highI; if ((Closed && highI < 2) || (!Closed && highI < 1)) return false; //create a new edge array ... TEdge *edges = new TEdge [highI +1]; bool IsFlat = true; //1. Basic (first) edge initialization ... try { edges[1].Curr = pg[1]; RangeTest(pg[0], m_UseFullRange); RangeTest(pg[highI], m_UseFullRange); InitEdge(&edges[0], &edges[1], &edges[highI], pg[0]); InitEdge(&edges[highI], &edges[0], &edges[highI-1], pg[highI]); for (int i = highI - 1; i >= 1; --i) { RangeTest(pg[i], m_UseFullRange); InitEdge(&edges[i], &edges[i+1], &edges[i-1], pg[i]); } } catch(...) { delete [] edges; throw; //range test fails } TEdge *eStart = &edges[0]; //2. Remove duplicate vertices, and (when closed) collinear edges ... TEdge *E = eStart, *eLoopStop = eStart; for (;;) { //nb: allows matching start and end points when not Closed ... if (E->Curr == E->Next->Curr && (Closed || E->Next != eStart)) { if (E == E->Next) break; if (E == eStart) eStart = E->Next; E = RemoveEdge(E); eLoopStop = E; continue; } if (E->Prev == E->Next) break; //only two vertices else if (Closed && SlopesEqual(E->Prev->Curr, E->Curr, E->Next->Curr, m_UseFullRange) && (!m_PreserveCollinear || !Pt2IsBetweenPt1AndPt3(E->Prev->Curr, E->Curr, E->Next->Curr))) { //Collinear edges are allowed for open paths but in closed paths //the default is to merge adjacent collinear edges into a single edge. //However, if the PreserveCollinear property is enabled, only overlapping //collinear edges (ie spikes) will be removed from closed paths. if (E == eStart) eStart = E->Next; E = RemoveEdge(E); E = E->Prev; eLoopStop = E; continue; } E = E->Next; if ((E == eLoopStop) || (!Closed && E->Next == eStart)) break; } if ((!Closed && (E == E->Next)) || (Closed && (E->Prev == E->Next))) { delete [] edges; return false; } if (!Closed) { m_HasOpenPaths = true; eStart->Prev->OutIdx = Skip; } //3. Do second stage of edge initialization ... E = eStart; do { InitEdge2(*E, PolyTyp); E = E->Next; if (IsFlat && E->Curr.Y != eStart->Curr.Y) IsFlat = false; } while (E != eStart); //4. Finally, add edge bounds to LocalMinima list ... //Totally flat paths must be handled differently when adding them //to LocalMinima list to avoid endless loops etc ... if (IsFlat) { if (Closed) { delete [] edges; return false; } E->Prev->OutIdx = Skip; MinimaList::value_type locMin; locMin.Y = E->Bot.Y; locMin.LeftBound = 0; locMin.RightBound = E; locMin.RightBound->Side = esRight; locMin.RightBound->WindDelta = 0; for (;;) { if (E->Bot.X != E->Prev->Top.X) ReverseHorizontal(*E); if (E->Next->OutIdx == Skip) break; E->NextInLML = E->Next; E = E->Next; } m_MinimaList.push_back(locMin); m_edges.push_back(edges); return true; } m_edges.push_back(edges); bool leftBoundIsForward; TEdge* EMin = 0; //workaround to avoid an endless loop in the while loop below when //open paths have matching start and end points ... if (E->Prev->Bot == E->Prev->Top) E = E->Next; for (;;) { E = FindNextLocMin(E); if (E == EMin) break; else if (!EMin) EMin = E; //E and E.Prev now share a local minima (left aligned if horizontal). //Compare their slopes to find which starts which bound ... MinimaList::value_type locMin; locMin.Y = E->Bot.Y; if (E->Dx < E->Prev->Dx) { locMin.LeftBound = E->Prev; locMin.RightBound = E; leftBoundIsForward = false; //Q.nextInLML = Q.prev } else { locMin.LeftBound = E; locMin.RightBound = E->Prev; leftBoundIsForward = true; //Q.nextInLML = Q.next } if (!Closed) locMin.LeftBound->WindDelta = 0; else if (locMin.LeftBound->Next == locMin.RightBound) locMin.LeftBound->WindDelta = -1; else locMin.LeftBound->WindDelta = 1; locMin.RightBound->WindDelta = -locMin.LeftBound->WindDelta; E = ProcessBound(locMin.LeftBound, leftBoundIsForward); if (E->OutIdx == Skip) E = ProcessBound(E, leftBoundIsForward); TEdge* E2 = ProcessBound(locMin.RightBound, !leftBoundIsForward); if (E2->OutIdx == Skip) E2 = ProcessBound(E2, !leftBoundIsForward); if (locMin.LeftBound->OutIdx == Skip) locMin.LeftBound = 0; else if (locMin.RightBound->OutIdx == Skip) locMin.RightBound = 0; m_MinimaList.push_back(locMin); if (!leftBoundIsForward) E = E2; } return true; } //------------------------------------------------------------------------------ bool ClipperBase::AddPaths(const Paths &ppg, PolyType PolyTyp, bool Closed) { bool result = false; for (Paths::size_type i = 0; i < ppg.size(); ++i) if (AddPath(ppg[i], PolyTyp, Closed)) result = true; return result; } //------------------------------------------------------------------------------ void ClipperBase::Clear() { DisposeLocalMinimaList(); for (EdgeList::size_type i = 0; i < m_edges.size(); ++i) { TEdge* edges = m_edges[i]; delete [] edges; } m_edges.clear(); m_UseFullRange = false; m_HasOpenPaths = false; } //------------------------------------------------------------------------------ void ClipperBase::Reset() { m_CurrentLM = m_MinimaList.begin(); if (m_CurrentLM == m_MinimaList.end()) return; //ie nothing to process std::sort(m_MinimaList.begin(), m_MinimaList.end(), LocMinSorter()); m_Scanbeam = ScanbeamList(); //clears/resets priority_queue //reset all edges ... for (MinimaList::iterator lm = m_MinimaList.begin(); lm != m_MinimaList.end(); ++lm) { InsertScanbeam(lm->Y); TEdge* e = lm->LeftBound; if (e) { e->Curr = e->Bot; e->Side = esLeft; e->OutIdx = Unassigned; } e = lm->RightBound; if (e) { e->Curr = e->Bot; e->Side = esRight; e->OutIdx = Unassigned; } } m_ActiveEdges = 0; m_CurrentLM = m_MinimaList.begin(); } //------------------------------------------------------------------------------ void ClipperBase::DisposeLocalMinimaList() { m_MinimaList.clear(); m_CurrentLM = m_MinimaList.begin(); } //------------------------------------------------------------------------------ bool ClipperBase::PopLocalMinima(cInt Y, const LocalMinimum *&locMin) { if (m_CurrentLM == m_MinimaList.end() || (*m_CurrentLM).Y != Y) return false; locMin = &(*m_CurrentLM); ++m_CurrentLM; return true; } //------------------------------------------------------------------------------ IntRect ClipperBase::GetBounds() { IntRect result; MinimaList::iterator lm = m_MinimaList.begin(); if (lm == m_MinimaList.end()) { result.left = result.top = result.right = result.bottom = 0; return result; } result.left = lm->LeftBound->Bot.X; result.top = lm->LeftBound->Bot.Y; result.right = lm->LeftBound->Bot.X; result.bottom = lm->LeftBound->Bot.Y; while (lm != m_MinimaList.end()) { //todo - needs fixing for open paths result.bottom = std::max(result.bottom, lm->LeftBound->Bot.Y); TEdge* e = lm->LeftBound; for (;;) { TEdge* bottomE = e; while (e->NextInLML) { if (e->Bot.X < result.left) result.left = e->Bot.X; if (e->Bot.X > result.right) result.right = e->Bot.X; e = e->NextInLML; } result.left = std::min(result.left, e->Bot.X); result.right = std::max(result.right, e->Bot.X); result.left = std::min(result.left, e->Top.X); result.right = std::max(result.right, e->Top.X); result.top = std::min(result.top, e->Top.Y); if (bottomE == lm->LeftBound) e = lm->RightBound; else break; } ++lm; } return result; } //------------------------------------------------------------------------------ void ClipperBase::InsertScanbeam(const cInt Y) { m_Scanbeam.push(Y); } //------------------------------------------------------------------------------ bool ClipperBase::PopScanbeam(cInt &Y) { if (m_Scanbeam.empty()) return false; Y = m_Scanbeam.top(); m_Scanbeam.pop(); while (!m_Scanbeam.empty() && Y == m_Scanbeam.top()) { m_Scanbeam.pop(); } // Pop duplicates. return true; } //------------------------------------------------------------------------------ void ClipperBase::DisposeAllOutRecs(){ for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) DisposeOutRec(i); m_PolyOuts.clear(); } //------------------------------------------------------------------------------ void ClipperBase::DisposeOutRec(PolyOutList::size_type index) { OutRec *outRec = m_PolyOuts[index]; if (outRec->Pts) DisposeOutPts(outRec->Pts); delete outRec; m_PolyOuts[index] = 0; } //------------------------------------------------------------------------------ void ClipperBase::DeleteFromAEL(TEdge *e) { TEdge* AelPrev = e->PrevInAEL; TEdge* AelNext = e->NextInAEL; if (!AelPrev && !AelNext && (e != m_ActiveEdges)) return; //already deleted if (AelPrev) AelPrev->NextInAEL = AelNext; else m_ActiveEdges = AelNext; if (AelNext) AelNext->PrevInAEL = AelPrev; e->NextInAEL = 0; e->PrevInAEL = 0; } //------------------------------------------------------------------------------ OutRec* ClipperBase::CreateOutRec() { OutRec* result = new OutRec; result->IsHole = false; result->IsOpen = false; result->FirstLeft = 0; result->Pts = 0; result->BottomPt = 0; result->PolyNd = 0; m_PolyOuts.push_back(result); result->Idx = (int)m_PolyOuts.size() - 1; return result; } //------------------------------------------------------------------------------ void ClipperBase::SwapPositionsInAEL(TEdge *Edge1, TEdge *Edge2) { //check that one or other edge hasn't already been removed from AEL ... if (Edge1->NextInAEL == Edge1->PrevInAEL || Edge2->NextInAEL == Edge2->PrevInAEL) return; if (Edge1->NextInAEL == Edge2) { TEdge* Next = Edge2->NextInAEL; if (Next) Next->PrevInAEL = Edge1; TEdge* Prev = Edge1->PrevInAEL; if (Prev) Prev->NextInAEL = Edge2; Edge2->PrevInAEL = Prev; Edge2->NextInAEL = Edge1; Edge1->PrevInAEL = Edge2; Edge1->NextInAEL = Next; } else if (Edge2->NextInAEL == Edge1) { TEdge* Next = Edge1->NextInAEL; if (Next) Next->PrevInAEL = Edge2; TEdge* Prev = Edge2->PrevInAEL; if (Prev) Prev->NextInAEL = Edge1; Edge1->PrevInAEL = Prev; Edge1->NextInAEL = Edge2; Edge2->PrevInAEL = Edge1; Edge2->NextInAEL = Next; } else { TEdge* Next = Edge1->NextInAEL; TEdge* Prev = Edge1->PrevInAEL; Edge1->NextInAEL = Edge2->NextInAEL; if (Edge1->NextInAEL) Edge1->NextInAEL->PrevInAEL = Edge1; Edge1->PrevInAEL = Edge2->PrevInAEL; if (Edge1->PrevInAEL) Edge1->PrevInAEL->NextInAEL = Edge1; Edge2->NextInAEL = Next; if (Edge2->NextInAEL) Edge2->NextInAEL->PrevInAEL = Edge2; Edge2->PrevInAEL = Prev; if (Edge2->PrevInAEL) Edge2->PrevInAEL->NextInAEL = Edge2; } if (!Edge1->PrevInAEL) m_ActiveEdges = Edge1; else if (!Edge2->PrevInAEL) m_ActiveEdges = Edge2; } //------------------------------------------------------------------------------ void ClipperBase::UpdateEdgeIntoAEL(TEdge *&e) { if (!e->NextInLML) throw clipperException("UpdateEdgeIntoAEL: invalid call"); e->NextInLML->OutIdx = e->OutIdx; TEdge* AelPrev = e->PrevInAEL; TEdge* AelNext = e->NextInAEL; if (AelPrev) AelPrev->NextInAEL = e->NextInLML; else m_ActiveEdges = e->NextInLML; if (AelNext) AelNext->PrevInAEL = e->NextInLML; e->NextInLML->Side = e->Side; e->NextInLML->WindDelta = e->WindDelta; e->NextInLML->WindCnt = e->WindCnt; e->NextInLML->WindCnt2 = e->WindCnt2; e = e->NextInLML; e->Curr = e->Bot; e->PrevInAEL = AelPrev; e->NextInAEL = AelNext; if (!IsHorizontal(*e)) InsertScanbeam(e->Top.Y); } //------------------------------------------------------------------------------ bool ClipperBase::LocalMinimaPending() { return (m_CurrentLM != m_MinimaList.end()); } //------------------------------------------------------------------------------ // TClipper methods ... //------------------------------------------------------------------------------ Clipper::Clipper(int initOptions) : ClipperBase() //constructor { m_ExecuteLocked = false; m_UseFullRange = false; m_ReverseOutput = ((initOptions & ioReverseSolution) != 0); m_StrictSimple = ((initOptions & ioStrictlySimple) != 0); m_PreserveCollinear = ((initOptions & ioPreserveCollinear) != 0); m_HasOpenPaths = false; #ifdef use_xyz m_ZFill = 0; #endif } //------------------------------------------------------------------------------ #ifdef use_xyz void Clipper::ZFillFunction(ZFillCallback zFillFunc) { m_ZFill = zFillFunc; } //------------------------------------------------------------------------------ #endif bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType fillType) { return Execute(clipType, solution, fillType, fillType); } //------------------------------------------------------------------------------ bool Clipper::Execute(ClipType clipType, PolyTree &polytree, PolyFillType fillType) { return Execute(clipType, polytree, fillType, fillType); } //------------------------------------------------------------------------------ bool Clipper::Execute(ClipType clipType, Paths &solution, PolyFillType subjFillType, PolyFillType clipFillType) { if( m_ExecuteLocked ) return false; if (m_HasOpenPaths) throw clipperException("Error: PolyTree struct is needed for open path clipping."); m_ExecuteLocked = true; solution.resize(0); m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; m_UsingPolyTree = false; bool succeeded = ExecuteInternal(); if (succeeded) BuildResult(solution); DisposeAllOutRecs(); m_ExecuteLocked = false; return succeeded; } //------------------------------------------------------------------------------ bool Clipper::Execute(ClipType clipType, PolyTree& polytree, PolyFillType subjFillType, PolyFillType clipFillType) { if( m_ExecuteLocked ) return false; m_ExecuteLocked = true; m_SubjFillType = subjFillType; m_ClipFillType = clipFillType; m_ClipType = clipType; m_UsingPolyTree = true; bool succeeded = ExecuteInternal(); if (succeeded) BuildResult2(polytree); DisposeAllOutRecs(); m_ExecuteLocked = false; return succeeded; } //------------------------------------------------------------------------------ void Clipper::FixHoleLinkage(OutRec &outrec) { //skip OutRecs that (a) contain outermost polygons or //(b) already have the correct owner/child linkage ... if (!outrec.FirstLeft || (outrec.IsHole != outrec.FirstLeft->IsHole && outrec.FirstLeft->Pts)) return; OutRec* orfl = outrec.FirstLeft; while (orfl && ((orfl->IsHole == outrec.IsHole) || !orfl->Pts)) orfl = orfl->FirstLeft; outrec.FirstLeft = orfl; } //------------------------------------------------------------------------------ bool Clipper::ExecuteInternal() { bool succeeded = true; try { Reset(); m_Maxima = MaximaList(); m_SortedEdges = 0; succeeded = true; cInt botY, topY; if (!PopScanbeam(botY)) return false; InsertLocalMinimaIntoAEL(botY); while (PopScanbeam(topY) || LocalMinimaPending()) { ProcessHorizontals(); ClearGhostJoins(); if (!ProcessIntersections(topY)) { succeeded = false; break; } ProcessEdgesAtTopOfScanbeam(topY); botY = topY; InsertLocalMinimaIntoAEL(botY); } } catch(...) { succeeded = false; } if (succeeded) { //fix orientations ... for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec *outRec = m_PolyOuts[i]; if (!outRec->Pts || outRec->IsOpen) continue; if ((outRec->IsHole ^ m_ReverseOutput) == (Area(*outRec) > 0)) ReversePolyPtLinks(outRec->Pts); } if (!m_Joins.empty()) JoinCommonEdges(); //unfortunately FixupOutPolygon() must be done after JoinCommonEdges() for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec *outRec = m_PolyOuts[i]; if (!outRec->Pts) continue; if (outRec->IsOpen) FixupOutPolyline(*outRec); else FixupOutPolygon(*outRec); } if (m_StrictSimple) DoSimplePolygons(); } ClearJoins(); ClearGhostJoins(); return succeeded; } //------------------------------------------------------------------------------ void Clipper::SetWindingCount(TEdge &edge) { TEdge *e = edge.PrevInAEL; //find the edge of the same polytype that immediately preceeds 'edge' in AEL while (e && ((e->PolyTyp != edge.PolyTyp) || (e->WindDelta == 0))) e = e->PrevInAEL; if (!e) { if (edge.WindDelta == 0) { PolyFillType pft = (edge.PolyTyp == ptSubject ? m_SubjFillType : m_ClipFillType); edge.WindCnt = (pft == pftNegative ? -1 : 1); } else edge.WindCnt = edge.WindDelta; edge.WindCnt2 = 0; e = m_ActiveEdges; //ie get ready to calc WindCnt2 } else if (edge.WindDelta == 0 && m_ClipType != ctUnion) { edge.WindCnt = 1; edge.WindCnt2 = e->WindCnt2; e = e->NextInAEL; //ie get ready to calc WindCnt2 } else if (IsEvenOddFillType(edge)) { //EvenOdd filling ... if (edge.WindDelta == 0) { //are we inside a subj polygon ... bool Inside = true; TEdge *e2 = e->PrevInAEL; while (e2) { if (e2->PolyTyp == e->PolyTyp && e2->WindDelta != 0) Inside = !Inside; e2 = e2->PrevInAEL; } edge.WindCnt = (Inside ? 0 : 1); } else { edge.WindCnt = edge.WindDelta; } edge.WindCnt2 = e->WindCnt2; e = e->NextInAEL; //ie get ready to calc WindCnt2 } else { //nonZero, Positive or Negative filling ... if (e->WindCnt * e->WindDelta < 0) { //prev edge is 'decreasing' WindCount (WC) toward zero //so we're outside the previous polygon ... if (Abs(e->WindCnt) > 1) { //outside prev poly but still inside another. //when reversing direction of prev poly use the same WC if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt; //otherwise continue to 'decrease' WC ... else edge.WindCnt = e->WindCnt + edge.WindDelta; } else //now outside all polys of same polytype so set own WC ... edge.WindCnt = (edge.WindDelta == 0 ? 1 : edge.WindDelta); } else { //prev edge is 'increasing' WindCount (WC) away from zero //so we're inside the previous polygon ... if (edge.WindDelta == 0) edge.WindCnt = (e->WindCnt < 0 ? e->WindCnt - 1 : e->WindCnt + 1); //if wind direction is reversing prev then use same WC else if (e->WindDelta * edge.WindDelta < 0) edge.WindCnt = e->WindCnt; //otherwise add to WC ... else edge.WindCnt = e->WindCnt + edge.WindDelta; } edge.WindCnt2 = e->WindCnt2; e = e->NextInAEL; //ie get ready to calc WindCnt2 } //update WindCnt2 ... if (IsEvenOddAltFillType(edge)) { //EvenOdd filling ... while (e != &edge) { if (e->WindDelta != 0) edge.WindCnt2 = (edge.WindCnt2 == 0 ? 1 : 0); e = e->NextInAEL; } } else { //nonZero, Positive or Negative filling ... while ( e != &edge ) { edge.WindCnt2 += e->WindDelta; e = e->NextInAEL; } } } //------------------------------------------------------------------------------ bool Clipper::IsEvenOddFillType(const TEdge& edge) const { if (edge.PolyTyp == ptSubject) return m_SubjFillType == pftEvenOdd; else return m_ClipFillType == pftEvenOdd; } //------------------------------------------------------------------------------ bool Clipper::IsEvenOddAltFillType(const TEdge& edge) const { if (edge.PolyTyp == ptSubject) return m_ClipFillType == pftEvenOdd; else return m_SubjFillType == pftEvenOdd; } //------------------------------------------------------------------------------ bool Clipper::IsContributing(const TEdge& edge) const { PolyFillType pft, pft2; if (edge.PolyTyp == ptSubject) { pft = m_SubjFillType; pft2 = m_ClipFillType; } else { pft = m_ClipFillType; pft2 = m_SubjFillType; } switch(pft) { case pftEvenOdd: //return false if a subj line has been flagged as inside a subj polygon if (edge.WindDelta == 0 && edge.WindCnt != 1) return false; break; case pftNonZero: if (Abs(edge.WindCnt) != 1) return false; break; case pftPositive: if (edge.WindCnt != 1) return false; break; default: //pftNegative if (edge.WindCnt != -1) return false; } switch(m_ClipType) { case ctIntersection: switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 != 0); case pftPositive: return (edge.WindCnt2 > 0); default: return (edge.WindCnt2 < 0); } break; case ctUnion: switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 == 0); case pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } break; case ctDifference: if (edge.PolyTyp == ptSubject) switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 == 0); case pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } else switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 != 0); case pftPositive: return (edge.WindCnt2 > 0); default: return (edge.WindCnt2 < 0); } break; case ctXor: if (edge.WindDelta == 0) //XOr always contributing unless open switch(pft2) { case pftEvenOdd: case pftNonZero: return (edge.WindCnt2 == 0); case pftPositive: return (edge.WindCnt2 <= 0); default: return (edge.WindCnt2 >= 0); } else return true; break; default: return true; } } //------------------------------------------------------------------------------ OutPt* Clipper::AddLocalMinPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt) { OutPt* result; TEdge *e, *prevE; if (IsHorizontal(*e2) || ( e1->Dx > e2->Dx )) { result = AddOutPt(e1, Pt); e2->OutIdx = e1->OutIdx; e1->Side = esLeft; e2->Side = esRight; e = e1; if (e->PrevInAEL == e2) prevE = e2->PrevInAEL; else prevE = e->PrevInAEL; } else { result = AddOutPt(e2, Pt); e1->OutIdx = e2->OutIdx; e1->Side = esRight; e2->Side = esLeft; e = e2; if (e->PrevInAEL == e1) prevE = e1->PrevInAEL; else prevE = e->PrevInAEL; } if (prevE && prevE->OutIdx >= 0 && prevE->Top.Y < Pt.Y && e->Top.Y < Pt.Y) { cInt xPrev = TopX(*prevE, Pt.Y); cInt xE = TopX(*e, Pt.Y); if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) && SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange)) { OutPt* outPt = AddOutPt(prevE, Pt); AddJoin(result, outPt, e->Top); } } return result; } //------------------------------------------------------------------------------ void Clipper::AddLocalMaxPoly(TEdge *e1, TEdge *e2, const IntPoint &Pt) { AddOutPt( e1, Pt ); if (e2->WindDelta == 0) AddOutPt(e2, Pt); if( e1->OutIdx == e2->OutIdx ) { e1->OutIdx = Unassigned; e2->OutIdx = Unassigned; } else if (e1->OutIdx < e2->OutIdx) AppendPolygon(e1, e2); else AppendPolygon(e2, e1); } //------------------------------------------------------------------------------ void Clipper::AddEdgeToSEL(TEdge *edge) { //SEL pointers in PEdge are reused to build a list of horizontal edges. //However, we don't need to worry about order with horizontal edge processing. if( !m_SortedEdges ) { m_SortedEdges = edge; edge->PrevInSEL = 0; edge->NextInSEL = 0; } else { edge->NextInSEL = m_SortedEdges; edge->PrevInSEL = 0; m_SortedEdges->PrevInSEL = edge; m_SortedEdges = edge; } } //------------------------------------------------------------------------------ bool Clipper::PopEdgeFromSEL(TEdge *&edge) { if (!m_SortedEdges) return false; edge = m_SortedEdges; DeleteFromSEL(m_SortedEdges); return true; } //------------------------------------------------------------------------------ void Clipper::CopyAELToSEL() { TEdge* e = m_ActiveEdges; m_SortedEdges = e; while ( e ) { e->PrevInSEL = e->PrevInAEL; e->NextInSEL = e->NextInAEL; e = e->NextInAEL; } } //------------------------------------------------------------------------------ void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt) { Join* j = new Join; j->OutPt1 = op1; j->OutPt2 = op2; j->OffPt = OffPt; m_Joins.push_back(j); } //------------------------------------------------------------------------------ void Clipper::ClearJoins() { for (JoinList::size_type i = 0; i < m_Joins.size(); i++) delete m_Joins[i]; m_Joins.resize(0); } //------------------------------------------------------------------------------ void Clipper::ClearGhostJoins() { for (JoinList::size_type i = 0; i < m_GhostJoins.size(); i++) delete m_GhostJoins[i]; m_GhostJoins.resize(0); } //------------------------------------------------------------------------------ void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt) { Join* j = new Join; j->OutPt1 = op; j->OutPt2 = 0; j->OffPt = OffPt; m_GhostJoins.push_back(j); } //------------------------------------------------------------------------------ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) { const LocalMinimum *lm; while (PopLocalMinima(botY, lm)) { TEdge* lb = lm->LeftBound; TEdge* rb = lm->RightBound; OutPt *Op1 = 0; if (!lb) { //nb: don't insert LB into either AEL or SEL InsertEdgeIntoAEL(rb, 0); SetWindingCount(*rb); if (IsContributing(*rb)) Op1 = AddOutPt(rb, rb->Bot); } else if (!rb) { InsertEdgeIntoAEL(lb, 0); SetWindingCount(*lb); if (IsContributing(*lb)) Op1 = AddOutPt(lb, lb->Bot); InsertScanbeam(lb->Top.Y); } else { InsertEdgeIntoAEL(lb, 0); InsertEdgeIntoAEL(rb, lb); SetWindingCount( *lb ); rb->WindCnt = lb->WindCnt; rb->WindCnt2 = lb->WindCnt2; if (IsContributing(*lb)) Op1 = AddLocalMinPoly(lb, rb, lb->Bot); InsertScanbeam(lb->Top.Y); } if (rb) { if (IsHorizontal(*rb)) { AddEdgeToSEL(rb); if (rb->NextInLML) InsertScanbeam(rb->NextInLML->Top.Y); } else InsertScanbeam( rb->Top.Y ); } if (!lb || !rb) continue; //if any output polygons share an edge, they'll need joining later ... if (Op1 && IsHorizontal(*rb) && m_GhostJoins.size() > 0 && (rb->WindDelta != 0)) { for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i) { Join* jr = m_GhostJoins[i]; //if the horizontal Rb and a 'ghost' horizontal overlap, then convert //the 'ghost' join to a real join ready for later ... if (HorzSegmentsOverlap(jr->OutPt1->Pt.X, jr->OffPt.X, rb->Bot.X, rb->Top.X)) AddJoin(jr->OutPt1, Op1, jr->OffPt); } } if (lb->OutIdx >= 0 && lb->PrevInAEL && lb->PrevInAEL->Curr.X == lb->Bot.X && lb->PrevInAEL->OutIdx >= 0 && SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) && (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0)) { OutPt *Op2 = AddOutPt(lb->PrevInAEL, lb->Bot); AddJoin(Op1, Op2, lb->Top); } if(lb->NextInAEL != rb) { if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 && SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) && (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0)) { OutPt *Op2 = AddOutPt(rb->PrevInAEL, rb->Bot); AddJoin(Op1, Op2, rb->Top); } TEdge* e = lb->NextInAEL; if (e) { while( e != rb ) { //nb: For calculating winding counts etc, IntersectEdges() assumes //that param1 will be to the Right of param2 ABOVE the intersection ... IntersectEdges(rb , e , lb->Curr); //order important here e = e->NextInAEL; } } } } } //------------------------------------------------------------------------------ void Clipper::DeleteFromSEL(TEdge *e) { TEdge* SelPrev = e->PrevInSEL; TEdge* SelNext = e->NextInSEL; if( !SelPrev && !SelNext && (e != m_SortedEdges) ) return; //already deleted if( SelPrev ) SelPrev->NextInSEL = SelNext; else m_SortedEdges = SelNext; if( SelNext ) SelNext->PrevInSEL = SelPrev; e->NextInSEL = 0; e->PrevInSEL = 0; } //------------------------------------------------------------------------------ #ifdef use_xyz void Clipper::SetZ(IntPoint& pt, TEdge& e1, TEdge& e2) { if (pt.Z != 0 || !m_ZFill) return; else if (pt == e1.Bot) pt.Z = e1.Bot.Z; else if (pt == e1.Top) pt.Z = e1.Top.Z; else if (pt == e2.Bot) pt.Z = e2.Bot.Z; else if (pt == e2.Top) pt.Z = e2.Top.Z; else (*m_ZFill)(e1.Bot, e1.Top, e2.Bot, e2.Top, pt); } //------------------------------------------------------------------------------ #endif void Clipper::IntersectEdges(TEdge *e1, TEdge *e2, IntPoint &Pt) { bool e1Contributing = ( e1->OutIdx >= 0 ); bool e2Contributing = ( e2->OutIdx >= 0 ); #ifdef use_xyz SetZ(Pt, *e1, *e2); #endif #ifdef use_lines //if either edge is on an OPEN path ... if (e1->WindDelta == 0 || e2->WindDelta == 0) { //ignore subject-subject open path intersections UNLESS they //are both open paths, AND they are both 'contributing maximas' ... if (e1->WindDelta == 0 && e2->WindDelta == 0) return; //if intersecting a subj line with a subj poly ... else if (e1->PolyTyp == e2->PolyTyp && e1->WindDelta != e2->WindDelta && m_ClipType == ctUnion) { if (e1->WindDelta == 0) { if (e2Contributing) { AddOutPt(e1, Pt); if (e1Contributing) e1->OutIdx = Unassigned; } } else { if (e1Contributing) { AddOutPt(e2, Pt); if (e2Contributing) e2->OutIdx = Unassigned; } } } else if (e1->PolyTyp != e2->PolyTyp) { //toggle subj open path OutIdx on/off when Abs(clip.WndCnt) == 1 ... if ((e1->WindDelta == 0) && abs(e2->WindCnt) == 1 && (m_ClipType != ctUnion || e2->WindCnt2 == 0)) { AddOutPt(e1, Pt); if (e1Contributing) e1->OutIdx = Unassigned; } else if ((e2->WindDelta == 0) && (abs(e1->WindCnt) == 1) && (m_ClipType != ctUnion || e1->WindCnt2 == 0)) { AddOutPt(e2, Pt); if (e2Contributing) e2->OutIdx = Unassigned; } } return; } #endif //update winding counts... //assumes that e1 will be to the Right of e2 ABOVE the intersection if ( e1->PolyTyp == e2->PolyTyp ) { if ( IsEvenOddFillType( *e1) ) { int oldE1WindCnt = e1->WindCnt; e1->WindCnt = e2->WindCnt; e2->WindCnt = oldE1WindCnt; } else { if (e1->WindCnt + e2->WindDelta == 0 ) e1->WindCnt = -e1->WindCnt; else e1->WindCnt += e2->WindDelta; if ( e2->WindCnt - e1->WindDelta == 0 ) e2->WindCnt = -e2->WindCnt; else e2->WindCnt -= e1->WindDelta; } } else { if (!IsEvenOddFillType(*e2)) e1->WindCnt2 += e2->WindDelta; else e1->WindCnt2 = ( e1->WindCnt2 == 0 ) ? 1 : 0; if (!IsEvenOddFillType(*e1)) e2->WindCnt2 -= e1->WindDelta; else e2->WindCnt2 = ( e2->WindCnt2 == 0 ) ? 1 : 0; } PolyFillType e1FillType, e2FillType, e1FillType2, e2FillType2; if (e1->PolyTyp == ptSubject) { e1FillType = m_SubjFillType; e1FillType2 = m_ClipFillType; } else { e1FillType = m_ClipFillType; e1FillType2 = m_SubjFillType; } if (e2->PolyTyp == ptSubject) { e2FillType = m_SubjFillType; e2FillType2 = m_ClipFillType; } else { e2FillType = m_ClipFillType; e2FillType2 = m_SubjFillType; } cInt e1Wc, e2Wc; switch (e1FillType) { case pftPositive: e1Wc = e1->WindCnt; break; case pftNegative: e1Wc = -e1->WindCnt; break; default: e1Wc = Abs(e1->WindCnt); } switch(e2FillType) { case pftPositive: e2Wc = e2->WindCnt; break; case pftNegative: e2Wc = -e2->WindCnt; break; default: e2Wc = Abs(e2->WindCnt); } if ( e1Contributing && e2Contributing ) { if ((e1Wc != 0 && e1Wc != 1) || (e2Wc != 0 && e2Wc != 1) || (e1->PolyTyp != e2->PolyTyp && m_ClipType != ctXor) ) { AddLocalMaxPoly(e1, e2, Pt); } else { AddOutPt(e1, Pt); AddOutPt(e2, Pt); SwapSides( *e1 , *e2 ); SwapPolyIndexes( *e1 , *e2 ); } } else if ( e1Contributing ) { if (e2Wc == 0 || e2Wc == 1) { AddOutPt(e1, Pt); SwapSides(*e1, *e2); SwapPolyIndexes(*e1, *e2); } } else if ( e2Contributing ) { if (e1Wc == 0 || e1Wc == 1) { AddOutPt(e2, Pt); SwapSides(*e1, *e2); SwapPolyIndexes(*e1, *e2); } } else if ( (e1Wc == 0 || e1Wc == 1) && (e2Wc == 0 || e2Wc == 1)) { //neither edge is currently contributing ... cInt e1Wc2, e2Wc2; switch (e1FillType2) { case pftPositive: e1Wc2 = e1->WindCnt2; break; case pftNegative : e1Wc2 = -e1->WindCnt2; break; default: e1Wc2 = Abs(e1->WindCnt2); } switch (e2FillType2) { case pftPositive: e2Wc2 = e2->WindCnt2; break; case pftNegative: e2Wc2 = -e2->WindCnt2; break; default: e2Wc2 = Abs(e2->WindCnt2); } if (e1->PolyTyp != e2->PolyTyp) { AddLocalMinPoly(e1, e2, Pt); } else if (e1Wc == 1 && e2Wc == 1) switch( m_ClipType ) { case ctIntersection: if (e1Wc2 > 0 && e2Wc2 > 0) AddLocalMinPoly(e1, e2, Pt); break; case ctUnion: if ( e1Wc2 <= 0 && e2Wc2 <= 0 ) AddLocalMinPoly(e1, e2, Pt); break; case ctDifference: if (((e1->PolyTyp == ptClip) && (e1Wc2 > 0) && (e2Wc2 > 0)) || ((e1->PolyTyp == ptSubject) && (e1Wc2 <= 0) && (e2Wc2 <= 0))) AddLocalMinPoly(e1, e2, Pt); break; case ctXor: AddLocalMinPoly(e1, e2, Pt); } else SwapSides( *e1, *e2 ); } } //------------------------------------------------------------------------------ void Clipper::SetHoleState(TEdge *e, OutRec *outrec) { TEdge *e2 = e->PrevInAEL; TEdge *eTmp = 0; while (e2) { if (e2->OutIdx >= 0 && e2->WindDelta != 0) { if (!eTmp) eTmp = e2; else if (eTmp->OutIdx == e2->OutIdx) eTmp = 0; } e2 = e2->PrevInAEL; } if (!eTmp) { outrec->FirstLeft = 0; outrec->IsHole = false; } else { outrec->FirstLeft = m_PolyOuts[eTmp->OutIdx]; outrec->IsHole = !outrec->FirstLeft->IsHole; } } //------------------------------------------------------------------------------ OutRec* GetLowermostRec(OutRec *outRec1, OutRec *outRec2) { //work out which polygon fragment has the correct hole state ... if (!outRec1->BottomPt) outRec1->BottomPt = GetBottomPt(outRec1->Pts); if (!outRec2->BottomPt) outRec2->BottomPt = GetBottomPt(outRec2->Pts); OutPt *OutPt1 = outRec1->BottomPt; OutPt *OutPt2 = outRec2->BottomPt; if (OutPt1->Pt.Y > OutPt2->Pt.Y) return outRec1; else if (OutPt1->Pt.Y < OutPt2->Pt.Y) return outRec2; else if (OutPt1->Pt.X < OutPt2->Pt.X) return outRec1; else if (OutPt1->Pt.X > OutPt2->Pt.X) return outRec2; else if (OutPt1->Next == OutPt1) return outRec2; else if (OutPt2->Next == OutPt2) return outRec1; else if (FirstIsBottomPt(OutPt1, OutPt2)) return outRec1; else return outRec2; } //------------------------------------------------------------------------------ bool OutRec1RightOfOutRec2(OutRec* outRec1, OutRec* outRec2) { do { outRec1 = outRec1->FirstLeft; if (outRec1 == outRec2) return true; } while (outRec1); return false; } //------------------------------------------------------------------------------ OutRec* Clipper::GetOutRec(int Idx) { OutRec* outrec = m_PolyOuts[Idx]; while (outrec != m_PolyOuts[outrec->Idx]) outrec = m_PolyOuts[outrec->Idx]; return outrec; } //------------------------------------------------------------------------------ void Clipper::AppendPolygon(TEdge *e1, TEdge *e2) { //get the start and ends of both output polygons ... OutRec *outRec1 = m_PolyOuts[e1->OutIdx]; OutRec *outRec2 = m_PolyOuts[e2->OutIdx]; OutRec *holeStateRec; if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2; else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1; else holeStateRec = GetLowermostRec(outRec1, outRec2); //get the start and ends of both output polygons and //join e2 poly onto e1 poly and delete pointers to e2 ... OutPt* p1_lft = outRec1->Pts; OutPt* p1_rt = p1_lft->Prev; OutPt* p2_lft = outRec2->Pts; OutPt* p2_rt = p2_lft->Prev; //join e2 poly onto e1 poly and delete pointers to e2 ... if( e1->Side == esLeft ) { if( e2->Side == esLeft ) { //z y x a b c ReversePolyPtLinks(p2_lft); p2_lft->Next = p1_lft; p1_lft->Prev = p2_lft; p1_rt->Next = p2_rt; p2_rt->Prev = p1_rt; outRec1->Pts = p2_rt; } else { //x y z a b c p2_rt->Next = p1_lft; p1_lft->Prev = p2_rt; p2_lft->Prev = p1_rt; p1_rt->Next = p2_lft; outRec1->Pts = p2_lft; } } else { if( e2->Side == esRight ) { //a b c z y x ReversePolyPtLinks(p2_lft); p1_rt->Next = p2_rt; p2_rt->Prev = p1_rt; p2_lft->Next = p1_lft; p1_lft->Prev = p2_lft; } else { //a b c x y z p1_rt->Next = p2_lft; p2_lft->Prev = p1_rt; p1_lft->Prev = p2_rt; p2_rt->Next = p1_lft; } } outRec1->BottomPt = 0; if (holeStateRec == outRec2) { if (outRec2->FirstLeft != outRec1) outRec1->FirstLeft = outRec2->FirstLeft; outRec1->IsHole = outRec2->IsHole; } outRec2->Pts = 0; outRec2->BottomPt = 0; outRec2->FirstLeft = outRec1; int OKIdx = e1->OutIdx; int ObsoleteIdx = e2->OutIdx; e1->OutIdx = Unassigned; //nb: safe because we only get here via AddLocalMaxPoly e2->OutIdx = Unassigned; TEdge* e = m_ActiveEdges; while( e ) { if( e->OutIdx == ObsoleteIdx ) { e->OutIdx = OKIdx; e->Side = e1->Side; break; } e = e->NextInAEL; } outRec2->Idx = outRec1->Idx; } //------------------------------------------------------------------------------ OutPt* Clipper::AddOutPt(TEdge *e, const IntPoint &pt) { if( e->OutIdx < 0 ) { OutRec *outRec = CreateOutRec(); outRec->IsOpen = (e->WindDelta == 0); OutPt* newOp = new OutPt; outRec->Pts = newOp; newOp->Idx = outRec->Idx; newOp->Pt = pt; newOp->Next = newOp; newOp->Prev = newOp; if (!outRec->IsOpen) SetHoleState(e, outRec); e->OutIdx = outRec->Idx; return newOp; } else { OutRec *outRec = m_PolyOuts[e->OutIdx]; //OutRec.Pts is the 'Left-most' point & OutRec.Pts.Prev is the 'Right-most' OutPt* op = outRec->Pts; bool ToFront = (e->Side == esLeft); if (ToFront && (pt == op->Pt)) return op; else if (!ToFront && (pt == op->Prev->Pt)) return op->Prev; OutPt* newOp = new OutPt; newOp->Idx = outRec->Idx; newOp->Pt = pt; newOp->Next = op; newOp->Prev = op->Prev; newOp->Prev->Next = newOp; op->Prev = newOp; if (ToFront) outRec->Pts = newOp; return newOp; } } //------------------------------------------------------------------------------ OutPt* Clipper::GetLastOutPt(TEdge *e) { OutRec *outRec = m_PolyOuts[e->OutIdx]; if (e->Side == esLeft) return outRec->Pts; else return outRec->Pts->Prev; } //------------------------------------------------------------------------------ void Clipper::ProcessHorizontals() { TEdge* horzEdge; while (PopEdgeFromSEL(horzEdge)) ProcessHorizontal(horzEdge); } //------------------------------------------------------------------------------ inline bool IsMinima(TEdge *e) { return e && (e->Prev->NextInLML != e) && (e->Next->NextInLML != e); } //------------------------------------------------------------------------------ inline bool IsMaxima(TEdge *e, const cInt Y) { return e && e->Top.Y == Y && !e->NextInLML; } //------------------------------------------------------------------------------ inline bool IsIntermediate(TEdge *e, const cInt Y) { return e->Top.Y == Y && e->NextInLML; } //------------------------------------------------------------------------------ TEdge *GetMaximaPair(TEdge *e) { if ((e->Next->Top == e->Top) && !e->Next->NextInLML) return e->Next; else if ((e->Prev->Top == e->Top) && !e->Prev->NextInLML) return e->Prev; else return 0; } //------------------------------------------------------------------------------ TEdge *GetMaximaPairEx(TEdge *e) { //as GetMaximaPair() but returns 0 if MaxPair isn't in AEL (unless it's horizontal) TEdge* result = GetMaximaPair(e); if (result && (result->OutIdx == Skip || (result->NextInAEL == result->PrevInAEL && !IsHorizontal(*result)))) return 0; return result; } //------------------------------------------------------------------------------ void Clipper::SwapPositionsInSEL(TEdge *Edge1, TEdge *Edge2) { if( !( Edge1->NextInSEL ) && !( Edge1->PrevInSEL ) ) return; if( !( Edge2->NextInSEL ) && !( Edge2->PrevInSEL ) ) return; if( Edge1->NextInSEL == Edge2 ) { TEdge* Next = Edge2->NextInSEL; if( Next ) Next->PrevInSEL = Edge1; TEdge* Prev = Edge1->PrevInSEL; if( Prev ) Prev->NextInSEL = Edge2; Edge2->PrevInSEL = Prev; Edge2->NextInSEL = Edge1; Edge1->PrevInSEL = Edge2; Edge1->NextInSEL = Next; } else if( Edge2->NextInSEL == Edge1 ) { TEdge* Next = Edge1->NextInSEL; if( Next ) Next->PrevInSEL = Edge2; TEdge* Prev = Edge2->PrevInSEL; if( Prev ) Prev->NextInSEL = Edge1; Edge1->PrevInSEL = Prev; Edge1->NextInSEL = Edge2; Edge2->PrevInSEL = Edge1; Edge2->NextInSEL = Next; } else { TEdge* Next = Edge1->NextInSEL; TEdge* Prev = Edge1->PrevInSEL; Edge1->NextInSEL = Edge2->NextInSEL; if( Edge1->NextInSEL ) Edge1->NextInSEL->PrevInSEL = Edge1; Edge1->PrevInSEL = Edge2->PrevInSEL; if( Edge1->PrevInSEL ) Edge1->PrevInSEL->NextInSEL = Edge1; Edge2->NextInSEL = Next; if( Edge2->NextInSEL ) Edge2->NextInSEL->PrevInSEL = Edge2; Edge2->PrevInSEL = Prev; if( Edge2->PrevInSEL ) Edge2->PrevInSEL->NextInSEL = Edge2; } if( !Edge1->PrevInSEL ) m_SortedEdges = Edge1; else if( !Edge2->PrevInSEL ) m_SortedEdges = Edge2; } //------------------------------------------------------------------------------ TEdge* GetNextInAEL(TEdge *e, Direction dir) { return dir == dLeftToRight ? e->NextInAEL : e->PrevInAEL; } //------------------------------------------------------------------------------ void GetHorzDirection(TEdge& HorzEdge, Direction& Dir, cInt& Left, cInt& Right) { if (HorzEdge.Bot.X < HorzEdge.Top.X) { Left = HorzEdge.Bot.X; Right = HorzEdge.Top.X; Dir = dLeftToRight; } else { Left = HorzEdge.Top.X; Right = HorzEdge.Bot.X; Dir = dRightToLeft; } } //------------------------------------------------------------------------ /******************************************************************************* * Notes: Horizontal edges (HEs) at scanline intersections (ie at the Top or * * Bottom of a scanbeam) are processed as if layered. The order in which HEs * * are processed doesn't matter. HEs intersect with other HE Bot.Xs only [#] * * (or they could intersect with Top.Xs only, ie EITHER Bot.Xs OR Top.Xs), * * and with other non-horizontal edges [*]. Once these intersections are * * processed, intermediate HEs then 'promote' the Edge above (NextInLML) into * * the AEL. These 'promoted' edges may in turn intersect [%] with other HEs. * *******************************************************************************/ void Clipper::ProcessHorizontal(TEdge *horzEdge) { Direction dir; cInt horzLeft, horzRight; bool IsOpen = (horzEdge->WindDelta == 0); GetHorzDirection(*horzEdge, dir, horzLeft, horzRight); TEdge* eLastHorz = horzEdge, *eMaxPair = 0; while (eLastHorz->NextInLML && IsHorizontal(*eLastHorz->NextInLML)) eLastHorz = eLastHorz->NextInLML; if (!eLastHorz->NextInLML) eMaxPair = GetMaximaPair(eLastHorz); MaximaList::const_iterator maxIt; MaximaList::const_reverse_iterator maxRit; if (m_Maxima.size() > 0) { //get the first maxima in range (X) ... if (dir == dLeftToRight) { maxIt = m_Maxima.begin(); while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++; if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X) maxIt = m_Maxima.end(); } else { maxRit = m_Maxima.rbegin(); while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++; if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X) maxRit = m_Maxima.rend(); } } OutPt* op1 = 0; for (;;) //loop through consec. horizontal edges { bool IsLastHorz = (horzEdge == eLastHorz); TEdge* e = GetNextInAEL(horzEdge, dir); while(e) { //this code block inserts extra coords into horizontal edges (in output //polygons) whereever maxima touch these horizontal edges. This helps //'simplifying' polygons (ie if the Simplify property is set). if (m_Maxima.size() > 0) { if (dir == dLeftToRight) { while (maxIt != m_Maxima.end() && *maxIt < e->Curr.X) { if (horzEdge->OutIdx >= 0 && !IsOpen) AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y)); maxIt++; } } else { while (maxRit != m_Maxima.rend() && *maxRit > e->Curr.X) { if (horzEdge->OutIdx >= 0 && !IsOpen) AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y)); maxRit++; } } }; if ((dir == dLeftToRight && e->Curr.X > horzRight) || (dir == dRightToLeft && e->Curr.X < horzLeft)) break; //Also break if we've got to the end of an intermediate horizontal edge ... //nb: Smaller Dx's are to the right of larger Dx's ABOVE the horizontal. if (e->Curr.X == horzEdge->Top.X && horzEdge->NextInLML && e->Dx < horzEdge->NextInLML->Dx) break; if (horzEdge->OutIdx >= 0 && !IsOpen) //note: may be done multiple times { #ifdef use_xyz if (dir == dLeftToRight) SetZ(e->Curr, *horzEdge, *e); else SetZ(e->Curr, *e, *horzEdge); #endif op1 = AddOutPt(horzEdge, e->Curr); TEdge* eNextHorz = m_SortedEdges; while (eNextHorz) { if (eNextHorz->OutIdx >= 0 && HorzSegmentsOverlap(horzEdge->Bot.X, horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X)) { OutPt* op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz->Top); } eNextHorz = eNextHorz->NextInSEL; } AddGhostJoin(op1, horzEdge->Bot); } //OK, so far we're still in range of the horizontal Edge but make sure //we're at the last of consec. horizontals when matching with eMaxPair if(e == eMaxPair && IsLastHorz) { if (horzEdge->OutIdx >= 0) AddLocalMaxPoly(horzEdge, eMaxPair, horzEdge->Top); DeleteFromAEL(horzEdge); DeleteFromAEL(eMaxPair); return; } if(dir == dLeftToRight) { IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y); IntersectEdges(horzEdge, e, Pt); } else { IntPoint Pt = IntPoint(e->Curr.X, horzEdge->Curr.Y); IntersectEdges( e, horzEdge, Pt); } TEdge* eNext = GetNextInAEL(e, dir); SwapPositionsInAEL( horzEdge, e ); e = eNext; } //end while(e) //Break out of loop if HorzEdge.NextInLML is not also horizontal ... if (!horzEdge->NextInLML || !IsHorizontal(*horzEdge->NextInLML)) break; UpdateEdgeIntoAEL(horzEdge); if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Bot); GetHorzDirection(*horzEdge, dir, horzLeft, horzRight); } //end for (;;) if (horzEdge->OutIdx >= 0 && !op1) { op1 = GetLastOutPt(horzEdge); TEdge* eNextHorz = m_SortedEdges; while (eNextHorz) { if (eNextHorz->OutIdx >= 0 && HorzSegmentsOverlap(horzEdge->Bot.X, horzEdge->Top.X, eNextHorz->Bot.X, eNextHorz->Top.X)) { OutPt* op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz->Top); } eNextHorz = eNextHorz->NextInSEL; } AddGhostJoin(op1, horzEdge->Top); } if (horzEdge->NextInLML) { if(horzEdge->OutIdx >= 0) { op1 = AddOutPt( horzEdge, horzEdge->Top); UpdateEdgeIntoAEL(horzEdge); if (horzEdge->WindDelta == 0) return; //nb: HorzEdge is no longer horizontal here TEdge* ePrev = horzEdge->PrevInAEL; TEdge* eNext = horzEdge->NextInAEL; if (ePrev && ePrev->Curr.X == horzEdge->Bot.X && ePrev->Curr.Y == horzEdge->Bot.Y && ePrev->WindDelta != 0 && (ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y && SlopesEqual(*horzEdge, *ePrev, m_UseFullRange))) { OutPt* op2 = AddOutPt(ePrev, horzEdge->Bot); AddJoin(op1, op2, horzEdge->Top); } else if (eNext && eNext->Curr.X == horzEdge->Bot.X && eNext->Curr.Y == horzEdge->Bot.Y && eNext->WindDelta != 0 && eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y && SlopesEqual(*horzEdge, *eNext, m_UseFullRange)) { OutPt* op2 = AddOutPt(eNext, horzEdge->Bot); AddJoin(op1, op2, horzEdge->Top); } } else UpdateEdgeIntoAEL(horzEdge); } else { if (horzEdge->OutIdx >= 0) AddOutPt(horzEdge, horzEdge->Top); DeleteFromAEL(horzEdge); } } //------------------------------------------------------------------------------ bool Clipper::ProcessIntersections(const cInt topY) { if( !m_ActiveEdges ) return true; try { BuildIntersectList(topY); size_t IlSize = m_IntersectList.size(); if (IlSize == 0) return true; if (IlSize == 1 || FixupIntersectionOrder()) ProcessIntersectList(); else return false; } catch(...) { m_SortedEdges = 0; DisposeIntersectNodes(); throw clipperException("ProcessIntersections error"); } m_SortedEdges = 0; return true; } //------------------------------------------------------------------------------ void Clipper::DisposeIntersectNodes() { for (size_t i = 0; i < m_IntersectList.size(); ++i ) delete m_IntersectList[i]; m_IntersectList.clear(); } //------------------------------------------------------------------------------ void Clipper::BuildIntersectList(const cInt topY) { if ( !m_ActiveEdges ) return; //prepare for sorting ... TEdge* e = m_ActiveEdges; m_SortedEdges = e; while( e ) { e->PrevInSEL = e->PrevInAEL; e->NextInSEL = e->NextInAEL; e->Curr.X = TopX( *e, topY ); e = e->NextInAEL; } //bubblesort ... bool isModified; do { isModified = false; e = m_SortedEdges; while( e->NextInSEL ) { TEdge *eNext = e->NextInSEL; IntPoint Pt; if(e->Curr.X > eNext->Curr.X) { IntersectPoint(*e, *eNext, Pt); if (Pt.Y < topY) Pt = IntPoint(TopX(*e, topY), topY); IntersectNode * newNode = new IntersectNode; newNode->Edge1 = e; newNode->Edge2 = eNext; newNode->Pt = Pt; m_IntersectList.push_back(newNode); SwapPositionsInSEL(e, eNext); isModified = true; } else e = eNext; } if( e->PrevInSEL ) e->PrevInSEL->NextInSEL = 0; else break; } while ( isModified ); m_SortedEdges = 0; //important } //------------------------------------------------------------------------------ void Clipper::ProcessIntersectList() { for (size_t i = 0; i < m_IntersectList.size(); ++i) { IntersectNode* iNode = m_IntersectList[i]; { IntersectEdges( iNode->Edge1, iNode->Edge2, iNode->Pt); SwapPositionsInAEL( iNode->Edge1 , iNode->Edge2 ); } delete iNode; } m_IntersectList.clear(); } //------------------------------------------------------------------------------ bool IntersectListSort(IntersectNode* node1, IntersectNode* node2) { return node2->Pt.Y < node1->Pt.Y; } //------------------------------------------------------------------------------ inline bool EdgesAdjacent(const IntersectNode &inode) { return (inode.Edge1->NextInSEL == inode.Edge2) || (inode.Edge1->PrevInSEL == inode.Edge2); } //------------------------------------------------------------------------------ bool Clipper::FixupIntersectionOrder() { //pre-condition: intersections are sorted Bottom-most first. //Now it's crucial that intersections are made only between adjacent edges, //so to ensure this the order of intersections may need adjusting ... CopyAELToSEL(); std::sort(m_IntersectList.begin(), m_IntersectList.end(), IntersectListSort); size_t cnt = m_IntersectList.size(); for (size_t i = 0; i < cnt; ++i) { if (!EdgesAdjacent(*m_IntersectList[i])) { size_t j = i + 1; while (j < cnt && !EdgesAdjacent(*m_IntersectList[j])) j++; if (j == cnt) return false; std::swap(m_IntersectList[i], m_IntersectList[j]); } SwapPositionsInSEL(m_IntersectList[i]->Edge1, m_IntersectList[i]->Edge2); } return true; } //------------------------------------------------------------------------------ void Clipper::DoMaxima(TEdge *e) { TEdge* eMaxPair = GetMaximaPairEx(e); if (!eMaxPair) { if (e->OutIdx >= 0) AddOutPt(e, e->Top); DeleteFromAEL(e); return; } TEdge* eNext = e->NextInAEL; while(eNext && eNext != eMaxPair) { IntersectEdges(e, eNext, e->Top); SwapPositionsInAEL(e, eNext); eNext = e->NextInAEL; } if(e->OutIdx == Unassigned && eMaxPair->OutIdx == Unassigned) { DeleteFromAEL(e); DeleteFromAEL(eMaxPair); } else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 ) { if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top); DeleteFromAEL(e); DeleteFromAEL(eMaxPair); } #ifdef use_lines else if (e->WindDelta == 0) { if (e->OutIdx >= 0) { AddOutPt(e, e->Top); e->OutIdx = Unassigned; } DeleteFromAEL(e); if (eMaxPair->OutIdx >= 0) { AddOutPt(eMaxPair, e->Top); eMaxPair->OutIdx = Unassigned; } DeleteFromAEL(eMaxPair); } #endif else throw clipperException("DoMaxima error"); } //------------------------------------------------------------------------------ void Clipper::ProcessEdgesAtTopOfScanbeam(const cInt topY) { TEdge* e = m_ActiveEdges; while( e ) { //1. process maxima, treating them as if they're 'bent' horizontal edges, // but exclude maxima with horizontal edges. nb: e can't be a horizontal. bool IsMaximaEdge = IsMaxima(e, topY); if(IsMaximaEdge) { TEdge* eMaxPair = GetMaximaPairEx(e); IsMaximaEdge = (!eMaxPair || !IsHorizontal(*eMaxPair)); } if(IsMaximaEdge) { if (m_StrictSimple) m_Maxima.push_back(e->Top.X); TEdge* ePrev = e->PrevInAEL; DoMaxima(e); if( !ePrev ) e = m_ActiveEdges; else e = ePrev->NextInAEL; } else { //2. promote horizontal edges, otherwise update Curr.X and Curr.Y ... if (IsIntermediate(e, topY) && IsHorizontal(*e->NextInLML)) { UpdateEdgeIntoAEL(e); if (e->OutIdx >= 0) AddOutPt(e, e->Bot); AddEdgeToSEL(e); } else { e->Curr.X = TopX( *e, topY ); e->Curr.Y = topY; #ifdef use_xyz e->Curr.Z = topY == e->Top.Y ? e->Top.Z : (topY == e->Bot.Y ? e->Bot.Z : 0); #endif } //When StrictlySimple and 'e' is being touched by another edge, then //make sure both edges have a vertex here ... if (m_StrictSimple) { TEdge* ePrev = e->PrevInAEL; if ((e->OutIdx >= 0) && (e->WindDelta != 0) && ePrev && (ePrev->OutIdx >= 0) && (ePrev->Curr.X == e->Curr.X) && (ePrev->WindDelta != 0)) { IntPoint pt = e->Curr; #ifdef use_xyz SetZ(pt, *ePrev, *e); #endif OutPt* op = AddOutPt(ePrev, pt); OutPt* op2 = AddOutPt(e, pt); AddJoin(op, op2, pt); //StrictlySimple (type-3) join } } e = e->NextInAEL; } } //3. Process horizontals at the Top of the scanbeam ... m_Maxima.sort(); ProcessHorizontals(); m_Maxima.clear(); //4. Promote intermediate vertices ... e = m_ActiveEdges; while(e) { if(IsIntermediate(e, topY)) { OutPt* op = 0; if( e->OutIdx >= 0 ) op = AddOutPt(e, e->Top); UpdateEdgeIntoAEL(e); //if output polygons share an edge, they'll need joining later ... TEdge* ePrev = e->PrevInAEL; TEdge* eNext = e->NextInAEL; if (ePrev && ePrev->Curr.X == e->Bot.X && ePrev->Curr.Y == e->Bot.Y && op && ePrev->OutIdx >= 0 && ePrev->Curr.Y > ePrev->Top.Y && SlopesEqual(e->Curr, e->Top, ePrev->Curr, ePrev->Top, m_UseFullRange) && (e->WindDelta != 0) && (ePrev->WindDelta != 0)) { OutPt* op2 = AddOutPt(ePrev, e->Bot); AddJoin(op, op2, e->Top); } else if (eNext && eNext->Curr.X == e->Bot.X && eNext->Curr.Y == e->Bot.Y && op && eNext->OutIdx >= 0 && eNext->Curr.Y > eNext->Top.Y && SlopesEqual(e->Curr, e->Top, eNext->Curr, eNext->Top, m_UseFullRange) && (e->WindDelta != 0) && (eNext->WindDelta != 0)) { OutPt* op2 = AddOutPt(eNext, e->Bot); AddJoin(op, op2, e->Top); } } e = e->NextInAEL; } } //------------------------------------------------------------------------------ void Clipper::FixupOutPolyline(OutRec &outrec) { OutPt *pp = outrec.Pts; OutPt *lastPP = pp->Prev; while (pp != lastPP) { pp = pp->Next; if (pp->Pt == pp->Prev->Pt) { if (pp == lastPP) lastPP = pp->Prev; OutPt *tmpPP = pp->Prev; tmpPP->Next = pp->Next; pp->Next->Prev = tmpPP; delete pp; pp = tmpPP; } } if (pp == pp->Prev) { DisposeOutPts(pp); outrec.Pts = 0; return; } } //------------------------------------------------------------------------------ void Clipper::FixupOutPolygon(OutRec &outrec) { //FixupOutPolygon() - removes duplicate points and simplifies consecutive //parallel edges by removing the middle vertex. OutPt *lastOK = 0; outrec.BottomPt = 0; OutPt *pp = outrec.Pts; bool preserveCol = m_PreserveCollinear || m_StrictSimple; for (;;) { if (pp->Prev == pp || pp->Prev == pp->Next) { DisposeOutPts(pp); outrec.Pts = 0; return; } //test for duplicate points and collinear edges ... if ((pp->Pt == pp->Next->Pt) || (pp->Pt == pp->Prev->Pt) || (SlopesEqual(pp->Prev->Pt, pp->Pt, pp->Next->Pt, m_UseFullRange) && (!preserveCol || !Pt2IsBetweenPt1AndPt3(pp->Prev->Pt, pp->Pt, pp->Next->Pt)))) { lastOK = 0; OutPt *tmp = pp; pp->Prev->Next = pp->Next; pp->Next->Prev = pp->Prev; pp = pp->Prev; delete tmp; } else if (pp == lastOK) break; else { if (!lastOK) lastOK = pp; pp = pp->Next; } } outrec.Pts = pp; } //------------------------------------------------------------------------------ int PointCount(OutPt *Pts) { if (!Pts) return 0; int result = 0; OutPt* p = Pts; do { result++; p = p->Next; } while (p != Pts); return result; } //------------------------------------------------------------------------------ void Clipper::BuildResult(Paths &polys) { polys.reserve(m_PolyOuts.size()); for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { if (!m_PolyOuts[i]->Pts) continue; Path pg; OutPt* p = m_PolyOuts[i]->Pts->Prev; int cnt = PointCount(p); if (cnt < 2) continue; pg.reserve(cnt); for (int i = 0; i < cnt; ++i) { pg.push_back(p->Pt); p = p->Prev; } polys.push_back(pg); } } //------------------------------------------------------------------------------ void Clipper::BuildResult2(PolyTree& polytree) { polytree.Clear(); polytree.AllNodes.reserve(m_PolyOuts.size()); //add each output polygon/contour to polytree ... for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++) { OutRec* outRec = m_PolyOuts[i]; int cnt = PointCount(outRec->Pts); if ((outRec->IsOpen && cnt < 2) || (!outRec->IsOpen && cnt < 3)) continue; FixHoleLinkage(*outRec); PolyNode* pn = new PolyNode(); //nb: polytree takes ownership of all the PolyNodes polytree.AllNodes.push_back(pn); outRec->PolyNd = pn; pn->Parent = 0; pn->Index = 0; pn->Contour.reserve(cnt); OutPt *op = outRec->Pts->Prev; for (int j = 0; j < cnt; j++) { pn->Contour.push_back(op->Pt); op = op->Prev; } } //fixup PolyNode links etc ... polytree.Childs.reserve(m_PolyOuts.size()); for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); i++) { OutRec* outRec = m_PolyOuts[i]; if (!outRec->PolyNd) continue; if (outRec->IsOpen) { outRec->PolyNd->m_IsOpen = true; polytree.AddChild(*outRec->PolyNd); } else if (outRec->FirstLeft && outRec->FirstLeft->PolyNd) outRec->FirstLeft->PolyNd->AddChild(*outRec->PolyNd); else polytree.AddChild(*outRec->PolyNd); } } //------------------------------------------------------------------------------ void SwapIntersectNodes(IntersectNode &int1, IntersectNode &int2) { //just swap the contents (because fIntersectNodes is a single-linked-list) IntersectNode inode = int1; //gets a copy of Int1 int1.Edge1 = int2.Edge1; int1.Edge2 = int2.Edge2; int1.Pt = int2.Pt; int2.Edge1 = inode.Edge1; int2.Edge2 = inode.Edge2; int2.Pt = inode.Pt; } //------------------------------------------------------------------------------ inline bool E2InsertsBeforeE1(TEdge &e1, TEdge &e2) { if (e2.Curr.X == e1.Curr.X) { if (e2.Top.Y > e1.Top.Y) return e2.Top.X < TopX(e1, e2.Top.Y); else return e1.Top.X > TopX(e2, e1.Top.Y); } else return e2.Curr.X < e1.Curr.X; } //------------------------------------------------------------------------------ bool GetOverlap(const cInt a1, const cInt a2, const cInt b1, const cInt b2, cInt& Left, cInt& Right) { if (a1 < a2) { if (b1 < b2) {Left = std::max(a1,b1); Right = std::min(a2,b2);} else {Left = std::max(a1,b2); Right = std::min(a2,b1);} } else { if (b1 < b2) {Left = std::max(a2,b1); Right = std::min(a1,b2);} else {Left = std::max(a2,b2); Right = std::min(a1,b1);} } return Left < Right; } //------------------------------------------------------------------------------ inline void UpdateOutPtIdxs(OutRec& outrec) { OutPt* op = outrec.Pts; do { op->Idx = outrec.Idx; op = op->Prev; } while(op != outrec.Pts); } //------------------------------------------------------------------------------ void Clipper::InsertEdgeIntoAEL(TEdge *edge, TEdge* startEdge) { if(!m_ActiveEdges) { edge->PrevInAEL = 0; edge->NextInAEL = 0; m_ActiveEdges = edge; } else if(!startEdge && E2InsertsBeforeE1(*m_ActiveEdges, *edge)) { edge->PrevInAEL = 0; edge->NextInAEL = m_ActiveEdges; m_ActiveEdges->PrevInAEL = edge; m_ActiveEdges = edge; } else { if(!startEdge) startEdge = m_ActiveEdges; while(startEdge->NextInAEL && !E2InsertsBeforeE1(*startEdge->NextInAEL , *edge)) startEdge = startEdge->NextInAEL; edge->NextInAEL = startEdge->NextInAEL; if(startEdge->NextInAEL) startEdge->NextInAEL->PrevInAEL = edge; edge->PrevInAEL = startEdge; startEdge->NextInAEL = edge; } } //---------------------------------------------------------------------- OutPt* DupOutPt(OutPt* outPt, bool InsertAfter) { OutPt* result = new OutPt; result->Pt = outPt->Pt; result->Idx = outPt->Idx; if (InsertAfter) { result->Next = outPt->Next; result->Prev = outPt; outPt->Next->Prev = result; outPt->Next = result; } else { result->Prev = outPt->Prev; result->Next = outPt; outPt->Prev->Next = result; outPt->Prev = result; } return result; } //------------------------------------------------------------------------------ bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, const IntPoint Pt, bool DiscardLeft) { Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? dRightToLeft : dLeftToRight); Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? dRightToLeft : dLeftToRight); if (Dir1 == Dir2) return false; //When DiscardLeft, we want Op1b to be on the Left of Op1, otherwise we //want Op1b to be on the Right. (And likewise with Op2 and Op2b.) //So, to facilitate this while inserting Op1b and Op2b ... //when DiscardLeft, make sure we're AT or RIGHT of Pt before adding Op1b, //otherwise make sure we're AT or LEFT of Pt. (Likewise with Op2b.) if (Dir1 == dLeftToRight) { while (op1->Next->Pt.X <= Pt.X && op1->Next->Pt.X >= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) op1 = op1->Next; if (DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next; op1b = DupOutPt(op1, !DiscardLeft); if (op1b->Pt != Pt) { op1 = op1b; op1->Pt = Pt; op1b = DupOutPt(op1, !DiscardLeft); } } else { while (op1->Next->Pt.X >= Pt.X && op1->Next->Pt.X <= op1->Pt.X && op1->Next->Pt.Y == Pt.Y) op1 = op1->Next; if (!DiscardLeft && (op1->Pt.X != Pt.X)) op1 = op1->Next; op1b = DupOutPt(op1, DiscardLeft); if (op1b->Pt != Pt) { op1 = op1b; op1->Pt = Pt; op1b = DupOutPt(op1, DiscardLeft); } } if (Dir2 == dLeftToRight) { while (op2->Next->Pt.X <= Pt.X && op2->Next->Pt.X >= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) op2 = op2->Next; if (DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next; op2b = DupOutPt(op2, !DiscardLeft); if (op2b->Pt != Pt) { op2 = op2b; op2->Pt = Pt; op2b = DupOutPt(op2, !DiscardLeft); }; } else { while (op2->Next->Pt.X >= Pt.X && op2->Next->Pt.X <= op2->Pt.X && op2->Next->Pt.Y == Pt.Y) op2 = op2->Next; if (!DiscardLeft && (op2->Pt.X != Pt.X)) op2 = op2->Next; op2b = DupOutPt(op2, DiscardLeft); if (op2b->Pt != Pt) { op2 = op2b; op2->Pt = Pt; op2b = DupOutPt(op2, DiscardLeft); }; }; if ((Dir1 == dLeftToRight) == DiscardLeft) { op1->Prev = op2; op2->Next = op1; op1b->Next = op2b; op2b->Prev = op1b; } else { op1->Next = op2; op2->Prev = op1; op1b->Prev = op2b; op2b->Next = op1b; } return true; } //------------------------------------------------------------------------------ bool Clipper::JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2) { OutPt *op1 = j->OutPt1, *op1b; OutPt *op2 = j->OutPt2, *op2b; //There are 3 kinds of joins for output polygons ... //1. Horizontal joins where Join.OutPt1 & Join.OutPt2 are vertices anywhere //along (horizontal) collinear edges (& Join.OffPt is on the same horizontal). //2. Non-horizontal joins where Join.OutPt1 & Join.OutPt2 are at the same //location at the Bottom of the overlapping segment (& Join.OffPt is above). //3. StrictSimple joins where edges touch but are not collinear and where //Join.OutPt1, Join.OutPt2 & Join.OffPt all share the same point. bool isHorizontal = (j->OutPt1->Pt.Y == j->OffPt.Y); if (isHorizontal && (j->OffPt == j->OutPt1->Pt) && (j->OffPt == j->OutPt2->Pt)) { //Strictly Simple join ... if (outRec1 != outRec2) return false; op1b = j->OutPt1->Next; while (op1b != op1 && (op1b->Pt == j->OffPt)) op1b = op1b->Next; bool reverse1 = (op1b->Pt.Y > j->OffPt.Y); op2b = j->OutPt2->Next; while (op2b != op2 && (op2b->Pt == j->OffPt)) op2b = op2b->Next; bool reverse2 = (op2b->Pt.Y > j->OffPt.Y); if (reverse1 == reverse2) return false; if (reverse1) { op1b = DupOutPt(op1, false); op2b = DupOutPt(op2, true); op1->Prev = op2; op2->Next = op1; op1b->Next = op2b; op2b->Prev = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } else { op1b = DupOutPt(op1, true); op2b = DupOutPt(op2, false); op1->Next = op2; op2->Prev = op1; op1b->Prev = op2b; op2b->Next = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } } else if (isHorizontal) { //treat horizontal joins differently to non-horizontal joins since with //them we're not yet sure where the overlapping is. OutPt1.Pt & OutPt2.Pt //may be anywhere along the horizontal edge. op1b = op1; while (op1->Prev->Pt.Y == op1->Pt.Y && op1->Prev != op1b && op1->Prev != op2) op1 = op1->Prev; while (op1b->Next->Pt.Y == op1b->Pt.Y && op1b->Next != op1 && op1b->Next != op2) op1b = op1b->Next; if (op1b->Next == op1 || op1b->Next == op2) return false; //a flat 'polygon' op2b = op2; while (op2->Prev->Pt.Y == op2->Pt.Y && op2->Prev != op2b && op2->Prev != op1b) op2 = op2->Prev; while (op2b->Next->Pt.Y == op2b->Pt.Y && op2b->Next != op2 && op2b->Next != op1) op2b = op2b->Next; if (op2b->Next == op2 || op2b->Next == op1) return false; //a flat 'polygon' cInt Left, Right; //Op1 --> Op1b & Op2 --> Op2b are the extremites of the horizontal edges if (!GetOverlap(op1->Pt.X, op1b->Pt.X, op2->Pt.X, op2b->Pt.X, Left, Right)) return false; //DiscardLeftSide: when overlapping edges are joined, a spike will created //which needs to be cleaned up. However, we don't want Op1 or Op2 caught up //on the discard Side as either may still be needed for other joins ... IntPoint Pt; bool DiscardLeftSide; if (op1->Pt.X >= Left && op1->Pt.X <= Right) { Pt = op1->Pt; DiscardLeftSide = (op1->Pt.X > op1b->Pt.X); } else if (op2->Pt.X >= Left&& op2->Pt.X <= Right) { Pt = op2->Pt; DiscardLeftSide = (op2->Pt.X > op2b->Pt.X); } else if (op1b->Pt.X >= Left && op1b->Pt.X <= Right) { Pt = op1b->Pt; DiscardLeftSide = op1b->Pt.X > op1->Pt.X; } else { Pt = op2b->Pt; DiscardLeftSide = (op2b->Pt.X > op2->Pt.X); } j->OutPt1 = op1; j->OutPt2 = op2; return JoinHorz(op1, op1b, op2, op2b, Pt, DiscardLeftSide); } else { //nb: For non-horizontal joins ... // 1. Jr.OutPt1.Pt.Y == Jr.OutPt2.Pt.Y // 2. Jr.OutPt1.Pt > Jr.OffPt.Y //make sure the polygons are correctly oriented ... op1b = op1->Next; while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Next; bool Reverse1 = ((op1b->Pt.Y > op1->Pt.Y) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)); if (Reverse1) { op1b = op1->Prev; while ((op1b->Pt == op1->Pt) && (op1b != op1)) op1b = op1b->Prev; if ((op1b->Pt.Y > op1->Pt.Y) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)) return false; }; op2b = op2->Next; while ((op2b->Pt == op2->Pt) && (op2b != op2))op2b = op2b->Next; bool Reverse2 = ((op2b->Pt.Y > op2->Pt.Y) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)); if (Reverse2) { op2b = op2->Prev; while ((op2b->Pt == op2->Pt) && (op2b != op2)) op2b = op2b->Prev; if ((op2b->Pt.Y > op2->Pt.Y) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)) return false; } if ((op1b == op1) || (op2b == op2) || (op1b == op2b) || ((outRec1 == outRec2) && (Reverse1 == Reverse2))) return false; if (Reverse1) { op1b = DupOutPt(op1, false); op2b = DupOutPt(op2, true); op1->Prev = op2; op2->Next = op1; op1b->Next = op2b; op2b->Prev = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } else { op1b = DupOutPt(op1, true); op2b = DupOutPt(op2, false); op1->Next = op2; op2->Prev = op1; op1b->Prev = op2b; op2b->Next = op1b; j->OutPt1 = op1; j->OutPt2 = op1b; return true; } } } //---------------------------------------------------------------------- static OutRec* ParseFirstLeft(OutRec* FirstLeft) { while (FirstLeft && !FirstLeft->Pts) FirstLeft = FirstLeft->FirstLeft; return FirstLeft; } //------------------------------------------------------------------------------ void Clipper::FixupFirstLefts1(OutRec* OldOutRec, OutRec* NewOutRec) { //tests if NewOutRec contains the polygon before reassigning FirstLeft for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec* outRec = m_PolyOuts[i]; OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft); if (outRec->Pts && firstLeft == OldOutRec) { if (Poly2ContainsPoly1(outRec->Pts, NewOutRec->Pts)) outRec->FirstLeft = NewOutRec; } } } //---------------------------------------------------------------------- void Clipper::FixupFirstLefts2(OutRec* InnerOutRec, OutRec* OuterOutRec) { //A polygon has split into two such that one is now the inner of the other. //It's possible that these polygons now wrap around other polygons, so check //every polygon that's also contained by OuterOutRec's FirstLeft container //(including 0) to see if they've become inner to the new inner polygon ... OutRec* orfl = OuterOutRec->FirstLeft; for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec* outRec = m_PolyOuts[i]; if (!outRec->Pts || outRec == OuterOutRec || outRec == InnerOutRec) continue; OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft); if (firstLeft != orfl && firstLeft != InnerOutRec && firstLeft != OuterOutRec) continue; if (Poly2ContainsPoly1(outRec->Pts, InnerOutRec->Pts)) outRec->FirstLeft = InnerOutRec; else if (Poly2ContainsPoly1(outRec->Pts, OuterOutRec->Pts)) outRec->FirstLeft = OuterOutRec; else if (outRec->FirstLeft == InnerOutRec || outRec->FirstLeft == OuterOutRec) outRec->FirstLeft = orfl; } } //---------------------------------------------------------------------- void Clipper::FixupFirstLefts3(OutRec* OldOutRec, OutRec* NewOutRec) { //reassigns FirstLeft WITHOUT testing if NewOutRec contains the polygon for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) { OutRec* outRec = m_PolyOuts[i]; OutRec* firstLeft = ParseFirstLeft(outRec->FirstLeft); if (outRec->Pts && firstLeft == OldOutRec) outRec->FirstLeft = NewOutRec; } } //---------------------------------------------------------------------- void Clipper::JoinCommonEdges() { for (JoinList::size_type i = 0; i < m_Joins.size(); i++) { Join* join = m_Joins[i]; OutRec *outRec1 = GetOutRec(join->OutPt1->Idx); OutRec *outRec2 = GetOutRec(join->OutPt2->Idx); if (!outRec1->Pts || !outRec2->Pts) continue; if (outRec1->IsOpen || outRec2->IsOpen) continue; //get the polygon fragment with the correct hole state (FirstLeft) //before calling JoinPoints() ... OutRec *holeStateRec; if (outRec1 == outRec2) holeStateRec = outRec1; else if (OutRec1RightOfOutRec2(outRec1, outRec2)) holeStateRec = outRec2; else if (OutRec1RightOfOutRec2(outRec2, outRec1)) holeStateRec = outRec1; else holeStateRec = GetLowermostRec(outRec1, outRec2); if (!JoinPoints(join, outRec1, outRec2)) continue; if (outRec1 == outRec2) { //instead of joining two polygons, we've just created a new one by //splitting one polygon into two. outRec1->Pts = join->OutPt1; outRec1->BottomPt = 0; outRec2 = CreateOutRec(); outRec2->Pts = join->OutPt2; //update all OutRec2.Pts Idx's ... UpdateOutPtIdxs(*outRec2); if (Poly2ContainsPoly1(outRec2->Pts, outRec1->Pts)) { //outRec1 contains outRec2 ... outRec2->IsHole = !outRec1->IsHole; outRec2->FirstLeft = outRec1; if (m_UsingPolyTree) FixupFirstLefts2(outRec2, outRec1); if ((outRec2->IsHole ^ m_ReverseOutput) == (Area(*outRec2) > 0)) ReversePolyPtLinks(outRec2->Pts); } else if (Poly2ContainsPoly1(outRec1->Pts, outRec2->Pts)) { //outRec2 contains outRec1 ... outRec2->IsHole = outRec1->IsHole; outRec1->IsHole = !outRec2->IsHole; outRec2->FirstLeft = outRec1->FirstLeft; outRec1->FirstLeft = outRec2; if (m_UsingPolyTree) FixupFirstLefts2(outRec1, outRec2); if ((outRec1->IsHole ^ m_ReverseOutput) == (Area(*outRec1) > 0)) ReversePolyPtLinks(outRec1->Pts); } else { //the 2 polygons are completely separate ... outRec2->IsHole = outRec1->IsHole; outRec2->FirstLeft = outRec1->FirstLeft; //fixup FirstLeft pointers that may need reassigning to OutRec2 if (m_UsingPolyTree) FixupFirstLefts1(outRec1, outRec2); } } else { //joined 2 polygons together ... outRec2->Pts = 0; outRec2->BottomPt = 0; outRec2->Idx = outRec1->Idx; outRec1->IsHole = holeStateRec->IsHole; if (holeStateRec == outRec2) outRec1->FirstLeft = outRec2->FirstLeft; outRec2->FirstLeft = outRec1; if (m_UsingPolyTree) FixupFirstLefts3(outRec2, outRec1); } } } //------------------------------------------------------------------------------ // ClipperOffset support functions ... //------------------------------------------------------------------------------ DoublePoint GetUnitNormal(const IntPoint &pt1, const IntPoint &pt2) { if(pt2.X == pt1.X && pt2.Y == pt1.Y) return DoublePoint(0, 0); double Dx = (double)(pt2.X - pt1.X); double dy = (double)(pt2.Y - pt1.Y); double f = 1 *1.0/ std::sqrt( Dx*Dx + dy*dy ); Dx *= f; dy *= f; return DoublePoint(dy, -Dx); } //------------------------------------------------------------------------------ // ClipperOffset class //------------------------------------------------------------------------------ ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance) { this->MiterLimit = miterLimit; this->ArcTolerance = arcTolerance; m_lowest.X = -1; } //------------------------------------------------------------------------------ ClipperOffset::~ClipperOffset() { Clear(); } //------------------------------------------------------------------------------ void ClipperOffset::Clear() { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) delete m_polyNodes.Childs[i]; m_polyNodes.Childs.clear(); m_lowest.X = -1; } //------------------------------------------------------------------------------ void ClipperOffset::AddPath(const Path& path, JoinType joinType, EndType endType) { int highI = (int)path.size() - 1; if (highI < 0) return; PolyNode* newNode = new PolyNode(); newNode->m_jointype = joinType; newNode->m_endtype = endType; //strip duplicate points from path and also get index to the lowest point ... if (endType == etClosedLine || endType == etClosedPolygon) while (highI > 0 && path[0] == path[highI]) highI--; newNode->Contour.reserve(highI + 1); newNode->Contour.push_back(path[0]); int j = 0, k = 0; for (int i = 1; i <= highI; i++) if (newNode->Contour[j] != path[i]) { j++; newNode->Contour.push_back(path[i]); if (path[i].Y > newNode->Contour[k].Y || (path[i].Y == newNode->Contour[k].Y && path[i].X < newNode->Contour[k].X)) k = j; } if (endType == etClosedPolygon && j < 2) { delete newNode; return; } m_polyNodes.AddChild(*newNode); //if this path's lowest pt is lower than all the others then update m_lowest if (endType != etClosedPolygon) return; if (m_lowest.X < 0) m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k); else { IntPoint ip = m_polyNodes.Childs[(int)m_lowest.X]->Contour[(int)m_lowest.Y]; if (newNode->Contour[k].Y > ip.Y || (newNode->Contour[k].Y == ip.Y && newNode->Contour[k].X < ip.X)) m_lowest = IntPoint(m_polyNodes.ChildCount() - 1, k); } } //------------------------------------------------------------------------------ void ClipperOffset::AddPaths(const Paths& paths, JoinType joinType, EndType endType) { for (Paths::size_type i = 0; i < paths.size(); ++i) AddPath(paths[i], joinType, endType); } //------------------------------------------------------------------------------ void ClipperOffset::FixOrientations() { //fixup orientations of all closed paths if the orientation of the //closed path with the lowermost vertex is wrong ... if (m_lowest.X >= 0 && !Orientation(m_polyNodes.Childs[(int)m_lowest.X]->Contour)) { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) { PolyNode& node = *m_polyNodes.Childs[i]; if (node.m_endtype == etClosedPolygon || (node.m_endtype == etClosedLine && Orientation(node.Contour))) ReversePath(node.Contour); } } else { for (int i = 0; i < m_polyNodes.ChildCount(); ++i) { PolyNode& node = *m_polyNodes.Childs[i]; if (node.m_endtype == etClosedLine && !Orientation(node.Contour)) ReversePath(node.Contour); } } } //------------------------------------------------------------------------------ void ClipperOffset::Execute(Paths& solution, double delta) { solution.clear(); FixOrientations(); DoOffset(delta); //now clean up 'corners' ... Clipper clpr; clpr.AddPaths(m_destPolys, ptSubject, true); if (delta > 0) { clpr.Execute(ctUnion, solution, pftPositive, pftPositive); } else { IntRect r = clpr.GetBounds(); Path outer(4); outer[0] = IntPoint(r.left - 10, r.bottom + 10); outer[1] = IntPoint(r.right + 10, r.bottom + 10); outer[2] = IntPoint(r.right + 10, r.top - 10); outer[3] = IntPoint(r.left - 10, r.top - 10); clpr.AddPath(outer, ptSubject, true); clpr.ReverseSolution(true); clpr.Execute(ctUnion, solution, pftNegative, pftNegative); if (solution.size() > 0) solution.erase(solution.begin()); } } //------------------------------------------------------------------------------ void ClipperOffset::Execute(PolyTree& solution, double delta) { solution.Clear(); FixOrientations(); DoOffset(delta); //now clean up 'corners' ... Clipper clpr; clpr.AddPaths(m_destPolys, ptSubject, true); if (delta > 0) { clpr.Execute(ctUnion, solution, pftPositive, pftPositive); } else { IntRect r = clpr.GetBounds(); Path outer(4); outer[0] = IntPoint(r.left - 10, r.bottom + 10); outer[1] = IntPoint(r.right + 10, r.bottom + 10); outer[2] = IntPoint(r.right + 10, r.top - 10); outer[3] = IntPoint(r.left - 10, r.top - 10); clpr.AddPath(outer, ptSubject, true); clpr.ReverseSolution(true); clpr.Execute(ctUnion, solution, pftNegative, pftNegative); //remove the outer PolyNode rectangle ... if (solution.ChildCount() == 1 && solution.Childs[0]->ChildCount() > 0) { PolyNode* outerNode = solution.Childs[0]; solution.Childs.reserve(outerNode->ChildCount()); solution.Childs[0] = outerNode->Childs[0]; solution.Childs[0]->Parent = outerNode->Parent; for (int i = 1; i < outerNode->ChildCount(); ++i) solution.AddChild(*outerNode->Childs[i]); } else solution.Clear(); } } //------------------------------------------------------------------------------ void ClipperOffset::DoOffset(double delta) { m_destPolys.clear(); m_delta = delta; //if Zero offset, just copy any CLOSED polygons to m_p and return ... if (NEAR_ZERO(delta)) { m_destPolys.reserve(m_polyNodes.ChildCount()); for (int i = 0; i < m_polyNodes.ChildCount(); i++) { PolyNode& node = *m_polyNodes.Childs[i]; if (node.m_endtype == etClosedPolygon) m_destPolys.push_back(node.Contour); } return; } //see offset_triginometry3.svg in the documentation folder ... if (MiterLimit > 2) m_miterLim = 2/(MiterLimit * MiterLimit); else m_miterLim = 0.5; double y; if (ArcTolerance <= 0.0) y = def_arc_tolerance; else if (ArcTolerance > std::fabs(delta) * def_arc_tolerance) y = std::fabs(delta) * def_arc_tolerance; else y = ArcTolerance; //see offset_triginometry2.svg in the documentation folder ... double steps = pi / std::acos(1 - y / std::fabs(delta)); if (steps > std::fabs(delta) * pi) steps = std::fabs(delta) * pi; //ie excessive precision check m_sin = std::sin(two_pi / steps); m_cos = std::cos(two_pi / steps); m_StepsPerRad = steps / two_pi; if (delta < 0.0) m_sin = -m_sin; m_destPolys.reserve(m_polyNodes.ChildCount() * 2); for (int i = 0; i < m_polyNodes.ChildCount(); i++) { PolyNode& node = *m_polyNodes.Childs[i]; m_srcPoly = node.Contour; int len = (int)m_srcPoly.size(); if (len == 0 || (delta <= 0 && (len < 3 || node.m_endtype != etClosedPolygon))) continue; m_destPoly.clear(); if (len == 1) { if (node.m_jointype == jtRound) { double X = 1.0, Y = 0.0; for (cInt j = 1; j <= steps; j++) { m_destPoly.push_back(IntPoint( Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta))); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } } else { double X = -1.0, Y = -1.0; for (int j = 0; j < 4; ++j) { m_destPoly.push_back(IntPoint( Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta))); if (X < 0) X = 1; else if (Y < 0) Y = 1; else X = -1; } } m_destPolys.push_back(m_destPoly); continue; } //build m_normals ... m_normals.clear(); m_normals.reserve(len); for (int j = 0; j < len - 1; ++j) m_normals.push_back(GetUnitNormal(m_srcPoly[j], m_srcPoly[j + 1])); if (node.m_endtype == etClosedLine || node.m_endtype == etClosedPolygon) m_normals.push_back(GetUnitNormal(m_srcPoly[len - 1], m_srcPoly[0])); else m_normals.push_back(DoublePoint(m_normals[len - 2])); if (node.m_endtype == etClosedPolygon) { int k = len - 1; for (int j = 0; j < len; ++j) OffsetPoint(j, k, node.m_jointype); m_destPolys.push_back(m_destPoly); } else if (node.m_endtype == etClosedLine) { int k = len - 1; for (int j = 0; j < len; ++j) OffsetPoint(j, k, node.m_jointype); m_destPolys.push_back(m_destPoly); m_destPoly.clear(); //re-build m_normals ... DoublePoint n = m_normals[len -1]; for (int j = len - 1; j > 0; j--) m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); m_normals[0] = DoublePoint(-n.X, -n.Y); k = 0; for (int j = len - 1; j >= 0; j--) OffsetPoint(j, k, node.m_jointype); m_destPolys.push_back(m_destPoly); } else { int k = 0; for (int j = 1; j < len - 1; ++j) OffsetPoint(j, k, node.m_jointype); IntPoint pt1; if (node.m_endtype == etOpenButt) { int j = len - 1; pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X * delta), (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta)); m_destPoly.push_back(pt1); pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X * delta), (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta)); m_destPoly.push_back(pt1); } else { int j = len - 1; k = len - 2; m_sinA = 0; m_normals[j] = DoublePoint(-m_normals[j].X, -m_normals[j].Y); if (node.m_endtype == etOpenSquare) DoSquare(j, k); else DoRound(j, k); } //re-build m_normals ... for (int j = len - 1; j > 0; j--) m_normals[j] = DoublePoint(-m_normals[j - 1].X, -m_normals[j - 1].Y); m_normals[0] = DoublePoint(-m_normals[1].X, -m_normals[1].Y); k = len - 1; for (int j = k - 1; j > 0; --j) OffsetPoint(j, k, node.m_jointype); if (node.m_endtype == etOpenButt) { pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta), (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta)); m_destPoly.push_back(pt1); pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta), (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta)); m_destPoly.push_back(pt1); } else { k = 1; m_sinA = 0; if (node.m_endtype == etOpenSquare) DoSquare(0, 1); else DoRound(0, 1); } m_destPolys.push_back(m_destPoly); } } } //------------------------------------------------------------------------------ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) { //cross product ... m_sinA = (m_normals[k].X * m_normals[j].Y - m_normals[j].X * m_normals[k].Y); if (std::fabs(m_sinA * m_delta) < 1.0) { //dot product ... double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y ); if (cosA > 0) // angle => 0 degrees { m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); return; } //else angle => 180 degrees } else if (m_sinA > 1.0) m_sinA = 1.0; else if (m_sinA < -1.0) m_sinA = -1.0; if (m_sinA * m_delta < 0) { m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); m_destPoly.push_back(m_srcPoly[j]); m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta), Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); } else switch (jointype) { case jtMiter: { double r = 1 + (m_normals[j].X * m_normals[k].X + m_normals[j].Y * m_normals[k].Y); if (r >= m_miterLim) DoMiter(j, k, r); else DoSquare(j, k); break; } case jtSquare: DoSquare(j, k); break; case jtRound: DoRound(j, k); break; } k = j; } //------------------------------------------------------------------------------ void ClipperOffset::DoSquare(int j, int k) { double dx = std::tan(std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx)))); m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)), Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx)))); } //------------------------------------------------------------------------------ void ClipperOffset::DoMiter(int j, int k, double r) { double q = m_delta / r; m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q), Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q))); } //------------------------------------------------------------------------------ void ClipperOffset::DoRound(int j, int k) { double a = std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1); double X = m_normals[k].X, Y = m_normals[k].Y, X2; for (int i = 0; i < steps; ++i) { m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + X * m_delta), Round(m_srcPoly[j].Y + Y * m_delta))); X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } m_destPoly.push_back(IntPoint( Round(m_srcPoly[j].X + m_normals[j].X * m_delta), Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); } //------------------------------------------------------------------------------ // Miscellaneous public functions //------------------------------------------------------------------------------ void Clipper::DoSimplePolygons() { PolyOutList::size_type i = 0; while (i < m_PolyOuts.size()) { OutRec* outrec = m_PolyOuts[i++]; OutPt* op = outrec->Pts; if (!op || outrec->IsOpen) continue; do //for each Pt in Polygon until duplicate found do ... { OutPt* op2 = op->Next; while (op2 != outrec->Pts) { if ((op->Pt == op2->Pt) && op2->Next != op && op2->Prev != op) { //split the polygon into two ... OutPt* op3 = op->Prev; OutPt* op4 = op2->Prev; op->Prev = op4; op4->Next = op; op2->Prev = op3; op3->Next = op2; outrec->Pts = op; OutRec* outrec2 = CreateOutRec(); outrec2->Pts = op2; UpdateOutPtIdxs(*outrec2); if (Poly2ContainsPoly1(outrec2->Pts, outrec->Pts)) { //OutRec2 is contained by OutRec1 ... outrec2->IsHole = !outrec->IsHole; outrec2->FirstLeft = outrec; if (m_UsingPolyTree) FixupFirstLefts2(outrec2, outrec); } else if (Poly2ContainsPoly1(outrec->Pts, outrec2->Pts)) { //OutRec1 is contained by OutRec2 ... outrec2->IsHole = outrec->IsHole; outrec->IsHole = !outrec2->IsHole; outrec2->FirstLeft = outrec->FirstLeft; outrec->FirstLeft = outrec2; if (m_UsingPolyTree) FixupFirstLefts2(outrec, outrec2); } else { //the 2 polygons are separate ... outrec2->IsHole = outrec->IsHole; outrec2->FirstLeft = outrec->FirstLeft; if (m_UsingPolyTree) FixupFirstLefts1(outrec, outrec2); } op2 = op; //ie get ready for the Next iteration } op2 = op2->Next; } op = op->Next; } while (op != outrec->Pts); } } //------------------------------------------------------------------------------ void ReversePath(Path& p) { std::reverse(p.begin(), p.end()); } //------------------------------------------------------------------------------ void ReversePaths(Paths& p) { for (Paths::size_type i = 0; i < p.size(); ++i) ReversePath(p[i]); } //------------------------------------------------------------------------------ void SimplifyPolygon(const Path &in_poly, Paths &out_polys, PolyFillType fillType) { Clipper c; c.StrictlySimple(true); c.AddPath(in_poly, ptSubject, true); c.Execute(ctUnion, out_polys, fillType, fillType); } //------------------------------------------------------------------------------ void SimplifyPolygons(const Paths &in_polys, Paths &out_polys, PolyFillType fillType) { Clipper c; c.StrictlySimple(true); c.AddPaths(in_polys, ptSubject, true); c.Execute(ctUnion, out_polys, fillType, fillType); } //------------------------------------------------------------------------------ void SimplifyPolygons(Paths &polys, PolyFillType fillType) { SimplifyPolygons(polys, polys, fillType); } //------------------------------------------------------------------------------ inline double DistanceSqrd(const IntPoint& pt1, const IntPoint& pt2) { double Dx = ((double)pt1.X - pt2.X); double dy = ((double)pt1.Y - pt2.Y); return (Dx*Dx + dy*dy); } //------------------------------------------------------------------------------ double DistanceFromLineSqrd( const IntPoint& pt, const IntPoint& ln1, const IntPoint& ln2) { //The equation of a line in general form (Ax + By + C = 0) //given 2 points (x?y? & (x?y? is ... //(y?- y?x + (x?- x?y + (y?- y?x?- (x?- x?y?= 0 //A = (y?- y?; B = (x?- x?; C = (y?- y?x?- (x?- x?y? //perpendicular distance of point (x?y? = (Ax?+ By?+ C)/Sqrt(A?+ B? //see http://en.wikipedia.org/wiki/Perpendicular_distance double A = double(ln1.Y - ln2.Y); double B = double(ln2.X - ln1.X); double C = A * ln1.X + B * ln1.Y; C = A * pt.X + B * pt.Y - C; return (C * C) / (A * A + B * B); } //--------------------------------------------------------------------------- bool SlopesNearCollinear(const IntPoint& pt1, const IntPoint& pt2, const IntPoint& pt3, double distSqrd) { //this function is more accurate when the point that's geometrically //between the other 2 points is the one that's tested for distance. //ie makes it more likely to pick up 'spikes' ... if (Abs(pt1.X - pt2.X) > Abs(pt1.Y - pt2.Y)) { if ((pt1.X > pt2.X) == (pt1.X < pt3.X)) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; else if ((pt2.X > pt1.X) == (pt2.X < pt3.X)) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } else { if ((pt1.Y > pt2.Y) == (pt1.Y < pt3.Y)) return DistanceFromLineSqrd(pt1, pt2, pt3) < distSqrd; else if ((pt2.Y > pt1.Y) == (pt2.Y < pt3.Y)) return DistanceFromLineSqrd(pt2, pt1, pt3) < distSqrd; else return DistanceFromLineSqrd(pt3, pt1, pt2) < distSqrd; } } //------------------------------------------------------------------------------ bool PointsAreClose(IntPoint pt1, IntPoint pt2, double distSqrd) { double Dx = (double)pt1.X - pt2.X; double dy = (double)pt1.Y - pt2.Y; return ((Dx * Dx) + (dy * dy) <= distSqrd); } //------------------------------------------------------------------------------ OutPt* ExcludeOp(OutPt* op) { OutPt* result = op->Prev; result->Next = op->Next; op->Next->Prev = result; result->Idx = 0; return result; } //------------------------------------------------------------------------------ void CleanPolygon(const Path& in_poly, Path& out_poly, double distance) { //distance = proximity in units/pixels below which vertices //will be stripped. Default ~= sqrt(2). size_t size = in_poly.size(); if (size == 0) { out_poly.clear(); return; } OutPt* outPts = new OutPt[size]; for (size_t i = 0; i < size; ++i) { outPts[i].Pt = in_poly[i]; outPts[i].Next = &outPts[(i + 1) % size]; outPts[i].Next->Prev = &outPts[i]; outPts[i].Idx = 0; } double distSqrd = distance * distance; OutPt* op = &outPts[0]; while (op->Idx == 0 && op->Next != op->Prev) { if (PointsAreClose(op->Pt, op->Prev->Pt, distSqrd)) { op = ExcludeOp(op); size--; } else if (PointsAreClose(op->Prev->Pt, op->Next->Pt, distSqrd)) { ExcludeOp(op->Next); op = ExcludeOp(op); size -= 2; } else if (SlopesNearCollinear(op->Prev->Pt, op->Pt, op->Next->Pt, distSqrd)) { op = ExcludeOp(op); size--; } else { op->Idx = 1; op = op->Next; } } if (size < 3) size = 0; out_poly.resize(size); for (size_t i = 0; i < size; ++i) { out_poly[i] = op->Pt; op = op->Next; } delete [] outPts; } //------------------------------------------------------------------------------ void CleanPolygon(Path& poly, double distance) { CleanPolygon(poly, poly, distance); } //------------------------------------------------------------------------------ void CleanPolygons(const Paths& in_polys, Paths& out_polys, double distance) { out_polys.resize(in_polys.size()); for (Paths::size_type i = 0; i < in_polys.size(); ++i) CleanPolygon(in_polys[i], out_polys[i], distance); } //------------------------------------------------------------------------------ void CleanPolygons(Paths& polys, double distance) { CleanPolygons(polys, polys, distance); } //------------------------------------------------------------------------------ void Minkowski(const Path& poly, const Path& path, Paths& solution, bool isSum, bool isClosed) { int delta = (isClosed ? 1 : 0); size_t polyCnt = poly.size(); size_t pathCnt = path.size(); Paths pp; pp.reserve(pathCnt); if (isSum) for (size_t i = 0; i < pathCnt; ++i) { Path p; p.reserve(polyCnt); for (size_t j = 0; j < poly.size(); ++j) p.push_back(IntPoint(path[i].X + poly[j].X, path[i].Y + poly[j].Y)); pp.push_back(p); } else for (size_t i = 0; i < pathCnt; ++i) { Path p; p.reserve(polyCnt); for (size_t j = 0; j < poly.size(); ++j) p.push_back(IntPoint(path[i].X - poly[j].X, path[i].Y - poly[j].Y)); pp.push_back(p); } solution.clear(); solution.reserve((pathCnt + delta) * (polyCnt + 1)); for (size_t i = 0; i < pathCnt - 1 + delta; ++i) for (size_t j = 0; j < polyCnt; ++j) { Path quad; quad.reserve(4); quad.push_back(pp[i % pathCnt][j % polyCnt]); quad.push_back(pp[(i + 1) % pathCnt][j % polyCnt]); quad.push_back(pp[(i + 1) % pathCnt][(j + 1) % polyCnt]); quad.push_back(pp[i % pathCnt][(j + 1) % polyCnt]); if (!Orientation(quad)) ReversePath(quad); solution.push_back(quad); } } //------------------------------------------------------------------------------ void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool pathIsClosed) { Minkowski(pattern, path, solution, true, pathIsClosed); Clipper c; c.AddPaths(solution, ptSubject, true); c.Execute(ctUnion, solution, pftNonZero, pftNonZero); } //------------------------------------------------------------------------------ void TranslatePath(const Path& input, Path& output, const IntPoint delta) { //precondition: input != output output.resize(input.size()); for (size_t i = 0; i < input.size(); ++i) output[i] = IntPoint(input[i].X + delta.X, input[i].Y + delta.Y); } //------------------------------------------------------------------------------ void MinkowskiSum(const Path& pattern, const Paths& paths, Paths& solution, bool pathIsClosed) { Clipper c; for (size_t i = 0; i < paths.size(); ++i) { Paths tmp; Minkowski(pattern, paths[i], tmp, true, pathIsClosed); c.AddPaths(tmp, ptSubject, true); if (pathIsClosed) { Path tmp2; TranslatePath(paths[i], tmp2, pattern[0]); c.AddPath(tmp2, ptClip, true); } } c.Execute(ctUnion, solution, pftNonZero, pftNonZero); } //------------------------------------------------------------------------------ void MinkowskiDiff(const Path& poly1, const Path& poly2, Paths& solution) { Minkowski(poly1, poly2, solution, false, true); Clipper c; c.AddPaths(solution, ptSubject, true); c.Execute(ctUnion, solution, pftNonZero, pftNonZero); } //------------------------------------------------------------------------------ enum NodeType {ntAny, ntOpen, ntClosed}; void AddPolyNodeToPaths(const PolyNode& polynode, NodeType nodetype, Paths& paths) { bool match = true; if (nodetype == ntClosed) match = !polynode.IsOpen(); else if (nodetype == ntOpen) return; if (!polynode.Contour.empty() && match) paths.push_back(polynode.Contour); for (int i = 0; i < polynode.ChildCount(); ++i) AddPolyNodeToPaths(*polynode.Childs[i], nodetype, paths); } //------------------------------------------------------------------------------ void PolyTreeToPaths(const PolyTree& polytree, Paths& paths) { paths.resize(0); paths.reserve(polytree.Total()); AddPolyNodeToPaths(polytree, ntAny, paths); } //------------------------------------------------------------------------------ void ClosedPathsFromPolyTree(const PolyTree& polytree, Paths& paths) { paths.resize(0); paths.reserve(polytree.Total()); AddPolyNodeToPaths(polytree, ntClosed, paths); } //------------------------------------------------------------------------------ void OpenPathsFromPolyTree(PolyTree& polytree, Paths& paths) { paths.resize(0); paths.reserve(polytree.Total()); //Open paths are top level only, so ... for (int i = 0; i < polytree.ChildCount(); ++i) if (polytree.Childs[i]->IsOpen()) paths.push_back(polytree.Childs[i]->Contour); } //------------------------------------------------------------------------------ std::ostream& operator <<(std::ostream &s, const IntPoint &p) { s << "(" << p.X << "," << p.Y << ")"; return s; } //------------------------------------------------------------------------------ std::ostream& operator <<(std::ostream &s, const Path &p) { if (p.empty()) return s; Path::size_type last = p.size() -1; for (Path::size_type i = 0; i < last; i++) s << "(" << p[i].X << "," << p[i].Y << "), "; s << "(" << p[last].X << "," << p[last].Y << ")\n"; return s; } //------------------------------------------------------------------------------ std::ostream& operator <<(std::ostream &s, const Paths &p) { for (Paths::size_type i = 0; i < p.size(); i++) s << p[i]; s << "\n"; return s; } //------------------------------------------------------------------------------ } //ClipperLib namespace
lymastee/gslib
ext/clipper/clipper.cpp
C++
mit
137,526
module AttrValidator # Copied from here https://github.com/rails/rails/blob/master/activesupport/lib/active_support/concern.rb # # A typical module looks like this: # # module M # def self.included(base) # base.extend ClassMethods # base.class_eval do # scope :disabled, -> { where(disabled: true) } # end # end # # module ClassMethods # ... # end # end # # By using <tt>ActiveSupport::Concern</tt> the above module could instead be # written as: # # require 'active_support/concern' # # module M # extend ActiveSupport::Concern # # included do # scope :disabled, -> { where(disabled: true) } # end # # module ClassMethods # ... # end # end # # Moreover, it gracefully handles module dependencies. Given a +Foo+ module # and a +Bar+ module which depends on the former, we would typically write the # following: # # module Foo # def self.included(base) # base.class_eval do # def self.method_injected_by_foo # ... # end # end # end # end # # module Bar # def self.included(base) # base.method_injected_by_foo # end # end # # class Host # include Foo # We need to include this dependency for Bar # include Bar # Bar is the module that Host really needs # end # # But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We # could try to hide these from +Host+ directly including +Foo+ in +Bar+: # # module Bar # include Foo # def self.included(base) # base.method_injected_by_foo # end # end # # class Host # include Bar # end # # Unfortunately this won't work, since when +Foo+ is included, its <tt>base</tt> # is the +Bar+ module, not the +Host+ class. With <tt>ActiveSupport::Concern</tt>, # module dependencies are properly resolved: # # require 'active_support/concern' # # module Foo # extend ActiveSupport::Concern # included do # def self.method_injected_by_foo # ... # end # end # end # # module Bar # extend ActiveSupport::Concern # include Foo # # included do # self.method_injected_by_foo # end # end # # class Host # include Bar # works, Bar takes care now of its dependencies # end module Concern class MultipleIncludedBlocks < StandardError #:nodoc: def initialize super "Cannot define multiple 'included' blocks for a Concern" end end def self.extended(base) #:nodoc: base.instance_variable_set(:@_dependencies, []) end def append_features(base) if base.instance_variable_defined?(:@_dependencies) base.instance_variable_get(:@_dependencies) << self return false else return false if base < self @_dependencies.each { |dep| base.send(:include, dep) } super base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods) base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block) end end def included(base = nil, &block) if base.nil? raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block) @_included_block = block else super end end end end
AlbertGazizov/attr_validator
lib/attr_validator/concern.rb
Ruby
mit
3,476
package ca.codybanman.AstroidEscape; import org.robovm.apple.foundation.NSAutoreleasePool; import org.robovm.apple.uikit.UIApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplication; import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration; import ca.codybanman.AstroidEscape.AEGame; public class IOSLauncher extends IOSApplication.Delegate { @Override protected IOSApplication createApplication() { IOSApplicationConfiguration config = new IOSApplicationConfiguration(); return new IOSApplication(new AEGame(), config); } public static void main(String[] argv) { NSAutoreleasePool pool = new NSAutoreleasePool(); UIApplication.main(argv, null, IOSLauncher.class); pool.close(); } }
crbanman/AstroidEscape
ios/src/ca/codybanman/AstroidEscape/IOSLauncher.java
Java
mit
772
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; using System.IO; namespace TimeOut { public partial class partido : Form { Team local; // Equipo local Team visitor; // Equipo visitante List<Registro> minuteToMinute = new List<Registro>(); Counter count = new Counter(); // Constante que guarda la cantidad limite // de faltas permitidas previo a la expulsión const int maxFaltas = 6; /* * Hay dos largos procesos en un partido, * suceden cuando hay Falta o cuando hay Balon Afuera. */ bool procesoFalta = false; bool procesoBalonAfuera = false; bool localTeamShoot = false; // Cantidad de tiros libres a tirar tras la falta int tirosLibresDisponibles = 0; // This will be checked in the close event, // avoiding unnintentional actions and lose of data. bool closeWindow = false; // Clase para guardar el registro completo del partido Match partidoJugado; // Archivo para guardar el registro del partido string archivoPartidos = ""; public string ArchivoPartidos { get { return archivoPartidos; } set { archivoPartidos = value; } } /// <summary> /// El constructor de la clase. /// </summary> /// <param name="a">Equipo local</param> /// <param name="b">Equipo visitante</param> public partido(Team a, Team b) { InitializeComponent(); local = a; visitor = b; if (a != null && b != null) { actualizarListbox(); this.label_tituloLocal.Text = local.Name; this.label_tituloVisitante.Text = visitor.Name; this.label_LTO_restante.Text = Team.TOmax.ToString(); this.label_VTO_restante.Text = Team.TOmax.ToString(); } } public void actualizarListbox() { cargarTitulares(); cargarVisitantes(); } void cargarTitulares() { listBox_LocalRoster.Items.Clear(); comboBox_LocalSubs.Items.Clear(); foreach (Player p in this.local.Players) { if (p.Starter) listBox_LocalRoster.Items.Add(p); else comboBox_LocalSubs.Items.Add(p); } listBox_LocalRoster.DisplayMember = "CompleteName"; comboBox_LocalSubs.DisplayMember = "CompleteName"; } void cargarVisitantes() { listBox_VisitorRoster.Items.Clear(); comboBox_VisitorSubs.Items.Clear(); foreach (Player p in this.visitor.Players) { if (p.Starter) listBox_VisitorRoster.Items.Add(p); else comboBox_VisitorSubs.Items.Add(p); } listBox_VisitorRoster.DisplayMember = "CompleteName"; comboBox_VisitorSubs.DisplayMember = "CompleteName"; } /// <summary> /// Agrega un partido en una lista generica. /// </summary> /// <param name="equipo">Partido que sera agregado a la lista.</param> /// <param name="listaEquipos">Lista que tiene el resto de los partidos</param> /// <returns>La misma lista con el partido agregado</returns> List<Match> addMatchToList(Match partido, List<Match> listaPartidos) { if (listaPartidos == null) listaPartidos = new List<Match>(); listaPartidos.Add(partido); return listaPartidos; } /// <summary> /// Guarda el partido y su información en el archivo /// </summary> void guardarPartidoEnArchivo() { // Load previous matchs from file List<Match> listaDePartidos = Main.CargarPartidos(); // Add the new match to the list listaDePartidos = addMatchToList(this.partidoJugado, listaDePartidos); // Store the updated list to the file StreamWriter flujo = new StreamWriter(this.archivoPartidos); XmlSerializer serial = new XmlSerializer(typeof(List<Match>)); serial.Serialize(flujo, listaDePartidos); flujo.Close(); } /// <summary> /// Guarda las estadísticas recogidas durante el partido. /// </summary> void guardarInformación() { // Crea la lista this.partidoJugado = new Match(); // Add match's metadata partidoJugado.Fecha = DateTime.Now; partidoJugado.EquipoLocal = local.Name; partidoJugado.EquipoVisitante = visitor.Name; // Agrega los nombres de TODOS los jugadores // y sus respectivas estadísticas foreach(Player p in local.Players) { partidoJugado.JugadoresLocales.Add(p.CompleteName); // Agrega las estadísticas sumandolas a las actuales partidoJugado.EstadisticasLocal.Asistencias += p.AsistenciasLogradas; partidoJugado.EstadisticasLocal.SimplesEncestados += p.TirosLibresAnotados; partidoJugado.EstadisticasLocal.SimplesFallidos += p.TirosLibresFallados; partidoJugado.EstadisticasLocal.DoblesEncestados += p.PuntosDoblesAnotados; partidoJugado.EstadisticasLocal.DoblesFallidos += p.PuntosDoblesFallados; partidoJugado.EstadisticasLocal.TriplesEncestados += p.PuntosTriplesAnotados; partidoJugado.EstadisticasLocal.TriplesFallidos += p.PuntosTriplesFallados; partidoJugado.EstadisticasLocal.RebotesDefensivos += p.RebotesDefensivos; partidoJugado.EstadisticasLocal.RebotesOfensivos += p.RebotesOfensivos; partidoJugado.EstadisticasLocal.Faltas += p.FaltasCometidas; } foreach(Player p in visitor.Players) { partidoJugado.JugadoresVisitantes.Add(p.CompleteName); // Agrega las estadísticas sumandolas a las actuales partidoJugado.EstadisticasVisitante.Asistencias += p.AsistenciasLogradas; partidoJugado.EstadisticasVisitante.SimplesEncestados += p.TirosLibresAnotados; partidoJugado.EstadisticasVisitante.SimplesFallidos += p.TirosLibresFallados; partidoJugado.EstadisticasVisitante.DoblesEncestados += p.PuntosDoblesAnotados; partidoJugado.EstadisticasVisitante.DoblesFallidos += p.PuntosDoblesFallados; partidoJugado.EstadisticasVisitante.TriplesEncestados += p.PuntosTriplesAnotados; partidoJugado.EstadisticasVisitante.TriplesFallidos += p.PuntosTriplesFallados; partidoJugado.EstadisticasVisitante.RebotesDefensivos += p.RebotesDefensivos; partidoJugado.EstadisticasVisitante.RebotesOfensivos += p.RebotesOfensivos; partidoJugado.EstadisticasVisitante.Faltas += p.FaltasCometidas; } guardarPartidoEnArchivo(); } /// <summary> /// Activa el botón de Comienzo del partido /// </summary> void activarContinuacion() { timer1.Stop(); button1.Text = "Comenzar"; button1.Enabled = true; this.button1.BackColor = Color.DeepSkyBlue; } /// <summary> /// Congela/detiene el reloj del partido y desactiva el botón de Comienzo /// </summary> void congelarContinuacion() { timer1.Stop(); button1.Text = "Parado"; button1.Enabled = false; this.button1.BackColor = Color.Red; } /// <summary> /// Pone el reloj a correr y desactiva el botón /// </summary> void correrContinuacion() { timer1.Enabled = true; button1.Text = "Pausar"; button1.Enabled = true; this.button1.BackColor = Color.Red; } /// <summary> /// Evento llamado cuando finaliza el encuentro. /// </summary> void finishMatch() { timer1.Stop(); button1.Text = "Finalizado"; button1.Enabled = false; button1.BackColor = Color.Black; // Almacena la información recolectada del encuentro guardarInformación(); // Display a minute-to-minute chart ShowEvents nuevo = new ShowEvents(this.minuteToMinute); nuevo.ShowDialog(); // Desactiva la pregunta al salir closeWindow = true; this.Close(); } /// <summary> /// Cambia el contexto de la ventana deacuerdo al momento correspondiente /// </summary> void finalizarCuarto() { count.resetCounter(); activarContinuacion(); // Restablece los tiempos muertos this.local.restartTO(); this.visitor.restartTO(); // Desactiva botones no disponibles desactivarCambio(); desactivarTO(); desactivarPuntos(); desactivarFalta(); desactivarPerdida(); desactivarRebotes(); if (this.lblCuarto.Text[0] == '1') this.lblCuarto.Text = "2do Cuarto"; else if (this.lblCuarto.Text[0] == '2') this.lblCuarto.Text = "3er Cuarto"; else if (this.lblCuarto.Text[0] == '3') this.lblCuarto.Text = "4to Cuarto"; else finishMatch(); } private void timer1_Tick(object sender, EventArgs e) { count.decCounter(); this.label_timer.Text = count.getCounter; if (count.getCounter == "00:00:00") finalizarCuarto(); } #region Activar y Desactivar botones y labels #region Desactivar y Activar puntos void desactivarDoblesLocal() { btn_dobleEncestado_L.Enabled = false; btn_dobleErrado_L.Enabled = false; } void desactivarDoblesVisitante() { btn_dobleEncestado_V.Enabled = false; btn_dobleErrado_V.Enabled = false; } void desactivarTriplesLocal() { btn_tripleEncestado_L.Enabled = false; btn_tripleErrado_L.Enabled = false; } void desactivarTriplesVisitante() { btn_tripleEncestado_V.Enabled = false; btn_tripleErrado_V.Enabled = false; } void desactivarPuntos() { desactivarDoblesLocal(); desactivarDoblesVisitante(); desactivarTriplesLocal(); desactivarTriplesVisitante(); } void activarDoblesLocal() { btn_dobleEncestado_L.Enabled = true; btn_dobleErrado_L.Enabled = true; } void activarDoblesVisitante() { btn_dobleEncestado_V.Enabled = true; btn_dobleErrado_V.Enabled = true; } void activarTriplesLocal() { btn_tripleEncestado_L.Enabled = true; btn_tripleErrado_L.Enabled = true; } void activarTriplesVisitante() { btn_tripleEncestado_V.Enabled = true; btn_tripleErrado_V.Enabled = true; } void activarPuntos() { activarDoblesLocal(); activarDoblesVisitante(); activarTriplesLocal(); activarTriplesVisitante(); } #endregion void activarFalta() { button_faltaL.Enabled = true; button_faltaV.Enabled = true; } void desactivarFalta() { button_faltaL.Enabled = false; button_faltaV.Enabled = false; } void activarPerdida() { //button_perdidaL.Enabled = true; //button_perdidaV.Enabled = true; } void desactivarPerdida() { //button_perdidaL.Enabled = false; //button_perdidaV.Enabled = false; } void activarCambio() { this.button_changeL.Visible = true; this.button_changeV.Visible = true; } void desactivarCambio() { this.button_changeL.Visible = false; this.button_changeV.Visible = false; } void activarTOLocal() { if (local.TiemposMuertosRestantes > 0) this.LocalTO.Enabled = true; } void activarTOVisitante() { if (visitor.TiemposMuertosRestantes > 0) this.VisitorTO.Enabled = true; } void activarTO() { activarTOLocal(); activarTOVisitante(); } void desactivarTOLocal() { this.LocalTO.Enabled = false; } void desactivarTOVisitante() { this.VisitorTO.Enabled = false; } void desactivarTO() { desactivarTOLocal(); desactivarTOVisitante(); } void activarLibreLocal() { btn_libreEncestado_L.Enabled = true; btn_libreErrado_L.Enabled = true; } void desactivarLibreLocal() { btn_libreEncestado_L.Enabled = false; btn_libreErrado_L.Enabled = false; } void activarLibreVisitante() { btn_libreEncestado_V.Enabled = true; btn_libreErrado_V.Enabled = true; } void desactivarLibreVisitante() { btn_libreEncestado_V.Enabled = false; btn_libreErrado_V.Enabled = false; } /// <summary> /// Activa el rebote defensivo del equipo defensor y /// el rebote ofensivo del equipo atacante /// </summary> /// <param name="defensivoLocal">Si es falso, el visitante esta defendiendo el rebote</param> void activarRebotes(bool defensivoLocal = true) { if (defensivoLocal) { this.btn_rebote_Defensivo_L.Visible = true; this.btn_rebote_Ofensivo_V.Visible = true; } else { this.btn_rebote_Ofensivo_L.Visible = true; this.btn_rebote_Defensivo_V.Visible = true; } } /// <summary> /// Desactiva TODOS los rebotes de TODOS los equipos /// </summary> void desactivarRebotes() { // Locales this.btn_rebote_Defensivo_L.Visible = false; this.btn_rebote_Ofensivo_L.Visible = false; // y Visitantes this.btn_rebote_Ofensivo_V.Visible = false; this.btn_rebote_Defensivo_V.Visible = false; } #endregion #region Registros void registrarSimple(string nombreJugador, bool encestado = true) { string cuarto = lblCuarto.Text[0].ToString(); string evento = (encestado) ? "Tiro Libre Anotado" : "Tiro Libre Fallado"; Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador); minuteToMinute.Add(r); } void registrarDoble(string nombreJugador, bool encestado = true) { string cuarto = lblCuarto.Text[0].ToString(); string evento = (encestado) ? "Doble Anotado" : "Doble Fallado"; Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador); minuteToMinute.Add(r); } void registrarTriple(string nombreJugador, bool encestado = true) { string cuarto = lblCuarto.Text[0].ToString(); string evento = (encestado) ? "Triple Anotado" : "Triple Fallado"; Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador); minuteToMinute.Add(r); } void registrarRebote(string nombreJugador, bool ofensivo = false) { string cuarto = lblCuarto.Text[0].ToString(); string evento = (ofensivo) ? "Rebote Ofensivo" : "Rebote Defensivo"; Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador); minuteToMinute.Add(r); } void registrarFalta(string nombreJugador) { string cuarto = lblCuarto.Text[0].ToString(); Registro r = new Registro(cuarto, this.label_timer.Text, "Falta", nombreJugador); minuteToMinute.Add(r); } /// <summary> /// Registra una canasta simple, doble o triple Encestada. Cambia el anotador del partido /// </summary> /// <param name="valor">Puede ser 1, 2 o 3</param> /// <param name="jugador">Jugador al que se le asignara el punto</param> /// <param name="local">Si es falso, corresponde al equipo visitante</param> void anotacion(int valor, Player jugador, bool local = true) { switch (valor) { case 1: jugador.TirosLibresAnotados++; registrarSimple(jugador.CompleteName); break; case 2: jugador.PuntosDoblesAnotados++; registrarDoble(jugador.CompleteName); break; case 3: jugador.PuntosTriplesAnotados++; registrarTriple(jugador.CompleteName); break; } Label score = null; if (local) score = this.label_ptsLocal; else score = this.label_ptsVsitor; int pts = Convert.ToInt32(score.Text) + valor; score.Text = pts.ToString(); } /// <summary> /// Registra una canasta simple, doble o triple Fallida. /// Of course it does not change the scorer /// </summary> /// <param name="valor">Puede ser 1, 2 o 3</param> /// <param name="jugador">Jugador al que se le asignara el fallo</param> void fallo(int valor, Player jugador) { switch (valor) { case 1: jugador.TirosLibresFallados++; registrarSimple(jugador.CompleteName, false); break; case 2: jugador.PuntosDoblesFallados++; registrarDoble(jugador.CompleteName, false); break; case 3: jugador.PuntosTriplesFallados++; registrarTriple(jugador.CompleteName, false); break; } } #endregion // ******************** // // * METODOS LLAMADOS * // // * POR EL USUARIO * // // ******************** // /// <summary> /// Sucede cuando el usuario presiona el boton de "Comienzo" del partido /// </summary> private void button1_Click(object sender, EventArgs e) { desactivarCambio(); desactivarRebotes(); desactivarPuntos(); desactivarPerdida(); desactivarFalta(); desactivarLibreLocal(); desactivarLibreVisitante(); if (procesoFalta) { MessageBox.Show("Se continua con los tiros libres.."); congelarContinuacion(); activarCambio(); // Check which team received fault and enable its free shoots if (localTeamShoot) activarLibreLocal(); else activarLibreVisitante(); localTeamShoot = false; } else { // Check if time is running... if (timer1.Enabled) { //... User want to stop timing desactivarPerdida(); desactivarPuntos(); desactivarFalta(); activarContinuacion(); activarCambio(); } else { //... User want to continue timing activarFalta(); activarPerdida(); activarTO(); activarPuntos(); correrContinuacion(); } } } /// <summary> /// Sucede cuando el usuario realiza un Tiempo Muerto para el LOCAL /// </summary> private void LocalTO_Click(object sender, EventArgs e) { // Cambia la interfaz del usuario // Parar reloj y dejarlo a disposición del usuario activarContinuacion(); activarCambio(); // Desactiva los controles no disponibles desactivarTO(); desactivarPuntos(); desactivarFalta(); desactivarPerdida(); desactivarLibreLocal(); desactivarRebotes(); // Asigna los tiempos muertos local.TiemposMuertosRestantes--; this.label_LTO_restante.Text = local.TiemposMuertosRestantes.ToString(); if (local.TiemposMuertosRestantes == 0) this.LocalTO.Enabled = false; if (procesoFalta) { localTeamShoot = true; } } /// <summary> /// Sucede cuando el usuario realiza un Tiempo Muerto para el VISITANTE /// </summary> private void VisitorTO_Click(object sender, EventArgs e) { // Cambia la interfaz del usuario // Parar reloj y dejarlo a disposición del usuario activarContinuacion(); activarCambio(); // Desactiva los controles no disponibles desactivarTO(); desactivarPuntos(); desactivarFalta(); desactivarPerdida(); desactivarLibreVisitante(); desactivarRebotes(); // Asigna los tiempos muertos visitor.TiemposMuertosRestantes--; this.label_VTO_restante.Text = visitor.TiemposMuertosRestantes.ToString(); if (visitor.TiemposMuertosRestantes == 0) this.VisitorTO.Enabled = false; } /// <summary> /// Sucede cuando el usuario quiere realizar un cambio del LOCAL /// </summary> private void button2_Click(object sender, EventArgs e) { if (listBox_LocalRoster.SelectedItem != null && comboBox_LocalSubs.SelectedItem != null) { Player p = (Player)listBox_LocalRoster.SelectedItem; p.Starter = false; p = (Player)comboBox_LocalSubs.SelectedItem; p.Starter = true; // Actualizar cargarTitulares(); } } /// <summary> /// Sucede cuando el usuario quiere realizar un cambio del VISITANTE /// </summary> private void button3_Click(object sender, EventArgs e) { if (listBox_VisitorRoster.SelectedItem != null && comboBox_VisitorSubs.SelectedItem != null) { Player p = (Player)listBox_VisitorRoster.SelectedItem; p.Starter = false; p = (Player)comboBox_VisitorSubs.SelectedItem; p.Starter = true; // Actualizar cargarVisitantes(); } } /// <summary> /// Sucede cuando el equipo LOCAL comete una falta /// </summary> private void button_faltaL_Click(object sender, EventArgs e) { congelarContinuacion(); desactivarFalta(); desactivarPerdida(); desactivarTOLocal(); activarTOVisitante(); if (listBox_LocalRoster.SelectedItem != null) { // Agrega la Falta al Jugador y Registra el evento Player p = (Player)listBox_LocalRoster.SelectedItem; p.FaltasCometidas++; registrarFalta(p.CompleteName); // Fire player from game if reached limit of faults committed if (p.FaltasCometidas == maxFaltas) listBox_LocalRoster.Items.Remove(p); // Check if player was shooting while received the fault DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?", "Posicion de tiro", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (userResponce == DialogResult.Yes) { //desactivarTO(); procesoFalta = true; // Activa el proceso falta desactivarDoblesLocal(); desactivarTriplesLocal(); } else // Saque desde el costado { desactivarPuntos(); desactivarRebotes(); // Activa el boton de Comienzo activarContinuacion(); procesoBalonAfuera = true; // Activa el proceso Balon Afuera } } else // No se conoce el jugador que realizo la falta { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; button_faltaL_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE comete una falta /// </summary> private void button_faltaV_Click(object sender, EventArgs e) { congelarContinuacion(); desactivarFalta(); desactivarPerdida(); desactivarTOVisitante(); activarTOLocal(); if (listBox_VisitorRoster.SelectedItem != null) { // Agrega la Falta al Jugador y Registra el evento Player p = (Player)listBox_VisitorRoster.SelectedItem; p.FaltasCometidas++; registrarFalta(p.CompleteName); // Fire player from game if reached limit of faults committed if (p.FaltasCometidas == maxFaltas) listBox_VisitorRoster.Items.Remove(p); // Check if player was shooting while received the fault DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?", "Posicion de tiro", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (userResponce == DialogResult.Yes) { //desactivarTO(); procesoFalta = true; // Activa el proceso falta desactivarDoblesVisitante(); desactivarTriplesVisitante(); } else // Saque desde el costado { desactivarPuntos(); desactivarRebotes(); // Activa el boton de Comienzo activarContinuacion(); procesoBalonAfuera = true; // Activa el proceso Balon Afuera } } else // No se conoce el jugador que realizo la falta { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; button_faltaV_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo LOCAL encesta un DOBLE /// </summary> private void btn_DobleEns_L_Click(object sender, EventArgs e) { // Detiene el reloj timer1.Enabled = false; Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { anotacion(2, aux); desactivarPuntos(); desactivarRebotes(); desactivarFalta(); desactivarPerdida(); // Check if player has received a fault while shooting if (procesoFalta) { // Cambia la interfaz del usuario activarTOLocal(); activarLibreLocal(); desactivarPuntos(); // Tira 1 tiro libre al recibir falta en zona de 2 punto tirosLibresDisponibles = 1; //TODO // Muestra el Estado //toolStripStatusLabel1.Text = "" } else { desactivarTOLocal(); // Activa el boton de Comienzo activarContinuacion(); } } else { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_DobleEns_L_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE encesta un DOBLE /// </summary> private void btn_dobleEncestado_V_Click(object sender, EventArgs e) { // Detiene el reloj timer1.Enabled = false; Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { anotacion(2, aux, false); desactivarPuntos(); desactivarRebotes(); desactivarFalta(); desactivarPerdida(); // Check if player has received a fault while shooting if (procesoFalta) { // Cambia la interfaz gráfica activarTOVisitante(); activarLibreVisitante(); desactivarPuntos(); // Tira 1 tiro libre al recibir falta en zona de 2 punto // Tira 1 tiro libre tirosLibresDisponibles = 1; } else { desactivarTOVisitante(); // Activa el boton de Comienzo activarContinuacion(); } } else { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_dobleEncestado_V_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo LOCAL encesta un TRIPLE /// </summary> private void btn_tripleEncestado_L_Click(object sender, EventArgs e) { // Detiene el reloj timer1.Enabled = false; Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { anotacion(3, aux); desactivarPuntos(); desactivarRebotes(); desactivarFalta(); desactivarPerdida(); // Check if player has received a fault while shooting if (procesoFalta) { // Cambia la interfaz del usuario activarTOLocal(); activarLibreLocal(); desactivarPuntos(); // Jugada de 4 puntos!! oh yeah! tirosLibresDisponibles = 1; // Tira 1 tiro libre } else { desactivarTOLocal(); // Activa el boton de Comienzo activarContinuacion(); } } else { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_DobleEns_L_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE encesta un TRIPLE /// </summary> private void btn_tripleEncestado_V_Click(object sender, EventArgs e) { // Detiene el reloj timer1.Enabled = false; Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { anotacion(3, aux, false); desactivarPuntos(); desactivarRebotes(); desactivarFalta(); desactivarPerdida(); // Check if player has received a fault while shooting if (procesoFalta) { // Cambia la interfaz del usuario activarTOVisitante(); activarLibreVisitante(); desactivarPuntos(); // Jugada de 4 puntos!! oh yeah! tirosLibresDisponibles = 1; // Tira 1 tiro libre } else { desactivarTOVisitante(); // Activa el boton de Comienzo activarContinuacion(); } } else { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_tripleEncestado_V_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo LOCAL erra un DOBLE /// </summary> private void btn_DobleErrado_L_Click(object sender, EventArgs e) { desactivarPuntos(); if (procesoFalta) { // Cambia la interfaz del usuario activarTOLocal(); activarLibreLocal(); desactivarFalta(); desactivarPerdida(); // Tirara 2 tiros libres tirosLibresDisponibles = 2; } else { Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { fallo(2, aux); // Change UI state activarRebotes(false); desactivarTOVisitante(); } else { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_DobleErrado_L_Click(sender, e); } } } /// <summary> /// Sucede cuando el equipo VISITANTE erra un DOBLE /// </summary> private void btn_dobleErrado_V_Click(object sender, EventArgs e) { desactivarPuntos(); if (procesoFalta) { // Cambia la interfaz del usuario activarTOVisitante(); activarLibreVisitante(); desactivarFalta(); desactivarPerdida(); // Tirara 2 tiros libres tirosLibresDisponibles = 2; } else { Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { fallo(2, aux); // Change UI state activarRebotes(); desactivarTOLocal(); } else { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_dobleErrado_V_Click(sender, e); } } } /// <summary> /// Sucede cuando el equipo LOCAL erra un TRIPLE /// </summary> private void btn_tripleErrado_L_Click(object sender, EventArgs e) { desactivarPuntos(); if (procesoFalta) { // Cambia la interfaz del usuario activarTOLocal(); activarLibreLocal(); desactivarFalta(); desactivarPerdida(); // Tirara 3 tiros libres tirosLibresDisponibles = 3; } else { Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { fallo(3, aux); // Change UI state activarRebotes(false); desactivarTOVisitante(); } else { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_DobleErrado_L_Click(sender, e); } } } /// <summary> /// Sucede cuando el equipo VISITANTE erra un TRIPLE /// </summary> private void btn_tripleErrado_V_Click(object sender, EventArgs e) { desactivarPuntos(); if (procesoFalta) { // Cambia la interfaz del usuario activarTOVisitante(); activarLibreVisitante(); desactivarFalta(); desactivarPerdida(); // Tirara 3 tiros libres tirosLibresDisponibles = 3; } else { Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { fallo(3, aux); // Change UI state activarRebotes(); desactivarTOLocal(); } else { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_dobleErrado_V_Click(sender, e); } } } /// <summary> /// Sucede cuando el equipo LOCAL logra un rebote OFENSIVO /// </summary> private void btn_rebote_L_Click(object sender, EventArgs e) { Player aux = (Player)listBox_LocalRoster.SelectedItem; if(aux != null) { // Registra el rebote aux.RebotesOfensivos++; registrarRebote(aux.CompleteName, true); // Cambial el entorno desactivarRebotes(); activarFalta(); activarPerdida(); activarPuntos(); // Activa TODOS los tiempos muertos activarTO(); // Vuelve a correr el reloj! correrContinuacion(); } else { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_rebote_L_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE logra un rebote OFENSIVO /// </summary> private void btn_rebote_Ofensivo_V_Click(object sender, EventArgs e) { Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { // Registra el rebote aux.RebotesOfensivos++; registrarRebote(aux.CompleteName, true); // Cambial el entorno desactivarRebotes(); activarFalta(); activarPerdida(); activarPuntos(); // Activa TODOS los tiempos muertos activarTO(); // Vuelve a correr el reloj! correrContinuacion(); } else { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_rebote_Ofensivo_V_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo LOCAL logra un rebote DEFENSIVO /// </summary> private void btn_rebote_Defensivo_L_Click(object sender, EventArgs e) { Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { // Registra el rebote aux.RebotesDefensivos++; registrarRebote(aux.CompleteName); // Cambial el entorno desactivarRebotes(); activarFalta(); activarPerdida(); activarPuntos(); // Activa TODOS los tiempos muertos activarTO(); // Vuelve a correr el reloj! correrContinuacion(); } else { SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_rebote_Defensivo_L_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE logra un rebote DEFENSIVO /// </summary> private void btn_rebote_Defensivo_V_Click(object sender, EventArgs e) { Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { // Registra el rebote aux.RebotesDefensivos++; registrarRebote(aux.CompleteName); // Cambial el entorno desactivarRebotes(); activarFalta(); activarPerdida(); activarPuntos(); // Activa TODOS los tiempos muertos activarTO(); // Vuelve a correr el reloj! correrContinuacion(); } else { SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_rebote_Defensivo_V_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo LOCAL encesto un Tiro Libre /// </summary> private void btn_libreEncestado_L_Click(object sender, EventArgs e) { tirosLibresDisponibles--; Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { anotacion(1, aux); if (tirosLibresDisponibles == 0) { // Cambia el tiempo muerto de mando activarTO(); desactivarTOLocal(); // Desactiva los tiros libres desactivarLibreLocal(); activarContinuacion(); procesoFalta = false; } } else { // Selecciona el jugador LOCAL que ENCESTO el tiro SelectPlayer nuevo = new SelectPlayer(local.Players); nuevo.ShowDialog(); this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_libreEncestado_L_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE encesto un Tiro Libre /// </summary> private void btn_libreEncestado_V_Click(object sender, EventArgs e) { tirosLibresDisponibles--; Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { anotacion(1, aux, false); if (tirosLibresDisponibles == 0) { // Cambia el tiempo muerto de mando activarTO(); desactivarTOVisitante(); desactivarLibreVisitante(); activarContinuacion(); procesoFalta = false; } } else { // Selecciona el jugador VISITANTE que ENCESTO el tiro SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_libreEncestado_V_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo LOCAL erra un tiro libre /// </summary> private void btn_libreErrado_L_Click(object sender, EventArgs e) { tirosLibresDisponibles--; Player aux = (Player)listBox_LocalRoster.SelectedItem; if (aux != null) { fallo(1, aux); if (tirosLibresDisponibles == 0) { desactivarLibreLocal(); correrContinuacion(); procesoFalta = false; // Se encienden los rebotes activarRebotes(false); } } else { // Selecciona el jugador LOCAL que FALLO el tiro SelectPlayer window = new SelectPlayer(local.Players); window.ShowDialog(); this.listBox_LocalRoster.SelectedItem = window.JugadorSeleccionado; btn_libreErrado_L_Click(sender, e); } } /// <summary> /// Sucede cuando el equipo VISITANTE erra un tiro libre /// </summary> private void btn_libreErrado_V_Click(object sender, EventArgs e) { tirosLibresDisponibles--; Player aux = (Player)listBox_VisitorRoster.SelectedItem; if (aux != null) { fallo(1, aux); if (tirosLibresDisponibles == 0) { desactivarLibreVisitante(); correrContinuacion(); procesoFalta = false; // Se encienden los rebotes activarRebotes(false); } } else { // Selecciona el jugador LOCAL que FALLO el tiro SelectPlayer nuevo = new SelectPlayer(visitor.Players); nuevo.ShowDialog(); this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado; btn_libreErrado_V_Click(sender, e); } } /// <summary> /// Abre un dialogo pidiendo confirmación al usuario para salir del programa /// </summary> private void partido_FormClosing(object sender, FormClosingEventArgs e) { if (!closeWindow) { DialogResult userResponce = MessageBox.Show("Esta seguro que desea cerrar la ventana?\n"+ "Los datos no seran guardados.", "Cerrar ventana", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (userResponce == System.Windows.Forms.DialogResult.No) e.Cancel = true; } } private void button_perdidaL_Click(object sender, EventArgs e) { desactivarPuntos(); desactivarRebotes(); desactivarFalta(); desactivarPerdida(); // Activa el boton de Comienzo activarContinuacion(); procesoBalonAfuera = true; // Activa el proceso Balon Afuera } private void button_perdidaV_Click(object sender, EventArgs e) { desactivarPuntos(); desactivarRebotes(); desactivarFalta(); desactivarPerdida(); // Activa el boton de Comienzo activarContinuacion(); procesoBalonAfuera = true; // Activa el proceso Balon Afuera } } }
CLN-Group/Time-Out
Time Out/partido.cs
C#
mit
41,256
#include "V3DResourceMemory.h" #include "V3DDevice.h" #include "V3DBuffer.h" #include "V3DImage.h" #include "V3DAdapter.h" /******************************/ /* public - V3DResourceMemory */ /******************************/ V3DResourceMemory* V3DResourceMemory::Create() { return V3D_NEW_T(V3DResourceMemory); } V3D_RESULT V3DResourceMemory::Initialize(IV3DDevice* pDevice, V3DFlags propertyFlags, uint64_t size, const wchar_t* pDebugName) { V3D_ASSERT(pDevice != nullptr); V3D_ASSERT(propertyFlags != 0); V3D_ASSERT(size != 0); m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice)); V3D_ADD_DEBUG_MEMORY_OBJECT(this, V3D_DEBUG_OBJECT_TYPE_RESOURCE_MEMORY, V3D_SAFE_NAME(this, pDebugName)); m_Source.memoryPropertyFlags = ToVkMemoryPropertyFlags(propertyFlags); // ---------------------------------------------------------------------------------------------------- // ƒƒ‚ƒŠ‚ðŠm•Û // ---------------------------------------------------------------------------------------------------- VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.allocationSize = size; allocInfo.memoryTypeIndex = m_pDevice->GetInternalAdapterPtr()->Vulkan_GetMemoryTypeIndex(m_Source.memoryPropertyFlags); VkResult vkResult = vkAllocateMemory(m_pDevice->GetSource().device, &allocInfo, nullptr, &m_Source.deviceMemory); if (vkResult != VK_SUCCESS) { return ToV3DResult(vkResult); } m_Source.memoryMappedRange.memory = m_Source.deviceMemory; V3D_ADD_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory, V3D_SAFE_NAME(this, pDebugName)); // ---------------------------------------------------------------------------------------------------- // ‹Lq‚ðÝ’è // ---------------------------------------------------------------------------------------------------- m_Desc.propertyFlags = propertyFlags; m_Desc.size = size; // ---------------------------------------------------------------------------------------------------- return V3D_OK; } V3D_RESULT V3DResourceMemory::Initialize(IV3DDevice* pDevice, V3DFlags propertyFlags, uint32_t resourceCount, IV3DResource** ppResources, const wchar_t* pDebugName) { V3D_ASSERT(pDevice != nullptr); V3D_ASSERT(propertyFlags != 0); V3D_ASSERT(resourceCount != 0); V3D_ASSERT(ppResources != nullptr); m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice)); V3D_ADD_DEBUG_MEMORY_OBJECT(this, V3D_DEBUG_OBJECT_TYPE_RESOURCE_MEMORY, V3D_SAFE_NAME(this, pDebugName)); // ---------------------------------------------------------------------------------------------------- // ƒŠƒ\[ƒX‚ðƒAƒ‰ƒCƒƒ“ƒg‚̑傫‚¢‡‚Ƀ\[ƒg // ---------------------------------------------------------------------------------------------------- STLVector<IV3DResource*> resources; resources.reserve(resourceCount); for (uint32_t i = 0; i < resourceCount; i++) { #ifdef V3D_DEBUG switch (ppResources[i]->GetResourceDesc().type) { case V3D_RESOURCE_TYPE_BUFFER: if (static_cast<V3DBuffer*>(ppResources[i])->CheckBindMemory() == true) { V3D_LOG_PRINT_ERROR(Log_Error_AlreadyBindResourceMemory, V3D_SAFE_NAME(this, pDebugName), V3D_LOG_TYPE(ppResources), i, static_cast<V3DBuffer*>(ppResources[i])->GetDebugName()); return V3D_ERROR_FAIL; } break; case V3D_RESOURCE_TYPE_IMAGE: if (static_cast<IV3DImageBase*>(ppResources[i])->CheckBindMemory() == true) { V3D_LOG_PRINT_ERROR(Log_Error_AlreadyBindResourceMemory, V3D_SAFE_NAME(this, pDebugName), V3D_LOG_TYPE(ppResources), i, static_cast<IV3DImageBase*>(ppResources[i])->GetDebugName()); return V3D_ERROR_FAIL; } break; } #endif //V3D_DEBUG resources.push_back(ppResources[i]); } std::sort(resources.begin(), resources.end(), [](const IV3DResource* lh, const IV3DResource* rh) { return lh->GetResourceDesc().memoryAlignment > rh->GetResourceDesc().memoryAlignment; }); // ---------------------------------------------------------------------------------------------------- // ƒAƒ‰ƒCƒƒ“ƒg‚ð‹C‚É‚µ‚‚Aƒƒ‚ƒŠ‚̃TƒCƒY‚ð‹‚ß‚é // ---------------------------------------------------------------------------------------------------- uint64_t vkMinAlignment = m_pDevice->GetSource().deviceProps.limits.minMemoryMapAlignment; VkDeviceSize vkAllocSize = 0; STLVector<VkDeviceSize> vkOffsets; vkOffsets.resize(resourceCount); for (uint32_t i = 0; i < resourceCount; i++) { const V3DResourceDesc& resourceDesc = ppResources[i]->GetResourceDesc(); VkDeviceSize vkAlignment = V3D_MAX(vkMinAlignment, resourceDesc.memoryAlignment); if (vkAllocSize % vkAlignment) { vkAllocSize = (vkAllocSize / vkAlignment) * vkAlignment + vkAlignment; } vkOffsets[i] = vkAllocSize; vkAllocSize += resourceDesc.memorySize; } // ---------------------------------------------------------------------------------------------------- // ƒƒ‚ƒŠ‚ðì¬ // ---------------------------------------------------------------------------------------------------- m_Source.memoryPropertyFlags = ToVkMemoryPropertyFlags(propertyFlags); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = nullptr; allocInfo.allocationSize = vkAllocSize; allocInfo.memoryTypeIndex = m_pDevice->GetInternalAdapterPtr()->Vulkan_GetMemoryTypeIndex(m_Source.memoryPropertyFlags); VkResult vkResult = vkAllocateMemory(m_pDevice->GetSource().device, &allocInfo, nullptr, &m_Source.deviceMemory); if (vkResult != VK_SUCCESS) { return ToV3DResult(vkResult); } m_Source.memoryMappedRange.memory = m_Source.deviceMemory; V3D_ADD_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory, V3D_SAFE_NAME(this, pDebugName)); // ---------------------------------------------------------------------------------------------------- // ‹Lq‚ðÝ’è // ---------------------------------------------------------------------------------------------------- m_Desc.propertyFlags = propertyFlags; m_Desc.size = vkAllocSize; // ---------------------------------------------------------------------------------------------------- // ƒŠƒ\[ƒX‚ðƒoƒCƒ“ƒh // ---------------------------------------------------------------------------------------------------- V3D_RESULT result = V3D_ERROR_FAIL; for (uint32_t i = 0; i < resourceCount; i++) { IV3DResource* pResource = ppResources[i]; switch (pResource->GetResourceDesc().type) { case V3D_RESOURCE_TYPE_BUFFER: result = static_cast<V3DBuffer*>(pResource)->BindMemory(this, vkOffsets[i]); if (result != V3D_OK) { return result; } break; case V3D_RESOURCE_TYPE_IMAGE: result = static_cast<V3DImage*>(pResource)->BindMemory(this, vkOffsets[i]); if (result != V3D_OK) { return result; } break; } } // ---------------------------------------------------------------------------------------------------- return V3D_OK; } const V3DResourceMemory::Source& V3DResourceMemory::GetSource() const { return m_Source; } V3D_RESULT V3DResourceMemory::Map(uint64_t offset, uint64_t size, void** ppMemory) { if (m_Desc.size < (offset + size)) { return V3D_ERROR_FAIL; } if (m_pMemory != nullptr) { *ppMemory = m_pMemory + offset; return V3D_OK; } if (m_Source.memoryMappedRange.size != 0) { return V3D_ERROR_FAIL; } VkResult vkResult = vkMapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, offset, size, 0, ppMemory); if (vkResult != VK_SUCCESS) { return ToV3DResult(vkResult); } m_Source.memoryMappedRange.offset = offset; m_Source.memoryMappedRange.size = size; if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { vkResult = vkInvalidateMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange); if (vkResult != VK_SUCCESS) { return ToV3DResult(vkResult); } } return V3D_OK; } V3D_RESULT V3DResourceMemory::Unmap() { if (m_pMemory != nullptr) { return V3D_OK; } if (m_Source.memoryMappedRange.size == 0) { return V3D_ERROR_FAIL; } V3D_RESULT result = V3D_OK; if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { VkResult vkResult = vkFlushMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange); if (vkResult != VK_SUCCESS) { result = ToV3DResult(vkResult); } } m_Source.memoryMappedRange.offset = 0; m_Source.memoryMappedRange.size = 0; vkUnmapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory); return result; } #ifdef V3D_DEBUG bool V3DResourceMemory::Debug_CheckMemory(uint64_t offset, uint64_t size) { return (m_Desc.size >= (offset + size)); } #endif //V3D_DEBUG /****************************************/ /* public override - IV3DResourceMemory */ /****************************************/ const V3DResourceMemoryDesc& V3DResourceMemory::GetDesc() const { return m_Desc; } V3D_RESULT V3DResourceMemory::BeginMap() { if (m_Source.memoryMappedRange.size != 0) { return V3D_ERROR_FAIL; } VkResult vkResult = vkMapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, 0, m_Desc.size, 0, reinterpret_cast<void**>(&m_pMemory)); if (vkResult != VK_SUCCESS) { return ToV3DResult(vkResult); } m_Source.memoryMappedRange.offset = 0; m_Source.memoryMappedRange.size = m_Desc.size; if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { vkResult = vkInvalidateMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange); if (vkResult != VK_SUCCESS) { return ToV3DResult(vkResult); } } return V3D_OK; } V3D_RESULT V3DResourceMemory::EndMap() { if (m_Source.memoryMappedRange.size == 0) { return V3D_ERROR_FAIL; } V3D_RESULT result = V3D_OK; if ((m_Source.memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) { VkResult vkResult = vkFlushMappedMemoryRanges(m_pDevice->GetSource().device, 1, &m_Source.memoryMappedRange); if (vkResult != VK_SUCCESS) { result = ToV3DResult(vkResult); } } m_Source.memoryMappedRange.offset = 0; m_Source.memoryMappedRange.size = 0; vkUnmapMemory(m_pDevice->GetSource().device, m_Source.deviceMemory); m_pMemory = nullptr; return result; } /*************************************/ /* public override - IV3DDeviceChild */ /*************************************/ void V3DResourceMemory::GetDevice(IV3DDevice** ppDevice) { (*ppDevice) = V3D_TO_ADD_REF(m_pDevice); } /********************************/ /* public override - IV3DObject */ /********************************/ int64_t V3DResourceMemory::GetRefCount() const { return m_RefCounter; } void V3DResourceMemory::AddRef() { V3D_REF_INC(m_RefCounter); } void V3DResourceMemory::Release() { if (V3D_REF_DEC(m_RefCounter)) { V3D_REF_FENCE(); V3D_DELETE_THIS_T(this, V3DResourceMemory); } } /*******************************/ /* private - V3DResourceMemory */ /*******************************/ V3DResourceMemory::V3DResourceMemory() : m_RefCounter(1), m_pDevice(nullptr), m_Desc({}), m_Source({}), m_pMemory(nullptr) { m_Source.deviceMemory = VK_NULL_HANDLE; m_Source.memoryMappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; m_Source.memoryMappedRange.pNext = nullptr; } V3DResourceMemory::~V3DResourceMemory() { if (m_pDevice != nullptr) { m_pDevice->NotifyReleaseResourceMemory(); } if (m_Source.deviceMemory != VK_NULL_HANDLE) { vkFreeMemory(m_pDevice->GetSource().device, m_Source.deviceMemory, nullptr); V3D_REMOVE_DEBUG_OBJECT(m_pDevice->GetInternalInstancePtr(), m_Source.deviceMemory); } V3D_REMOVE_DEBUG_MEMORY_OBJECT(this); V3D_RELEASE(m_pDevice); }
mixberry8/v3d
build/runtime/source/V3DResourceMemory.cpp
C++
mit
12,042
<?php namespace Peridot\Leo\Interfaces; use Peridot\Leo\Assertion; use Peridot\Leo\Interfaces\Assert\CollectionAssertTrait; use Peridot\Leo\Interfaces\Assert\ObjectAssertTrait; use Peridot\Leo\Interfaces\Assert\TypeAssertTrait; use Peridot\Leo\Leo; /** * Assert is a non-chainable, object oriented interface * on top of a Leo Assertion. * * @method instanceOf() instanceOf(object $actual, string $expected, string $message = "") Perform an instanceof assertion. * @method include() include(array $haystack, string $expected, string $message = "") Perform an inclusion assertion. * * @package Peridot\Leo\Interfaces */ class Assert { use TypeAssertTrait; use ObjectAssertTrait; use CollectionAssertTrait; /** * An array of operators mapping to assertions. * * @var array */ public static $operators = [ '==' => 'loosely->equal', '===' => 'equal', '>' => 'above', '>=' => 'least', '<' => 'below', '<=' => 'most', '!=' => 'not->loosely->equal', '!==' => 'not->equal', ]; /** * @var Assertion */ protected $assertion; /** * @param Assertion $assertion */ public function __construct(Assertion $assertion = null) { if ($assertion === null) { $assertion = Leo::assertion(); } $this->assertion = $assertion; } /** * Perform an a loose equality assertion. * * @param mixed $actual * @param mixed $expected * @param string $message */ public function equal($actual, $expected, $message = '') { $this->assertion->setActual($actual); return $this->assertion->to->loosely->equal($expected, $message); } /** * Perform a negated loose equality assertion. * * @param mixed $actual * @param mixed $expected * @param string $message */ public function notEqual($actual, $expected, $message = '') { $this->assertion->setActual($actual); return $this->assertion->to->not->equal($expected, $message); } /** * Performs a throw assertion. * * @param callable $fn * @param $exceptionType * @param string $exceptionMessage * @param string $message */ public function throws(callable $fn, $exceptionType, $exceptionMessage = '', $message = '') { $this->assertion->setActual($fn); return $this->assertion->to->throw($exceptionType, $exceptionMessage, $message); } /** * Performs a negated throw assertion. * * @param callable $fn * @param $exceptionType * @param string $exceptionMessage * @param string $message */ public function doesNotThrow(callable $fn, $exceptionType, $exceptionMessage = '', $message = '') { $this->assertion->setActual($fn); return $this->assertion->not->to->throw($exceptionType, $exceptionMessage, $message); } /** * Perform an ok assertion. * * @param mixed $object * @param string $message */ public function ok($object, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->be->ok($message); } /** * Perform a negated assertion. * * @param mixed $object * @param string $message */ public function notOk($object, $message = '') { $this->assertion->setActual($object); return $this->assertion->to->not->be->ok($message); } /** * Perform a strict equality assertion. * * @param mixed $actual * @param mixed $expected * @param string $message */ public function strictEqual($actual, $expected, $message = '') { $this->assertion->setActual($actual); return $this->assertion->to->equal($expected, $message); } /** * Perform a negated strict equality assertion. * * @param mixed $actual * @param mixed $expected * @param string $message */ public function notStrictEqual($actual, $expected, $message = '') { $this->assertion->setActual($actual); return $this->assertion->to->not->equal($expected, $message); } /** * Perform a pattern assertion. * * @param string $value * @param string $pattern * @param string $message */ public function match($value, $pattern, $message = '') { $this->assertion->setActual($value); return $this->assertion->to->match($pattern, $message); } /** * Perform a negated pattern assertion. * * @param string $value * @param string $pattern * @param string $message */ public function notMatch($value, $pattern, $message = '') { $this->assertion->setActual($value); return $this->assertion->to->not->match($pattern, $message); } /** * Compare two values using the given operator. * * @param mixed $left * @param string $operator * @param mixed $right * @param string $message */ public function operator($left, $operator, $right, $message = '') { if (!isset(static::$operators[$operator])) { throw new \InvalidArgumentException("Invalid operator $operator"); } $this->assertion->setActual($left); return $this->assertion->{static::$operators[$operator]}($right, $message); } /** * Defined to allow use of reserved words for methods. * * @param $method * @param $args */ public function __call($method, $args) { switch ($method) { case 'instanceOf': return call_user_func_array([$this, 'isInstanceOf'], $args); case 'include': return call_user_func_array([$this, 'isIncluded'], $args); default: throw new \BadMethodCallException("Call to undefined method $method"); } } }
peridot-php/leo
src/Interfaces/Assert.php
PHP
mit
6,019
<?php declare(strict_types=1); namespace Gitilicious\GitClient\Test\Unit\Cli\Output; use Gitilicious\GitClient\Cli\Output\Output; class OutputTest extends \PHPUnit_Framework_TestCase { public function testGetNumberOfLines() { $output = new Output('foo' . PHP_EOL . 'bar'); $this->assertSame(2, $output->getNumberOfLines()); } public function testGetLineWhenItExists() { $output = new Output('foo' . PHP_EOL . 'bar'); $this->assertSame('foo', $output->getLine(1)); $this->assertSame('bar', $output->getLine(2)); } public function testGetLineWhenItDoesNotExist() { $output = new Output('foo' . PHP_EOL . 'bar'); $this->assertSame('', $output->getLine(3)); } }
Gitilicious/git-client
tests/Unit/Cli/Output/OutputTest.php
PHP
mit
758
black = '#202427'; red = '#EB6A58'; // red green = '#49A61D'; // green yellow = '#959721'; // yellow blue = '#798FB7'; // blue magenta = '#CD7B7E'; // pink cyan = '#4FA090'; // cyan white = '#909294'; // light gray lightBlack = '#292B35'; // medium gray lightRed = '#DB7824'; // red lightGreen = '#09A854'; // green lightYellow = '#AD8E4B'; // yellow lightBlue = '#309DC1'; // blue lightMagenta= '#C874C2'; // pink lightCyan = '#1BA2A0'; // cyan lightWhite = '#8DA3B8'; // white t.prefs_.set('color-palette-overrides', [ black , red , green , yellow, blue , magenta , cyan , white, lightBlack , lightRed , lightGreen , lightYellow, lightBlue , lightMagenta , lightCyan , lightWhite ]); t.prefs_.set('cursor-color', lightWhite); t.prefs_.set('foreground-color', lightWhite); t.prefs_.set('background-color', black);
iamruinous/dotfiles
blink/themes/tempus_winter.js
JavaScript
mit
966
import cuid from "cuid"; import Result, { isError } from "../../common/Result"; import assert from "assert"; import { di, singleton, diKey } from "../../common/di"; import { ILocalFiles, ILocalFilesKey } from "../../common/LocalFiles"; import { IStoreDB, IStoreDBKey, MergeEntity } from "../../common/db/StoreDB"; import { ApplicationDto, applicationKey, CanvasDto, DiagramDto, DiagramInfoDto, DiagramInfoDtos, FileDto, } from "./StoreDtos"; import { LocalEntity } from "../../common/db/LocalDB"; import { RemoteEntity } from "../../common/db/RemoteDB"; export interface Configuration { onRemoteChanged: (keys: string[]) => void; onSyncChanged: (isOK: boolean, error?: Error) => void; isSyncEnabled: boolean; } export const IStoreKey = diKey<IStore>(); export interface IStore { configure(config: Partial<Configuration>): void; triggerSync(): Promise<Result<void>>; openNewDiagram(): DiagramDto; tryOpenMostResentDiagram(): Promise<Result<DiagramDto>>; tryOpenDiagram(diagramId: string): Promise<Result<DiagramDto>>; setDiagramName(name: string): void; exportDiagram(): DiagramDto; // Used for print or export getRootCanvas(): CanvasDto; getCanvas(canvasId: string): CanvasDto; writeCanvas(canvas: CanvasDto): void; getMostResentDiagramId(): Result<string>; getRecentDiagrams(): DiagramInfoDto[]; deleteDiagram(diagramId: string): void; saveDiagramToFile(): void; loadDiagramFromFile(): Promise<Result<string>>; saveAllDiagramsToFile(): Promise<void>; } const rootCanvasId = "root"; const defaultApplicationDto: ApplicationDto = { diagramInfos: {} }; const defaultDiagramDto: DiagramDto = { id: "", name: "", canvases: {} }; @singleton(IStoreKey) export class Store implements IStore { private currentDiagramId: string = ""; private config: Configuration = { onRemoteChanged: () => {}, onSyncChanged: () => {}, isSyncEnabled: false, }; constructor( // private localData: ILocalData = di(ILocalDataKey), private localFiles: ILocalFiles = di(ILocalFilesKey), private db: IStoreDB = di(IStoreDBKey) ) {} public configure(config: Partial<Configuration>): void { this.config = { ...this.config, ...config }; this.db.configure({ onConflict: (local: LocalEntity, remote: RemoteEntity) => this.onEntityConflict(local, remote), ...config, onRemoteChanged: (keys: string[]) => this.onRemoteChange(keys), }); } public triggerSync(): Promise<Result<void>> { return this.db.triggerSync(); } public openNewDiagram(): DiagramDto { const now = Date.now(); const id = cuid(); const name = this.getUniqueName(); console.log("new diagram", id, name); const diagramDto: DiagramDto = { id: id, name: name, canvases: {}, }; const applicationDto = this.getApplicationDto(); applicationDto.diagramInfos[id] = { id: id, name: name, accessed: now, }; this.db.monitorRemoteEntities([id, applicationKey]); this.db.writeBatch([ { key: applicationKey, value: applicationDto }, { key: id, value: diagramDto }, ]); this.currentDiagramId = id; return diagramDto; } public async tryOpenMostResentDiagram(): Promise<Result<DiagramDto>> { const id = this.getMostResentDiagramId(); if (isError(id)) { return id as Error; } const diagramDto = await this.db.tryReadLocalThenRemote<DiagramDto>(id); if (isError(diagramDto)) { return diagramDto; } this.db.monitorRemoteEntities([id, applicationKey]); this.currentDiagramId = id; return diagramDto; } public async tryOpenDiagram(id: string): Promise<Result<DiagramDto>> { const diagramDto = await this.db.tryReadLocalThenRemote<DiagramDto>(id); if (isError(diagramDto)) { return diagramDto; } this.db.monitorRemoteEntities([id, applicationKey]); this.currentDiagramId = id; // Too support most recently used diagram feature, we update accessed time const applicationDto = this.getApplicationDto(); const diagramInfo = applicationDto.diagramInfos[id]; applicationDto.diagramInfos[id] = { ...diagramInfo, accessed: Date.now() }; this.db.writeBatch([{ key: applicationKey, value: applicationDto }]); return diagramDto; } public getRootCanvas(): CanvasDto { return this.getCanvas(rootCanvasId); } public getCanvas(canvasId: string): CanvasDto { const diagramDto = this.getDiagramDto(); const canvasDto = diagramDto.canvases[canvasId]; assert(canvasDto); return canvasDto; } public writeCanvas(canvasDto: CanvasDto): void { const diagramDto = this.getDiagramDto(); const id = diagramDto.id; diagramDto.canvases[canvasDto.id] = canvasDto; this.db.writeBatch([{ key: id, value: diagramDto }]); } public getRecentDiagrams(): DiagramInfoDto[] { return Object.values(this.getApplicationDto().diagramInfos).sort((i1, i2) => i1.accessed < i2.accessed ? 1 : i1.accessed > i2.accessed ? -1 : 0 ); } // For printing/export public exportDiagram(): DiagramDto { return this.getDiagramDto(); } public deleteDiagram(id: string): void { console.log("Delete diagram", id); const applicationDto = this.getApplicationDto(); delete applicationDto.diagramInfos[id]; this.db.writeBatch([{ key: applicationKey, value: applicationDto }]); this.db.removeBatch([id]); } public setDiagramName(name: string): void { const diagramDto = this.getDiagramDto(); const id = diagramDto.id; diagramDto.name = name; const applicationDto = this.getApplicationDto(); applicationDto.diagramInfos[id] = { ...applicationDto.diagramInfos[id], name: name, accessed: Date.now(), }; this.db.writeBatch([ { key: applicationKey, value: applicationDto }, { key: id, value: diagramDto }, ]); } public async loadDiagramFromFile(): Promise<Result<string>> { const fileText = await this.localFiles.loadFile(); const fileDto: FileDto = JSON.parse(fileText); // if (!(await this.sync.uploadDiagrams(fileDto.diagrams))) { // // save locally // fileDto.diagrams.forEach((d: DiagramDto) => this.local.writeDiagram(d)); // } //fileDto.diagrams.forEach((d: DiagramDto) => this.local.writeDiagram(d)); const firstDiagramId = fileDto.diagrams[0]?.id; if (!firstDiagramId) { return new Error("No valid diagram in file"); } return firstDiagramId; } public saveDiagramToFile(): void { const diagramDto = this.getDiagramDto(); const fileDto: FileDto = { diagrams: [diagramDto] }; const fileText = JSON.stringify(fileDto, null, 2); this.localFiles.saveFile(`${diagramDto.name}.json`, fileText); } public async saveAllDiagramsToFile(): Promise<void> { // let diagrams = await this.sync.downloadAllDiagrams(); // if (!diagrams) { // // Read from local // diagrams = this.local.readAllDiagrams(); // } // let diagrams = this.local.readAllDiagrams(); // const fileDto = { diagrams: diagrams }; // const fileText = JSON.stringify(fileDto, null, 2); // this.localFiles.saveFile(`diagrams.json`, fileText); } public getMostResentDiagramId(): Result<string> { const resentDiagrams = this.getRecentDiagrams(); if (resentDiagrams.length === 0) { return new RangeError("not found"); } return resentDiagrams[0].id; } public getApplicationDto(): ApplicationDto { return this.db.readLocal<ApplicationDto>( applicationKey, defaultApplicationDto ); } private onRemoteChange(keys: string[]) { this.config.onRemoteChanged(keys); } private onEntityConflict( local: LocalEntity, remote: RemoteEntity ): MergeEntity { if ("diagramInfos" in local.value) { return this.onApplicationConflict(local, remote); } return this.onDiagramConflict(local, remote); } private onApplicationConflict( local: LocalEntity, remote: RemoteEntity ): MergeEntity { console.warn("Application conflict", local, remote); const mergeDiagramInfos = ( newerDiagrams: DiagramInfoDtos, olderDiagrams: DiagramInfoDtos ): DiagramInfoDtos => { let mergedDiagrams = { ...olderDiagrams, ...newerDiagrams }; Object.keys(newerDiagrams).forEach((key) => { if (!(key in newerDiagrams)) { delete mergedDiagrams[key]; } }); return mergedDiagrams; }; if (local.version >= remote.version) { // Local entity has more edits, merge diagram infos, but priorities remote const applicationDto: ApplicationDto = { diagramInfos: mergeDiagramInfos( local.value.diagramInfos, remote.value.diagramInfos ), }; return { key: local.key, value: applicationDto, version: local.version, }; } // Remote entity since that has more edits, merge diagram infos, but priorities local const applicationDto: ApplicationDto = { diagramInfos: mergeDiagramInfos( remote.value.diagramInfos, local.value.diagramInfos ), }; return { key: remote.key, value: applicationDto, version: remote.version, }; } private onDiagramConflict( local: LocalEntity, remote: RemoteEntity ): MergeEntity { console.warn("Diagram conflict", local, remote); if (local.version >= remote.version) { // use local since it has more edits return { key: local.key, value: local.value, version: local.version, }; } // Use remote entity since that has more edits return { key: remote.key, value: remote.value, version: remote.version, }; } private getDiagramDto(): DiagramDto { return this.db.readLocal<DiagramDto>( this.currentDiagramId, defaultDiagramDto ); } private getUniqueName(): string { const diagrams = Object.values(this.getApplicationDto().diagramInfos); for (let i = 0; i < 99; i++) { const name = "Name" + (i > 0 ? ` (${i})` : ""); if (!diagrams.find((d) => d.name === name)) { return name; } } return "Name"; } }
michael-reichenauer/Dependinator
Web/src/application/diagram/Store.ts
TypeScript
mit
10,268
<html> <head> <title>Julian Fellows's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Julian Fellows's panel show appearances</h1> <p>Julian Fellows has appeared in <span class="total">1</span> episodes between 2003-2003. Note that these appearances may be for more than one person if multiple people have the same name.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances male" title="1"></div><span class="year">2003</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2003-05-22</strong> / <a href="../shows/call-my-bluff.html">Call My Bluff</a></li> </ol> </div> </body> </html>
slowe/panelshows
people/7g6x6fja.html
HTML
mit
1,004
var createSubmit = function(name, primus, keyDict) { return function(event) { var message = $('#message').val(); if (message.length === 0) { event.preventDefault(); return; } $('#message').val(''); $('#message').focus(); var BigInteger = forge.jsbn.BigInteger; var data = JSON.parse(sessionStorage[name]); var pem = data.pem; var privateKey = forge.pki.privateKeyFromPem(pem); var ownPublicKey = forge.pki.setRsaPublicKey(new BigInteger(data.n), new BigInteger(data.e)); var keys = []; var iv = forge.random.getBytesSync(16); var key = forge.random.getBytesSync(16); var cipher = forge.cipher.createCipher('AES-CBC', key); cipher.start({iv: iv}); cipher.update(forge.util.createBuffer(message, 'utf8')); cipher.finish(); var encryptedMessage = cipher.output.getBytes(); var encryptedKey = ownPublicKey.encrypt(key, 'RSA-OAEP'); keys.push({ 'name': name, 'key': encryptedKey }); var md = forge.md.sha1.create(); md.update(message, 'utf8'); var signature = privateKey.sign(md); var recipients = $.map($("#recipients").tokenfield("getTokens"), function(o) {return o.value;}); var deferredRequests = []; for (var i = 0; i < recipients.length; i++) { (function (index) { var retrieveKey = function(pk) { if (pk === false) { return; } if (keyDict[recipients[i]] === undefined) { keyDict[recipients[i]] = pk; } var publicKey = forge.pki.setRsaPublicKey(new BigInteger(pk.n), new BigInteger(pk.e)); var encryptedKey = publicKey.encrypt(key, 'RSA-OAEP'); keys.push({ 'name': recipients[index], 'key': encryptedKey }); } if (keyDict[recipients[i]] === undefined) { deferredRequests.push($.post('/user/getpublickey', {'name' : recipients[i]}, retrieveKey)); } else { retrieveKey(keyDict[recipients[i]]); } })(i); } $.when.apply(null, deferredRequests).done(function() { primus.substream('messageStream').write({'message': encryptedMessage, 'keys': keys, 'iv': iv, 'signature': signature, 'recipients': recipients}); }); event.preventDefault(); }; };
raytracer/CryptoGraph
src/client/stream/createSubmit.js
JavaScript
mit
2,725
<?php namespace action\sub; use net\shawn_huang\pretty\Action; class Index extends Action { protected function run() { $this->put([ 'holy' => 'shit' ]); } }
Cretty/pretty-php
test/test_classes/action/sub/Index.class.php
PHP
mit
195
<?php namespace keeko\account\action; use keeko\framework\foundation\AbstractAction; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use keeko\framework\domain\payload\Success; /** * User Widget * * This code is automatically created. Modifications will probably be overwritten. * * @author gossi */ class AccountWidgetAction extends AbstractAction { /** * Automatically generated run method * * @param Request $request * @return Response */ public function run(Request $request) { $prefs = $this->getServiceContainer()->getPreferenceLoader()->getSystemPreferences(); $translator = $this->getServiceContainer()->getTranslator(); return $this->responder->run($request, new Success([ 'account_url' => $prefs->getAccountUrl(), 'destination' => $prefs->getAccountUrl() . '/' . $translator->trans('slug.login'), 'redirect' => $request->getUri(), 'login_label' => $prefs->getUserLogin() ])); } }
keeko/account
src/action/AccountWidgetAction.php
PHP
mit
978
// Copyright (c) 2015-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <zmq/zmqabstractnotifier.h> #include <util.h> CZMQAbstractNotifier::~CZMQAbstractNotifier() { assert(!psocket); } bool CZMQAbstractNotifier::NotifyBlock(const CBlockIndex * /*CBlockIndex*/) { return true; } bool CZMQAbstractNotifier::NotifyTransaction(const CTransaction &/*transaction*/) { return true; } bool CZMQAbstractNotifier::NotifyTransactionLock(const CTransactionRef &/*transaction*/) { return true; }
globaltoken/globaltoken
src/zmq/zmqabstractnotifier.cpp
C++
mit
636
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.21-2-15 description: Array.prototype.reduce - 'length' is property of the global object includes: - runTestCase.js - fnGlobalObject.js ---*/ function testcase() { function callbackfn(prevVal, curVal, idx, obj) { return (obj.length === 2); } try { var oldLen = fnGlobalObject().length; fnGlobalObject()[0] = 12; fnGlobalObject()[1] = 11; fnGlobalObject()[2] = 9; fnGlobalObject().length = 2; return Array.prototype.reduce.call(fnGlobalObject(), callbackfn, 1) === true; } finally { delete fnGlobalObject()[0]; delete fnGlobalObject()[1]; delete fnGlobalObject()[2]; fnGlobalObject().length = oldLen; } } runTestCase(testcase);
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Array/prototype/reduce/15.4.4.21-2-15.js
JavaScript
mit
1,201
import builder = require('botbuilder'); export module Helpers { export class API { public static async DownloadJson(url:string, post:boolean=false, options:any=undefined): Promise<string>{ return new Promise<string>(resolve => { var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xhr = new XMLHttpRequest(); xhr.onload = function (){ try { resolve(xhr.responseText); } catch(e){ console.log("Error while calling api: " + e.message); } }; xhr.open(options ? "POST" : "GET", url, true); xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(JSON.stringify(options)); }); } } export enum SearchType { "code", "documentation" }; }
meulta/babylonjsbot
Common/Helpers.ts
TypeScript
mit
983
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WingtipToys.Models; namespace WingtipToys.Logic { public class AddProducts { public bool AddProduct(string ProductName, string ProductDesc, string ProductPrice, string ProductCategory, string ProductImagePath) { var myProduct = new Product(); myProduct.ProductName = ProductName; myProduct.Description = ProductDesc; myProduct.UnitPrice = Convert.ToDouble(ProductPrice); myProduct.ImagePath = ProductImagePath; myProduct.CategoryID = Convert.ToInt32(ProductCategory); using (ProductContext _db = new ProductContext()) { // Add product to DB. _db.Products.Add(myProduct); _db.SaveChanges(); } // Success. return true; } } }
zacblazic/wingtip-toys
WingtipToys/Logic/AddProducts.cs
C#
mit
934
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; import com.azure.resourcemanager.security.fluent.models.SecureScoreControlDefinitionItemInner; /** An instance of this class provides access to all the operations defined in SecureScoreControlDefinitionsClient. */ public interface SecureScoreControlDefinitionsClient { /** * List the available security controls, their assessments, and the max score. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> list(); /** * List the available security controls, their assessments, and the max score. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> list(Context context); /** * For a specified subscription, list the available security controls, their assessments, and the max score. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(); /** * For a specified subscription, list the available security controls, their assessments, and the max score. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(Context context); }
Azure/azure-sdk-for-java
sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/fluent/SecureScoreControlDefinitionsClient.java
Java
mit
3,054
<?php namespace Seahinet\Catalog\Indexer; use Seahinet\Catalog\Model\Collection\Product; use Seahinet\Catalog\Model\Product as ProductModel; use Seahinet\Catalog\Model\Collection\Category; use Seahinet\Lib\Db\Sql\Ddl\Column\UnsignedInteger; use Seahinet\Lib\Indexer\Handler\AbstractHandler; use Seahinet\Lib\Indexer\Handler\Database; use Seahinet\Lib\Indexer\Provider; use Seahinet\Lib\Model\Collection\Language; use Zend\Db\Sql\Ddl; class Url implements Provider { use \Seahinet\Lib\Traits\Container; protected $path = []; public function provideStructure(AbstractHandler $handler) { if ($handler instanceof Database) { $adapter = $this->getContainer()->get('dbAdapter'); $platform = $adapter->getPlatform(); $languages = new Language; $languages->columns(['id']); foreach ($languages as $language) { $table = 'catalog_url_' . $language['id'] . '_index'; $adapter->query( 'DROP TABLE IF EXISTS ' . $table, $adapter::QUERY_MODE_EXECUTE ); $ddl = new Ddl\CreateTable($table); $ddl->addColumn(new UnsignedInteger('product_id', true, 0)) ->addColumn(new UnsignedInteger('category_id', false, 0)) ->addColumn(new Ddl\Column\Varchar('path', 512, false)) ->addConstraint(new Ddl\Constraint\UniqueKey(['category_id', 'product_id'], 'UNQ_' . strtoupper($table) . '_CATEGORY_ID_PRODUCT_ID')) ->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '_ID_PRODUCT_ENTITY_ID', 'product_id', 'product_entity', 'id', 'CASCADE', 'CASCADE')) ->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '_ID_CATEGORY_ENTITY_ID', 'category_id', 'category_entity', 'id', 'CASCADE', 'CASCADE')) ->addConstraint(new Ddl\Index\Index('path', 'IDX_' . strtoupper($table) . '_PATH')); $adapter->query( $ddl->getSqlString($platform), $adapter::QUERY_MODE_EXECUTE ); } } else { $handler->buildStructure([['attr' => 'path', 'is_unique' => 1]]); } return true; } public function provideData(AbstractHandler $handler) { $languages = new Language; $languages->columns(['id']); foreach ($languages as $language) { $categories = new Category($language['id']); $categories->where(['status' => 1]); $categories->load(false); $data = [$language['id'] => []]; $tree = []; foreach ($categories as $category) { $tree[$category['id']] = [ 'object' => $category, 'pid' => (int) $category['parent_id'] ]; } foreach ($categories as $category) { if ($path = $this->getPath($category, $tree)) { $data[$language['id']][$category['id']] = [ 'product_id' => null, 'category_id' => $category['id'], 'path' => $path ]; } } $handler->buildData($data); $products = new Product($language['id']); $products->where(['status' => 1])->limit(50); $init = $data; for ($i = 0;; $i++) { $data = [$language['id'] => []]; $products->reset('offset')->offset(50 * $i); $products->load(false, true); if (!$products->count()) { break; } foreach ($products as $product) { $product = new ProductModel($language['id'], $product); $categories = $product->getCategories(); foreach ($categories as $category) { $data[$language['id']][] = [ 'product_id' => $product['id'], 'category_id' => $category['id'], 'path' => (isset($init[$language['id']][$category['id']]['path']) ? ($init[$language['id']][$category['id']]['path'] . '/') : '') . $product['uri_key'] ]; } } $data[$language['id']] = array_values($data[$language['id']]); $handler->buildData($data); } } return true; } private function getPath($category, $tree) { if (isset($this->path[$category['id'] . '#' . $category['uri_key']])) { return $this->path[$category['id'] . '#' . $category['uri_key']]; } if (!isset($category['uri_key'])) { return ''; } $path = $category['uri_key']; $pid = (int) $category['parent_id']; if ($pid && isset($tree[$pid])) { $path = trim($this->getPath($tree[$pid]['object'], $tree) . '/' . $path, '/'); } $this->path[$category['id'] . '#' . $category['uri_key']] = $path; return $path; } }
peachyang/py_website
app/code/Catalog/Indexer/Url.php
PHP
mit
5,418
package org.superboot.service; import com.querydsl.core.types.Predicate; import org.springframework.data.domain.Pageable; import org.superboot.base.BaseException; import org.superboot.base.BaseResponse; /** * <b> 错误日志服务接口 </b> * <p> * 功能描述: * </p> */ public interface ErrorLogService { /** * 按照微服务模块进行分组统计 * * @return * @throws BaseException */ BaseResponse getErrorLogGroupByAppName() throws BaseException; /** * 获取错误日志列表信息 * * @param pageable 分页信息 * @param predicate 查询参数 * @return * @throws BaseException */ BaseResponse getErrorLogList(Pageable pageable, Predicate predicate) throws BaseException; /** * 获取错误日志记录数 * * @return * @throws BaseException */ BaseResponse getErrorLogCount(Predicate predicate) throws BaseException; /** * 查询错误日志详细信息 * * @param id * @return * @throws BaseException */ BaseResponse getErrorLogItem(String id) throws BaseException; }
7040210/SuperBoot
super-boot-global/src/main/java/org/superboot/service/ErrorLogService.java
Java
mit
1,147
UNIX BUILD NOTES ================ Build Instructions: Ubuntu & Debian Build requirements: ------------------- ```bash sudo apt-get install build-essential libtool autotools-dev automake pkg-config libssl-dev libevent-dev bsdmainutils ``` BOOST ----- ```bash sudo apt-get install libboost-all-dev ``` BDB --- For Ubuntu only: db4.8 packages are available here. You can add the repository and install using the following commands: ```bash sudo apt-get install software-properties-common sudo add-apt-repository ppa:bitcoin/bitcoin sudo apt-get update sudo apt-get install libdb4.8-dev libdb4.8++-dev ``` Ubuntu and Debian have their own libdb-dev and libdb++-dev packages, but these will install BerkeleyDB 5.1 or later, which break binary wallet compatibility with the distributed executables which are based on BerkeleyDB 4.8 MINIUPNPC --------- ```bash sudo apt-get install libminiupnpc-dev ``` QT5 --- ```bash sudo apt-get install libqt5gui5 libqt5core5a libqt5dbus5 qttools5-dev qttools5-dev-tools libprotobuf-dev protobuf-compiler sudo apt-get install qt5-default -y ``` QRENCODE -------- ```bash sudo apt-get install libqrencode-dev (optional) ``` secp256k1 --------- ```bash sudo apt-get install libsecp256k1-dev ``` OR ```bash git clone https://github.com/bitcoin/bitcoin cd /path/to/bitcoin-sources/src/sect256k1 ./autogen.sh ./configure --enable-static --disable-shared --enable-module-recovery make sudo make install ``` BUILD ===== ```bash git clone https://github.com/atcsecure/blocknet.git cd /path/to/blocknet git checkout xbridge-new-2 cp config.orig.pri config.pri /path/to/qmake blocknet-qt.pro (etc. /usr/lib/x86_64-linux-gnu/qt5/bin on ubuntu) make ```
atcsecure/blocknet
doc/build-ubuntu-debian-w-xbridge.md
Markdown
mit
1,690
$(function () { var $container = $('#container'); var certificatesInfo = $container.data('certinfo'); var runDate = $container.data('rundate'); $('#created_date').html(runDate); var sorted_certificates = Object.keys(certificatesInfo) .sort(function( a, b ) { return certificatesInfo[a].info.days_left - certificatesInfo[b].info.days_left; }).map(function(sortedKey) { return certificatesInfo[sortedKey]; }); var card_html = String() +'<div class="col-xs-12 col-md-6 col-xl-4">' +' <div class="card text-xs-center" style="border-color:#333;">' +' <div class="card-header" style="overflow:hidden;">' +' <h4 class="text-muted" style="margin-bottom:0;">{{server}}</h4>' +' </div>' +' <div class="card-block {{background}}">' +' <h1 class="card-text display-4" style="margin-top:0;margin-bottom:-1rem;">{{days_left}}</h1>' +' <p class="card-text" style="margin-bottom:.75rem;"><small>days left</small></p>' +' </div>' +' <div class="card-footer">' +' <h6 class="text-muted" style="margin-bottom:.5rem;">Issued by: {{issuer}}</h6>' +' <h6 class="text-muted" style=""><small>{{issuer_cn}}</small></h6>' +' <h6 class="text-muted" style="margin-bottom:0;"><small>{{common_name}}</small></h6>' +' </div>' +' </div>' +'</div>'; function insert_card(json) { var card_template = Handlebars.compile(card_html), html = card_template(json); $('#panel').append(html); }; sorted_certificates.forEach(function(element, index, array){ var json = { 'server': element.server, 'days_left': element.info.days_left, 'issuer': element.issuer.org, 'common_name': element.subject.common_name, 'issuer_cn': element.issuer.common_name } if (element.info.days_left <= 30 ){ json.background = 'card-inverse card-danger'; } else if (element.info.days_left > 30 && element.info.days_left <= 60 ) { json.background = 'card-inverse card-warning'; } else if (element.info.days_left === "??") { json.background = 'card-inverse card-info'; } else { json.background = 'card-inverse card-success'; } insert_card(json); }); });
JensDebergh/certificate-dashboard
public/js/tls-dashboard/scripts.js
JavaScript
mit
2,250
--- title: "Configuring the Terminal on a New Macbook" date: 2016-06-01 21:12:00 category: post tags: [efficiency, osx, shell, sublime] --- I bought a new Macbook Pro Retina today for personal use, and spent most of the day re-configuring the terminal and development environment to match my old machine. This post is both a reference for my future self (to save some time with future environment configuration) and a set of recommendations for anyone looking for some time saving tricks. ## [Changing `ls` Colors][ls]{:target="_blank"} The default colors displayed in the output of the `ls` command in the terminal don't make any differentiation between folders or file types. The guide above highlights a few environment variables to set in your `~/.bash_profile` that allow for customization of the colors of `ls` output. This is exceedingly helpful when trying to navigate foreign folder structures, or trying to find that one executable in a sea of non executables. The variables are as follows: {% highlight shell %} export CLICOLOR=1 # tells the shell to apply coloring to command output (just needs to be set) export LSCOLORS=exfxcxdxbxegedabagacad # configuration of colors for particular file types # NOTE: see the article linked above for detail on LSCOLORS values {% endhighlight %} ## [Sublime Text Symlink][subl]{:target="_blank"} My text editor of preference is Sublime, so the article linked above is applicable for creating a symlink for its CLI and adding it to your path. This is convenient since it allows you to open a file (or folder) in your text editor of choice ***from the command line***, instead of having to open files manually from the editor itself. Once you create the symlink, make sure you add the location of the link to your path and put it in your `~/.bash_profile`. {% highlight shell %} export PATH=$PATH:~/.bin # augments PATH with location of sublime symlink {% endhighlight %} ## Additional Sublime Configuration On the topic of Sublime, I recommend enabling the following options in `Preferences > Settings - User`: {%highlight json%} { "trim_trailing_white_space_on_save": true, "ensure_newline_at_eof_on_save": true, "scroll_past_end": true } {%endhighlight%} `trim_trailing_white_space_on_save` will do just that, making your diffs in github easier to parse through. `ensure_newline_at_eof_on_save` is also self explanatory, and keeps your files consistent with the expectation of many unix based text editing utilities that non-empty files have a newline `\n` at the end. Github also tracks this in files, so having it enabled ensures all of your files remain consistent and do not show up in diffs because newlines were removed. `scroll_past_end` lets the editor scroll further down than the last line of the file. This is useful to bring text at the end of a file higher up in the editor, without needing to add a bunch of unnecessary blank lines. ## [Current Git Branch in Your PS1][gbps1]{:target="_blank"} This one blew my mind when I enabled it, and also taught me how to configure the "Prompt String 1" (PS1) that displays by default in the terminal. Just follow the instructions in the post above, which involves adding a shell function to your `~/.bash_profile` that checks for the presence of a git repository and parses the text of the current branch. If a branch was found, the name of the branch will be added to your `PS1`, right before your cursor! Knowing what branch you're on is critical when working on a complex project with multiple branches, preventing inadvertent work in / commits to the wrong branch. ## [Tab Completion of Git Branches][tab]{:target="_blank"} Another trick that saves me a lot of time is tab completion of git branches. Without this, you are forced to type out the full branch name to which you are switching, which slows you down. See the SO post linked above for details on enabling this. It involves downloading a script that performs the tab completion logic (credit to Shawn O. Pearce <[email protected]>) and sourcing it in your `~/.bash_profile`. In all honestly I haven't looked through the script in much detail... but works like a charm! Let me know in the comments if you have any additional time saving tricks that you think I've missed. I'm always interested in improving my personal development process. [ls]: http://osxdaily.com/2012/02/21/add-color-to-the-terminal-in-mac-os-x/ [subl]: http://stackoverflow.com/questions/16199581/opening-sublime-text-on-command-line-as-subl-on-mac-os#answer-16495202 [gbps1]: https://coderwall.com/p/fasnya/add-git-branch-name-to-bash-prompt [tab]: http://apple.stackexchange.com/a/55886
bambielli/bambielli.github.io
_posts/2016-06-01-computer-set-up.md
Markdown
mit
4,669
from PIL import Image import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np img1 = Image.open('multipage.tif') # The following approach seems to be having issue with the # current TIFF format data print('The size of each frame is:') print(img1.size) # Plots first frame print('Frame 1') fig1 = plt.figure(1) img1.seek(0) # for i in range(250): # pixA11 = img1.getpixel((1,i)) # print(pixA11) f1 = list(img1.getdata()) print(f1[1000]) plt.imshow(img1) fig1.show() input() # Plots eleventh frame # print('Frame 11') # fig2 = plt.figure(2) # img1.seek(10) # # for i in range(250): # # pixB11 = img1.getpixel((1,i)) # # print(pixB11) # f2 = list(img1.getdata()) # print(f2[10000]) # plt.imshow(img1) # fig2.show() # input() # Create a new image fig3 = plt.figure(3) imgAvg = Image.new(img1.mode, img1.size) print(img1.mode) print(img1.size) fAvg = list() pix = imgAvg.load() for i in range(512): for j in range(512): pixVal = (f1[i*512+j] + f1[i*512+j]) / 2 # fAvg.append(pixVal) fAvg.insert(i*512+j,pixVal) imgAvg.putdata(fAvg) imgAvg.save('avg.tiff') plt.imshow(imgAvg) fig3.show() print('Average') # The following is necessary to keep the above figures 'alive' input() # data = random.random((256, 256)) # img1 = Image.fromarray(data) # img1.save('test.tiff')
johnrocamora/ImagePy
max_tiff.py
Python
mit
1,346
FROM nginx MAINTAINER Konstantin Volodin, [email protected] COPY nginx.conf /etc/nginx EXPOSE 80 EXPOSE 5500 ENTRYPOINT nginx -g "daemon off;"
volodink/itstime4science
loadb/Dockerfile
Dockerfile
mit
157
FROM golang:alpine as build WORKDIR /go/src COPY main.go . RUN go build -o /go/bin/memhogger . FROM alpine LABEL maintainer="Michael Gasch <[email protected]>" COPY --from=build /go/bin/memhogger /bin/memhogger ENTRYPOINT ["memhogger"]
embano1/gotutorials
memhogger/Dockerfile
Dockerfile
mit
235
-- phpMyAdmin SQL Dump -- version 4.0.9 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: May 11, 2014 at 07:52 AM -- Server version: 5.6.14 -- PHP Version: 5.5.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `apdb` -- -- -------------------------------------------------------- -- -- Table structure for table `bm2` -- CREATE TABLE IF NOT EXISTS `bm2` ( `date` int(11) NOT NULL, `att` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bm2` -- INSERT INTO `bm2` (`date`, `att`) VALUES (1, 90), (2, 88), (3, 0), (4, 88), (5, 90), (6, 92), (7, 88), (8, 90), (9, 86), (10, 0), (11, 86), (12, 0), (13, 85), (14, 90), (15, 92), (16, 88), (17, 0), (18, 86), (19, 92), (20, 93), (21, 90), (22, 90), (23, 92), (24, 0), (25, 93), (26, 93), (27, 93), (28, 93), (29, 93), (30, 0), (31, 0); -- -------------------------------------------------------- -- -- Table structure for table `fan` -- CREATE TABLE IF NOT EXISTS `fan` ( `date` date NOT NULL, `ta` int(11) NOT NULL, `fb` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `school_name` -- CREATE TABLE IF NOT EXISTS `school_name` ( `sid` varchar(5) NOT NULL, `sname` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `school_name` -- INSERT INTO `school_name` (`sid`, `sname`) VALUES ('s1', 'GLPS- NELGULI'), ('', ''), ('s2', 'GLPS SEETHARAMAM PALYA '), ('s3', 'RBANMS - HPS - DICKENSON ROAD '), ('s4', 'GHPS - BASAVANNA NAGARA'), ('s5', 'GLPS - SADANA PALYA'); -- -------------------------------------------------------- -- -- Table structure for table `superv` -- CREATE TABLE IF NOT EXISTS `superv` ( `date` date NOT NULL, `te` int(11) NOT NULL, `fb` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `superv2` -- CREATE TABLE IF NOT EXISTS `superv2` ( `date` int(11) NOT NULL, `te` int(11) NOT NULL, `fb` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `superv2` -- INSERT INTO `superv2` (`date`, `te`, `fb`) VALUES (1, 90, ''), (2, 84, ''), (3, 0, ''), (4, 86, ''), (5, 91, ''), (6, 92, ''), (7, 89, ''), (8, 88, ''), (9, 87, ''), (10, 0, ''), (11, 88, ''), (12, 0, ''), (13, 86, ''), (14, 92, ''), (15, 92, ''), (16, 90, ''), (17, 0, ''), (18, 88, ''), (19, 92, ''), (20, 94, ''), (21, 90, ''), (22, 91, ''), (23, 92, ''), (24, 0, ''), (25, 92, ''), (26, 92, ''), (27, 92, ''), (28, 90, ''), (29, 92, ''), (30, 0, ''), (31, 0, ''); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
code-for-india/cfi_akshaya_patra
apdb.sql
SQL
mit
3,116
package com.InfinityRaider.AgriCraft.utility; import com.InfinityRaider.AgriCraft.items.ItemAgricraft; import com.InfinityRaider.AgriCraft.items.ItemNugget; import com.InfinityRaider.AgriCraft.reference.Data; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class OreDictHelper { private static final Map<String, Block> oreBlocks = new HashMap<String, Block>(); private static final Map<String, Integer> oreBlockMeta = new HashMap<String, Integer>(); private static final Map<String, Item> nuggets = new HashMap<String, Item>(); private static final Map<String, Integer> nuggetMeta = new HashMap<String, Integer>(); public static Block getOreBlockForName(String name) { return oreBlocks.get(name); } public static int getOreMetaForName(String name) { return oreBlockMeta.get(name); } public static Item getNuggetForName(String name) { return nuggets.get(name); } public static int getNuggetMetaForName(String name) { return nuggetMeta.get(name); } //checks if an itemstack has this ore dictionary entry public static boolean hasOreId(ItemStack stack, String tag) { if(stack==null || stack.getItem()==null) { return false; } int[] ids = OreDictionary.getOreIDs(stack); for(int id:ids) { if(OreDictionary.getOreName(id).equals(tag)) { return true; } } return false; } public static boolean hasOreId(Block block, String tag) { return block != null && hasOreId(new ItemStack(block), tag); } //checks if two blocks have the same ore dictionary entry public static boolean isSameOre(Block block1, int meta1, Block block2, int meta2) { if(block1==block2 && meta1==meta2) { return true; } if(block1==null || block2==null) { return false; } int[] ids1 = OreDictionary.getOreIDs(new ItemStack(block1, 1, meta1)); int[] ids2 = OreDictionary.getOreIDs(new ItemStack(block2, 1, meta2)); for (int id1:ids1) { for (int id2:ids2) { if (id1==id2) { return true; } } } return false; } //finds the ingot for a nugget ore dictionary entry public static ItemStack getIngot(String ore) { ItemStack ingot = null; ArrayList<ItemStack> entries = OreDictionary.getOres("ingot" + ore); if (entries.size() > 0 && entries.get(0).getItem() != null) { ingot = entries.get(0); } return ingot; } //finds what ores and nuggets are already registered in the ore dictionary public static void getRegisteredOres() { //Vanilla for (String oreName : Data.vanillaNuggets) { getOreBlock(oreName); if(oreBlocks.get(oreName)!=null) { getNugget(oreName); } } //Modded for (String[] data : Data.modResources) { String oreName = data[0]; getOreBlock(oreName); if(oreBlocks.get(oreName)!=null) { getNugget(oreName); } } } private static void getOreBlock(String oreName) { for (ItemStack itemStack : OreDictionary.getOres("ore"+oreName)) { if (itemStack.getItem() instanceof ItemBlock) { ItemBlock block = (ItemBlock) itemStack.getItem(); oreBlocks.put(oreName, block.field_150939_a); oreBlockMeta.put(oreName, itemStack.getItemDamage()); break; } } } private static void getNugget(String oreName) { List<ItemStack> nuggets = OreDictionary.getOres("nugget" + oreName); if (!nuggets.isEmpty()) { Item nugget = nuggets.get(0).getItem(); OreDictHelper.nuggets.put(oreName, nugget); nuggetMeta.put(oreName, nuggets.get(0).getItemDamage()); } else { ItemAgricraft nugget = new ItemNugget(oreName); OreDictionary.registerOre("nugget"+oreName, nugget); OreDictHelper.nuggets.put(oreName, nugget); nuggetMeta.put(oreName, 0); } } public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed) { return getFruitsFromOreDict(seed, true); } public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed, boolean sameMod) { String seedModId = IOHelper.getModId(seed); ArrayList<ItemStack> fruits = new ArrayList<ItemStack>(); for(int id:OreDictionary.getOreIDs(seed)) { if(OreDictionary.getOreName(id).substring(0,4).equalsIgnoreCase("seed")) { String name = OreDictionary.getOreName(id).substring(4); ArrayList<ItemStack> fromOredict = OreDictionary.getOres("crop"+name); for(ItemStack stack:fromOredict) { if(stack==null || stack.getItem()==null) { continue; } String stackModId = IOHelper.getModId(stack); if((!sameMod) || stackModId.equals(seedModId)) { fruits.add(stack); } } } } return fruits; } }
HenryLoenwind/AgriCraft
src/main/java/com/InfinityRaider/AgriCraft/utility/OreDictHelper.java
Java
mit
5,607
'use strict'; //Setting up route angular.module('socketio-area').config(['$stateProvider', function($stateProvider) { // Socketio area state routing $stateProvider. state('socketio-area', { url: '/socketio', templateUrl: 'modules/socketio-area/views/socketio-area.client.view.html' }); } ]);
NeverOddOrEven/testarea
public/modules/socketio-area/config/socketio-area.client.routes.js
JavaScript
mit
308
#include "utlua.h" #ifdef __linux__ #include <limits.h> #include <linux/netfilter_ipv4.h> #endif #include <net/if.h> #define LUA_TCPD_CONNECTION_TYPE "<tcpd.connect>" #define LUA_TCPD_SERVER_TYPE "<tcpd.bind %s %d>" #define LUA_TCPD_ACCEPT_TYPE "<tcpd.accept %s %d>" #if FAN_HAS_OPENSSL typedef struct { SSL_CTX *ssl_ctx; char *key; int retainCount; } SSLCTX; #endif typedef struct { struct bufferevent *buf; #if FAN_HAS_OPENSSL SSLCTX *sslctx; int ssl_verifyhost; int ssl_verifypeer; const char *ssl_error; #endif lua_State *mainthread; int onReadRef; int onSendReadyRef; int onDisconnectedRef; int onConnectedRef; char *host; char *ssl_host; int port; int send_buffer_size; int receive_buffer_size; int interface; lua_Number read_timeout; lua_Number write_timeout; } Conn; #if FAN_HAS_OPENSSL #define VERIFY_DEPTH 5 static int conn_index = 0; #endif typedef struct { struct evconnlistener *listener; lua_State *mainthread; int onAcceptRef; int onSSLHostNameRef; char *host; int port; int ipv6; #if FAN_HAS_OPENSSL int ssl; SSL_CTX *ctx; EC_KEY *ecdh; #endif int send_buffer_size; int receive_buffer_size; } SERVER; typedef struct { struct bufferevent *buf; lua_State *mainthread; int onReadRef; int onSendReadyRef; int selfRef; char ip[INET6_ADDRSTRLEN]; int port; int onDisconnectedRef; } ACCEPT; #define TCPD_ACCEPT_UNREF(accept) \ CLEAR_REF(accept->mainthread, accept->onSendReadyRef) \ CLEAR_REF(accept->mainthread, accept->onReadRef) \ CLEAR_REF(accept->mainthread, accept->onDisconnectedRef) \ CLEAR_REF(accept->mainthread, accept->selfRef) LUA_API int lua_tcpd_server_close(lua_State *L) { SERVER *serv = luaL_checkudata(L, 1, LUA_TCPD_SERVER_TYPE); CLEAR_REF(L, serv->onAcceptRef) CLEAR_REF(L, serv->onSSLHostNameRef) if (serv->host) { free(serv->host); serv->host = NULL; } if (event_mgr_base_current() && serv->listener) { evconnlistener_free(serv->listener); serv->listener = NULL; } #if FAN_HAS_OPENSSL if (serv->ctx) { SSL_CTX_free(serv->ctx); EC_KEY_free(serv->ecdh); serv->ctx = NULL; serv->ecdh = NULL; } #endif return 0; } LUA_API int lua_tcpd_server_gc(lua_State *L) { return lua_tcpd_server_close(L); } LUA_API int lua_tcpd_accept_tostring(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); lua_pushfstring(L, LUA_TCPD_ACCEPT_TYPE, accept->ip, accept->port); return 1; } LUA_API int lua_tcpd_server_tostring(lua_State *L) { SERVER *serv = luaL_checkudata(L, 1, LUA_TCPD_SERVER_TYPE); if (serv->listener) { char host[INET6_ADDRSTRLEN]; regress_get_socket_host(evconnlistener_get_fd(serv->listener), host); lua_pushfstring( L, LUA_TCPD_SERVER_TYPE, host, regress_get_socket_port(evconnlistener_get_fd(serv->listener))); } else { lua_pushfstring(L, LUA_TCPD_SERVER_TYPE, 0); } return 1; } static void tcpd_accept_eventcb(struct bufferevent *bev, short events, void *arg) { ACCEPT *accept = (ACCEPT *)arg; if (events & BEV_EVENT_ERROR || events & BEV_EVENT_EOF || events & BEV_EVENT_TIMEOUT) { if (events & BEV_EVENT_ERROR) { #if DEBUG printf("BEV_EVENT_ERROR %s\n", evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR())); #endif } bufferevent_free(bev); accept->buf = NULL; if (accept->onDisconnectedRef != LUA_NOREF) { lua_State *mainthread = accept->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onDisconnectedRef); if (events & BEV_EVENT_ERROR && EVUTIL_SOCKET_ERROR()) { lua_pushstring(co, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR())); } else if (events & BEV_EVENT_TIMEOUT) { lua_pushstring(co, "timeout"); } else if (events & BEV_EVENT_EOF) { lua_pushstring(co, "client disconnected"); } else { lua_pushnil(co); } CLEAR_REF(mainthread, accept->onDisconnectedRef) FAN_RESUME(co, mainthread, 1); POP_REF(mainthread); } TCPD_ACCEPT_UNREF(accept) } else { } } #define BUFLEN 1024 static void tcpd_accept_readcb(struct bufferevent *bev, void *ctx) { ACCEPT *accept = (ACCEPT *)ctx; char buf[BUFLEN]; int n; BYTEARRAY ba = {0}; bytearray_alloc(&ba, BUFLEN * 2); struct evbuffer *input = bufferevent_get_input(bev); while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0) { bytearray_writebuffer(&ba, buf, n); } bytearray_read_ready(&ba); if (accept->onReadRef != LUA_NOREF) { lua_State *mainthread = accept->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onReadRef); lua_pushlstring(co, (const char *)ba.buffer, ba.total); FAN_RESUME(co, mainthread, 1); POP_REF(mainthread); } bytearray_dealloc(&ba); } static void tcpd_accept_writecb(struct bufferevent *bev, void *ctx) { ACCEPT *accept = (ACCEPT *)ctx; if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) { if (accept->onSendReadyRef != LUA_NOREF) { lua_State *mainthread = accept->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, accept->onSendReadyRef); FAN_RESUME(co, mainthread, 0); POP_REF(mainthread); } } } void connlistener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *addr, int socklen, void *arg) { SERVER *serv = (SERVER *)arg; if (serv->onAcceptRef != LUA_NOREF) { lua_State *mainthread = serv->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, serv->onAcceptRef); ACCEPT *accept = lua_newuserdata(co, sizeof(ACCEPT)); memset(accept, 0, sizeof(ACCEPT)); accept->buf = NULL; accept->mainthread = mainthread; accept->selfRef = LUA_NOREF; accept->onReadRef = LUA_NOREF; accept->onSendReadyRef = LUA_NOREF; accept->onDisconnectedRef = LUA_NOREF; luaL_getmetatable(co, LUA_TCPD_ACCEPT_TYPE); lua_setmetatable(co, -2); struct event_base *base = evconnlistener_get_base(listener); struct bufferevent *bev; #if FAN_HAS_OPENSSL if (serv->ssl && serv->ctx) { bev = bufferevent_openssl_socket_new( base, fd, SSL_new(serv->ctx), BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); } else { #endif bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); #if FAN_HAS_OPENSSL } #endif bufferevent_setcb(bev, tcpd_accept_readcb, tcpd_accept_writecb, tcpd_accept_eventcb, accept); bufferevent_enable(bev, EV_READ | EV_WRITE); if (serv->send_buffer_size) { setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &serv->send_buffer_size, sizeof(serv->send_buffer_size)); } if (serv->receive_buffer_size) { setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &serv->receive_buffer_size, sizeof(serv->receive_buffer_size)); } memset(accept->ip, 0, INET6_ADDRSTRLEN); if (addr->sa_family == AF_INET) { struct sockaddr_in *addr_in = (struct sockaddr_in *)addr; inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), accept->ip, INET_ADDRSTRLEN); accept->port = ntohs(addr_in->sin_port); } else { struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)addr; inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), accept->ip, INET6_ADDRSTRLEN); accept->port = ntohs(addr_in->sin6_port); } accept->buf = bev; FAN_RESUME(co, mainthread, 1); POP_REF(mainthread); } } LUA_API int tcpd_accept_bind(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); luaL_checktype(L, 2, LUA_TTABLE); lua_settop(L, 2); lua_pushvalue(L, 1); accept->selfRef = luaL_ref(L, LUA_REGISTRYINDEX); SET_FUNC_REF_FROM_TABLE(L, accept->onReadRef, 2, "onread") SET_FUNC_REF_FROM_TABLE(L, accept->onSendReadyRef, 2, "onsendready") SET_FUNC_REF_FROM_TABLE(L, accept->onDisconnectedRef, 2, "ondisconnected") lua_pushstring(L, accept->ip); lua_pushinteger(L, accept->port); return 2; } #if FAN_HAS_OPENSSL static int ssl_servername_cb(SSL *s, int *ad, void *arg) { const char *hostname = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); // if (hostname) // printf("Hostname in TLS extension: \"%s\"\n", hostname); SERVER *serv = (SERVER *)arg; if (hostname && serv->onSSLHostNameRef != LUA_NOREF) { lua_State *mainthread = serv->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, serv->onSSLHostNameRef); lua_pushstring(co, hostname); FAN_RESUME(co, mainthread, 1); POP_REF(mainthread); } // if (!p->servername) // return SSL_TLSEXT_ERR_NOACK; // if (servername) { // if (strcasecmp(servername, p->servername)) // return p->extension_error; // } return SSL_TLSEXT_ERR_OK; } #endif static void tcpd_server_rebind(lua_State *L, SERVER *serv) { if (serv->listener) { evconnlistener_free(serv->listener); serv->listener = NULL; } if (serv->host) { char portbuf[6]; evutil_snprintf(portbuf, sizeof(portbuf), "%d", serv->port); struct evutil_addrinfo hints = {0}; struct evutil_addrinfo *answer = NULL; hints.ai_family = serv->ipv6 ? AF_INET6 : AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = EVUTIL_AI_ADDRCONFIG; int err = evutil_getaddrinfo(serv->host, portbuf, &hints, &answer); if (err < 0 || !answer) { luaL_error(L, "invaild bind address %s:%d", serv->host, serv->port); } serv->listener = evconnlistener_new_bind(event_mgr_base(), connlistener_cb, serv, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, answer->ai_addr, answer->ai_addrlen); evutil_freeaddrinfo(answer); } else { struct sockaddr *addr = NULL; size_t addr_size = 0; struct sockaddr_in sin; struct sockaddr_in6 sin6; memset(&sin, 0, sizeof(sin)); memset(&sin6, 0, sizeof(sin6)); if (!serv->ipv6) { addr = (struct sockaddr *)&sin; addr_size = sizeof(sin); sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(0); sin.sin_port = htons(serv->port); } else { addr = (struct sockaddr *)&sin6; addr_size = sizeof(sin6); sin6.sin6_family = AF_INET6; // sin6.sin6_addr.s6_addr sin6.sin6_port = htons(serv->port); } serv->listener = evconnlistener_new_bind( event_mgr_base(), connlistener_cb, serv, LEV_OPT_CLOSE_ON_FREE | LEV_OPT_REUSEABLE, -1, addr, addr_size); } } LUA_API int lua_tcpd_server_rebind(lua_State *L) { SERVER *serv = luaL_checkudata(L, 1, LUA_TCPD_SERVER_TYPE); tcpd_server_rebind(L, serv); return 0; } LUA_API int tcpd_bind(lua_State *L) { event_mgr_init(); luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); SERVER *serv = lua_newuserdata(L, sizeof(SERVER)); memset(serv, 0, sizeof(SERVER)); luaL_getmetatable(L, LUA_TCPD_SERVER_TYPE); lua_setmetatable(L, -2); serv->mainthread = utlua_mainthread(L); SET_FUNC_REF_FROM_TABLE(L, serv->onAcceptRef, 1, "onaccept") SET_FUNC_REF_FROM_TABLE(L, serv->onSSLHostNameRef, 1, "onsslhostname") DUP_STR_FROM_TABLE(L, serv->host, 1, "host") SET_INT_FROM_TABLE(L, serv->port, 1, "port") lua_getfield(L, 1, "ssl"); int ssl = lua_toboolean(L, -1); lua_pop(L, 1); #if FAN_HAS_OPENSSL serv->ssl = ssl; if (serv->ssl) { lua_getfield(L, 1, "cert"); const char *cert = lua_tostring(L, -1); lua_getfield(L, 1, "key"); const char *key = lua_tostring(L, -1); if (cert && key) { SSL_CTX *ctx = SSL_CTX_new(TLS_server_method()); SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, serv); serv->ctx = ctx; SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE | 0); // SSL_OP_NO_SSLv2 serv->ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (!serv->ecdh) { die_most_horribly_from_openssl_error("EC_KEY_new_by_curve_name"); } if (1 != SSL_CTX_set_tmp_ecdh(ctx, serv->ecdh)) { die_most_horribly_from_openssl_error("SSL_CTX_set_tmp_ecdh"); } server_setup_certs(ctx, cert, key); } lua_pop(L, 2); } #else if (ssl) { luaL_error(L, "ssl is not supported on micro version."); } #endif SET_INT_FROM_TABLE(L, serv->send_buffer_size, 1, "send_buffer_size") SET_INT_FROM_TABLE(L, serv->receive_buffer_size, 1, "receive_buffer_size") lua_getfield(L, 1, "ipv6"); serv->ipv6 = lua_toboolean(L, -1); lua_pop(L, 1); tcpd_server_rebind(L, serv); if (!serv->listener) { return 0; } else { if (!serv->port) { serv->port = regress_get_socket_port(evconnlistener_get_fd(serv->listener)); } lua_pushinteger(L, serv->port); return 2; } } static void tcpd_conn_readcb(struct bufferevent *bev, void *ctx) { Conn *conn = (Conn *)ctx; char buf[BUFLEN]; int n; BYTEARRAY ba; bytearray_alloc(&ba, BUFLEN * 2); struct evbuffer *input = bufferevent_get_input(bev); while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0) { bytearray_writebuffer(&ba, buf, n); } bytearray_read_ready(&ba); if (conn->onReadRef != LUA_NOREF) { lua_State *mainthread = conn->mainthread; lua_lock(mainthread); lua_rawgeti(mainthread, LUA_REGISTRYINDEX, conn->onReadRef); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_xmove(mainthread, co, 1); lua_unlock(mainthread); lua_pushlstring(co, (const char *)ba.buffer, ba.total); FAN_RESUME(co, mainthread, 1); POP_REF(mainthread); } bytearray_dealloc(&ba); } static void tcpd_conn_writecb(struct bufferevent *bev, void *ctx) { Conn *conn = (Conn *)ctx; if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) { if (conn->onSendReadyRef != LUA_NOREF) { lua_State *mainthread = conn->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onSendReadyRef); FAN_RESUME(co, mainthread, 0); POP_REF(mainthread); } } } static void tcpd_conn_eventcb(struct bufferevent *bev, short events, void *arg) { Conn *conn = (Conn *)arg; if (events & BEV_EVENT_CONNECTED) { // printf("tcp connected.\n"); if (conn->onConnectedRef != LUA_NOREF) { lua_State *mainthread = conn->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onConnectedRef); FAN_RESUME(co, mainthread, 0); POP_REF(mainthread); } } else if (events & BEV_EVENT_ERROR || events & BEV_EVENT_EOF || events & BEV_EVENT_TIMEOUT) { #if FAN_HAS_OPENSSL SSL *ssl = bufferevent_openssl_get_ssl(bev); if (ssl) { SSL_set_shutdown(ssl, SSL_RECEIVED_SHUTDOWN); SSL_shutdown(ssl); } #endif bufferevent_free(bev); conn->buf = NULL; if (conn->onDisconnectedRef != LUA_NOREF) { lua_State *mainthread = conn->mainthread; lua_lock(mainthread); lua_State *co = lua_newthread(mainthread); PUSH_REF(mainthread); lua_unlock(mainthread); lua_rawgeti(co, LUA_REGISTRYINDEX, conn->onDisconnectedRef); if (events & BEV_EVENT_TIMEOUT) { if (events & BEV_EVENT_READING) { lua_pushliteral(co, "read timeout"); } else if (events & BEV_EVENT_WRITING) { lua_pushliteral(co, "write timeout"); } else { lua_pushliteral(co, "unknown timeout"); } } else if (events & BEV_EVENT_ERROR) { #if FAN_HAS_OPENSSL if (conn->ssl_error) { lua_pushfstring(co, "SSLError: %s", conn->ssl_error); } else { #endif int err = bufferevent_socket_get_dns_error(bev); if (err) { lua_pushstring(co, evutil_gai_strerror(err)); } else if (EVUTIL_SOCKET_ERROR()) { lua_pushstring( co, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR())); } else { lua_pushnil(co); } #if FAN_HAS_OPENSSL } #endif } else if (events & BEV_EVENT_EOF) { lua_pushliteral(co, "server disconnected"); } else { lua_pushnil(co); } FAN_RESUME(co, mainthread, 1); POP_REF(mainthread); } } } #if FAN_HAS_OPENSSL static int ssl_verifypeer_cb(int preverify_ok, X509_STORE_CTX *ctx) { if (!preverify_ok) { SSL *ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); Conn *conn = SSL_get_ex_data(ssl, conn_index); int err = X509_STORE_CTX_get_error(ctx); conn->ssl_error = strdup(X509_verify_cert_error_string(err)); } return preverify_ok; } #endif static void luatcpd_reconnect(Conn *conn) { if (conn->buf) { bufferevent_free(conn->buf); conn->buf = NULL; } #if FAN_HAS_OPENSSL conn->ssl_error = 0; if (conn->sslctx) { SSL *ssl = SSL_new(conn->sslctx->ssl_ctx); SSL_set_ex_data(ssl, conn_index, conn); if (conn->ssl_verifyhost && (conn->ssl_host ?: conn->host)) { SSL_set_hostflags(ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); if (!SSL_set1_host(ssl, conn->ssl_host ?: conn->host)) { printf("SSL_set1_host '%s' failed!\n", conn->ssl_host ?: conn->host); } } /* Enable peer verification (with a non-null callback if desired) */ if (conn->ssl_verifypeer) { SSL_set_verify(ssl, SSL_VERIFY_PEER, NULL); } else { SSL_set_verify(ssl, SSL_VERIFY_NONE, NULL); } SSL_set_tlsext_host_name(ssl, conn->ssl_host ?: conn->host); conn->buf = bufferevent_openssl_socket_new( event_mgr_base(), -1, ssl, BUFFEREVENT_SSL_CONNECTING, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); #ifdef EVENT__NUMERIC_VERSION #if (EVENT__NUMERIC_VERSION >= 0x02010500) bufferevent_openssl_set_allow_dirty_shutdown(conn->buf, 1); #endif #endif } else { #endif conn->buf = bufferevent_socket_new( event_mgr_base(), -1, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS); #if FAN_HAS_OPENSSL } #endif int rc = bufferevent_socket_connect_hostname(conn->buf, event_mgr_dnsbase(), AF_UNSPEC, conn->host, conn->port); evutil_socket_t fd = bufferevent_getfd(conn->buf); if (conn->send_buffer_size) { setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &conn->send_buffer_size, sizeof(conn->send_buffer_size)); } if (conn->receive_buffer_size) { setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &conn->receive_buffer_size, sizeof(conn->receive_buffer_size)); } #ifdef IP_BOUND_IF if (conn->interface) { setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &conn->interface, sizeof(conn->interface)); } #endif if (rc < 0) { LOGE("could not connect to %s:%d %s", conn->host, conn->port, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR())); bufferevent_free(conn->buf); conn->buf = NULL; return; } bufferevent_enable(conn->buf, EV_WRITE | EV_READ); bufferevent_setcb(conn->buf, tcpd_conn_readcb, tcpd_conn_writecb, tcpd_conn_eventcb, conn); } LUA_API int tcpd_connect(lua_State *L) { event_mgr_init(); luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); Conn *conn = lua_newuserdata(L, sizeof(Conn)); memset(conn, 0, sizeof(Conn)); luaL_getmetatable(L, LUA_TCPD_CONNECTION_TYPE); lua_setmetatable(L, -2); conn->mainthread = utlua_mainthread(L); conn->buf = NULL; #if FAN_HAS_OPENSSL conn->sslctx = NULL; conn->ssl_error = 0; #endif conn->send_buffer_size = 0; conn->receive_buffer_size = 0; SET_FUNC_REF_FROM_TABLE(L, conn->onReadRef, 1, "onread") SET_FUNC_REF_FROM_TABLE(L, conn->onSendReadyRef, 1, "onsendready") SET_FUNC_REF_FROM_TABLE(L, conn->onDisconnectedRef, 1, "ondisconnected") SET_FUNC_REF_FROM_TABLE(L, conn->onConnectedRef, 1, "onconnected") DUP_STR_FROM_TABLE(L, conn->host, 1, "host") SET_INT_FROM_TABLE(L, conn->port, 1, "port") lua_getfield(L, 1, "ssl"); int ssl = lua_toboolean(L, -1); lua_pop(L, 1); #if FAN_HAS_OPENSSL lua_getfield(L, 1, "ssl_verifyhost"); conn->ssl_verifyhost = (int)luaL_optinteger(L, -1, 1); lua_pop(L, 1); lua_getfield(L, 1, "ssl_verifypeer"); conn->ssl_verifypeer = (int)luaL_optinteger(L, -1, 1); lua_pop(L, 1); DUP_STR_FROM_TABLE(L, conn->ssl_host, 1, "ssl_host") if (ssl) { lua_getfield(L, 1, "cainfo"); const char *cainfo = luaL_optstring(L, -1, NULL); lua_pop(L, 1); lua_getfield(L, 1, "capath"); const char *capath = luaL_optstring(L, -1, NULL); lua_pop(L, 1); lua_getfield(L, 1, "pkcs12.path"); const char *p12path = luaL_optstring(L, -1, NULL); lua_pop(L, 1); lua_getfield(L, 1, "pkcs12.password"); const char *p12password = luaL_optstring(L, -1, NULL); lua_pop(L, 1); if (!cainfo && !capath) { cainfo = "cert.pem"; } BYTEARRAY ba = {0}; bytearray_alloc(&ba, BUFLEN); bytearray_writebuffer(&ba, "SSL_CTX:", strlen("SSL_CTX_")); if (cainfo) { bytearray_writebuffer(&ba, cainfo, strlen(cainfo)); } if (capath) { bytearray_writebuffer(&ba, capath, strlen(capath)); } if (p12path) { bytearray_writebuffer(&ba, p12path, strlen(p12path)); } if (p12password) { bytearray_writebuffer(&ba, p12password, strlen(p12password)); } bytearray_write8(&ba, 0); bytearray_read_ready(&ba); char *cache_key = strdup((const char *)ba.buffer); bytearray_dealloc(&ba); lua_getfield(L, LUA_REGISTRYINDEX, cache_key); if (lua_isnil(L, -1)) { SSLCTX *sslctx = lua_newuserdata(L, sizeof(SSLCTX)); sslctx->key = strdup(cache_key); sslctx->ssl_ctx = SSL_CTX_new(TLS_method()); conn->sslctx = sslctx; sslctx->retainCount = 1; lua_setfield(L, LUA_REGISTRYINDEX, cache_key); if (!SSL_CTX_load_verify_locations(sslctx->ssl_ctx, cainfo, capath)) { printf("SSL_CTX_load_verify_locations failed: cainfo=%s capath=%s\n", cainfo, capath); } #ifdef SSL_MODE_RELEASE_BUFFERS SSL_CTX_set_mode(sslctx->ssl_ctx, SSL_MODE_RELEASE_BUFFERS); #endif SSL_CTX_set_options(sslctx->ssl_ctx, SSL_OP_NO_COMPRESSION); SSL_CTX_set_verify(sslctx->ssl_ctx, SSL_VERIFY_PEER, ssl_verifypeer_cb); while (p12path) { FILE *fp = NULL; EVP_PKEY *pkey = NULL; X509 *cert = NULL; STACK_OF(X509) *ca = NULL; PKCS12 *p12 = NULL; if ((fp = fopen(p12path, "rb")) == NULL) { fprintf(stderr, "Error opening file %s\n", p12path); break; } p12 = d2i_PKCS12_fp(fp, NULL); fclose(fp); if (!p12) { fprintf(stderr, "Error reading PKCS#12 file\n"); ERR_print_errors_fp(stderr); break; } if (!PKCS12_parse(p12, p12password, &pkey, &cert, &ca)) { fprintf(stderr, "Error parsing PKCS#12 file\n"); ERR_print_errors_fp(stderr); } else { SSL_CTX_use_certificate(sslctx->ssl_ctx, cert); if (ca && sk_X509_num(ca)) { int i = 0; for (i = 0; i < sk_X509_num(ca); i++) { SSL_CTX_use_certificate(sslctx->ssl_ctx, sk_X509_value(ca, i)); } } SSL_CTX_use_PrivateKey(sslctx->ssl_ctx, pkey); sk_X509_pop_free(ca, X509_free); X509_free(cert); EVP_PKEY_free(pkey); } PKCS12_free(p12); p12 = NULL; break; } } else { SSLCTX *sslctx = lua_touserdata(L, -1); sslctx->retainCount++; conn->sslctx = sslctx; } lua_pop(L, 1); FREE_STR(cache_key); } #else if (ssl) { luaL_error(L, "ssl is not supported on micro version."); } #endif SET_INT_FROM_TABLE(L, conn->send_buffer_size, 1, "send_buffer_size") SET_INT_FROM_TABLE(L, conn->receive_buffer_size, 1, "receive_buffer_size") lua_getfield(L, 1, "read_timeout"); lua_Number read_timeout = (int)luaL_optnumber(L, -1, 0); conn->read_timeout = read_timeout; lua_pop(L, 1); lua_getfield(L, 1, "write_timeout"); lua_Number write_timeout = (int)luaL_optnumber(L, -1, 0); conn->write_timeout = write_timeout; lua_pop(L, 1); lua_getfield(L, 1, "interface"); if (lua_type(L, -1) == LUA_TSTRING) { const char *interface = lua_tostring(L, -1); conn->interface = if_nametoindex(interface); } lua_pop(L, 1); luatcpd_reconnect(conn); return 1; } static const luaL_Reg tcpdlib[] = { {"bind", tcpd_bind}, {"connect", tcpd_connect}, {NULL, NULL}}; LUA_API int tcpd_conn_close(lua_State *L) { Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE); if (event_mgr_base_current() && conn->buf) { bufferevent_free(conn->buf); conn->buf = NULL; } CLEAR_REF(L, conn->onReadRef) CLEAR_REF(L, conn->onSendReadyRef) CLEAR_REF(L, conn->onDisconnectedRef) CLEAR_REF(L, conn->onConnectedRef) FREE_STR(conn->host) FREE_STR(conn->ssl_host) #if FAN_HAS_OPENSSL if (conn->sslctx) { conn->sslctx->retainCount--; if (conn->sslctx->retainCount <= 0) { lua_pushnil(L); lua_setfield(L, LUA_REGISTRYINDEX, conn->sslctx->key); SSL_CTX_free(conn->sslctx->ssl_ctx); free(conn->sslctx->key); } conn->sslctx = NULL; } #endif return 0; } LUA_API int tcpd_conn_gc(lua_State *L) { return tcpd_conn_close(L); } LUA_API int tcpd_accept_remote(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); lua_newtable(L); lua_pushstring(L, accept->ip); lua_setfield(L, -2, "ip"); lua_pushinteger(L, accept->port); lua_setfield(L, -2, "port"); return 1; } #ifdef __linux__ LUA_API int tcpd_accept_original_dst(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); evutil_socket_t fd = bufferevent_getfd(accept->buf); struct sockaddr_storage ss; socklen_t len = sizeof(struct sockaddr_storage); if (getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &ss, &len)) { lua_pushnil(L); lua_pushfstring(L, "getsockopt: %s", strerror(errno)); return 2; } char host[INET6_ADDRSTRLEN]; int port = 0; if (ss.ss_family == AF_INET) { struct sockaddr_in *addr_in = (struct sockaddr_in *)&ss; port = ntohs(((struct sockaddr_in *)&ss)->sin_port); inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), host, INET_ADDRSTRLEN); } else if (ss.ss_family == AF_INET6) { struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)&ss; port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port); inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), host, INET6_ADDRSTRLEN); } lua_pushstring(L, host); lua_pushinteger(L, port); return 2; } #endif LUA_API int tcpd_accept_getsockname(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); evutil_socket_t fd = bufferevent_getfd(accept->buf); struct sockaddr_storage ss; socklen_t len = sizeof(struct sockaddr_storage); if (getsockname(fd, (struct sockaddr *)&ss, &len)) { lua_pushnil(L); lua_pushfstring(L, "getsockname: %s", strerror(errno)); return 2; } char host[INET6_ADDRSTRLEN]; int port = 0; if (ss.ss_family == AF_INET) { struct sockaddr_in *addr_in = (struct sockaddr_in *)&ss; port = ntohs(((struct sockaddr_in *)&ss)->sin_port); inet_ntop(addr_in->sin_family, (void *)&(addr_in->sin_addr), host, INET_ADDRSTRLEN); } else if (ss.ss_family == AF_INET6) { struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)&ss; port = ntohs(((struct sockaddr_in6 *)&ss)->sin6_port); inet_ntop(addr_in->sin6_family, (void *)&(addr_in->sin6_addr), host, INET6_ADDRSTRLEN); } lua_pushstring(L, host); lua_pushinteger(L, port); return 2; } LUA_API int tcpd_accept_close(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); if (event_mgr_base_current() && accept->buf) { bufferevent_free(accept->buf); accept->buf = NULL; } TCPD_ACCEPT_UNREF(accept) return 0; } LUA_API int lua_tcpd_accept_gc(lua_State *L) { return tcpd_accept_close(L); } LUA_API int tcpd_accept_read_pause(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); if (accept->buf) { bufferevent_disable(accept->buf, EV_READ); } return 0; } LUA_API int tcpd_accept_read_resume(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); if (accept->buf) { bufferevent_enable(accept->buf, EV_READ); } return 0; } LUA_API int tcpd_conn_read_pause(lua_State *L) { Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE); if (conn->buf) { bufferevent_disable(conn->buf, EV_READ); } return 0; } LUA_API int tcpd_conn_read_resume(lua_State *L) { Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE); if (conn->buf) { bufferevent_enable(conn->buf, EV_READ); } return 0; } LUA_API int tcpd_conn_send(lua_State *L) { Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE); size_t len = 0; const char *data = luaL_checklstring(L, 2, &len); if (data && len > 0 && conn->buf) { if (conn->read_timeout > 0) { struct timeval tv1; d2tv(conn->read_timeout, &tv1); if (conn->write_timeout > 0) { struct timeval tv2; d2tv(conn->write_timeout, &tv2); bufferevent_set_timeouts(conn->buf, &tv1, &tv2); } else { bufferevent_set_timeouts(conn->buf, &tv1, NULL); } } else { if (conn->write_timeout > 0) { struct timeval tv2; d2tv(conn->write_timeout, &tv2); bufferevent_set_timeouts(conn->buf, NULL, &tv2); } } bufferevent_write(conn->buf, data, len); size_t total = evbuffer_get_length(bufferevent_get_output(conn->buf)); lua_pushinteger(L, total); } else { lua_pushinteger(L, -1); } return 1; } LUA_API int tcpd_conn_reconnect(lua_State *L) { Conn *conn = luaL_checkudata(L, 1, LUA_TCPD_CONNECTION_TYPE); luatcpd_reconnect(conn); return 0; } LUA_API int tcpd_accept_flush(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); int mode = luaL_optinteger(L, 2, BEV_NORMAL); lua_pushinteger(L, bufferevent_flush(accept->buf, EV_WRITE, mode)); return 1; } LUA_API int tcpd_accept_send(lua_State *L) { ACCEPT *accept = luaL_checkudata(L, 1, LUA_TCPD_ACCEPT_TYPE); size_t len = 0; const char *data = luaL_checklstring(L, 2, &len); if (data && len > 0 && accept->buf) { bufferevent_write(accept->buf, data, len); size_t total = evbuffer_get_length(bufferevent_get_output(accept->buf)); lua_pushinteger(L, total); } else { lua_pushinteger(L, -1); } return 1; } LUA_API int luaopen_fan_tcpd(lua_State *L) { #if FAN_HAS_OPENSSL conn_index = SSL_get_ex_new_index(0, "conn_index", NULL, NULL, NULL); #endif luaL_newmetatable(L, LUA_TCPD_CONNECTION_TYPE); lua_pushcfunction(L, &tcpd_conn_send); lua_setfield(L, -2, "send"); lua_pushcfunction(L, &tcpd_conn_read_pause); lua_setfield(L, -2, "pause_read"); lua_pushcfunction(L, &tcpd_conn_read_resume); lua_setfield(L, -2, "resume_read"); lua_pushcfunction(L, &tcpd_conn_close); lua_setfield(L, -2, "close"); lua_pushcfunction(L, &tcpd_conn_reconnect); lua_setfield(L, -2, "reconnect"); lua_pushstring(L, "__index"); lua_pushvalue(L, -2); lua_rawset(L, -3); lua_pushstring(L, "__gc"); lua_pushcfunction(L, &tcpd_conn_gc); lua_rawset(L, -3); lua_pop(L, 1); luaL_newmetatable(L, LUA_TCPD_ACCEPT_TYPE); lua_pushcfunction(L, &tcpd_accept_send); lua_setfield(L, -2, "send"); lua_pushcfunction(L, &tcpd_accept_flush); lua_setfield(L, -2, "flush"); lua_pushcfunction(L, &tcpd_accept_close); lua_setfield(L, -2, "close"); lua_pushcfunction(L, &tcpd_accept_read_pause); lua_setfield(L, -2, "pause_read"); lua_pushcfunction(L, &tcpd_accept_read_resume); lua_setfield(L, -2, "resume_read"); lua_pushcfunction(L, &tcpd_accept_bind); lua_setfield(L, -2, "bind"); lua_pushcfunction(L, &tcpd_accept_remote); lua_setfield(L, -2, "remoteinfo"); lua_pushcfunction(L, &tcpd_accept_getsockname); lua_setfield(L, -2, "getsockname"); #ifdef __linux__ lua_pushcfunction(L, &tcpd_accept_original_dst); lua_setfield(L, -2, "original_dst"); #endif lua_pushstring(L, "__index"); lua_pushvalue(L, -2); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcfunction(L, &lua_tcpd_accept_tostring); lua_rawset(L, -3); lua_pushstring(L, "__gc"); lua_pushcfunction(L, &lua_tcpd_accept_gc); lua_rawset(L, -3); lua_pop(L, 1); luaL_newmetatable(L, LUA_TCPD_SERVER_TYPE); lua_pushstring(L, "close"); lua_pushcfunction(L, &lua_tcpd_server_close); lua_rawset(L, -3); lua_pushcfunction(L, &lua_tcpd_server_rebind); lua_setfield(L, -2, "rebind"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, &lua_tcpd_server_gc); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcfunction(L, &lua_tcpd_server_tostring); lua_rawset(L, -3); lua_pushstring(L, "__index"); lua_pushvalue(L, -2); lua_rawset(L, -3); lua_pop(L, 1); lua_newtable(L); luaL_register(L, "tcpd", tcpdlib); return 1; }
luafan/luafan
src/tcpd.c
C
mit
34,905
/** * configuration for grunt tasks * @module Gruntfile */ module.exports = function(grunt) { /** load tasks */ require('load-grunt-tasks')(grunt); /** config for build paths */ var config = { dist: { dir: 'dist/', StoreFactory: 'dist/StoreFactory.js', ngStoreFactory: 'dist/ngStore.js' }, src: { dir: 'src/' }, tmp: { dir: 'tmp/' } }; /** paths to files */ var files = { /** src files */ Factory: [ 'StoreFactory.js' ], /** src files */ Store: [ 'Store.js' ], }; /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ /** config for grunt tasks */ var taskConfig = { /** concatentation tasks for building the source files */ concat: { StoreFactory: { options: { // stripBanners: true banner: '', footer: '', }, src: (function() { var cwd = config.src.dir, queue = [].concat(files.Factory, files.Store); return queue.map(function(path) { return cwd + path; }); })(), dest: config.dist.StoreFactory, }, ngSession: { options: { banner: 'angular.module("ngStore", [])\n' + '.service("ngStore", [\n' + 'function() {\n\n', footer: '\n\n' + 'return new StoreFactory();\n\n}' + '\n]);' }, src: (function() { return [ config.dist.StoreFactory, ]; })(), dest: config.dist.ngStoreFactory } }, /** uglify (javascript minification) config */ uglify: { StoreFactory: { options: {}, files: [ { src: config.dist.StoreFactory, dest: (function() { var split = config.dist.StoreFactory.split('.'); split.pop(); // removes `js` extension split.push('min'); // adds `min` extension split.push('js'); // adds `js` extension return split.join('.'); })() } ] }, ngStoreFactory: { options: {}, files: [ { src: config.dist.ngStoreFactory, dest: (function() { var split = config.dist.ngStoreFactory.split('.'); split.pop(); // removes `js` extension split.push('min'); // adds `min` extension split.push('js'); // adds `js` extension return split.join('.'); })() } ] } } }; /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ /* # # # # # # # # # # # # # # # # # # # # */ // register default & custom tasks grunt.initConfig(taskConfig); grunt.registerTask('default', [ 'build' ]); grunt.registerTask('build', [ 'concat', 'uglify' ]); };
ishmaelthedestroyer/ngStore
Gruntfile.js
JavaScript
mit
3,141
#requires -Modules InvokeBuild [CmdletBinding()] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingWriteHost', '')] [System.Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingEmptyCatchBlock', '')] param( [String[]]$Tag, [String[]]$ExcludeTag = @("Integration"), [String]$PSGalleryAPIKey, [String]$GithubAccessToken ) $WarningPreference = "Continue" if ($PSBoundParameters.ContainsKey('Verbose')) { $VerbosePreference = "Continue" } if ($PSBoundParameters.ContainsKey('Debug')) { $DebugPreference = "Continue" } try { $script:IsWindows = (-not (Get-Variable -Name IsWindows -ErrorAction Ignore)) -or $IsWindows $script:IsLinux = (Get-Variable -Name IsLinux -ErrorAction Ignore) -and $IsLinux $script:IsMacOS = (Get-Variable -Name IsMacOS -ErrorAction Ignore) -and $IsMacOS $script:IsCoreCLR = $PSVersionTable.ContainsKey('PSEdition') -and $PSVersionTable.PSEdition -eq 'Core' } catch { } Set-StrictMode -Version Latest Import-Module "$PSScriptRoot/Tools/BuildTools.psm1" -Force -ErrorAction Stop if ($BuildTask -notin @("SetUp", "InstallDependencies")) { Import-Module BuildHelpers -Force -ErrorAction Stop Invoke-Init } #region SetUp # Synopsis: Proxy task task Init { Invoke-Init } # Synopsis: Get the next version for the build task GetNextVersion { $manifestVersion = [Version](Get-Metadata -Path $env:BHPSModuleManifest) try { $env:CurrentOnlineVersion = [Version](Find-Module -Name $env:BHProjectName).Version $nextOnlineVersion = Get-NextNugetPackageVersion -Name $env:BHProjectName if ( ($manifestVersion.Major -gt $nextOnlineVersion.Major) -or ($manifestVersion.Minor -gt $nextOnlineVersion.Minor) # -or ($manifestVersion.Build -gt $nextOnlineVersion.Build) ) { $env:NextBuildVersion = [Version]::New($manifestVersion.Major, $manifestVersion.Minor, 0) } else { $env:NextBuildVersion = $nextOnlineVersion } } catch { $env:NextBuildVersion = $manifestVersion } } #endregion Setup #region HarmonizeVariables switch ($true) { { $IsWindows } { $OS = "Windows" if (-not ($IsCoreCLR)) { $OSVersion = $PSVersionTable.BuildVersion.ToString() } } { $IsLinux } { $OS = "Linux" } { $IsMacOs } { $OS = "OSX" } { $IsCoreCLR } { $OSVersion = $PSVersionTable.OS } } #endregion HarmonizeVariables #region DebugInformation task ShowInfo Init, GetNextVersion, { Write-Build Gray Write-Build Gray ('Running in: {0}' -f $env:BHBuildSystem) Write-Build Gray '-------------------------------------------------------' Write-Build Gray Write-Build Gray ('Project name: {0}' -f $env:BHProjectName) Write-Build Gray ('Project root: {0}' -f $env:BHProjectPath) Write-Build Gray ('Build Path: {0}' -f $env:BHBuildOutput) Write-Build Gray ('Current (online) Version: {0}' -f $env:CurrentOnlineVersion) Write-Build Gray '-------------------------------------------------------' Write-Build Gray Write-Build Gray ('Branch: {0}' -f $env:BHBranchName) Write-Build Gray ('Commit: {0}' -f $env:BHCommitMessage) Write-Build Gray ('Build #: {0}' -f $env:BHBuildNumber) Write-Build Gray ('Next Version: {0}' -f $env:NextBuildVersion) Write-Build Gray '-------------------------------------------------------' Write-Build Gray Write-Build Gray ('PowerShell version: {0}' -f $PSVersionTable.PSVersion.ToString()) Write-Build Gray ('OS: {0}' -f $OS) Write-Build Gray ('OS Version: {0}' -f $OSVersion) Write-Build Gray } #endregion DebugInformation #region BuildRelease # Synopsis: Build a shippable release task Build Init, GenerateExternalHelp, CopyModuleFiles, UpdateManifest, CompileModule, PrepareTests # Synopsis: Generate ./Release structure task CopyModuleFiles { # Setup if (-not (Test-Path "$env:BHBuildOutput/$env:BHProjectName")) { $null = New-Item -Path "$env:BHBuildOutput/$env:BHProjectName" -ItemType Directory } # Copy module Copy-Item -Path "$env:BHModulePath/*" -Destination "$env:BHBuildOutput/$env:BHProjectName" -Recurse -Force # Copy additional files Copy-Item -Path @( "$env:BHProjectPath/CHANGELOG.md" "$env:BHProjectPath/LICENSE" "$env:BHProjectPath/README.md" ) -Destination "$env:BHBuildOutput/$env:BHProjectName" -Force } # Synopsis: Prepare tests for ./Release task PrepareTests Init, { $null = New-Item -Path "$env:BHBuildOutput/Tests" -ItemType Directory -ErrorAction SilentlyContinue Copy-Item -Path "$env:BHProjectPath/Tests" -Destination $env:BHBuildOutput -Recurse -Force Copy-Item -Path "$env:BHProjectPath/PSScriptAnalyzerSettings.psd1" -Destination $env:BHBuildOutput -Force } # Synopsis: Compile all functions into the .psm1 file task CompileModule Init, { $regionsToKeep = @('Dependencies', 'Configuration') $targetFile = "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psm1" $content = Get-Content -Encoding UTF8 -LiteralPath $targetFile $capture = $false $compiled = "" foreach ($line in $content) { if ($line -match "^#region ($($regionsToKeep -join "|"))$") { $capture = $true } if (($capture -eq $true) -and ($line -match "^#endregion")) { $capture = $false } if ($capture) { $compiled += "$line`r`n" } } $PublicFunctions = @( Get-ChildItem -Path "$env:BHBuildOutput/$env:BHProjectName/Public/*.ps1" -ErrorAction SilentlyContinue ) $PrivateFunctions = @( Get-ChildItem -Path "$env:BHBuildOutput/$env:BHProjectName/Private/*.ps1" -ErrorAction SilentlyContinue ) foreach ($function in @($PublicFunctions + $PrivateFunctions)) { $compiled += (Get-Content -Path $function.FullName -Raw) $compiled += "`r`n" } Set-Content -LiteralPath $targetFile -Value $compiled -Encoding UTF8 -Force Remove-Utf8Bom -Path $targetFile "Private", "Public" | Foreach-Object { Remove-Item -Path "$env:BHBuildOutput/$env:BHProjectName/$_" -Recurse -Force } } # Synopsis: Use PlatyPS to generate External-Help task GenerateExternalHelp Init, { Import-Module platyPS -Force foreach ($locale in (Get-ChildItem "$env:BHProjectPath/docs" -Attribute Directory)) { New-ExternalHelp -Path "$($locale.FullName)" -OutputPath "$env:BHModulePath/$($locale.Basename)" -Force New-ExternalHelp -Path "$($locale.FullName)/commands" -OutputPath "$env:BHModulePath/$($locale.Basename)" -Force } Remove-Module platyPS } # Synopsis: Update the manifest of the module task UpdateManifest GetNextVersion, { Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue Import-Module $env:BHPSModuleManifest -Force $ModuleAlias = @(Get-Alias | Where-Object { $_.ModuleName -eq "$env:BHProjectName" }) BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName ModuleVersion -Value $env:NextBuildVersion # BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName FileList -Value (Get-ChildItem "$env:BHBuildOutput/$env:BHProjectName" -Recurse).Name BuildHelpers\Set-ModuleFunctions -Name "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -FunctionsToExport ([string[]](Get-ChildItem "$env:BHBuildOutput/$env:BHProjectName/Public/*.ps1").BaseName) BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName AliasesToExport -Value '' if ($ModuleAlias) { BuildHelpers\Update-Metadata -Path "$env:BHBuildOutput/$env:BHProjectName/$env:BHProjectName.psd1" -PropertyName AliasesToExport -Value @($ModuleAlias.Name) } } # Synopsis: Create a ZIP file with this build task Package Init, { Assert-True { Test-Path "$env:BHBuildOutput\$env:BHProjectName" } "Missing files to package" Remove-Item "$env:BHBuildOutput\$env:BHProjectName.zip" -ErrorAction SilentlyContinue $null = Compress-Archive -Path "$env:BHBuildOutput\$env:BHProjectName" -DestinationPath "$env:BHBuildOutput\$env:BHProjectName.zip" } #endregion BuildRelease #region Test task Test Init, { Assert-True { Test-Path $env:BHBuildOutput -PathType Container } "Release path must exist" Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue <# $params = @{ Path = "$env:BHBuildOutput/$env:BHProjectName" Include = '*.ps1', '*.psm1' Recurse = $True Exclude = $CodeCoverageExclude } $codeCoverageFiles = Get-ChildItem @params #> try { $parameter = @{ Script = "$env:BHBuildOutput/Tests/*" Tag = $Tag ExcludeTag = $ExcludeTag Show = "Fails" PassThru = $true OutputFile = "$env:BHProjectPath/Test-$OS-$($PSVersionTable.PSVersion.ToString()).xml" OutputFormat = "NUnitXml" # CodeCoverage = $codeCoverageFiles } $testResults = Invoke-Pester @parameter Assert-True ($testResults.FailedCount -eq 0) "$($testResults.FailedCount) Pester test(s) failed." } catch { throw $_ } }, { Init } #endregion #region Publish # Synopsis: Publish a new release on github and the PSGallery task Deploy Init, PublishToGallery, TagReplository, UpdateHomepage # Synpsis: Publish the $release to the PSGallery task PublishToGallery { Assert-True (-not [String]::IsNullOrEmpty($PSGalleryAPIKey)) "No key for the PSGallery" Assert-True { Get-Module $env:BHProjectName -ListAvailable } "Module $env:BHProjectName is not available" Remove-Module $env:BHProjectName -ErrorAction Ignore Publish-Module -Name $env:BHProjectName -NuGetApiKey $PSGalleryAPIKey } # Synopsis: push a tag with the version to the git repository task TagReplository GetNextVersion, Package, { $releaseText = "Release version $env:NextBuildVersion" Set-GitUser # Push a tag to the repository Write-Build Gray "git checkout $ENV:BHBranchName" cmd /c "git checkout $ENV:BHBranchName 2>&1" Write-Build Gray "git tag -a v$env:NextBuildVersion -m `"$releaseText`"" cmd /c "git tag -a v$env:NextBuildVersion -m `"$releaseText`" 2>&1" Write-Build Gray "git push origin v$env:NextBuildVersion" cmd /c "git push origin v$env:NextBuildVersion 2>&1" Write-Build Gray "Publish v$env:NextBuildVersion as a GitHub release" $release = @{ AccessToken = $GithubAccessToken TagName = "v$env:NextBuildVersion" Name = "Version $env:NextBuildVersion" ReleaseText = $releaseText RepositoryOwner = "AtlassianPS" Artifact = "$env:BHBuildOutput\$env:BHProjectName.zip" } Publish-GithubRelease @release } # Synopsis: Update the version of this module that the homepage uses task UpdateHomepage { try { Set-GitUser Write-Build Gray "git close .../AtlassianPS.github.io --recursive" $null = cmd /c "git clone https://github.com/AtlassianPS/AtlassianPS.github.io --recursive 2>&1" Push-Location "AtlassianPS.github.io/" Write-Build Gray "git submodule foreach git pull origin master" $null = cmd /c "git submodule foreach git pull origin master 2>&1" Write-Build Gray "git status -s" $status = cmd /c "git status -s 2>&1" if ($status -contains " M modules/$env:BHProjectName") { Write-Build Gray "git add modules/$env:BHProjectName" $null = cmd /c "git add modules/$env:BHProjectName 2>&1" Write-Build Gray "git commit -m `"Update module $env:BHProjectName`"" cmd /c "git commit -m `"Update module $env:BHProjectName`" 2>&1" Write-Build Gray "git push" cmd /c "git push 2>&1" } Pop-Location } catch { Write-Warning "Failed to deploy to homepage" } } #endregion Publish #region Cleaning tasks # Synopsis: Clean the working dir task Clean Init, RemoveGeneratedFiles, RemoveTestResults # Synopsis: Remove generated and temp files. task RemoveGeneratedFiles { Remove-Item "$env:BHModulePath/en-US/*" -Force -ErrorAction SilentlyContinue Remove-Item $env:BHBuildOutput -Force -Recurse -ErrorAction SilentlyContinue } # Synopsis: Remove Pester results task RemoveTestResults { Remove-Item "Test-*.xml" -Force -ErrorAction SilentlyContinue } #endregion task . ShowInfo, Clean, Build, Test Remove-Item -Path Env:\BH*
AtlassianPS/JiraPS
JiraPS.build.ps1
PowerShell
mit
12,832
/** * Module dependencies. */ var express = require('express'); var path = require('path'); var api = require('./lib/api'); var seo = require('./lib/seo'); var app = module.exports = express(); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('change this value to something unique')); app.use(express.cookieSession()); app.use(express.compress()); app.use(api); app.use(seo); app.use(express.static(path.join(__dirname, '../build'))); app.use(app.router); app.get('/loaderio-995e64d5aae415e1f10d60c9391e37ac/', function(req, res, next) { res.send('loaderio-995e64d5aae415e1f10d60c9391e37ac'); }); if ('development' === app.get('env')) { app.use(express.errorHandler()); } var cacheBuster = function(req, res, next){ res.header("Cache-Control", "no-cache, no-store, must-revalidate"); res.header("Pragma", "no-cache"); res.header("Expires", 0); next(); }; // @todo isolate to api routes... app.use(cacheBuster); // catch all which sends all urls to index page, thus starting our app // @note that because Express routes are registered in order, and we already defined our api routes // this catch all will not effect prior routes. app.use(function(req, res, next) { app.get('*', function(req, res, next) { //return res.ok('catch all'); res.redirect('/#!' + req.url); }); });
brettshollenberger/rootstrikers
server/app.js
JavaScript
mit
1,520
# KnockGame This sketch is responsible for the **Handshake** and **Knock** interfaces. # External Libraries ## SerialCommand https://github.com/kroimon/Arduino-SerialCommand
anyWareSculpture/physical
arduino/old/KnockGame/README.md
Markdown
mit
178
#include <iostream> #include <string> #include <forward_list> using namespace std; void insert(forward_list<string>& fst, const string& to_find, const string& to_add); int main() { forward_list<string> fst{ "pen", "pineapple", "apple", "pen" }; insert(fst, "pen", "and"); for (auto& i : fst) cout << i << " "; cout << endl; return 0; } void insert(forward_list<string>& fst, const string& to_find, const string& to_add) { auto prev = fst.before_begin(); for (auto iter = fst.begin(); iter != fst.end(); prev = iter++) { if (*iter == to_find) { fst.insert_after(iter, to_add); return; } } fst.insert_after(prev, to_add); return; }
sanerror/sanerror-Cpp-Primer-Answers
ch9/ex9_28.cpp
C++
mit
682
/* * MIT License * * Copyright (c) 2017 Alessandro Arcangeli <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mrkoopa.jfbx; public interface FbxCameraStereo extends FbxCamera { }
mrkoopa/jfbx
java/mrkoopa/jfbx/FbxCameraStereo.java
Java
mit
1,258