code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Thu Oct 15 19:26:57 UTC 2015 --> <title>RetryPolicy (AWS SDK for Java - 1.10.27)</title> <meta name="date" content="2015-10-15"> <link rel="stylesheet" type="text/css" href="../../../JavaDoc.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="RetryPolicy (AWS SDK for Java - 1.10.27)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <!-- Scripts for Syntax Highlighter START--> <script id="syntaxhighlight_script_core" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shCore.js"> </script> <script id="syntaxhighlight_script_java" type="text/javascript" src = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/scripts/shBrushJava.js"> </script> <link id="syntaxhighlight_css_core" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shCoreDefault.css"/> <link id="syntaxhighlight_css_theme" rel="stylesheet" type="text/css" href = "http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/resources/syntaxhighlight/styles/shThemeDefault.css"/> <!-- Scripts for Syntax Highlighter END--> <div> <!-- BEGIN-SECTION --> <div id="divsearch" style="float:left;"> <span id="lblsearch" for="searchQuery"> <label>Search</label> </span> <form id="nav-search-form" target="_parent" method="get" action="http://docs.aws.amazon.com/search/doc-search.html#facet_doc_guide=API+Reference&facet_doc_product=AWS+SDK+for+Java"> <div id="nav-searchfield-outer" class="nav-sprite"> <div class="nav-searchfield-inner nav-sprite"> <div id="nav-searchfield-width"> <input id="nav-searchfield" name="searchQuery"> </div> </div> </div> <div id="nav-search-button" class="nav-sprite"> <input alt="" id="nav-search-button-inner" type="image"> </div> <input name="searchPath" type="hidden" value="documentation-guide" /> <input name="this_doc_product" type="hidden" value="AWS SDK for Java" /> <input name="this_doc_guide" type="hidden" value="API Reference" /> <input name="doc_locale" type="hidden" value="en_us" /> </form> </div> <!-- END-SECTION --> <!-- BEGIN-FEEDBACK-SECTION --> <div id="feedback-section"> <h3>Did this page help you?</h3> <div id="feedback-link-sectioin"> <a id="feedback_yes" target="_blank" style="display:inline;">Yes</a>&nbsp;&nbsp; <a id="feedback_no" target="_blank" style="display:inline;">No</a>&nbsp;&nbsp; <a id="go_cti" target="_blank" style="display:inline;">Tell us about it...</a> </div> </div> <script type="text/javascript"> window.onload = function(){ /* Dynamically add feedback links */ var javadoc_root_name = "/javadoc/"; var javadoc_path = location.href.substring(0, location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var file_path = location.href.substring(location.href.lastIndexOf(javadoc_root_name) + javadoc_root_name.length); var feedback_yes_url = javadoc_path + "javadoc-resources/feedbackyes.html?topic_id="; var feedback_no_url = javadoc_path + "javadoc-resources/feedbackno.html?topic_id="; var feedback_tellmore_url = "https://aws-portal.amazon.com/gp/aws/html-forms-controller/documentation/aws_doc_feedback_04?service_name=Java-Ref&file_name="; if(file_path != "overview-frame.html") { var file_name = file_path.replace(/[/.]/g, '_'); document.getElementById("feedback_yes").setAttribute("href", feedback_yes_url + file_name); document.getElementById("feedback_no").setAttribute("href", feedback_no_url + file_name); document.getElementById("go_cti").setAttribute("href", feedback_tellmore_url + file_name); } else { // hide the search box and the feeback links in overview-frame page, // show "AWS SDK for Java" instead. document.getElementById("feedback-section").outerHTML = "AWS SDK for Java"; document.getElementById("divsearch").outerHTML = ""; } }; </script> <!-- END-FEEDBACK-SECTION --> </div> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/amazonaws/retry/PredefinedRetryPolicies.SDKDefaultRetryCondition.html" title="class in com.amazonaws.retry"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/amazonaws/retry/RetryPolicy.html" target="_top">Frames</a></li> <li><a href="RetryPolicy.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.amazonaws.retry</div> <h2 title="Class RetryPolicy" class="title">Class RetryPolicy</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.amazonaws.retry.RetryPolicy</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>@Immutable public final class <span class="strong">RetryPolicy</span> extends java.lang.Object</pre> <div class="block">Retry policy that can be configured on a specific service client using <a href="../../../com/amazonaws/ClientConfiguration.html" title="class in com.amazonaws"><code>ClientConfiguration</code></a>. This class is immutable, therefore safe to be shared by multiple clients.</div> <dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../com/amazonaws/ClientConfiguration.html" title="class in com.amazonaws"><code>ClientConfiguration</code></a>, <a href="../../../com/amazonaws/retry/PredefinedRetryPolicies.html" title="class in com.amazonaws.retry"><code>PredefinedRetryPolicies</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry">RetryPolicy.BackoffStrategy</a></strong></code> <div class="block">The hook for providing custom back-off strategy to control the sleep time between retries.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.RetryCondition.html" title="interface in com.amazonaws.retry">RetryPolicy.RetryCondition</a></strong></code> <div class="block">The hook for providing custom condition on whether a failed request should be retried.</div> </td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.html#RetryPolicy(com.amazonaws.retry.RetryPolicy.RetryCondition,%20com.amazonaws.retry.RetryPolicy.BackoffStrategy,%20int,%20boolean)">RetryPolicy</a></strong>(<a href="../../../com/amazonaws/retry/RetryPolicy.RetryCondition.html" title="interface in com.amazonaws.retry">RetryPolicy.RetryCondition</a>&nbsp;retryCondition, <a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry">RetryPolicy.BackoffStrategy</a>&nbsp;backoffStrategy, int&nbsp;maxErrorRetry, boolean&nbsp;honorMaxErrorRetryInClientConfig)</code> <div class="block">Constructs a new retry policy.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</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> <tr class="altColor"> <td class="colFirst"><code><a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry">RetryPolicy.BackoffStrategy</a></code></td> <td class="colLast"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.html#getBackoffStrategy()">getBackoffStrategy</a></strong>()</code> <div class="block">Returns the back-off strategy included in this retry policy.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.html#getMaxErrorRetry()">getMaxErrorRetry</a></strong>()</code> <div class="block">Returns the maximum number of retry attempts.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../com/amazonaws/retry/RetryPolicy.RetryCondition.html" title="interface in com.amazonaws.retry">RetryPolicy.RetryCondition</a></code></td> <td class="colLast"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.html#getRetryCondition()">getRetryCondition</a></strong>()</code> <div class="block">Returns the retry condition included in this retry policy.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../com/amazonaws/retry/RetryPolicy.html#isMaxErrorRetryInClientConfigHonored()">isMaxErrorRetryInClientConfigHonored</a></strong>()</code> <div class="block">Returns whether this retry policy should honor the max error retry set in ClientConfiguration.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="RetryPolicy(com.amazonaws.retry.RetryPolicy.RetryCondition, com.amazonaws.retry.RetryPolicy.BackoffStrategy, int, boolean)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>RetryPolicy</h4> <pre>public&nbsp;RetryPolicy(<a href="../../../com/amazonaws/retry/RetryPolicy.RetryCondition.html" title="interface in com.amazonaws.retry">RetryPolicy.RetryCondition</a>&nbsp;retryCondition, <a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry">RetryPolicy.BackoffStrategy</a>&nbsp;backoffStrategy, int&nbsp;maxErrorRetry, boolean&nbsp;honorMaxErrorRetryInClientConfig)</pre> <div class="block">Constructs a new retry policy. See <a href="../../../com/amazonaws/retry/PredefinedRetryPolicies.html" title="class in com.amazonaws.retry"><code>PredefinedRetryPolicies</code></a> for some pre-defined policy components, and also the default policies used by SDK.</div> <dl><dt><span class="strong">Parameters:</span></dt><dd><code>retryCondition</code> - Retry condition on whether a specific request and exception should be retried. If null value is specified, the SDK' default retry condition is used.</dd><dd><code>backoffStrategy</code> - Back-off strategy for controlling how long the next retry should wait. If null value is specified, the SDK' default exponential back-off strategy is used.</dd><dd><code>maxErrorRetry</code> - Maximum number of retry attempts for failed requests.</dd><dd><code>honorMaxErrorRetryInClientConfig</code> - Whether this retry policy should honor the max error retry set by <a href="../../../com/amazonaws/ClientConfiguration.html#setMaxErrorRetry(int)"><code>ClientConfiguration.setMaxErrorRetry(int)</code></a></dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../com/amazonaws/ClientConfiguration.html" title="class in com.amazonaws"><code>ClientConfiguration</code></a>, <a href="../../../com/amazonaws/retry/PredefinedRetryPolicies.html" title="class in com.amazonaws.retry"><code>PredefinedRetryPolicies</code></a></dd></dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getRetryCondition()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getRetryCondition</h4> <pre>public&nbsp;<a href="../../../com/amazonaws/retry/RetryPolicy.RetryCondition.html" title="interface in com.amazonaws.retry">RetryPolicy.RetryCondition</a>&nbsp;getRetryCondition()</pre> <div class="block">Returns the retry condition included in this retry policy.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The retry condition included in this retry policy.</dd></dl> </li> </ul> <a name="getBackoffStrategy()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getBackoffStrategy</h4> <pre>public&nbsp;<a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry">RetryPolicy.BackoffStrategy</a>&nbsp;getBackoffStrategy()</pre> <div class="block">Returns the back-off strategy included in this retry policy.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The back-off strategy included in this retry policy.</dd></dl> </li> </ul> <a name="getMaxErrorRetry()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getMaxErrorRetry</h4> <pre>public&nbsp;int&nbsp;getMaxErrorRetry()</pre> <div class="block">Returns the maximum number of retry attempts.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>The maximum number of retry attempts.</dd></dl> </li> </ul> <a name="isMaxErrorRetryInClientConfigHonored()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>isMaxErrorRetryInClientConfigHonored</h4> <pre>public&nbsp;boolean&nbsp;isMaxErrorRetryInClientConfigHonored()</pre> <div class="block">Returns whether this retry policy should honor the max error retry set in ClientConfiguration.</div> <dl><dt><span class="strong">Returns:</span></dt><dd>Whether this retry policy should honor the max error retry set in ClientConfiguration</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../com/amazonaws/ClientConfiguration.html#setMaxErrorRetry(int)"><code>ClientConfiguration.setMaxErrorRetry(int)</code></a></dd></dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> <div> <!-- Script for Syntax Highlighter START --> <script type="text/javascript"> SyntaxHighlighter.all() </script> <!-- Script for Syntax Highlighter END --> </div> <script src="http://a0.awsstatic.com/chrome/js/1.0.46/jquery.1.9.js" type="text/javascript"></script> <script>jQuery.noConflict();</script> <script> jQuery(function ($) { $("div.header").prepend('<!--REGION_DISCLAIMER_DO_NOT_REMOVE-->'); }); </script> <!-- BEGIN-URCHIN-TRACKER --> <script src="http://l0.awsstatic.com/js/urchin.js" type="text/javascript"></script> <script type="text/javascript">urchinTracker();</script> <!-- END-URCHIN-TRACKER --> <!-- SiteCatalyst code version: H.25.2. Copyright 1996-2012 Adobe, Inc. All Rights Reserved. More info available at http://www.omniture.com --> <script language="JavaScript" type="text/javascript" src="https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js (view-source:https://media.amazonwebservices.com/js/sitecatalyst/s_code.min.js)" /> <script language="JavaScript" type="text/javascript"> <!-- // Documentation Service Name s.prop66='AWS SDK for Java'; s.eVar66='D=c66'; // Documentation Guide Name s.prop65='API Reference'; s.eVar65='D=c65'; var s_code=s.t();if(s_code)document.write(s_code) //--> </script> <script language="JavaScript" type="text/javascript"> <!--if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-') //--> </script> <noscript> <img src="http://amazonwebservices.d2.sc.omtrdc.net/b/ss/awsamazondev/1/H.25.2--NS/0" height="1" width="1" border="0" alt="" /> </noscript> <!--/DO NOT REMOVE/--> <!-- End SiteCatalyst code version: H.25.2. --> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/amazonaws/retry/PredefinedRetryPolicies.SDKDefaultRetryCondition.html" title="class in com.amazonaws.retry"><span class="strong">Prev Class</span></a></li> <li><a href="../../../com/amazonaws/retry/RetryPolicy.BackoffStrategy.html" title="interface in com.amazonaws.retry"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/amazonaws/retry/RetryPolicy.html" target="_top">Frames</a></li> <li><a href="RetryPolicy.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_class_summary">Nested</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> Copyright &#169; 2013 Amazon Web Services, Inc. All Rights Reserved. </small></p> </body> </html>
TomNong/Project2-Intel-Edison
documentation/javadoc/com/amazonaws/retry/RetryPolicy.html
HTML
apache-2.0
22,870
package ca.sfu.client; import java.awt.Container; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SpringLayout; import ca.sfu.network.NetworkHelper; public class MainFrame extends JFrame { private static final long serialVersionUID = 1L; /* Client object */ private Client client = new Client(); Thread clientThread; private static final String SERVER_IP = "142.58.35.135"; private static final String CLIENT_IP = "142.58.35."; /* New UI widgets */ JLabel clientIpLabel = new JLabel("Client IP"); JTextField clientIp = new JTextField(15); JLabel serverIpLabel = new JLabel("Server IP"); JTextField serverIp = new JTextField(15); JButton connectBtn = new JButton("Connect"); boolean connected; public MainFrame() { Container contentPane = getContentPane(); String clientIpAddr = NetworkHelper.getHostStaticIp(); serverIp.setText(SERVER_IP); if(clientIp != null) clientIp.setText(clientIpAddr); else clientIp.setText(CLIENT_IP); SpringLayout layout = new SpringLayout(); contentPane.setLayout(layout); /* Add to content pane */ contentPane.add(clientIpLabel); contentPane.add(clientIp); contentPane.add(serverIpLabel); contentPane.add(serverIp); contentPane.add(connectBtn); connectBtn.setFocusable(false); /* Regular expression */ // String ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\."; // String ValidHostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$"; // final String IPADDRESS_PATTERN = ValidIpAddressRegex + ValidHostnameRegex; /* Put UI constrains */ layout.putConstraint(SpringLayout.WEST, clientIpLabel, 15, SpringLayout.WEST, contentPane); layout.putConstraint(SpringLayout.NORTH, clientIpLabel, 30, SpringLayout.NORTH, contentPane); layout.putConstraint(SpringLayout.NORTH, clientIp, 30, SpringLayout.NORTH, contentPane); layout.putConstraint(SpringLayout.WEST, clientIp, 80, SpringLayout.WEST, clientIpLabel); layout.putConstraint(SpringLayout.WEST, serverIpLabel, 15, SpringLayout.WEST, contentPane); layout.putConstraint(SpringLayout.NORTH, serverIpLabel, 30, SpringLayout.NORTH, clientIpLabel); layout.putConstraint(SpringLayout.NORTH, serverIp, 30, SpringLayout.NORTH, clientIp); layout.putConstraint(SpringLayout.WEST, serverIp, 80, SpringLayout.WEST, serverIpLabel); layout.putConstraint(SpringLayout.NORTH, connectBtn, 40, SpringLayout.NORTH, serverIpLabel); layout.putConstraint(SpringLayout.HORIZONTAL_CENTER, connectBtn, 0, SpringLayout.HORIZONTAL_CENTER, contentPane); /* Set listener */ connectBtn.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { if(!connected) { System.out.println("Connecting..."); clientThread = new Thread() { public void run() { try { client.startClient(serverIp.getText(), clientIp.getText()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; clientThread.start(); connectBtn.setText("Disconnect"); } else { client.quit(); /* Add disconnect function here */ } connected = !connected; } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); this.addWindowListener(new WindowListener() { @Override public void windowActivated(WindowEvent arg0) { } @Override public void windowClosed(WindowEvent arg0) { } @Override public void windowClosing(WindowEvent arg0) { client.quit(); } @Override public void windowDeactivated(WindowEvent arg0) { } @Override public void windowDeiconified(WindowEvent arg0) { } @Override public void windowIconified(WindowEvent arg0) { } @Override public void windowOpened(WindowEvent arg0) { } }); connected = false; setSize(300, 180); setTitle("Client"); } public static void main(String[] argv) { MainFrame frame = new MainFrame(); frame.setVisible(true); } }
yukezhu/LifeGameSim
GameOfLifeClient/src/ca/sfu/client/MainFrame.java
Java
apache-2.0
4,665
#!/bin/bash BASEDIR=`dirname $0` JAR="${BASEDIR}/../target/disassembler.jar" java -jar ${JAR} $1 $1.javr.asm java -jar ${JAR} --avr-as $1 $1.avr-as.asm
toby1984/javr
scripts/disassemble.sh
Shell
apache-2.0
154
package example import common._ object Lists { /** * This method computes the sum of all elements in the list xs. There are * multiple techniques that can be used for implementing this method, and * you will learn during the class. * * For this example assignment you can use the following methods in class * `List`: * * - `xs.isEmpty: Boolean` returns `true` if the list `xs` is empty * - `xs.head: Int` returns the head element of the list `xs`. If the list * is empty an exception is thrown * - `xs.tail: List[Int]` returns the tail of the list `xs`, i.e. the the * list `xs` without its `head` element * * ''Hint:'' instead of writing a `for` or `while` loop, think of a recursive * solution. * * @param xs A list of natural numbers * @return The sum of all elements in `xs` */ def sum(xs: List[Int]): Int = { if (xs.isEmpty) 0 else xs.head + sum(xs.tail) } /** * This method returns the largest element in a list of integers. If the * list `xs` is empty it throws a `java.util.NoSuchElementException`. * * You can use the same methods of the class `List` as mentioned above. * * ''Hint:'' Again, think of a recursive solution instead of using looping * constructs. You might need to define an auxiliary method. * * @param xs A list of natural numbers * @return The largest element in `xs` * @throws java.util.NoSuchElementException if `xs` is an empty list */ def max(xs: List[Int]): Int = { if (xs.isEmpty) throw new NoSuchElementException if (xs.size == 1) { xs.head } else { val head = xs.head val maxVal = max(xs.tail) if (head > maxVal) head else maxVal } } }
spolnik/scala-workspace
scala-learning/example/src/main/scala/example/Lists.scala
Scala
apache-2.0
1,773
package actors.messages /** * Created by becker on 2/4/15. */ case object StartMessage case object StopMessage
dockarium-io/dockarium-io
server/app/actors/messages/Messages.scala
Scala
apache-2.0
113
# Gymnopilus carbonarius (Fr.) Murrill, 1912 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Mycologia 4(5): 256 (1912) #### Original name Agaricus carbonarius Batsch, 1783 ### Remarks null
mdoering/backbone
life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Strophariaceae/Pholiota/Pholiota highlandensis/ Syn. Gymnopilus carbonarius/README.md
Markdown
apache-2.0
250
<?php // @link http://schemas.wbeme.com/json-schema/eme/users/event/user-deleted/latest.json# namespace Eme\Schemas\Users\Event; use Gdbots\Pbj\Message; interface UserDeleted extends Message { }
wb-eme/schemas
build/php/src/Eme/Schemas/Users/Event/UserDeleted.php
PHP
apache-2.0
197
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ /** * Entity objects describing simple payment financial instruments. */ package com.opengamma.strata.product.payment;
ChinaQuants/Strata
modules/product/src/main/java/com/opengamma/strata/product/payment/package-info.java
Java
apache-2.0
261
/** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.matthewmitchell.nubitsj.core; import static com.google.common.base.Preconditions.checkArgument; /** * <p>Represents the "inv" P2P network message. An inv contains a list of hashes of either blocks or transactions. It's * a bandwidth optimization - on receiving some data, a (fully validating) peer sends every connected peer an inv * containing the hash of what it saw. It'll only transmit the full thing if a peer asks for it with a * {@link GetDataMessage}.</p> */ public class InventoryMessage extends ListMessage { private static final long serialVersionUID = -7050246551646107066L; /** A hard coded constant in the protocol. */ public static final int MAX_INV_SIZE = 50000; public InventoryMessage(NetworkParameters params, byte[] bytes) throws ProtocolException { super(params, bytes); } /** * Deserializes an 'inv' message. * @param params NetworkParameters object. * @param payload Nubits protocol formatted byte array containing message content. * @param parseLazy Whether to perform a full parse immediately or delay until a read is requested. * @param parseRetain Whether to retain the backing byte array for quick reserialization. * If true and the backing byte array is invalidated due to modification of a field then * the cached bytes may be repopulated and retained if the message is serialized again in the future. * @param length The length of message if known. Usually this is provided when deserializing of the wire * as the length will be provided as part of the header. If unknown then set to Message.UNKNOWN_LENGTH * @throws ProtocolException */ public InventoryMessage(NetworkParameters params, byte[] payload, boolean parseLazy, boolean parseRetain, int length) throws ProtocolException { super(params, payload, parseLazy, parseRetain, length); } public InventoryMessage(NetworkParameters params) { super(params); } public void addBlock(Block block) { addItem(new InventoryItem(InventoryItem.Type.Block, block.getHash())); } public void addTransaction(Transaction tx) { addItem(new InventoryItem(InventoryItem.Type.Transaction, tx.getHash())); } /** Creates a new inv message for the given transactions. */ public static InventoryMessage with(Transaction... txns) { checkArgument(txns.length > 0); InventoryMessage result = new InventoryMessage(txns[0].getParams()); for (Transaction tx : txns) result.addTransaction(tx); return result; } }
Cybnate/NuBitsj
core/src/main/java/com/matthewmitchell/nubitsj/core/InventoryMessage.java
Java
apache-2.0
3,212
package io.github.giovibal.mqtt; import io.vertx.core.Vertx; import io.vertx.core.shareddata.LocalMap; import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; /** * Created by giovanni on 10/05/2014. * Manages subscritpions and MQTT topic rules */ public class MQTTTopicsManager implements ITopicsManager { public MQTTTopicsManager() {} // 286 millis public boolean match(String topic, String topicFilter) { if(topicFilter.equals(topic)) { return true; } else { if (topicFilter.contains("+") && !topicFilter.endsWith("#")) { int topicSlashCount = countSlash(topic); int tsubSlashCount = countSlash(topicFilter); if (topicSlashCount == tsubSlashCount) { String pattern = toPattern(topicFilter); if (topic.matches(pattern)) { return true; } } } else if (topicFilter.contains("+") || topicFilter.endsWith("#")) { int topicSlashCount = countSlash(topic); int tsubSlashCount = countSlash(topicFilter); if (topicSlashCount >= tsubSlashCount) { String pattern = toPattern(topicFilter); if (topic.matches(pattern)) { return true; } } } } return false; } // 2 sec private String toPattern(String subscribedTopic) { String pattern = subscribedTopic; pattern = pattern.replaceAll("#", ".*"); pattern = pattern.replaceAll("\\+", "[^/]*"); return pattern; } // 446 millis private int countSlash(String s) { int count = s.replaceAll("[^/]", "").length(); return count; } }
GruppoFilippetti/vertx-mqtt-broker
src/main/java/io/github/giovibal/mqtt/MQTTTopicsManager.java
Java
apache-2.0
1,872
package net.kernal.spiderman.worker.result; import net.kernal.spiderman.worker.Task; import net.kernal.spiderman.worker.extract.ExtractResult; import net.kernal.spiderman.worker.extract.ExtractTask; /** * 结果任务 * <Short overview of features> * <Features detail> * * @author qwop * @date May 21, 2017 * @version [The version number, May 21, 2017] * @see [Related classes/methods] * @since [Products/Module version] */ public class ResultTask extends Task { private static final long serialVersionUID = -7531379852428467887L; private ExtractResult result; public ResultTask(ExtractTask task, ExtractResult result) { super(task.getSeed(), task.getSource(), task.getGroup(), task.getRequest()); this.result = result; } public ExtractResult getResult() { return result; } public String getKey() { final String keyValue = result.getFields().getString(result.getKeyFieldName()); return "result_"+result.getPageName()+"#"+result.getModelName()+"#"+keyValue+"#"+getSeed().getUrl()+"#"+getRequest().getUrl(); } }
qwop/spiderman2
src/main/java/net/kernal/spiderman/worker/result/ResultTask.java
Java
apache-2.0
1,062
#region Copyright & License // Copyright © 2012 - 2017 François Chabot, Yves Dierick // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Diagnostics.CodeAnalysis; using System.ServiceModel; using Microsoft.BizTalk.Adapter.Wcf.Config; namespace Be.Stateless.BizTalk.Dsl.Binding.Adapter { public abstract partial class WcfNetTcpAdapter { #region Nested Type: Inbound /// <summary> /// The WCF-NetTcp adapter provides connected cross-computer or cross-process communication in an environment in /// which both services and clients are WCF based. It provides full access to SOAP security, reliability, and /// transaction features. This adapter uses the TCP transport, and messages have binary encoding. /// </summary> /// <remarks> /// You use the WCF-NetTcp receive adapter to receive WCF service requests through the TCP protocol. A receive /// location that uses the WCF-NetTcp receive adapter can be configured as one-way or request-response (two-way). /// </remarks> /// <seealso href="https://msdn.microsoft.com/en-us/library/bb226419.aspx">What Is the WCF-NetTcp Adapter?</seealso> /// <seealso href="https://msdn.microsoft.com/en-us/library/bb226412.aspx">How to Configure a WCF-NetTcp Receive Location</seealso>. /// <seealso href="https://msdn.microsoft.com/en-us/library/bb246097.aspx">WCF-NetTcp Transport Properties Dialog Box, Receive, Security Tab</seealso> /// <seealso href="https://msdn.microsoft.com/en-us/library/bb245991.aspx">WCF Adapters Property Schema and Properties</seealso>. [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Public API")] public class Inbound : WcfNetTcpAdapter<NetTcpRLConfig>, IInboundAdapter, IAdapterConfigInboundIncludeExceptionDetailInFaults, IAdapterConfigInboundSuspendRequestMessageOnFailure, IAdapterConfigMaxConcurrentCalls, IAdapterConfigServiceCertificate, IAdapterConfigSSO { public Inbound() { // Binding Tab - Connection Pool Settings LeaseTimeout = TimeSpan.FromMinutes(5); // Binding Tab - Service Throttling Behavior Settings MaxConcurrentCalls = 200; // Messages Tab - Error Handling Settings SuspendRequestMessageOnFailure = true; IncludeExceptionDetailInFaults = true; } public Inbound(Action<Inbound> adapterConfigurator) : this() { adapterConfigurator(this); } #region IAdapterConfigInboundIncludeExceptionDetailInFaults Members public bool IncludeExceptionDetailInFaults { get { return _adapterConfig.IncludeExceptionDetailInFaults; } set { _adapterConfig.IncludeExceptionDetailInFaults = value; } } #endregion #region IAdapterConfigInboundSuspendRequestMessageOnFailure Members public bool SuspendRequestMessageOnFailure { get { return _adapterConfig.SuspendMessageOnFailure; } set { _adapterConfig.SuspendMessageOnFailure = value; } } #endregion #region IAdapterConfigMaxConcurrentCalls Members public int MaxConcurrentCalls { get { return _adapterConfig.MaxConcurrentCalls; } set { _adapterConfig.MaxConcurrentCalls = value; } } #endregion #region IAdapterConfigServiceCertificate Members /// <summary> /// Specify the thumbprint of the X.509 certificate for this receive location that the clients use to /// authenticate the service. The certificate to be used for this property must be installed into the My store /// in the Current User location. /// </summary> /// <remarks> /// <para> /// You must install the service certificate into the Current User location of the user account for the receive /// handler hosting this receive location. /// </para> /// <para> /// It defaults to an <see cref="string.Empty"/> string. /// </para> /// </remarks> public string ServiceCertificate { get { return _adapterConfig.ServiceCertificate; } set { _adapterConfig.ServiceCertificate = value; } } #endregion #region IAdapterConfigSSO Members /// <summary> /// Specify whether to use Enterprise Single Sign-On (SSO) to retrieve client credentials to issue an SSO /// ticket. /// </summary> /// <remarks> /// For more information about the security configurations supporting SSO, see the section, "Enterprise Single /// Sign-On Supportability for the WCF-NetTcp Receive Adapter" in <see /// href="https://msdn.microsoft.com/en-us/library/bb246097.aspx">WCF-NetTcp Transport Properties Dialog Box, /// Receive, Security Tab</see>. Box, Receive, Security Tab. /// </remarks> public bool UseSSO { get { return _adapterConfig.UseSSO; } set { _adapterConfig.UseSSO = value; } } #endregion #region Binding Tab - Connection Pool Settings /// <summary> /// Specify the maximum lifetime of an active pooled connection. After the specified time elapses, the /// connection closes after the current request is serviced. /// </summary> /// <remarks> /// <para> /// The WCF-NetTcp adapter leverages the <see cref="NetTcpBinding"/> class to communicate with an endpoint. /// When using the <see cref="NetTcpBinding"/> in load-balanced scenarios, consider reducing the default lease /// timeout. /// </para> /// <para> /// It defaults to 00:05:00. /// </para> /// </remarks> public TimeSpan LeaseTimeout { get { return _adapterConfig.LeaseTimeout; } set { _adapterConfig.LeaseTimeout = value; } } #endregion } #endregion } }
icraftsoftware/BizTalk.Factory
src/BizTalk.Dsl/Dsl/Binding/Adapter/WcfNetTcpAdapter.Inbound.cs
C#
apache-2.0
6,212
#pragma once #include <exception> #include <string> #if defined DLL_EXPORT #define SILENCE_EXPORT __declspec(dllexport) #else #define SILENCE_EXPORT __declspec(dllimport) #endif #pragma warning(disable: 4290) #pragma warning(disable: 4275) #pragma warning(disable: 4251) enum class Component { Label, Texture, Network, Game, Window, Renderer, Audio, FileIO, System }; enum class Author { William }; class SILENCE_EXPORT Error : public std::exception { std::string errorMessage; Component system; Author owner; public: Error(Component sys, std::string msg, Author user = Author::William); virtual ~Error() throw(); const char * title() const; const char * what() const override; };
william-taylor/silence-enter-the-forest
Silence.Core/Exception.h
C
apache-2.0
730
package com.pi4j.io.gpio.event; /* * #%L * ********************************************************************** * ORGANIZATION : Pi4J * PROJECT : Pi4J :: Java Library (Core) * FILENAME : PinAnalogValueChangeEvent.java * * This file is part of the Pi4J project. More information about * this project can be found here: http://www.pi4j.com/ * ********************************************************************** * %% * Copyright (C) 2012 - 2013 Pi4J * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.pi4j.io.gpio.Pin; /** * GPIO analog pin value change event. * * @author Robert Savage (<a * href="http://www.savagehomeautomation.com">http://www.savagehomeautomation.com</a>) */ public class PinAnalogValueChangeEvent extends PinEvent { private static final long serialVersionUID = -6210539419288104794L; private final double value; /** * Default event constructor * * @param obj Ignore this parameter * @param pin GPIO pin number (not header pin number; not wiringPi pin number) * @param value New GPIO pin analog value. */ public PinAnalogValueChangeEvent(Object obj, Pin pin, double value) { super(obj, pin, PinEventType.ANALOG_VALUE_CHANGE); this.value = value; } /** * Get the new pin value raised in this event. * * @return GPIO pin value */ public double getValue() { return value; } }
starksm64/pi4j
pi4j-core/src/main/java/com/pi4j/io/gpio/event/PinAnalogValueChangeEvent.java
Java
apache-2.0
1,991
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), 'Library\\' => array($baseDir . '/lib'), 'JmesPath\\' => array($vendorDir . '/mtdowling/jmespath.php/src'), 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), 'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'), 'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'), 'Config\\' => array($baseDir . '/config'), 'Aws\\' => array($vendorDir . '/aws/aws-sdk-php/src'), );
xfsnow/serverless
face/functions/list/vendor/composer/autoload_psr4.php
PHP
apache-2.0
659
/** * ContactServiceSoap.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.evolveum.polygon.connector.liferay.contact; public interface ContactServiceSoap extends java.rmi.Remote { public com.evolveum.polygon.connector.liferay.contact.ContactSoap getContact(long contactId) throws java.rmi.RemoteException; public int getContactsCount(long classNameId, long classPK) throws java.rmi.RemoteException; public com.evolveum.polygon.connector.liferay.contact.ContactSoap[] getContacts(long classNameId, long classPK, int start, int end, com.evolveum.polygon.connector.liferay.contact.OrderByComparator orderByComparator) throws java.rmi.RemoteException; }
Evolveum/connector-liferay
src/main/java/com/evolveum/polygon/connector/liferay/contact/ContactServiceSoap.java
Java
apache-2.0
769
package com.google.sampling.experiential.cloudsql.columns; import com.pacoapp.paco.shared.model2.EventBaseColumns; public class EventServerColumns extends EventBaseColumns { public static final String WHO = "who"; //since when is a keyword, we have to always use a back tick when we use it in any sql query. public static final String WHEN = "`when`"; public static final String WHEN_FRAC_SEC = "when_fractional_sec"; public static final String ARCHIVE_FLAG = "archive_flag"; public static final String JOINED = "joined"; public static final String SORT_DATE = "sort_date"; public static final String CLIENT_TIME_ZONE = "client_timezone"; public static final String PACO_VERSION = "paco_version"; public static final String APP_ID = "app_id"; public static final String SORT_DATE_UTC = "sort_date_utc"; public static final String RESPONSE_TIME_UTC = "response_time_utc"; public static final String SCHEDULE_TIME_UTC = "schedule_time_utc"; public static final String EXPERIMENT_VERSION_GROUP_MAPPING_ID = "experiment_version_group_mapping_id"; }
google/paco
Paco-Server/src/com/google/sampling/experiential/cloudsql/columns/EventServerColumns.java
Java
apache-2.0
1,078
//Bind pages to tabs var pages = document.getElementById('pages'); var tabs = document.getElementById('tabs'); var aboutpages = document.getElementById('aboutpages'); var gamepages = document.getElementById('gamepages'); var gamehome = document.getElementById('gamehome'); if (tabs.addEventListener){ tabs.addEventListener('core-select', function() { // home page selected if(tabs.selected == 0){ pages.selected = 0; pages.style.display = ""; gamepages.style.display = "none"; aboutpages.style.display = "none"; } // game page selected else if (tabs.selected == 1){ pages.style.display = "none"; gamepages.selected = 0; gamepages.style.display = ""; gamehome.style.display = ""; aboutpages.style.display = "none"; } // about page selected else if (tabs.selected == 2){ pages.style.display = "none"; gamepages.style.display = "none"; aboutpages.selected = 0; aboutpages.style.display = ""; } }); } else if (tabs.attachEvent){ tabs.attachEvent('core-select', function() { // home page selected if(tabs.selected == 0){ pages.selected = 0; pages.style.display = ""; gamepages.style.display = "none"; aboutpages.style.display = "none"; } // game page selected else if (tabs.selected == 1){ pages.style.display = "none"; gamepages.selected = 0; gamepages.style.display = ""; gamehome.style.display = ""; aboutpages.style.display = "none"; } // about page selected else if (tabs.selected == 2){ pages.style.display = "none"; gamepages.style.display = "none"; aboutpages.selected = 0; aboutpages.style.display = ""; } }); }
kevxiao/cow-egg-game
scripts/binding.js
JavaScript
apache-2.0
1,693
package org.gradle.test.performance.mediummonolithicjavaproject.p260; public class Production5218 { private Production5215 property0; public Production5215 getProperty0() { return property0; } public void setProperty0(Production5215 value) { property0 = value; } private Production5216 property1; public Production5216 getProperty1() { return property1; } public void setProperty1(Production5216 value) { property1 = value; } private Production5217 property2; public Production5217 getProperty2() { return property2; } public void setProperty2(Production5217 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p260/Production5218.java
Java
apache-2.0
1,963
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2021 Senparc 文件名:StoreBaseInfo.cs 文件功能描述:门店基础信息 创建标识:Senparc - 20150513 ----------------------------------------------------------------*/ using System.Collections.Generic; namespace Senparc.Weixin.MP.AdvancedAPIs.Poi { /// <summary> /// 可以被修改的门店基础信息 /// </summary> public class StoreBaseInfoCanBeUpdate { /// <summary> /// 门店的电话 /// 必填 /// </summary> public string telephone { get; set; } /// <summary> /// 图片列表,url 形式,可以有多张图片,尺寸为640*340px。必须为上一接口生成的url /// 必填 /// </summary> public List<Store_Photo> photo_list { get; set; } /// <summary> /// 推荐品,餐厅可为推荐菜;酒店为推荐套房;景点为推荐游玩景点等,针对自己行业的推荐内容 /// 非必填 /// </summary> public string recommend { get; set; } /// <summary> /// 特色服务,如免费wifi,免费停车,送货上门等商户能提供的特色功能或服务 /// 必填 /// </summary> public string special { get; set; } /// <summary> /// 商户简介,主要介绍商户信息等 /// 非必填 /// </summary> public string introduction { get; set; } /// <summary> /// 营业时间,24 小时制表示,用“-”连接,如8:00-20:00 /// 必填 /// </summary> public string open_time { get; set; } /// <summary> /// 人均价格,大于0 的整 /// 非必填 /// </summary> public int avg_price { get; set; } } /// <summary> /// 门店基础信息 /// </summary> public class StoreBaseInfo : StoreBaseInfoCanBeUpdate { /// <summary> /// 商户自己的id,用于后续审核通过收到poi_id 的通知时,做对应关系。请商户自己保证唯一识别性 /// 非必填 /// </summary> public string sid { get; set; } /// <summary> /// 门店名称 /// 必填 /// </summary> public string business_name { get; set; } /// <summary> /// 分店名称 /// 非必填 /// </summary> public string branch_name { get; set; } /// <summary> /// 门店所在的省 /// 必填 /// </summary> public string province { get; set; } /// <summary> /// 门店所在的市 /// 必填 /// </summary> public string city { get; set; } /// <summary> /// 门店所在的区 /// 非必填 /// </summary> public string district { get; set; } /// <summary> /// 门店所在的详细街道地址 /// 必填 /// </summary> public string address { get; set; } /// <summary> /// 门店的类型(酒店、餐饮、购物...) /// 必填 /// </summary> public string[] categories { get; set; } /// <summary> /// 坐标类型,1 为火星坐标(目前只能选1) /// </summary> public int offset_type { get; set; } /// <summary> /// 门店所在地理位置的经度(建议使用腾讯地图定位经纬度) /// 必填 /// </summary> public string longitude { get; set; } /// <summary> /// 门店所在地理位置的纬度 /// 必填 /// </summary> public string latitude { get; set; } } public class Store_Photo { /// <summary> /// 图片Url /// </summary> public string photo_url { get; set; } } }
mc7246/WeiXinMPSDK
src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/Poi/StoreJson/StoreBaseInfo.cs
C#
apache-2.0
4,835
--- layout: post title: "一个小型的Web多线程服务器开发笔记" subtitle: "" description: "web server Linux http tcp" date: 2017-05-24 01:00:00 author: "Scalpel" header-img: "img/home-bg-o.jpg" tags: - Linux - 网络编程 ---   首先说一下服务器支持的功能:支持POST和GET方法,目录浏览,可以提供静态与动态两种服务,采用了预线程化的并发技术,[项目主页](https://github.com/scalpelx/Web_Server)。   服务器采用生产者-消费者模型,主线程不断地接受来自客户端的连接请求,并将连接描述符放到一个缓冲区中,每一个线程池中的线程反复地从这个缓冲区中取出可用的描述符,为客户端服务,具体代码如下: ```c sbuf_t sbuf; //缓冲区 int main(int argc, char* argv[]) { //判断参数 if (argc != 2) { perror("usage: webserver <port>"); exit(1); } //分配套接字 int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd == -1) { perror("Can't allocate sockfd"); exit(1); } //设置服务器套接字地址 struct sockaddr_in clientaddr, serveraddr; memset(&serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(atoi(argv[1])); //绑定并监听 if (bind(sockfd, (const struct sockaddr *) &serveraddr, sizeof(serveraddr)) == -1) { perror("Bind Error"); exit(1); } if (listen(sockfd, 4096) == -1) { perror("Listen Error"); exit(1); } sbuf_init(&sbuf, SBUFSIZE); //初始化缓冲区 pthread_t tid; //创建线程 for (int i = 0; i < NTHREADS; ++i) if (pthread_create(&tid, NULL, thread, NULL) != 0) { perror("Create pthread error"); exit(1); } while (true) { socklen_t clientlen = sizeof(clientaddr); //建立连接 int connfd = accept(sockfd, (struct sockaddr *) &clientaddr, &clientlen); if (connfd == -1) { perror("Connect Error"); exit(1); } char addr[INET_ADDRSTRLEN]; printf("Accepted connection from (%s:%s)\n", inet_ntop(AF_INET, &clientaddr.sin_addr, addr, INET_ADDRSTRLEN), argv[1]); sbuf_insert(&sbuf, connfd); //将当前已连接套接字添加到缓存中 } sbuf_destroy(&sbuf); } void* thread(void *vargp) { if (thread_detach(pthread_self()) != 0) //分离当前线程 { perror("Detach pthread error"); exit(1); } while (true) { int connfd = sbuf_remove(&sbuf); //从缓存中取可连接的套接字 //处理连接请求 work(connfd); close(connfd); } return NULL; } ```   sbuf_t的结构如下: ```c typedef struct { int *buf; //缓冲区 int cnt; //缓冲区可以保存的项目大小 int begin; //首项目 int end; //尾项目 sem_t mutex; //缓冲区互斥量 sem_t slots; //有多少空余位置 sem_t items; //缓冲区已保存多少项目 } sbuf_t; ```   sbuf_init初始化缓冲区,sbuf_destroy销毁缓冲区sbuf_insert向缓冲区添加一个项目,具体过程为:等待一个空位置可以,加锁,添加,解锁,sbuf_remove是从缓存区移除一个项目,具体代码如下: ```c void P(sem_t *sem) //封装的PV操作 { if (sem_wait(sem) == -1) perror("P error"); } void V(sem_t *sem) { if (sem_post(sem) == -1) perror("V error"); } void sbuf_init(sbuf_t *sp, int cnt) { sp->buf = calloc(cnt, sizeof(int)); if (sp->buf == NULL) { perror("Calloc error"); exit(1); } sp->cnt = cnt; sp->begin = sp->end = 0; if (sem_init(&sp->mutex, 0, 1) == -1) { perror("Sem_init error"); exit(1); } if (sem_init(&sp->slots, 0, cnt) == -1) { perror("Sem_init error"); exit(1); } if (sem_init(&sp->items, 0, 0) == -1) { perror("Sem_init error"); exit(1); } } void sbuf_destory(sbuf_t *sp) { free(sp->buf); } void sbuf_insert(sbuf_t *sp, int item) { P(&sp->slots); P(&sp->mutex); sp->buf[(++sp->end) % (sp->cnt)] = item; V(&sp->mutex); V(&sp->items); } int sbuf_remove(sbuf_t *sp) { int item; P(&sp->items); P(&sp->mutex); item = sp->buf[(++sp->begin) % (sp->cnt)]; V(&sp->mutex); V(&sp->slots); return item; } ```   work函数处理一个HTTP事务,首先读取并且处理请求行,判断它的请求方法是GET还是POST,根据请求方法来处理请求报头,然后将URI解析为文件名和参数串,根据解析结果判断请求是静态还是动态内容并提供,如果是目录则显示目录内容,具体代码如下: ```c void work(int fd) { char buf[MAXLINE] = {0}; rio_t rio; rio_readinitb(&rio, fd); //读取并解析请求行 if (rio_readlineb(&rio, buf, MAXLINE) == -1) { perror("Read error"); exit(1); } puts("Request headers:"); puts(buf); char method[MAXLINE], uri[MAXLINE], version[MAXLINE]; sscanf(buf, "%s %s %s", method, uri, version); //判断请求方式 bool isGET = !strcasecmp(method, "GET"), isPOST = !strcasecmp(method, "POST"); if (!isGET && !isPOST) { print_error(fd, method, "501", "Not implemented", "The server does not implement this method"); return; } //读取请求报头 char content[MAXLINE] = {0}; if (isGET) read_get_requesthdrs(&rio); else read_post_requesthdrs(&rio, content); //将URI解析为文件名和参数串并判断提供何种内容 char filename[MAXLINE] = {0}, cgiargs[MAXLINE] = {0}; bool is_static = analyse_uri(uri, filename, cgiargs); struct stat sbuf; if (stat(filename, &sbuf) < 0) { print_error(fd, filename, "404", "Not found", "The server could not find this file"); return; } if(S_ISDIR(sbuf.st_mode)) serve_dir(fd, filename); //显示目录内容 else if (is_static) { if (isPOST) { print_error(fd, filename, "405", "Method Not Allowed", "Request method POST is not allowed for the URL"); return; } if (!(S_ISREG(sbuf.st_mode)) && !(S_IRUSR & sbuf.st_mode)) { print_error(fd, filename, "403", "Forbidden", "The server could not read this file"); return; } static_serve(fd, filename, sbuf.st_size); } else //动态内容 { if (!(S_ISREG(sbuf.st_mode)) && !(S_IXUSR & sbuf.st_mode)) { print_error(fd, filename, "403", "Forbidden", "The server could not run the CGI program"); return; } if (isPOST) strcpy(cgiargs, content); dynamic_serve(fd, filename, cgiargs); } } ```   如果是GET方法,则忽略报头,如果是POST,则根据Content-Length读取报文: ```c oid read_get_requesthdrs(rio_t *rp) { char buf[MAXLINE]; if (rio_readlineb(rp, buf, MAXLINE) == -1) { perror("Read error"); exit(1); } while (strcmp(buf, "\r\n")) { if (rio_readlineb(rp, buf, MAXLINE) == -1) { perror("Read error"); exit(1); } printf("%s", buf); } } void read_post_requesthdrs(rio_t *rp, char *content) { char buf[MAXLINE]; int contentlength = 0; if (rio_readlineb(rp, buf, MAXLINE) == -1) { perror("Read error"); exit(1); } while (strcmp(buf, "\r\n")) { if (rio_readlineb(rp, buf, MAXLINE) == -1) { perror("Read error"); exit(1); } printf("%s", buf); if (strstr(buf, "Content-Length: ") == buf) contentlength = atoi(buf + strlen("Content-Length: ")); //获得长度 } //读入报文体 int n; if ((n = rio_readnb(rp, content, contentlength)) != contentlength) { perror("Read POST content error"); if (n == -1) exit(1); contentlength = n; } content[contentlength] = '\0'; puts(content); } ```   print_error函数用来发送相关的错误消息给客户端,并显示为HTML页面,analyse_uri则将URI解析为文件名和参数串,并根据是否工作在cgi目录下判断是否为动态服务: ```c void print_error(int fd, char *cause, char *errnum, char *shortmsg, char *longmsg) { char buf[MAXLINE] = {0}, body[MAXLINE] = {0}; //输出HTTP响应 if (rio_writen(fd, buf, strlen(buf)) == -1) { perror("Write error"); exit(-1); } sprintf(buf, "Content-Type: text/html\r\n"); if (rio_writen(fd, buf, strlen(buf)) == -1) { perror("Write error"); exit(-1); } sprintf(buf, "Content-Length: %lu\r\n\r\n", strlen(body)); if (rio_writen(fd, buf, strlen(buf)) == -1) { perror("Write error"); exit(-1); } //建立并输出HTTP响应体 sprintf(body, "<html><title>Server Error</title>"); sprintf(body, "%s<body bgcolor=""ffffff"">\r\n", body); sprintf(body, "%s%s: %s\r\n", body, errnum, shortmsg); sprintf(body, "%s<p>%s: %s\r\n", body, longmsg, cause); sprintf(body, "%s<hr><em>The Web Server</em></body></html>\r\n", body); sprintf(buf, "HTTP/1.0 %s %s \r\n", errnum, shortmsg); if (rio_writen(fd, body, strlen(body)) == -1) { perror("Write error"); exit(-1); } } bool analyse_uri(char *uri, char *filename, char *cgiargs) { //默认可执行文件主目录为cgi if (!strstr(uri, "cgi")) //静态内容 { strcpy(cgiargs, ""); //清空参数字符串 strcpy(filename, "."); strcat(filename, uri); //将uri转为相对路径名 if (strlen(uri) == 0 || (strlen(uri) == 1 && uri[0] == '/')) //如果uri以/结尾,则将默认文件名加在后面 strcat(filename, "index.html"); return true; } else { char *ptr = index(uri, '?'); //找到文件名与参数字符串分隔符 if (ptr) { strcpy(cgiargs, ptr + 1); //提前参数字符串 *ptr = '\0'; } else strcpy(cgiargs, ""); strcpy(filename, "."); strcat(filename, uri); //将uri剩下的部分转为相对路径名 return false; } } ```   如果是目录,则根据文件名提取目录名,并且遍历这个目录,显示所有的文件链接,大小和修改时间,供用户浏览和打开: ```c void serve_dir(int fd, char *dirpath) { char *p = strrchr(dirpath, '/'); ++p; char dir[MAXLINE] = {0}; strcpy(dir, p); //复制目录名 strcat(dir, "/"); DIR *dp; if((dp = opendir(dirpath)) == NULL) { perror("Cann't open the dir"); exit(1); } char fbuf[MAXLINE] = {0}; sprintf(fbuf, "<html><title>Display directory content</title>"); sprintf(fbuf, "%s<body bgcolor=""ffffff"" font-family=Consolas><table cellspacing=""10"">\r\n", fbuf); struct dirent *dirp; while((dirp = readdir(dp)) != NULL) //遍历目录 { if(!strcmp(dirp->d_name, ".") || !strcmp(dirp->d_name, "..")) continue; char filepath[MAXLINE] = {0}; sprintf(filepath, "%s/%s", dirpath, dirp->d_name); struct stat sbuf; stat(filepath, &sbuf); sprintf(fbuf,"%s<tr><td><a href=%s%s>%s</a></td><td>%ld</td><td>%s</td></tr>\r\n", fbuf, dir, dirp->d_name, dirp->d_name, sbuf.st_size, ctime_r(&sbuf.st_mtime)); } closedir(dp); sprintf(fbuf,"%s</table></body></html>\r\n", fbuf); char buf[MAXLINE] = {0}; sprintf(buf, "HTTP/1.0 200 OK\r\n"); sprintf(buf, "%sServer: The Web Server\r\n", buf); sprintf(buf, "%sContent-Tength: %lu\r\n", buf, strlen(buf)); sprintf(buf, "%sContent-Type: %s\r\n\r\n", buf, "text/html"); rio_writen(fd, buf, strlen(buf)); rio_writen(fd, fbuf, strlen(fbuf)); } ```   服务器可以提供以下几种类型的静态内容:HTML文件,JPG,PNG,GIF格式的图片和无格式的文本: ```c void static_serve(int fd, char *filename, int filesize) { char buf[MAXLINE] = {0}, filetype[MAXLINE] = {0}; get_filetype(filename, filetype); //获得文件类型 //给客户端发送HTTP响应头 sprintf(buf, "HTTP/1.0 200 OK\r\n"); sprintf(buf, "%sServer: The Web Server\r\n", buf); sprintf(buf, "%sConnection: close\r\n", buf); sprintf(buf, "%sContent-length: %d\r\n", buf, filesize); sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, filetype); if (rio_writen(fd, buf, strlen(buf)) == -1) { perror("Write error"); exit(1); } puts("Response headers:"); printf("%s", buf); //打开请求文件 int srcfd = open(filename, O_RDONLY, 0); if (srcfd < 0 ) { perror("Can't open the file"); exit(1); } //将请求文件内容映射到一个虚拟内存空间 char *srcp = mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0); if (srcp == (void *)-1) { perror("mmap error"); exit(1); } close(srcfd); //将内容发送到客户端 if (rio_writen(fd, srcp, filesize) == -1) { perror("Write error"); exit(1); } //释放虚拟内存 munmap(srcp, filesize); } //获取文件类型 void get_filetype(char *filename, char *filetype) { if (strstr(filename, ".html")) strcpy(filetype, "text/html"); else if (strstr(filename, ".gif")) strcpy(filetype, "image/gif"); else if (strstr(filename, ".png")) strcpy(filetype, "image/png"); else if (strstr(filename, ".jpg")) strcpy(filetype, "image/jpg"); else strcpy(filetype, "text/plain"); } ```   动态服务则通过用URI的CGI参数来初始化QUERY_STRING环境变量,然后运行CGI程序: ```c void dynamic_serve(int fd, char *filename, char *cgiargs) { char buf[MAXLINE] = {0}, *emptylist[] = {NULL}; //向客户端发送响应行 sprintf(buf, "HTTP/1.0 200 OK\r\n"); if (rio_writen(fd, buf, strlen(buf)) == -1) { perror("Write error"); exit(1); } sprintf(buf, "Server: The Web Server\r\n"); if (rio_writen(fd, buf, strlen(buf)) == -1) { perror("Write error"); exit(1); } if (fork() == 0) //Child { setenv("QUERY_STRING", cgiargs, 1); //用CGI参数初始化环境变量 dup2(fd, STDOUT_FILENO); execve(filename, emptylist, environ); //执行CGI程序 } wait(NULL); //父进程阻塞 } ```
scalpelx/scalpelx.github.io
_posts/2017-05-24-webserver.markdown
Markdown
apache-2.0
15,066
# TraffiKill //NOTE TO SELF: FusedLocationProviderClient API doesn't work on Nexus based Emulators as of 14th April 2015. Works on Physical devices.
karanaggarwal1/TraffiKill
README.md
Markdown
apache-2.0
153
package org.sur.ds.selection; import org.junit.Assert; import org.junit.Test; public class DutchFlagProblemTest { @Test public void testSolve1() { Integer[] numbers = new Integer[]{2,1,0,2,0,1}; DutchFlagProblem dfp = new DutchFlagProblem(); dfp.solve(numbers); Integer[] expected = new Integer[]{0,0,1,1,2,2}; Assert.assertArrayEquals(expected, numbers); } @Test public void testSolve2() { Integer[] numbers = new Integer[]{1,0,2,2,0,1}; DutchFlagProblem dfp = new DutchFlagProblem(); dfp.solve(numbers); Integer[] expected = new Integer[]{0,0,1,1,2,2}; Assert.assertArrayEquals(expected, numbers); } }
bluewolf8/examples
BasicAlgorithms/src/test/java/org/sur/ds/selection/DutchFlagProblemTest.java
Java
apache-2.0
636
// ------------------------------------------------------------------------------------------------- // <copyright file="EnumValue.cs" company="RHEA System S.A."> // // Copyright 2017 RHEA System S.A. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> // ------------------------------------------------------------------------------------------------ namespace ReqIFSharp { using System.Threading; using System.Threading.Tasks; using System.Xml; using Microsoft.Extensions.Logging; /// <summary> /// The class <see cref="EnumValue"/> represents enumeration literals. /// </summary> public class EnumValue : Identifiable { /// <summary> /// Initializes a new instance of the <see cref="EnumValue"/> class. /// </summary> public EnumValue() { } /// <summary> /// Initializes a new instance of the <see cref="EnumValue"/> class. /// </summary> /// <param name="datatypeDefinitionEnumeration"> /// The owning <see cref="DatatypeDefinitionEnumeration"/> /// </param> /// <param name="loggerFactory"> /// The (injected) <see cref="ILoggerFactory"/> used to setup logging /// </param> internal EnumValue(DatatypeDefinitionEnumeration datatypeDefinitionEnumeration, ILoggerFactory loggerFactory) : base(loggerFactory) { this.DataTpeDefEnum = datatypeDefinitionEnumeration; this.DataTpeDefEnum.SpecifiedValues.Add(this); } /// <summary> /// Gets or sets the owned <see cref="EmbeddedValue"/> /// </summary> public EmbeddedValue Properties { get; set; } /// <summary> /// Gets or sets the owning <see cref="DatatypeDefinitionEnumeration"/> class. /// </summary> public DatatypeDefinitionEnumeration DataTpeDefEnum { get; set; } /// <summary> /// Generates a <see cref="EnumValue"/> object from its XML representation. /// </summary> /// <param name="reader"> /// an instance of <see cref="XmlReader"/> /// </param> internal override void ReadXml(XmlReader reader) { base.ReadXml(reader); using (var subtree = reader.ReadSubtree()) { while (subtree.Read()) { if (subtree.MoveToContent() == XmlNodeType.Element && reader.LocalName == "EMBEDDED-VALUE") { var embeddedValue = new EmbeddedValue(this, this.loggerFactory); embeddedValue.ReadXml(subtree); } } } } /// <summary> /// Asynchronously generates a <see cref="EnumValue"/> object from its XML representation. /// </summary> /// <param name="reader"> /// an instance of <see cref="XmlReader"/> /// </param> /// <param name="token"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> internal async Task ReadXmlAsync(XmlReader reader, CancellationToken token) { base.ReadXml(reader); using (var subtree = reader.ReadSubtree()) { while (await subtree.ReadAsync()) { if (token.IsCancellationRequested) { token.ThrowIfCancellationRequested(); } if (await subtree.MoveToContentAsync() == XmlNodeType.Element && reader.LocalName == "EMBEDDED-VALUE") { var embeddedValue = new EmbeddedValue(this, this.loggerFactory); embeddedValue.ReadXml(subtree); } } } } /// <summary> /// Converts a <see cref="AttributeDefinition"/> object into its XML representation. /// </summary> /// <param name="writer"> /// an instance of <see cref="XmlWriter"/> /// </param> internal override void WriteXml(XmlWriter writer) { base.WriteXml(writer); if (this.Properties == null) { return; } writer.WriteStartElement("PROPERTIES"); writer.WriteStartElement("EMBEDDED-VALUE"); this.Properties.WriteXml(writer); writer.WriteEndElement(); writer.WriteEndElement(); } /// <summary> /// Asynchronously converts a <see cref="AttributeDefinition"/> object into its XML representation. /// </summary> /// <param name="writer"> /// an instance of <see cref="XmlWriter"/> /// </param> /// <param name="token"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> internal override async Task WriteXmlAsync(XmlWriter writer, CancellationToken token) { await base.WriteXmlAsync(writer, token); if (this.Properties == null) { return; } await writer.WriteStartElementAsync(null, "PROPERTIES", null); await writer.WriteStartElementAsync(null, "EMBEDDED-VALUE", null); await this.Properties.WriteXmlAsync(writer, token); await writer.WriteEndElementAsync(); await writer.WriteEndElementAsync(); } } }
RHEAGROUP/reqifsharp
ReqIFSharp/Datatype/EnumValue.cs
C#
apache-2.0
6,181
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.xml} class, which represents a * loaded XML document. */ ( function() { /* global ActiveXObject */ CKEDITOR.plugins.add( 'xml', {} ); /** * Represents a loaded XML document. * * var xml = new CKEDITOR.xml( '<books><book title="My Book" /></books>' ); * * @class * @constructor Creates xml class instance. * @param {Object/String} xmlObjectOrData A native XML (DOM document) object or * a string containing the XML definition to be loaded. */ CKEDITOR.xml = function( xmlObjectOrData ) { var baseXml = null; if ( typeof xmlObjectOrData == 'object' ) baseXml = xmlObjectOrData; else { var data = ( xmlObjectOrData || '' ).replace( /&nbsp;/g, '\xA0' ); // Check ActiveXObject before DOMParser, because IE10+ support both, but // there's no XPath support in DOMParser instance. // Also, the only check for ActiveXObject which still works in IE11+ is with `in` operator. if ( 'ActiveXObject' in window ) { try { baseXml = new ActiveXObject( 'MSXML2.DOMDocument' ); } catch ( e ) { try { baseXml = new ActiveXObject( 'Microsoft.XmlDom' ); } catch ( err ) {} } if ( baseXml ) { baseXml.async = false; baseXml.resolveExternals = false; baseXml.validateOnParse = false; baseXml.loadXML( data ); } } else if ( window.DOMParser ) { baseXml = ( new DOMParser() ).parseFromString( data, 'text/xml' ); } } /** * The native XML (DOM document) used by the class instance. * * @property {Object} */ this.baseXml = baseXml; }; CKEDITOR.xml.prototype = { /** * Get a single node from the XML document, based on a XPath query. * * // Create the XML instance. * var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' ); * // Get the first <item> node. * var itemNode = <b>xml.selectSingleNode( 'list/item' )</b>; * // Alert "item". * alert( itemNode.nodeName ); * * @param {String} xpath The XPath query to execute. * @param {Object} [contextNode] The XML DOM node to be used as the context * for the XPath query. The document root is used by default. * @returns {Object} A XML node element or null if the query has no results. */ selectSingleNode: function( xpath, contextNode ) { var baseXml = this.baseXml; if ( contextNode || ( contextNode = baseXml ) ) { if ( 'selectSingleNode' in contextNode ) // IEs return contextNode.selectSingleNode( xpath ); else if ( baseXml.evaluate ) { // Others var result = baseXml.evaluate( xpath, contextNode, null, 9, null ); return ( result && result.singleNodeValue ) || null; } } return null; }, /** * Gets a list node from the XML document, based on a XPath query. * * // Create the XML instance. * var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' ); * // Get all <item> nodes. * var itemNodes = xml.selectNodes( 'list/item' ); * // Alert "item" twice, one for each <item>. * for ( var i = 0; i < itemNodes.length; i++ ) * alert( itemNodes[i].nodeName ); * * @param {String} xpath The XPath query to execute. * @param {Object} [contextNode] The XML DOM node to be used as the context * for the XPath query. The document root is used by default. * @returns {Array} An array containing all matched nodes. The array will * be empty if the query has no results. */ selectNodes: function( xpath, contextNode ) { var baseXml = this.baseXml, nodes = []; if ( contextNode || ( contextNode = baseXml ) ) { if ( 'selectNodes' in contextNode ) // IEs return contextNode.selectNodes( xpath ); else if ( baseXml.evaluate ) { // Others var result = baseXml.evaluate( xpath, contextNode, null, 5, null ); if ( result ) { var node; while ( ( node = result.iterateNext() ) ) nodes.push( node ); } } } return nodes; }, /** * Gets the string representation of hte inner contents of a XML node, * based on a XPath query. * * // Create the XML instance. * var xml = new CKEDITOR.xml( '<list><item id="test1" /><item id="test2" /></list>' ); * // Alert "<item id="test1" /><item id="test2" />". * alert( xml.getInnerXml( 'list' ) ); * * @param {String} xpath The XPath query to execute. * @param {Object} [contextNode] The XML DOM node to be used as the context * for the XPath query. The document root is used by default. * @returns {String} The textual representation of the inner contents of * the node or null if the query has no results. */ getInnerXml: function( xpath, contextNode ) { var node = this.selectSingleNode( xpath, contextNode ), xml = []; if ( node ) { node = node.firstChild; while ( node ) { if ( node.xml ) // IEs xml.push( node.xml ); else if ( window.XMLSerializer ) // Others xml.push( ( new XMLSerializer() ).serializeToString( node ) ); node = node.nextSibling; } } return xml.length ? xml.join( '' ) : null; } }; } )();
tambora-org/dockerCRE
volumes/www/survey/third_party/ckeditor/plugins/xml/plugin.js
JavaScript
apache-2.0
5,473
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.hadoop.gcsio; import static com.google.common.base.Preconditions.checkArgument; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableMap; import java.util.Map; import javax.annotation.Nullable; /** * Options that can be specified when creating a file in the {@link GoogleCloudStorageFileSystem}. */ @AutoValue public abstract class CreateFileOptions { public static final CreateFileOptions DEFAULT_NO_OVERWRITE = builder().build(); public static final CreateFileOptions DEFAULT_OVERWRITE = builder().setOverwriteExisting(true).build(); public static Builder builder() { return new AutoValue_CreateFileOptions.Builder() .setAttributes(ImmutableMap.of()) .setContentType(CreateObjectOptions.CONTENT_TYPE_DEFAULT) .setEnsureNoDirectoryConflict(true) .setOverwriteExisting(false) .setOverwriteGenerationId(StorageResourceId.UNKNOWN_GENERATION_ID); } public abstract Builder toBuilder(); /** Extended attributes to set when creating a file. */ public abstract ImmutableMap<String, byte[]> getAttributes(); /** Content-type to set when creating a file. */ @Nullable public abstract String getContentType(); /** * If true, makes sure there isn't already a directory object of the same name. If false, you run * the risk of creating hard-to-cleanup/access files whose names collide with directory names. If * already sure no such directory exists, then this is safe to set for improved performance. */ public abstract boolean isEnsureNoDirectoryConflict(); /** Whether to overwrite an existing file with the same name. */ public abstract boolean isOverwriteExisting(); /** * Generation of existing object to overwrite. Ignored if set to {@link * StorageResourceId#UNKNOWN_GENERATION_ID}, but otherwise this is used instead of {@code * overwriteExisting}, where 0 indicates no existing object, and otherwise an existing object will * only be overwritten by the newly created file if its generation matches this provided * generationId. */ public abstract long getOverwriteGenerationId(); /** Builder for {@link CreateFileOptions} */ @AutoValue.Builder public abstract static class Builder { public abstract Builder setAttributes(Map<String, byte[]> attributes); public abstract Builder setContentType(String contentType); public abstract Builder setEnsureNoDirectoryConflict(boolean ensureNoDirectoryConflict); public abstract Builder setOverwriteGenerationId(long overwriteGenerationId); public abstract Builder setOverwriteExisting(boolean overwriteExisting); abstract CreateFileOptions autoBuild(); public CreateFileOptions build() { CreateFileOptions options = autoBuild(); checkArgument( !options.getAttributes().containsKey("Content-Type"), "The Content-Type attribute must be provided explicitly via the 'contentType' parameter"); return options; } } }
GoogleCloudDataproc/hadoop-connectors
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/CreateFileOptions.java
Java
apache-2.0
3,632
/* * Copyright 2006-2008 Web Cohesion * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.enunciate.main; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.filters.ExpandProperties; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; import org.codehaus.enunciate.EnunciateException; import org.codehaus.enunciate.config.EnunciateConfiguration; import org.codehaus.enunciate.modules.DeploymentModule; import org.codehaus.enunciate.modules.BasicAppModule; import org.xml.sax.SAXException; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.ServiceLoader; /** * Ant task for enunciate. * * @author Ryan Heaton */ public class EnunciateTask extends MatchingTask { private boolean verbose = false; private boolean debug = false; private boolean compileDebugInfo = true; private String encoding; private File configFile; private File basedir; private Path classpath; private File generateDir; private File compileDir; private File buildDir; private File packageDir; private File scratchDir; private File gwtHome; private File flexHome; private String javacSourceVersion = null; private String javacTargetVersion = null; private Enunciate.Target target; private final ArrayList<Export> exports = new ArrayList<Export>(); private final ArrayList<JavacArgument> javacArguments = new ArrayList<JavacArgument>(); /** * Executes the enunciate task. */ @Override public void execute() throws BuildException { if (basedir == null) { throw new BuildException("A base directory must be specified."); } if (gwtHome != null) { System.setProperty("gwt.home", this.gwtHome.getAbsolutePath()); } if (flexHome != null) { System.setProperty("flex.home", this.flexHome.getAbsolutePath()); } DirectoryScanner scanner = getDirectoryScanner(basedir); scanner.scan(); String[] files = scanner.getIncludedFiles(); for (int i = 0; i < files.length; i++) { File file = new File(basedir, files[i]); files[i] = file.getAbsolutePath(); } try { Enunciate proxy = new AntLoggingEnunciate(files); EnunciateConfiguration config; if (classpath != null) { proxy.setRuntimeClasspath(classpath.toString()); //set up the classloader for the Enunciate invocation. AntClassLoader loader = new AntClassLoader(Enunciate.class.getClassLoader(), getProject(), this.classpath, true); proxy.setBuildClasspath(loader.getClasspath()); Thread.currentThread().setContextClassLoader(loader); ArrayList<DeploymentModule> modules = new ArrayList<DeploymentModule>(); Iterator<DeploymentModule> discoveredModules = ServiceLoader.load(DeploymentModule.class, loader).iterator(); getProject().log("Loading modules from the specified classpath...."); while (discoveredModules.hasNext()) { DeploymentModule discoveredModule = (DeploymentModule) discoveredModules.next(); getProject().log("Discovered module " + discoveredModule.getName()); modules.add(discoveredModule); } //make sure a basic app module is there. modules.add(new BasicAppModule()); config = new EnunciateConfiguration(modules); } else { config = new EnunciateConfiguration(); } proxy.setConfig(config); if (this.configFile != null) { getProject().log("Loading config " + this.configFile); ExpandProperties reader = new ExpandProperties(new FileReader(this.configFile)); reader.setProject(getProject()); config.load(reader); proxy.setConfigFile(this.configFile); } if (this.generateDir != null) { proxy.setGenerateDir(this.generateDir); } if (this.compileDir != null) { proxy.setCompileDir(this.compileDir); } if (this.buildDir != null) { proxy.setBuildDir(this.buildDir); } if (this.packageDir != null) { proxy.setPackageDir(this.packageDir); } if (this.scratchDir != null) { proxy.setScratchDir(this.scratchDir); } if (this.target != null) { proxy.setTarget(this.target); } if (this.javacSourceVersion != null) { proxy.setJavacSourceVersion(this.javacSourceVersion); } if (this.javacTargetVersion != null) { proxy.setJavacTargetVersion(this.javacTargetVersion); } for (Export export : exports) { proxy.addExport(export.getArtifactId(), export.getDestination()); } for (JavacArgument javacArgument : this.javacArguments) { proxy.getConfiguredJavacArguments().add(javacArgument.getArgument()); } if (encoding != null) { proxy.setEncoding(encoding); } proxy.setVerbose(verbose); proxy.setDebug(debug); proxy.execute(); } catch (IOException e) { throw new BuildException(e); } catch (EnunciateException e) { throw new BuildException(e); } catch (SAXException e) { throw new BuildException(e); } } public void setEncoding(String encoding) { this.encoding = encoding; } /** * The base directory for the source files. * * @param basedir The base directory for the source files. */ public void setBasedir(File basedir) { this.basedir = basedir; } /** * The base directory for the source files. * * @param basedir The base directory for the source files. */ public void setDir(File basedir) { setBasedir(basedir); } /** * The generate directory. * * @param generateDir The generate directory. */ public void setGenerateDir(File generateDir) { this.generateDir = generateDir; } /** * The compile directory. * * @param compileDir The compile directory. */ public void setCompileDir(File compileDir) { this.compileDir = compileDir; } /** * The build directory. * * @param buildDir The build directory. */ public void setBuildDir(File buildDir) { this.buildDir = buildDir; } /** * The package directory. * * @param packageDir The package directory. */ public void setPackageDir(File packageDir) { this.packageDir = packageDir; } /** * Enunciate scratch directory. * * @param scratchDir The scratch directory */ public void setScratchDir(File scratchDir) { this.scratchDir = scratchDir; } /** * Whether to be verbose. * * @param verbose Whether to be verbose. */ public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * Whether to print debugging information. * * @param debug Whether to print debugging information. */ public void setDebug(boolean debug) { this.debug = debug; } /** * The enunciate config file. * * @param config The enunciate config file. */ public void setConfigFile(File config) { this.configFile = config; } /** * The target. * * @param target The target. */ public void setTarget(String target) { this.target = Enunciate.Target.valueOf(target.toUpperCase()); } /** * The path to gwt home. * * @param gwtHome The path to gwt home. */ public void setGwtHome(File gwtHome) { this.gwtHome = gwtHome; } /** * The path to flex home. * * @param flexHome The path to flex home. */ public void setFlexHome(File flexHome) { this.flexHome = flexHome; } /** * Whether to compile with debug info. * * @return Whether to compile with debug info. */ public boolean isCompileDebugInfo() { return compileDebugInfo; } /** * Whether to compile with debug info. * * @param compileDebugInfo Whether to compile with debug info. */ public void setCompileDebugInfo(boolean compileDebugInfo) { this.compileDebugInfo = compileDebugInfo; } /** * javac -source version parameter * * @param javacSourceVersion javac -source version parameter */ public void setJavacSourceVersion(String javacSourceVersion) { this.javacSourceVersion = javacSourceVersion; } /** * javac -target version parameter * * @param javacTargetVersion javac -target version parameter */ public void setJavacTargetVersion(String javacTargetVersion) { this.javacTargetVersion = javacTargetVersion; } /** * The classpath to use to enunciate. * * @param classpath The classpath to use to enunciate. */ public void setClasspath(Path classpath) { if (this.classpath == null) { this.classpath = classpath; } else { this.classpath.append(classpath); } } /** * The classpath to use to enunciate. * * @return The classpath to use to enunciate. */ public Path getClasspath() { return classpath; } /** * Adds a path to the classpath. * * @return The path. */ public Path createClasspath() { if (classpath == null) { classpath = new Path(getProject()); } return classpath.createPath(); } /** * Adds a reference to a classpath defined elsewhere. * * @param ref a reference to a classpath. */ public void setClasspathRef(Reference ref) { createClasspath().setRefid(ref); } /** * Creates a nested export task. * * @return the nested export task. */ public Export createExport() { Export export = new Export(); this.exports.add(export); return export; } /** * Creates a nested javac argument. * * @return the nested javac argument. */ public JavacArgument createJavacArgument() { JavacArgument export = new JavacArgument(); this.javacArguments.add(export); return export; } /** * A nested export task. */ public static class Export { private String artifactId; private File destination; /** * The id of the artifact to export. * * @return The id of the artifact to export. */ public String getArtifactId() { return artifactId; } /** * The id of the artifact to export. * * @param artifactId The id of the artifact to export. */ public void setArtifactId(String artifactId) { this.artifactId = artifactId; } /** * The destination (file or directory) of the export. * * @return The destination (file or directory) of the export. */ public File getDestination() { return destination; } /** * The destination (file or directory) of the export. * * @param destination The destination (file or directory) of the export. */ public void setDestination(File destination) { this.destination = destination; } } /** * A nested javac argument task. */ public static class JavacArgument { private String argument; /** * The argument. * * @return The argument */ public String getArgument() { return argument; } /** * The argument. * * @param argument The javac argument. */ public void setArgument(String argument) { this.argument = argument; } } /** * An Enunciate mechanism that leverages Ant's logging capabilities, too. */ private class AntLoggingEnunciate extends Enunciate { public AntLoggingEnunciate(String[] sourceFiles) { super(sourceFiles); } @Override public void debug(String message, Object... formatArgs) { if (debug) { getProject().log(String.format(message, formatArgs), Project.MSG_VERBOSE); } } @Override public void info(String message, Object... formatArgs) { if (verbose) { getProject().log(String.format(message, formatArgs), Project.MSG_INFO); } } @Override public void warn(String message, Object... formatArgs) { getProject().log(String.format(message, formatArgs), Project.MSG_WARN); } @Override public void error(String message, Object... formatArgs) { getProject().log(String.format(message, formatArgs), Project.MSG_ERR); } } }
garyhodgson/enunciate
core/src/main/java/org/codehaus/enunciate/main/EnunciateTask.java
Java
apache-2.0
12,942
/* Copyright (c) 2014-2015 F-Secure See LICENSE for details */  using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using FSecure.Utils.ExtensionMethods; using System.Windows; using System.Windows.Media; using System.Diagnostics; namespace FSecure.Lokki.Utils { class LokkiUtils { public static string GetInitials(string name) { var parts = name.Split(' '); if (parts.Length == 0) { return ""; } string initials = ""; if (parts.Length == 1) { initials = parts[0].Left(2); } else { initials = parts[0].Left(1); initials += parts[parts.Length - 1].Left(1); } return initials.ToUpper(CultureInfo.CurrentCulture); } public static void DumpVisualTree(object element, int logindent = 0) { string indent = ""; for (int i = 0; i < logindent; i++) { indent += " "; } Debug.WriteLine(indent + element.ToString()); var children = VisualTreeHelper.GetChildrenCount(element as DependencyObject); for (int i = 0; i < children; i++) { var c = VisualTreeHelper.GetChild(element as DependencyObject, i); DumpVisualTree(c, logindent + 1); } } } }
F-Secure/lokki-wp8
Utils/LokkiUtils.cs
C#
apache-2.0
1,626
/* * * Copyright (c) 2021 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <app-common/zap-generated/cluster-objects.h> #include <app-common/zap-generated/enums.h> #include <app/CommandHandler.h> #include <app/ConcreteCommandPath.h> #include <app/data-model/DecodableList.h> #include <app/util/af.h> #include <lib/core/Optional.h> namespace chip { namespace app { namespace Clusters { // TODO: Should this be OTAProvider::Delegate? /** @brief * Defines methods for implementing application-specific logic for the OTA Provider Cluster. */ class OTAProviderDelegate { public: virtual EmberAfStatus HandleQueryImage(CommandHandler * commandObj, const ConcreteCommandPath & commandPath, const OtaSoftwareUpdateProvider::Commands::QueryImage::DecodableType & commandData) = 0; virtual EmberAfStatus HandleApplyUpdateRequest(CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const OtaSoftwareUpdateProvider::Commands::ApplyUpdateRequest::DecodableType & commandData) = 0; virtual EmberAfStatus HandleNotifyUpdateApplied(CommandHandler * commandObj, const chip::app::ConcreteCommandPath & commandPath, const OtaSoftwareUpdateProvider::Commands::NotifyUpdateApplied::DecodableType & commandData) = 0; virtual ~OTAProviderDelegate() = default; }; } // namespace Clusters } // namespace app } // namespace chip
project-chip/connectedhomeip
src/app/clusters/ota-provider/ota-provider-delegate.h
C
apache-2.0
2,086
/** * FreeRDP: A Remote Desktop Protocol Implementation * Terminal Server Gateway (TSG) * * Copyright 2012 Fujitsu Technology Solutions GmbH * Copyright 2012 Dmitrij Jasnov <dmitrij.jasnov@ts.fujitsu.com> * Copyright 2015 Thincast Technologies GmbH * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <winpr/ndr.h> #include <winpr/error.h> #include <winpr/print.h> #include <winpr/stream.h> #include <freerdp/log.h> #include "rpc_bind.h" #include "rpc_client.h" #include "tsg.h" #include "../../crypto/opensslcompat.h" #define TAG FREERDP_TAG("core.gateway.tsg") typedef WCHAR* RESOURCENAME; typedef struct _tsendpointinfo { RESOURCENAME* resourceName; UINT32 numResourceNames; RESOURCENAME* alternateResourceNames; UINT16 numAlternateResourceNames; UINT32 Port; } TSENDPOINTINFO, *PTSENDPOINTINFO; typedef struct _TSG_PACKET_HEADER { UINT16 ComponentId; UINT16 PacketId; } TSG_PACKET_HEADER, *PTSG_PACKET_HEADER; typedef struct _TSG_CAPABILITY_NAP { UINT32 capabilities; } TSG_CAPABILITY_NAP, *PTSG_CAPABILITY_NAP; typedef union { TSG_CAPABILITY_NAP tsgCapNap; } TSG_CAPABILITIES_UNION, *PTSG_CAPABILITIES_UNION; typedef struct _TSG_PACKET_CAPABILITIES { UINT32 capabilityType; TSG_CAPABILITIES_UNION tsgPacket; } TSG_PACKET_CAPABILITIES, *PTSG_PACKET_CAPABILITIES; typedef struct _TSG_PACKET_VERSIONCAPS { TSG_PACKET_HEADER tsgHeader; PTSG_PACKET_CAPABILITIES tsgCaps; UINT32 numCapabilities; UINT16 majorVersion; UINT16 minorVersion; UINT16 quarantineCapabilities; } TSG_PACKET_VERSIONCAPS, *PTSG_PACKET_VERSIONCAPS; typedef struct _TSG_PACKET_QUARCONFIGREQUEST { UINT32 flags; } TSG_PACKET_QUARCONFIGREQUEST, *PTSG_PACKET_QUARCONFIGREQUEST; typedef struct _TSG_PACKET_QUARREQUEST { UINT32 flags; WCHAR* machineName; UINT32 nameLength; BYTE* data; UINT32 dataLen; } TSG_PACKET_QUARREQUEST, *PTSG_PACKET_QUARREQUEST; typedef struct _TSG_REDIRECTION_FLAGS { BOOL enableAllRedirections; BOOL disableAllRedirections; BOOL driveRedirectionDisabled; BOOL printerRedirectionDisabled; BOOL portRedirectionDisabled; BOOL reserved; BOOL clipboardRedirectionDisabled; BOOL pnpRedirectionDisabled; } TSG_REDIRECTION_FLAGS, *PTSG_REDIRECTION_FLAGS; typedef struct _TSG_PACKET_RESPONSE { UINT32 flags; UINT32 reserved; BYTE* responseData; UINT32 responseDataLen; TSG_REDIRECTION_FLAGS redirectionFlags; } TSG_PACKET_RESPONSE, *PTSG_PACKET_RESPONSE; typedef struct _TSG_PACKET_QUARENC_RESPONSE { UINT32 flags; UINT32 certChainLen; WCHAR* certChainData; GUID nonce; PTSG_PACKET_VERSIONCAPS versionCaps; } TSG_PACKET_QUARENC_RESPONSE, *PTSG_PACKET_QUARENC_RESPONSE; typedef struct TSG_PACKET_STRING_MESSAGE { INT32 isDisplayMandatory; INT32 isConsentMandatory; UINT32 msgBytes; WCHAR* msgBuffer; } TSG_PACKET_STRING_MESSAGE; typedef struct TSG_PACKET_REAUTH_MESSAGE { UINT64 tunnelContext; } TSG_PACKET_REAUTH_MESSAGE, *PTSG_PACKET_REAUTH_MESSAGE; typedef struct _TSG_PACKET_MSG_RESPONSE { UINT32 msgID; UINT32 msgType; INT32 isMsgPresent; } TSG_PACKET_MSG_RESPONSE, *PTSG_PACKET_MSG_RESPONSE; typedef struct TSG_PACKET_CAPS_RESPONSE { TSG_PACKET_QUARENC_RESPONSE pktQuarEncResponse; TSG_PACKET_MSG_RESPONSE pktConsentMessage; } TSG_PACKET_CAPS_RESPONSE, *PTSG_PACKET_CAPS_RESPONSE; typedef struct TSG_PACKET_MSG_REQUEST { UINT32 maxMessagesPerBatch; } TSG_PACKET_MSG_REQUEST, *PTSG_PACKET_MSG_REQUEST; typedef struct _TSG_PACKET_AUTH { TSG_PACKET_VERSIONCAPS tsgVersionCaps; UINT32 cookieLen; BYTE* cookie; } TSG_PACKET_AUTH, *PTSG_PACKET_AUTH; typedef union { PTSG_PACKET_VERSIONCAPS packetVersionCaps; PTSG_PACKET_AUTH packetAuth; } TSG_INITIAL_PACKET_TYPE_UNION, *PTSG_INITIAL_PACKET_TYPE_UNION; typedef struct TSG_PACKET_REAUTH { UINT64 tunnelContext; UINT32 packetId; TSG_INITIAL_PACKET_TYPE_UNION tsgInitialPacket; } TSG_PACKET_REAUTH, *PTSG_PACKET_REAUTH; typedef union { PTSG_PACKET_HEADER packetHeader; PTSG_PACKET_VERSIONCAPS packetVersionCaps; PTSG_PACKET_QUARCONFIGREQUEST packetQuarConfigRequest; PTSG_PACKET_QUARREQUEST packetQuarRequest; PTSG_PACKET_RESPONSE packetResponse; PTSG_PACKET_QUARENC_RESPONSE packetQuarEncResponse; PTSG_PACKET_CAPS_RESPONSE packetCapsResponse; PTSG_PACKET_MSG_REQUEST packetMsgRequest; PTSG_PACKET_MSG_RESPONSE packetMsgResponse; PTSG_PACKET_AUTH packetAuth; PTSG_PACKET_REAUTH packetReauth; } TSG_PACKET_TYPE_UNION; typedef struct _TSG_PACKET { UINT32 packetId; TSG_PACKET_TYPE_UNION tsgPacket; } TSG_PACKET, *PTSG_PACKET; struct rdp_tsg { BIO* bio; rdpRpc* rpc; UINT16 Port; LPWSTR Hostname; LPWSTR MachineName; TSG_STATE state; UINT32 TunnelId; UINT32 ChannelId; BOOL reauthSequence; rdpSettings* settings; rdpTransport* transport; UINT64 ReauthTunnelContext; CONTEXT_HANDLE TunnelContext; CONTEXT_HANDLE ChannelContext; CONTEXT_HANDLE NewTunnelContext; CONTEXT_HANDLE NewChannelContext; TSG_PACKET_REAUTH packetReauth; TSG_PACKET_CAPABILITIES tsgCaps; TSG_PACKET_VERSIONCAPS packetVersionCaps; }; static BOOL tsg_stream_align(wStream* s, size_t align) { size_t pos; size_t offset = 0; if (!s) return FALSE; pos = Stream_GetPosition(s); if ((pos % align) != 0) offset = align - pos % align; return Stream_SafeSeek(s, offset); } static BIO_METHOD* BIO_s_tsg(void); /** * RPC Functions: http://msdn.microsoft.com/en-us/library/windows/desktop/aa378623/ * Remote Procedure Call: http://msdn.microsoft.com/en-us/library/windows/desktop/aa378651/ * RPC NDR Interface Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/hh802752/ */ /** * call sequence with silent reauth: * * TsProxyCreateTunnelRequest() * TsProxyCreateTunnelResponse(TunnelContext) * TsProxyAuthorizeTunnelRequest(TunnelContext) * TsProxyAuthorizeTunnelResponse() * TsProxyMakeTunnelCallRequest(TunnelContext) * TsProxyCreateChannelRequest(TunnelContext) * TsProxyCreateChannelResponse(ChannelContext) * TsProxySetupReceivePipeRequest(ChannelContext) * TsProxySendToServerRequest(ChannelContext) * * ... * * TsProxyMakeTunnelCallResponse(reauth) * TsProxyCreateTunnelRequest() * TsProxyMakeTunnelCallRequest(TunnelContext) * TsProxyCreateTunnelResponse(NewTunnelContext) * TsProxyAuthorizeTunnelRequest(NewTunnelContext) * TsProxyAuthorizeTunnelResponse() * TsProxyCreateChannelRequest(NewTunnelContext) * TsProxyCreateChannelResponse(NewChannelContext) * TsProxyCloseChannelRequest(NewChannelContext) * TsProxyCloseTunnelRequest(NewTunnelContext) * TsProxyCloseChannelResponse(NullChannelContext) * TsProxyCloseTunnelResponse(NullTunnelContext) * TsProxySendToServerRequest(ChannelContext) */ static int TsProxySendToServer(handle_t IDL_handle, const byte pRpcMessage[], UINT32 count, UINT32* lengths) { wStream* s; rdpTsg* tsg; int length; const byte* buffer1 = NULL; const byte* buffer2 = NULL; const byte* buffer3 = NULL; UINT32 buffer1Length; UINT32 buffer2Length; UINT32 buffer3Length; UINT32 numBuffers = 0; UINT32 totalDataBytes = 0; tsg = (rdpTsg*) IDL_handle; buffer1Length = buffer2Length = buffer3Length = 0; if (count > 0) { numBuffers++; buffer1 = &pRpcMessage[0]; buffer1Length = lengths[0]; totalDataBytes += lengths[0] + 4; } if (count > 1) { numBuffers++; buffer2 = &pRpcMessage[1]; buffer2Length = lengths[1]; totalDataBytes += lengths[1] + 4; } if (count > 2) { numBuffers++; buffer3 = &pRpcMessage[2]; buffer3Length = lengths[2]; totalDataBytes += lengths[2] + 4; } length = 28 + totalDataBytes; s = Stream_New(NULL, length); if (!s) { WLog_ERR(TAG, "Stream_New failed!"); return -1; } /* PCHANNEL_CONTEXT_HANDLE_NOSERIALIZE_NR (20 bytes) */ Stream_Write(s, &tsg->ChannelContext.ContextType, 4); /* ContextType (4 bytes) */ Stream_Write(s, tsg->ChannelContext.ContextUuid, 16); /* ContextUuid (16 bytes) */ Stream_Write_UINT32_BE(s, totalDataBytes); /* totalDataBytes (4 bytes) */ Stream_Write_UINT32_BE(s, numBuffers); /* numBuffers (4 bytes) */ if (buffer1Length > 0) Stream_Write_UINT32_BE(s, buffer1Length); /* buffer1Length (4 bytes) */ if (buffer2Length > 0) Stream_Write_UINT32_BE(s, buffer2Length); /* buffer2Length (4 bytes) */ if (buffer3Length > 0) Stream_Write_UINT32_BE(s, buffer3Length); /* buffer3Length (4 bytes) */ if (buffer1Length > 0) Stream_Write(s, buffer1, buffer1Length); /* buffer1 (variable) */ if (buffer2Length > 0) Stream_Write(s, buffer2, buffer2Length); /* buffer2 (variable) */ if (buffer3Length > 0) Stream_Write(s, buffer3, buffer3Length); /* buffer3 (variable) */ if (!rpc_client_write_call(tsg->rpc, s, TsProxySendToServerOpnum)) return -1; return length; } /** * OpNum = 1 * * HRESULT TsProxyCreateTunnel( * [in, ref] PTSG_PACKET tsgPacket, * [out, ref] PTSG_PACKET* tsgPacketResponse, * [out] PTUNNEL_CONTEXT_HANDLE_SERIALIZE* tunnelContext, * [out] unsigned long* tunnelId * ); */ static BOOL TsProxyCreateTunnelWriteRequest(rdpTsg* tsg, PTSG_PACKET tsgPacket) { BOOL rc = FALSE; BOOL write = TRUE; UINT16 opnum = 0; wStream* s; rdpRpc* rpc; if (!tsg || !tsg->rpc) return FALSE; rpc = tsg->rpc; WLog_DBG(TAG, "TsProxyCreateTunnelWriteRequest"); s = Stream_New(NULL, 108); if (!s) return FALSE; switch (tsgPacket->packetId) { case TSG_PACKET_TYPE_VERSIONCAPS: { PTSG_PACKET_VERSIONCAPS packetVersionCaps = tsgPacket->tsgPacket.packetVersionCaps; PTSG_CAPABILITY_NAP tsgCapNap = &packetVersionCaps->tsgCaps->tsgPacket.tsgCapNap; Stream_Write_UINT32(s, tsgPacket->packetId); /* PacketId (4 bytes) */ Stream_Write_UINT32(s, tsgPacket->packetId); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, 0x00020000); /* PacketVersionCapsPtr (4 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->tsgHeader.ComponentId); /* ComponentId (2 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->tsgHeader.PacketId); /* PacketId (2 bytes) */ Stream_Write_UINT32(s, 0x00020004); /* TsgCapsPtr (4 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->numCapabilities); /* NumCapabilities (4 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->majorVersion); /* MajorVersion (2 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->minorVersion); /* MinorVersion (2 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->quarantineCapabilities); /* QuarantineCapabilities (2 bytes) */ /* 4-byte alignment (30 + 2) */ Stream_Write_UINT16(s, 0x0000); /* pad (2 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->numCapabilities); /* MaxCount (4 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->tsgCaps->capabilityType); /* CapabilityType (4 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->tsgCaps->capabilityType); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, tsgCapNap->capabilities); /* capabilities (4 bytes) */ /** * The following 60-byte structure is apparently undocumented, * but parts of it can be matched to known C706 data structures. */ /* * 8-byte constant (8A E3 13 71 02 F4 36 71) also observed here: * http://lists.samba.org/archive/cifs-protocol/2010-July/001543.html */ Stream_Write_UINT8(s, 0x8A); Stream_Write_UINT8(s, 0xE3); Stream_Write_UINT8(s, 0x13); Stream_Write_UINT8(s, 0x71); Stream_Write_UINT8(s, 0x02); Stream_Write_UINT8(s, 0xF4); Stream_Write_UINT8(s, 0x36); Stream_Write_UINT8(s, 0x71); Stream_Write_UINT32(s, 0x00040001); /* 1.4 (version?) */ Stream_Write_UINT32(s, 0x00000001); /* 1 (element count?) */ /* p_cont_list_t */ Stream_Write_UINT8(s, 2); /* ncontext_elem */ Stream_Write_UINT8(s, 0x40); /* reserved1 */ Stream_Write_UINT16(s, 0x0028); /* reserved2 */ /* p_syntax_id_t */ Stream_Write(s, &TSGU_UUID, sizeof(p_uuid_t)); Stream_Write_UINT32(s, TSGU_SYNTAX_IF_VERSION); /* p_syntax_id_t */ Stream_Write(s, &NDR_UUID, sizeof(p_uuid_t)); Stream_Write_UINT32(s, NDR_SYNTAX_IF_VERSION); opnum = TsProxyCreateTunnelOpnum; } break; case TSG_PACKET_TYPE_REAUTH: { PTSG_PACKET_REAUTH packetReauth = tsgPacket->tsgPacket.packetReauth; PTSG_PACKET_VERSIONCAPS packetVersionCaps = packetReauth->tsgInitialPacket.packetVersionCaps; PTSG_CAPABILITY_NAP tsgCapNap = &packetVersionCaps->tsgCaps->tsgPacket.tsgCapNap; Stream_Write_UINT32(s, tsgPacket->packetId); /* PacketId (4 bytes) */ Stream_Write_UINT32(s, tsgPacket->packetId); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, 0x00020000); /* PacketReauthPtr (4 bytes) */ Stream_Write_UINT32(s, 0); /* ??? (4 bytes) */ Stream_Write_UINT64(s, packetReauth->tunnelContext); /* TunnelContext (8 bytes) */ Stream_Write_UINT32(s, TSG_PACKET_TYPE_VERSIONCAPS); /* PacketId (4 bytes) */ Stream_Write_UINT32(s, TSG_PACKET_TYPE_VERSIONCAPS); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, 0x00020004); /* PacketVersionCapsPtr (4 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->tsgHeader.ComponentId); /* ComponentId (2 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->tsgHeader.PacketId); /* PacketId (2 bytes) */ Stream_Write_UINT32(s, 0x00020008); /* TsgCapsPtr (4 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->numCapabilities); /* NumCapabilities (4 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->majorVersion); /* MajorVersion (2 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->minorVersion); /* MinorVersion (2 bytes) */ Stream_Write_UINT16(s, packetVersionCaps->quarantineCapabilities); /* QuarantineCapabilities (2 bytes) */ /* 4-byte alignment (30 + 2) */ Stream_Write_UINT16(s, 0x0000); /* pad (2 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->numCapabilities); /* MaxCount (4 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->tsgCaps->capabilityType); /* CapabilityType (4 bytes) */ Stream_Write_UINT32(s, packetVersionCaps->tsgCaps->capabilityType); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, tsgCapNap->capabilities); /* capabilities (4 bytes) */ opnum = TsProxyCreateTunnelOpnum; } break; default: write = FALSE; break; } rc = TRUE; if (write) return rpc_client_write_call(rpc, s, opnum); Stream_Free(s, TRUE); return rc; } static BOOL TsProxyCreateTunnelReadResponse(rdpTsg* tsg, RPC_PDU* pdu, CONTEXT_HANDLE* tunnelContext, UINT32* tunnelId) { BOOL rc = FALSE; UINT32 count; UINT32 Pointer; PTSG_PACKET packet; UINT32 SwitchValue; UINT32 MessageSwitchValue = 0; UINT32 IsMessagePresent; UINT32 MsgBytes; PTSG_PACKET_CAPABILITIES tsgCaps = NULL; PTSG_PACKET_VERSIONCAPS versionCaps = NULL; PTSG_PACKET_CAPS_RESPONSE packetCapsResponse = NULL; PTSG_PACKET_QUARENC_RESPONSE packetQuarEncResponse = NULL; WLog_DBG(TAG, "TsProxyCreateTunnelReadResponse"); if (!pdu) return FALSE; packet = (PTSG_PACKET) calloc(1, sizeof(TSG_PACKET)); if (!packet) return FALSE; if (Stream_GetRemainingLength(pdu->s) < 12) goto fail; Stream_Seek_UINT32(pdu->s); /* PacketPtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packet->packetId); /* PacketId (4 bytes) */ Stream_Read_UINT32(pdu->s, SwitchValue); /* SwitchValue (4 bytes) */ if ((packet->packetId == TSG_PACKET_TYPE_CAPS_RESPONSE) && (SwitchValue == TSG_PACKET_TYPE_CAPS_RESPONSE)) { packetCapsResponse = (PTSG_PACKET_CAPS_RESPONSE) calloc(1, sizeof(TSG_PACKET_CAPS_RESPONSE)); if (!packetCapsResponse) goto fail; packet->tsgPacket.packetCapsResponse = packetCapsResponse; if (Stream_GetRemainingLength(pdu->s) < 32) goto fail; Stream_Seek_UINT32(pdu->s); /* PacketQuarResponsePtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packetCapsResponse->pktQuarEncResponse.flags); /* Flags (4 bytes) */ Stream_Read_UINT32(pdu->s, packetCapsResponse->pktQuarEncResponse.certChainLen); /* CertChainLength (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* CertChainDataPtr (4 bytes) */ Stream_Read(pdu->s, &packetCapsResponse->pktQuarEncResponse.nonce, 16); /* Nonce (16 bytes) */ Stream_Read_UINT32(pdu->s, Pointer); /* VersionCapsPtr (4 bytes) */ if ((Pointer == 0x0002000C) || (Pointer == 0x00020008)) { if (Stream_GetRemainingLength(pdu->s) < 16) goto fail; Stream_Seek_UINT32(pdu->s); /* MsgId (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* MsgType (4 bytes) */ Stream_Read_UINT32(pdu->s, IsMessagePresent); /* IsMessagePresent (4 bytes) */ Stream_Read_UINT32(pdu->s, MessageSwitchValue); /* MessageSwitchValue (4 bytes) */ } if (packetCapsResponse->pktQuarEncResponse.certChainLen > 0) { if (Stream_GetRemainingLength(pdu->s) < 16) goto fail; Stream_Read_UINT32(pdu->s, Pointer); /* MsgPtr (4 bytes): 0x00020014 */ Stream_Seek_UINT32(pdu->s); /* MaxCount (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* Offset (4 bytes) */ Stream_Read_UINT32(pdu->s, count); /* ActualCount (4 bytes) */ /* * CertChainData is a wide character string, and the count is * given in characters excluding the null terminator, therefore: * size = (count * 2) */ if (!Stream_SafeSeek(pdu->s, count * 2)) /* CertChainData */ goto fail; /* 4-byte alignment */ if (!tsg_stream_align(pdu->s, 4)) goto fail; } else { if (Stream_GetRemainingLength(pdu->s) < 4) goto fail; Stream_Read_UINT32(pdu->s, Pointer); /* Ptr (4 bytes) */ } versionCaps = (PTSG_PACKET_VERSIONCAPS) calloc(1, sizeof(TSG_PACKET_VERSIONCAPS)); if (!versionCaps) goto fail; packetCapsResponse->pktQuarEncResponse.versionCaps = versionCaps; if (Stream_GetRemainingLength(pdu->s) < 18) goto fail; Stream_Read_UINT16(pdu->s, versionCaps->tsgHeader.ComponentId); /* ComponentId (2 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->tsgHeader.PacketId); /* PacketId (2 bytes) */ if (versionCaps->tsgHeader.ComponentId != TS_GATEWAY_TRANSPORT) { WLog_ERR(TAG, "Unexpected ComponentId: 0x%04"PRIX16", Expected TS_GATEWAY_TRANSPORT", versionCaps->tsgHeader.ComponentId); goto fail; } Stream_Read_UINT32(pdu->s, Pointer); /* TsgCapsPtr (4 bytes) */ Stream_Read_UINT32(pdu->s, versionCaps->numCapabilities); /* NumCapabilities (4 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->majorVersion); /* MajorVersion (2 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->minorVersion); /* MinorVersion (2 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->quarantineCapabilities); /* QuarantineCapabilities (2 bytes) */ /* 4-byte alignment */ if (!tsg_stream_align(pdu->s, 4)) goto fail; tsgCaps = (PTSG_PACKET_CAPABILITIES) calloc(1, sizeof(TSG_PACKET_CAPABILITIES)); if (!tsgCaps) goto fail; versionCaps->tsgCaps = tsgCaps; if (Stream_GetRemainingLength(pdu->s) < 16) goto fail; Stream_Seek_UINT32(pdu->s); /* MaxCount (4 bytes) */ Stream_Read_UINT32(pdu->s, tsgCaps->capabilityType); /* CapabilityType (4 bytes) */ Stream_Read_UINT32(pdu->s, SwitchValue); /* SwitchValue (4 bytes) */ if ((SwitchValue != TSG_CAPABILITY_TYPE_NAP) || (tsgCaps->capabilityType != TSG_CAPABILITY_TYPE_NAP)) { WLog_ERR(TAG, "Unexpected CapabilityType: 0x%08"PRIX32", Expected TSG_CAPABILITY_TYPE_NAP", tsgCaps->capabilityType); goto fail; } Stream_Read_UINT32(pdu->s, tsgCaps->tsgPacket.tsgCapNap.capabilities); /* Capabilities (4 bytes) */ switch (MessageSwitchValue) { case TSG_ASYNC_MESSAGE_CONSENT_MESSAGE: case TSG_ASYNC_MESSAGE_SERVICE_MESSAGE: if (Stream_GetRemainingLength(pdu->s) < 16) goto fail; Stream_Seek_UINT32(pdu->s); /* IsDisplayMandatory (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* IsConsent Mandatory (4 bytes) */ Stream_Read_UINT32(pdu->s, MsgBytes); Stream_Read_UINT32(pdu->s, Pointer); if (Pointer) { if (Stream_GetRemainingLength(pdu->s) < 12) goto fail; Stream_Seek_UINT32(pdu->s); /* MaxCount (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* Offset (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* Length (4 bytes) */ } if (MsgBytes > TSG_MESSAGING_MAX_MESSAGE_LENGTH) { WLog_ERR(TAG, "Out of Spec Message Length %"PRIu32"", MsgBytes); goto fail; } if (!Stream_SafeSeek(pdu->s, MsgBytes)) goto fail; break; case TSG_ASYNC_MESSAGE_REAUTH: { if (!tsg_stream_align(pdu->s, 8)) goto fail; if (Stream_GetRemainingLength(pdu->s) < 8) goto fail; Stream_Seek_UINT64(pdu->s); /* TunnelContext (8 bytes) */ } break; default: WLog_ERR(TAG, "Unexpected Message Type: 0x%"PRIX32"", MessageSwitchValue); goto fail; } if (!tsg_stream_align(pdu->s, 4)) goto fail; /* TunnelContext (20 bytes) */ if (Stream_GetRemainingLength(pdu->s) < 24) goto fail; Stream_Read_UINT32(pdu->s, tunnelContext->ContextType); /* ContextType (4 bytes) */ Stream_Read(pdu->s, tunnelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ Stream_Read_UINT32(pdu->s, *tunnelId); /* TunnelId (4 bytes) */ /* ReturnValue (4 bytes) */ } else if ((packet->packetId == TSG_PACKET_TYPE_QUARENC_RESPONSE) && (SwitchValue == TSG_PACKET_TYPE_QUARENC_RESPONSE)) { packetQuarEncResponse = (PTSG_PACKET_QUARENC_RESPONSE) calloc(1, sizeof(TSG_PACKET_QUARENC_RESPONSE)); if (!packetQuarEncResponse) goto fail; packet->tsgPacket.packetQuarEncResponse = packetQuarEncResponse; if (Stream_GetRemainingLength(pdu->s) < 32) goto fail; Stream_Seek_UINT32(pdu->s); /* PacketQuarResponsePtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packetQuarEncResponse->flags); /* Flags (4 bytes) */ Stream_Read_UINT32(pdu->s, packetQuarEncResponse->certChainLen); /* CertChainLength (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* CertChainDataPtr (4 bytes) */ Stream_Read(pdu->s, &packetQuarEncResponse->nonce, 16); /* Nonce (16 bytes) */ if (packetQuarEncResponse->certChainLen > 0) { if (Stream_GetRemainingLength(pdu->s) < 16) goto fail; Stream_Read_UINT32(pdu->s, Pointer); /* Ptr (4 bytes): 0x0002000C */ Stream_Seek_UINT32(pdu->s); /* MaxCount (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* Offset (4 bytes) */ Stream_Read_UINT32(pdu->s, count); /* ActualCount (4 bytes) */ /* * CertChainData is a wide character string, and the count is * given in characters excluding the null terminator, therefore: * size = (count * 2) */ if (!Stream_SafeSeek(pdu->s, count * 2)) /* CertChainData */ goto fail; /* 4-byte alignment */ if (!tsg_stream_align(pdu->s, 4)) goto fail; } else { if (Stream_GetRemainingLength(pdu->s) < 4) goto fail; Stream_Read_UINT32(pdu->s, Pointer); /* Ptr (4 bytes): 0x00020008 */ } versionCaps = (PTSG_PACKET_VERSIONCAPS) calloc(1, sizeof(TSG_PACKET_VERSIONCAPS)); if (!versionCaps) goto fail; packetQuarEncResponse->versionCaps = versionCaps; if (Stream_GetRemainingLength(pdu->s) < 18) goto fail; Stream_Read_UINT16(pdu->s, versionCaps->tsgHeader.ComponentId); /* ComponentId (2 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->tsgHeader.PacketId); /* PacketId (2 bytes) */ if (versionCaps->tsgHeader.ComponentId != TS_GATEWAY_TRANSPORT) { WLog_ERR(TAG, "Unexpected ComponentId: 0x%04"PRIX16", Expected TS_GATEWAY_TRANSPORT", versionCaps->tsgHeader.ComponentId); goto fail; } Stream_Read_UINT32(pdu->s, Pointer); /* TsgCapsPtr (4 bytes) */ Stream_Read_UINT32(pdu->s, versionCaps->numCapabilities); /* NumCapabilities (4 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->majorVersion); /* MajorVersion (2 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->majorVersion); /* MinorVersion (2 bytes) */ Stream_Read_UINT16(pdu->s, versionCaps->quarantineCapabilities); /* QuarantineCapabilities (2 bytes) */ /* 4-byte alignment */ if (!tsg_stream_align(pdu->s, 4)) goto fail; if (Stream_GetRemainingLength(pdu->s) < 36) goto fail; /* Not sure exactly what this is */ Stream_Seek_UINT32(pdu->s); /* 0x00000001 (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* 0x00000001 (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* 0x00000001 (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* 0x00000002 (4 bytes) */ /* TunnelContext (20 bytes) */ Stream_Read_UINT32(pdu->s, tunnelContext->ContextType); /* ContextType (4 bytes) */ Stream_Read(pdu->s, tunnelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ } else { WLog_ERR(TAG, "Unexpected PacketId: 0x%08"PRIX32", Expected TSG_PACKET_TYPE_CAPS_RESPONSE " "or TSG_PACKET_TYPE_QUARENC_RESPONSE", packet->packetId); goto fail; } rc = TRUE; fail: free(packetQuarEncResponse); free(packetCapsResponse); free(versionCaps); free(tsgCaps); free(packet); return rc; } /** * OpNum = 2 * * HRESULT TsProxyAuthorizeTunnel( * [in] PTUNNEL_CONTEXT_HANDLE_NOSERIALIZE tunnelContext, * [in, ref] PTSG_PACKET tsgPacket, * [out, ref] PTSG_PACKET* tsgPacketResponse * ); * */ static BOOL TsProxyAuthorizeTunnelWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* tunnelContext) { UINT32 pad; wStream* s; size_t count; UINT32 offset; rdpRpc* rpc; if (!tsg || !tsg->rpc || !tunnelContext || !tsg->MachineName) return FALSE; count = _wcslen(tsg->MachineName) + 1; rpc = tsg->rpc; WLog_DBG(TAG, "TsProxyAuthorizeTunnelWriteRequest"); s = Stream_New(NULL, 1024 + count * 2); if (!s) return FALSE; /* TunnelContext (20 bytes) */ Stream_Write_UINT32(s, tunnelContext->ContextType); /* ContextType (4 bytes) */ Stream_Write(s, &tunnelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ /* 4-byte alignment */ Stream_Write_UINT32(s, TSG_PACKET_TYPE_QUARREQUEST); /* PacketId (4 bytes) */ Stream_Write_UINT32(s, TSG_PACKET_TYPE_QUARREQUEST); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, 0x00020000); /* PacketQuarRequestPtr (4 bytes) */ Stream_Write_UINT32(s, 0x00000000); /* Flags (4 bytes) */ Stream_Write_UINT32(s, 0x00020004); /* MachineNamePtr (4 bytes) */ Stream_Write_UINT32(s, count); /* NameLength (4 bytes) */ Stream_Write_UINT32(s, 0x00020008); /* DataPtr (4 bytes) */ Stream_Write_UINT32(s, 0); /* DataLength (4 bytes) */ /* MachineName */ Stream_Write_UINT32(s, count); /* MaxCount (4 bytes) */ Stream_Write_UINT32(s, 0); /* Offset (4 bytes) */ Stream_Write_UINT32(s, count); /* ActualCount (4 bytes) */ Stream_Write_UTF16_String(s, tsg->MachineName, count); /* Array */ /* 4-byte alignment */ offset = Stream_GetPosition(s); pad = rpc_offset_align(&offset, 4); Stream_Zero(s, pad); Stream_Write_UINT32(s, 0x00000000); /* MaxCount (4 bytes) */ Stream_SealLength(s); return rpc_client_write_call(rpc, s, TsProxyAuthorizeTunnelOpnum); } static BOOL TsProxyAuthorizeTunnelReadResponse(rdpTsg* tsg, RPC_PDU* pdu) { BOOL rc = FALSE; UINT32 Pointer; UINT32 SizeValue; UINT32 SwitchValue; UINT32 idleTimeout; PTSG_PACKET packet = NULL; PTSG_PACKET_RESPONSE packetResponse = NULL; WLog_DBG(TAG, "TsProxyAuthorizeTunnelReadResponse"); if (!pdu) return FALSE; packet = (PTSG_PACKET) calloc(1, sizeof(TSG_PACKET)); if (!packet) return FALSE; if (Stream_GetRemainingLength(pdu->s) < 68) goto fail; Stream_Seek_UINT32(pdu->s); /* PacketPtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packet->packetId); /* PacketId (4 bytes) */ Stream_Read_UINT32(pdu->s, SwitchValue); /* SwitchValue (4 bytes) */ if (packet->packetId == E_PROXY_NAP_ACCESSDENIED) { WLog_ERR(TAG, "status: E_PROXY_NAP_ACCESSDENIED (0x%08X)", E_PROXY_NAP_ACCESSDENIED); WLog_ERR(TAG, "Ensure that the Gateway Connection Authorization Policy is correct"); goto fail; } if ((packet->packetId != TSG_PACKET_TYPE_RESPONSE) || (SwitchValue != TSG_PACKET_TYPE_RESPONSE)) { WLog_ERR(TAG, "Unexpected PacketId: 0x%08"PRIX32", Expected TSG_PACKET_TYPE_RESPONSE", packet->packetId); goto fail; } packetResponse = (PTSG_PACKET_RESPONSE) calloc(1, sizeof(TSG_PACKET_RESPONSE)); if (!packetResponse) goto fail; packet->tsgPacket.packetResponse = packetResponse; Stream_Read_UINT32(pdu->s, Pointer); /* PacketResponsePtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->flags); /* Flags (4 bytes) */ if (packetResponse->flags != TSG_PACKET_TYPE_QUARREQUEST) { WLog_ERR(TAG, "Unexpected Packet Response Flags: 0x%08"PRIX32", Expected TSG_PACKET_TYPE_QUARREQUEST", packetResponse->flags); goto fail; } Stream_Seek_UINT32(pdu->s); /* Reserved (4 bytes) */ Stream_Read_UINT32(pdu->s, Pointer); /* ResponseDataPtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->responseDataLen); /* ResponseDataLength (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.enableAllRedirections); /* EnableAllRedirections (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.disableAllRedirections); /* DisableAllRedirections (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.driveRedirectionDisabled); /* DriveRedirectionDisabled (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.printerRedirectionDisabled); /* PrinterRedirectionDisabled (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.portRedirectionDisabled); /* PortRedirectionDisabled (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.reserved); /* Reserved (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.clipboardRedirectionDisabled); /* ClipboardRedirectionDisabled (4 bytes) */ Stream_Read_UINT32(pdu->s, packetResponse->redirectionFlags.pnpRedirectionDisabled); /* PnpRedirectionDisabled (4 bytes) */ Stream_Read_UINT32(pdu->s, SizeValue); /* (4 bytes) */ if (SizeValue != packetResponse->responseDataLen) { WLog_ERR(TAG, "Unexpected size value: %"PRIu32", expected: %"PRIu32"", SizeValue, packetResponse->responseDataLen); goto fail; } if (Stream_GetRemainingLength(pdu->s) < SizeValue) goto fail; if (SizeValue == 4) Stream_Read_UINT32(pdu->s, idleTimeout); else Stream_Seek(pdu->s, SizeValue); /* ResponseData */ rc = TRUE; fail: free(packetResponse); free(packet); return rc; } /** * OpNum = 3 * * HRESULT TsProxyMakeTunnelCall( * [in] PTUNNEL_CONTEXT_HANDLE_NOSERIALIZE tunnelContext, * [in] unsigned long procId, * [in, ref] PTSG_PACKET tsgPacket, * [out, ref] PTSG_PACKET* tsgPacketResponse * ); */ static BOOL TsProxyMakeTunnelCallWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* tunnelContext, UINT32 procId) { wStream* s; rdpRpc* rpc; if (!tsg || !tsg->rpc || !tunnelContext) return FALSE; rpc = tsg->rpc; WLog_DBG(TAG, "TsProxyMakeTunnelCallWriteRequest"); s = Stream_New(NULL, 40); if (!s) return FALSE; /* TunnelContext (20 bytes) */ Stream_Write_UINT32(s, tunnelContext->ContextType); /* ContextType (4 bytes) */ Stream_Write(s, tunnelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ Stream_Write_UINT32(s, procId); /* ProcId (4 bytes) */ /* 4-byte alignment */ Stream_Write_UINT32(s, TSG_PACKET_TYPE_MSGREQUEST_PACKET); /* PacketId (4 bytes) */ Stream_Write_UINT32(s, TSG_PACKET_TYPE_MSGREQUEST_PACKET); /* SwitchValue (4 bytes) */ Stream_Write_UINT32(s, 0x00020000); /* PacketMsgRequestPtr (4 bytes) */ Stream_Write_UINT32(s, 0x00000001); /* MaxMessagesPerBatch (4 bytes) */ return rpc_client_write_call(rpc, s, TsProxyMakeTunnelCallOpnum); } static BOOL TsProxyReadPacketSTringMessage(rdpTsg* tsg, wStream* s, TSG_PACKET_STRING_MESSAGE* msg) { UINT32 Pointer, ActualCount, MaxCount; if (!tsg || !s || !msg) return FALSE; if (Stream_GetRemainingLength(s) < 32) return FALSE; Stream_Read_UINT32(s, Pointer); /* ConsentMessagePtr (4 bytes) */ Stream_Read_INT32(s, msg->isDisplayMandatory); /* IsDisplayMandatory (4 bytes) */ Stream_Read_INT32(s, msg->isConsentMandatory); /* IsConsentMandatory (4 bytes) */ Stream_Read_UINT32(s, msg->msgBytes); /* MsgBytes (4 bytes) */ Stream_Read_UINT32(s, Pointer); /* MsgPtr (4 bytes) */ Stream_Read_UINT32(s, MaxCount); /* MaxCount (4 bytes) */ Stream_Seek_UINT32(s); /* Offset (4 bytes) */ Stream_Read_UINT32(s, ActualCount); /* ActualCount (4 bytes) */ if (msg->msgBytes < ActualCount * 2) return FALSE; if (Stream_GetRemainingLength(s) < msg->msgBytes) return FALSE; msg->msgBuffer = (WCHAR*)Stream_Pointer(s); Stream_Seek(s, msg->msgBytes); return TRUE; } static BOOL TsProxyMakeTunnelCallReadResponse(rdpTsg* tsg, RPC_PDU* pdu) { BOOL rc = FALSE; UINT32 Pointer; UINT32 SwitchValue; TSG_PACKET packet; char* messageText = NULL; TSG_PACKET_MSG_RESPONSE packetMsgResponse = { 0 }; TSG_PACKET_STRING_MESSAGE packetStringMessage = { 0 }; TSG_PACKET_REAUTH_MESSAGE packetReauthMessage = { 0 }; WLog_DBG(TAG, "TsProxyMakeTunnelCallReadResponse"); /* This is an asynchronous response */ if (!pdu) return FALSE; if (Stream_GetRemainingLength(pdu->s) < 28) goto fail; Stream_Seek_UINT32(pdu->s); /* PacketPtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packet.packetId); /* PacketId (4 bytes) */ Stream_Read_UINT32(pdu->s, SwitchValue); /* SwitchValue (4 bytes) */ if ((packet.packetId != TSG_PACKET_TYPE_MESSAGE_PACKET) || (SwitchValue != TSG_PACKET_TYPE_MESSAGE_PACKET)) { WLog_ERR(TAG, "Unexpected PacketId: 0x%08"PRIX32", Expected TSG_PACKET_TYPE_MESSAGE_PACKET", packet.packetId); goto fail; } Stream_Read_UINT32(pdu->s, Pointer); /* PacketMsgResponsePtr (4 bytes) */ Stream_Read_UINT32(pdu->s, packetMsgResponse.msgID); /* MsgId (4 bytes) */ Stream_Read_UINT32(pdu->s, packetMsgResponse.msgType); /* MsgType (4 bytes) */ Stream_Read_INT32(pdu->s, packetMsgResponse.isMsgPresent); /* IsMsgPresent (4 bytes) */ /* 2.2.9.2.1.9 TSG_PACKET_MSG_RESPONSE: Ignore empty message body. */ if (!packetMsgResponse.isMsgPresent) { rc = TRUE; goto fail; } Stream_Read_UINT32(pdu->s, SwitchValue); /* SwitchValue (4 bytes) */ switch (SwitchValue) { case TSG_ASYNC_MESSAGE_CONSENT_MESSAGE: if (!TsProxyReadPacketSTringMessage(tsg, pdu->s, &packetStringMessage)) goto fail; ConvertFromUnicode(CP_UTF8, 0, packetStringMessage.msgBuffer, packetStringMessage.msgBytes/2, &messageText, 0, NULL, NULL); WLog_INFO(TAG, "Consent Message: %s", messageText); free(messageText); if (tsg->rpc && tsg->rpc->context && tsg->rpc->context->instance) { rc = IFCALLRESULT(TRUE, tsg->rpc->context->instance->PresentGatewayMessage, tsg->rpc->context->instance, SwitchValue, packetStringMessage.isDisplayMandatory != 0, packetStringMessage.isConsentMandatory != 0, packetStringMessage.msgBytes, packetStringMessage.msgBuffer); } break; case TSG_ASYNC_MESSAGE_SERVICE_MESSAGE: if (!TsProxyReadPacketSTringMessage(tsg, pdu->s, &packetStringMessage)) goto fail; ConvertFromUnicode(CP_UTF8, 0, packetStringMessage.msgBuffer, packetStringMessage.msgBytes/2, &messageText, 0, NULL, NULL); WLog_INFO(TAG, "Service Message: %s", messageText); free(messageText); if (tsg->rpc && tsg->rpc->context && tsg->rpc->context->instance) { rc = IFCALLRESULT(TRUE, tsg->rpc->context->instance->PresentGatewayMessage, tsg->rpc->context->instance, SwitchValue, packetStringMessage.isDisplayMandatory != 0, packetStringMessage.isConsentMandatory != 0, packetStringMessage.msgBytes, packetStringMessage.msgBuffer); } break; case TSG_ASYNC_MESSAGE_REAUTH: if (Stream_GetRemainingLength(pdu->s) < 20) goto fail; Stream_Read_UINT32(pdu->s, Pointer); /* ReauthMessagePtr (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* alignment pad (4 bytes) */ Stream_Read_UINT64(pdu->s, packetReauthMessage.tunnelContext); /* TunnelContext (8 bytes) */ Stream_Seek_UINT32(pdu->s); /* ReturnValue (4 bytes) */ tsg->ReauthTunnelContext = packetReauthMessage.tunnelContext; break; default: WLog_ERR(TAG, "unexpected message type: %"PRIu32"", SwitchValue); goto fail; } rc = TRUE; fail: return rc; } /** * OpNum = 4 * * HRESULT TsProxyCreateChannel( * [in] PTUNNEL_CONTEXT_HANDLE_NOSERIALIZE tunnelContext, * [in, ref] PTSENDPOINTINFO tsEndPointInfo, * [out] PCHANNEL_CONTEXT_HANDLE_SERIALIZE* channelContext, * [out] unsigned long* channelId * ); */ static BOOL TsProxyCreateChannelWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* tunnelContext) { size_t count; wStream* s; rdpRpc* rpc; WLog_DBG(TAG, "TsProxyCreateChannelWriteRequest"); if (!tsg || !tsg->rpc || !tunnelContext || !tsg->Hostname) return FALSE; rpc = tsg->rpc; count = _wcslen(tsg->Hostname) + 1; s = Stream_New(NULL, 60 + count * 2); if (!s) return FALSE; /* TunnelContext (20 bytes) */ Stream_Write_UINT32(s, tunnelContext->ContextType); /* ContextType (4 bytes) */ Stream_Write(s, tunnelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ /* TSENDPOINTINFO */ Stream_Write_UINT32(s, 0x00020000); /* ResourceNamePtr (4 bytes) */ Stream_Write_UINT32(s, 0x00000001); /* NumResourceNames (4 bytes) */ Stream_Write_UINT32(s, 0x00000000); /* AlternateResourceNamesPtr (4 bytes) */ Stream_Write_UINT16(s, 0x0000); /* NumAlternateResourceNames (2 bytes) */ Stream_Write_UINT16(s, 0x0000); /* Pad (2 bytes) */ /* Port (4 bytes) */ Stream_Write_UINT16(s, 0x0003); /* ProtocolId (RDP = 3) (2 bytes) */ Stream_Write_UINT16(s, tsg->Port); /* PortNumber (0xD3D = 3389) (2 bytes) */ Stream_Write_UINT32(s, 0x00000001); /* NumResourceNames (4 bytes) */ Stream_Write_UINT32(s, 0x00020004); /* ResourceNamePtr (4 bytes) */ Stream_Write_UINT32(s, count); /* MaxCount (4 bytes) */ Stream_Write_UINT32(s, 0); /* Offset (4 bytes) */ Stream_Write_UINT32(s, count); /* ActualCount (4 bytes) */ Stream_Write_UTF16_String(s, tsg->Hostname, count); /* Array */ return rpc_client_write_call(rpc, s, TsProxyCreateChannelOpnum); } static BOOL TsProxyCreateChannelReadResponse(rdpTsg* tsg, RPC_PDU* pdu, CONTEXT_HANDLE* channelContext, UINT32* channelId) { BOOL rc = FALSE; WLog_DBG(TAG, "TsProxyCreateChannelReadResponse"); if (!pdu) return FALSE; if (Stream_GetRemainingLength(pdu->s) < 28) goto fail; /* ChannelContext (20 bytes) */ Stream_Read_UINT32(pdu->s, channelContext->ContextType); /* ContextType (4 bytes) */ Stream_Read(pdu->s, channelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ Stream_Read_UINT32(pdu->s, *channelId); /* ChannelId (4 bytes) */ Stream_Seek_UINT32(pdu->s); /* ReturnValue (4 bytes) */ rc = TRUE; fail: return rc; } /** * HRESULT TsProxyCloseChannel( * [in, out] PCHANNEL_CONTEXT_HANDLE_NOSERIALIZE* context * ); */ static BOOL TsProxyCloseChannelWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* context) { wStream* s; rdpRpc* rpc; WLog_DBG(TAG, "TsProxyCloseChannelWriteRequest"); if (!tsg || !tsg->rpc || !context) return FALSE; rpc = tsg->rpc; s = Stream_New(NULL, 20); if (!s) return FALSE; /* ChannelContext (20 bytes) */ Stream_Write_UINT32(s, context->ContextType); /* ContextType (4 bytes) */ Stream_Write(s, context->ContextUuid, 16); /* ContextUuid (16 bytes) */ return rpc_client_write_call(rpc, s, TsProxyCloseChannelOpnum); } static BOOL TsProxyCloseChannelReadResponse(rdpTsg* tsg, RPC_PDU* pdu, CONTEXT_HANDLE* context) { BOOL rc = FALSE; WLog_DBG(TAG, "TsProxyCloseChannelReadResponse"); if (!pdu) return FALSE; if (Stream_GetRemainingLength(pdu->s) < 24) goto fail; /* ChannelContext (20 bytes) */ Stream_Read_UINT32(pdu->s, context->ContextType); /* ContextType (4 bytes) */ Stream_Read(pdu->s, context->ContextUuid, 16); /* ContextUuid (16 bytes) */ Stream_Seek_UINT32(pdu->s); /* ReturnValue (4 bytes) */ rc = TRUE; fail: return rc; } /** * HRESULT TsProxyCloseTunnel( * [in, out] PTUNNEL_CONTEXT_HANDLE_SERIALIZE* context * ); */ static BOOL TsProxyCloseTunnelWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* context) { wStream* s; rdpRpc* rpc; WLog_DBG(TAG, "TsProxyCloseTunnelWriteRequest"); if (!tsg || !tsg->rpc || !context) return FALSE; rpc = tsg->rpc; s = Stream_New(NULL, 20); if (!s) return FALSE; /* TunnelContext (20 bytes) */ Stream_Write_UINT32(s, context->ContextType); /* ContextType (4 bytes) */ Stream_Write(s, context->ContextUuid, 16); /* ContextUuid (16 bytes) */ return rpc_client_write_call(rpc, s, TsProxyCloseTunnelOpnum); } static BOOL TsProxyCloseTunnelReadResponse(rdpTsg* tsg, RPC_PDU* pdu, CONTEXT_HANDLE* context) { BOOL rc = FALSE; WLog_DBG(TAG, "TsProxyCloseTunnelReadResponse"); if (!pdu || !context) return FALSE; if (Stream_GetRemainingLength(pdu->s) < 24) goto fail; /* TunnelContext (20 bytes) */ Stream_Read_UINT32(pdu->s, context->ContextType); /* ContextType (4 bytes) */ Stream_Read(pdu->s, context->ContextUuid, 16); /* ContextUuid (16 bytes) */ Stream_Seek_UINT32(pdu->s); /* ReturnValue (4 bytes) */ rc = TRUE; fail: return rc; } /** * OpNum = 8 * * DWORD TsProxySetupReceivePipe( * [in, max_is(32767)] byte pRpcMessage[] * ); */ static BOOL TsProxySetupReceivePipeWriteRequest(rdpTsg* tsg, CONTEXT_HANDLE* channelContext) { wStream* s; rdpRpc* rpc; WLog_DBG(TAG, "TsProxySetupReceivePipeWriteRequest"); if (!tsg || !tsg->rpc || !channelContext) return FALSE; rpc = tsg->rpc; s = Stream_New(NULL, 20); if (!s) return FALSE; /* ChannelContext (20 bytes) */ Stream_Write_UINT32(s, channelContext->ContextType); /* ContextType (4 bytes) */ Stream_Write(s, channelContext->ContextUuid, 16); /* ContextUuid (16 bytes) */ return rpc_client_write_call(rpc, s, TsProxySetupReceivePipeOpnum); } static BOOL tsg_transition_to_state(rdpTsg* tsg, TSG_STATE state) { const char* str = "TSG_STATE_UNKNOWN"; switch (state) { case TSG_STATE_INITIAL: str = "TSG_STATE_INITIAL"; break; case TSG_STATE_CONNECTED: str = "TSG_STATE_CONNECTED"; break; case TSG_STATE_AUTHORIZED: str = "TSG_STATE_AUTHORIZED"; break; case TSG_STATE_CHANNEL_CREATED: str = "TSG_STATE_CHANNEL_CREATED"; break; case TSG_STATE_PIPE_CREATED: str = "TSG_STATE_PIPE_CREATED"; break; case TSG_STATE_TUNNEL_CLOSE_PENDING: str = "TSG_STATE_TUNNEL_CLOSE_PENDING"; break; case TSG_STATE_CHANNEL_CLOSE_PENDING: str = "TSG_STATE_CHANNEL_CLOSE_PENDING"; break; case TSG_STATE_FINAL: str = "TSG_STATE_FINAL"; break; } WLog_DBG(TAG, "%s", str); return tsg_set_state(tsg, state); } BOOL tsg_proxy_begin(rdpTsg* tsg) { TSG_PACKET tsgPacket; PTSG_CAPABILITY_NAP tsgCapNap; PTSG_PACKET_VERSIONCAPS packetVersionCaps; if (!tsg) return FALSE; packetVersionCaps = &tsg->packetVersionCaps; packetVersionCaps->tsgCaps = &tsg->tsgCaps; tsgCapNap = &tsg->tsgCaps.tsgPacket.tsgCapNap; tsgPacket.packetId = TSG_PACKET_TYPE_VERSIONCAPS; tsgPacket.tsgPacket.packetVersionCaps = packetVersionCaps; packetVersionCaps->tsgHeader.ComponentId = TS_GATEWAY_TRANSPORT; packetVersionCaps->tsgHeader.PacketId = TSG_PACKET_TYPE_VERSIONCAPS; packetVersionCaps->numCapabilities = 1; packetVersionCaps->majorVersion = 1; packetVersionCaps->minorVersion = 1; packetVersionCaps->quarantineCapabilities = 0; packetVersionCaps->tsgCaps->capabilityType = TSG_CAPABILITY_TYPE_NAP; /* * Using reduced capabilities appears to trigger * TSG_PACKET_TYPE_QUARENC_RESPONSE instead of TSG_PACKET_TYPE_CAPS_RESPONSE * * However, reduced capabilities may break connectivity with servers enforcing features, such as * "Only allow connections from Remote Desktop Services clients that support RD Gateway messaging" */ tsgCapNap->capabilities = TSG_NAP_CAPABILITY_QUAR_SOH | TSG_NAP_CAPABILITY_IDLE_TIMEOUT | TSG_MESSAGING_CAP_CONSENT_SIGN | TSG_MESSAGING_CAP_SERVICE_MSG | TSG_MESSAGING_CAP_REAUTH; if (!TsProxyCreateTunnelWriteRequest(tsg, &tsgPacket)) { WLog_ERR(TAG, "TsProxyCreateTunnel failure"); tsg_transition_to_state(tsg, TSG_STATE_FINAL); return FALSE; } return tsg_transition_to_state(tsg, TSG_STATE_INITIAL); } static BOOL tsg_proxy_reauth(rdpTsg* tsg) { TSG_PACKET tsgPacket; PTSG_PACKET_REAUTH packetReauth; PTSG_PACKET_VERSIONCAPS packetVersionCaps; if (!tsg) return FALSE; tsg->reauthSequence = TRUE; packetReauth = &tsg->packetReauth; packetVersionCaps = &tsg->packetVersionCaps; if (!packetReauth || !packetVersionCaps) return FALSE; tsgPacket.packetId = TSG_PACKET_TYPE_REAUTH; tsgPacket.tsgPacket.packetReauth = &tsg->packetReauth; packetReauth->tunnelContext = tsg->ReauthTunnelContext; packetReauth->packetId = TSG_PACKET_TYPE_VERSIONCAPS; packetReauth->tsgInitialPacket.packetVersionCaps = packetVersionCaps; if (!TsProxyCreateTunnelWriteRequest(tsg, &tsgPacket)) { WLog_ERR(TAG, "TsProxyCreateTunnel failure"); tsg_transition_to_state(tsg, TSG_STATE_FINAL); return FALSE; } if (!TsProxyMakeTunnelCallWriteRequest(tsg, &tsg->TunnelContext, TSG_TUNNEL_CALL_ASYNC_MSG_REQUEST)) { WLog_ERR(TAG, "TsProxyMakeTunnelCall failure"); tsg_transition_to_state(tsg, TSG_STATE_FINAL); return FALSE; } return tsg_transition_to_state(tsg, TSG_STATE_INITIAL); } BOOL tsg_recv_pdu(rdpTsg* tsg, RPC_PDU* pdu) { BOOL rc = FALSE; RpcClientCall* call; rdpRpc* rpc; if (!tsg || !tsg->rpc || !pdu) return FALSE; rpc = tsg->rpc; Stream_SealLength(pdu->s); Stream_SetPosition(pdu->s, 0); if (!(pdu->Flags & RPC_PDU_FLAG_STUB)) { if (!Stream_SafeSeek(pdu->s, 24)) return FALSE; } switch (tsg->state) { case TSG_STATE_INITIAL: { CONTEXT_HANDLE* TunnelContext; TunnelContext = (tsg->reauthSequence) ? &tsg->NewTunnelContext : &tsg->TunnelContext; if (!TsProxyCreateTunnelReadResponse(tsg, pdu, TunnelContext, &tsg->TunnelId)) { WLog_ERR(TAG, "TsProxyCreateTunnelReadResponse failure"); return FALSE; } if (!tsg_transition_to_state(tsg, TSG_STATE_CONNECTED)) return FALSE; if (!TsProxyAuthorizeTunnelWriteRequest(tsg, TunnelContext)) { WLog_ERR(TAG, "TsProxyAuthorizeTunnel failure"); return FALSE; } rc = TRUE; } break; case TSG_STATE_CONNECTED: { CONTEXT_HANDLE* TunnelContext; TunnelContext = (tsg->reauthSequence) ? &tsg->NewTunnelContext : &tsg->TunnelContext; if (!TsProxyAuthorizeTunnelReadResponse(tsg, pdu)) { WLog_ERR(TAG, "TsProxyAuthorizeTunnelReadResponse failure"); return FALSE; } if (!tsg_transition_to_state(tsg, TSG_STATE_AUTHORIZED)) return FALSE; if (!tsg->reauthSequence) { if (!TsProxyMakeTunnelCallWriteRequest(tsg, TunnelContext, TSG_TUNNEL_CALL_ASYNC_MSG_REQUEST)) { WLog_ERR(TAG, "TsProxyMakeTunnelCall failure"); return FALSE; } } if (!TsProxyCreateChannelWriteRequest(tsg, TunnelContext)) { WLog_ERR(TAG, "TsProxyCreateChannel failure"); return FALSE; } rc = TRUE; } break; case TSG_STATE_AUTHORIZED: call = rpc_client_call_find_by_id(rpc->client, pdu->CallId); if (!call) return FALSE; if (call->OpNum == TsProxyMakeTunnelCallOpnum) { if (!TsProxyMakeTunnelCallReadResponse(tsg, pdu)) { WLog_ERR(TAG, "TsProxyMakeTunnelCallReadResponse failure"); return FALSE; } rc = TRUE; } else if (call->OpNum == TsProxyCreateChannelOpnum) { CONTEXT_HANDLE ChannelContext; if (!TsProxyCreateChannelReadResponse(tsg, pdu, &ChannelContext, &tsg->ChannelId)) { WLog_ERR(TAG, "TsProxyCreateChannelReadResponse failure"); return FALSE; } if (!tsg->reauthSequence) CopyMemory(&tsg->ChannelContext, &ChannelContext, sizeof(CONTEXT_HANDLE)); else CopyMemory(&tsg->NewChannelContext, &ChannelContext, sizeof(CONTEXT_HANDLE)); if (!tsg_transition_to_state(tsg, TSG_STATE_CHANNEL_CREATED)) return FALSE; if (!tsg->reauthSequence) { if (!TsProxySetupReceivePipeWriteRequest(tsg, &tsg->ChannelContext)) { WLog_ERR(TAG, "TsProxySetupReceivePipe failure"); return FALSE; } } else { if (!TsProxyCloseChannelWriteRequest(tsg, &tsg->NewChannelContext)) { WLog_ERR(TAG, "TsProxyCloseChannelWriteRequest failure"); return FALSE; } if (!TsProxyCloseTunnelWriteRequest(tsg, &tsg->NewTunnelContext)) { WLog_ERR(TAG, "TsProxyCloseTunnelWriteRequest failure"); return FALSE; } } rc = tsg_transition_to_state(tsg, TSG_STATE_PIPE_CREATED); tsg->reauthSequence = FALSE; } else { WLog_ERR(TAG, "TSG_STATE_AUTHORIZED unexpected OpNum: %"PRIu32"\n", call->OpNum); } break; case TSG_STATE_CHANNEL_CREATED: break; case TSG_STATE_PIPE_CREATED: call = rpc_client_call_find_by_id(rpc->client, pdu->CallId); if (!call) return FALSE; if (call->OpNum == TsProxyMakeTunnelCallOpnum) { if (!TsProxyMakeTunnelCallReadResponse(tsg, pdu)) { WLog_ERR(TAG, "TsProxyMakeTunnelCallReadResponse failure"); return FALSE; } rc = TRUE; if (tsg->ReauthTunnelContext) rc = tsg_proxy_reauth(tsg); } else if (call->OpNum == TsProxyCloseChannelOpnum) { CONTEXT_HANDLE ChannelContext; if (!TsProxyCloseChannelReadResponse(tsg, pdu, &ChannelContext)) { WLog_ERR(TAG, "TsProxyCloseChannelReadResponse failure"); return FALSE; } rc = TRUE; } else if (call->OpNum == TsProxyCloseTunnelOpnum) { CONTEXT_HANDLE TunnelContext; if (!TsProxyCloseTunnelReadResponse(tsg, pdu, &TunnelContext)) { WLog_ERR(TAG, "TsProxyCloseTunnelReadResponse failure"); return FALSE; } rc = TRUE; } break; case TSG_STATE_TUNNEL_CLOSE_PENDING: { CONTEXT_HANDLE ChannelContext; if (!TsProxyCloseChannelReadResponse(tsg, pdu, &ChannelContext)) { WLog_ERR(TAG, "TsProxyCloseChannelReadResponse failure"); return FALSE; } if (!tsg_transition_to_state(tsg, TSG_STATE_CHANNEL_CLOSE_PENDING)) return FALSE; if (!TsProxyCloseChannelWriteRequest(tsg, NULL)) { WLog_ERR(TAG, "TsProxyCloseChannelWriteRequest failure"); return FALSE; } if (!TsProxyMakeTunnelCallWriteRequest(tsg, &tsg->TunnelContext, TSG_TUNNEL_CANCEL_ASYNC_MSG_REQUEST)) { WLog_ERR(TAG, "TsProxyMakeTunnelCall failure"); return FALSE; } rc = TRUE; } break; case TSG_STATE_CHANNEL_CLOSE_PENDING: { CONTEXT_HANDLE TunnelContext; if (!TsProxyCloseTunnelReadResponse(tsg, pdu, &TunnelContext)) { WLog_ERR(TAG, "TsProxyCloseTunnelReadResponse failure"); return FALSE; } rc = tsg_transition_to_state(tsg, TSG_STATE_FINAL); } break; case TSG_STATE_FINAL: break; } return rc; } BOOL tsg_check_event_handles(rdpTsg* tsg) { if (rpc_client_in_channel_recv(tsg->rpc) < 0) return FALSE; if (rpc_client_out_channel_recv(tsg->rpc) < 0) return FALSE; return TRUE; } DWORD tsg_get_event_handles(rdpTsg* tsg, HANDLE* events, DWORD count) { UINT32 nCount = 0; rdpRpc* rpc = tsg->rpc; RpcVirtualConnection* connection = rpc->VirtualConnection; if (events && (nCount < count)) { events[nCount] = rpc->client->PipeEvent; nCount++; } else return 0; if (connection->DefaultInChannel && connection->DefaultInChannel->common.tls) { if (events && (nCount < count)) { BIO_get_event(connection->DefaultInChannel->common.tls->bio, &events[nCount]); nCount++; } else return 0; } if (connection->NonDefaultInChannel && connection->NonDefaultInChannel->common.tls) { if (events && (nCount < count)) { BIO_get_event(connection->NonDefaultInChannel->common.tls->bio, &events[nCount]); nCount++; } else return 0; } if (connection->DefaultOutChannel && connection->DefaultOutChannel->common.tls) { if (events && (nCount < count)) { BIO_get_event(connection->DefaultOutChannel->common.tls->bio, &events[nCount]); nCount++; } else return 0; } if (connection->NonDefaultOutChannel && connection->NonDefaultOutChannel->common.tls) { if (events && (nCount < count)) { BIO_get_event(connection->NonDefaultOutChannel->common.tls->bio, &events[nCount]); nCount++; } else return 0; } return nCount; } static BOOL tsg_set_hostname(rdpTsg* tsg, const char* hostname) { free(tsg->Hostname); tsg->Hostname = NULL; ConvertToUnicode(CP_UTF8, 0, hostname, -1, &tsg->Hostname, 0); return TRUE; } static BOOL tsg_set_machine_name(rdpTsg* tsg, const char* machineName) { free(tsg->MachineName); tsg->MachineName = NULL; ConvertToUnicode(CP_UTF8, 0, machineName, -1, &tsg->MachineName, 0); return TRUE; } BOOL tsg_connect(rdpTsg* tsg, const char* hostname, UINT16 port, int timeout) { DWORD nCount; HANDLE events[64]; rdpRpc* rpc = tsg->rpc; rdpSettings* settings = rpc->settings; rdpTransport* transport = rpc->transport; tsg->Port = port; tsg->transport = transport; if (!settings->GatewayPort) settings->GatewayPort = 443; if (!tsg_set_hostname(tsg, hostname)) return FALSE; if (!tsg_set_machine_name(tsg, settings->ComputerName)) return FALSE; if (!rpc_connect(rpc, timeout)) { WLog_ERR(TAG, "rpc_connect error!"); return FALSE; } nCount = tsg_get_event_handles(tsg, events, 64); if (nCount == 0) return FALSE; while (tsg->state != TSG_STATE_PIPE_CREATED) { WaitForMultipleObjects(nCount, events, FALSE, 250); if (!tsg_check_event_handles(tsg)) { WLog_ERR(TAG, "tsg_check failure"); transport->layer = TRANSPORT_LAYER_CLOSED; return FALSE; } } WLog_INFO(TAG, "TS Gateway Connection Success"); tsg->bio = BIO_new(BIO_s_tsg()); if (!tsg->bio) return FALSE; BIO_set_data(tsg->bio, (void*) tsg); return TRUE; } BOOL tsg_disconnect(rdpTsg* tsg) { /** * Gateway Shutdown Phase * * Client Server * | | * |-------------TsProxyCloseChannel Request---------->| * | | * |<-------TsProxySetupReceivePipe Final Response-----| * |<-----------TsProxyCloseChannel Response-----------| * | | * |----TsProxyMakeTunnelCall Request (cancel async)-->| * | | * |<---TsProxyMakeTunnelCall Response (call async)----| * |<---TsProxyMakeTunnelCall Response (cancel async)--| * | | * |--------------TsProxyCloseTunnel Request---------->| * |<-------------TsProxyCloseTunnel Response----------| * | | */ if (!tsg) return FALSE; if (tsg->state != TSG_STATE_TUNNEL_CLOSE_PENDING) { if (!TsProxyCloseChannelWriteRequest(tsg, &tsg->ChannelContext)) return FALSE; return tsg_transition_to_state(tsg, TSG_STATE_CHANNEL_CLOSE_PENDING); } return TRUE; } /** * @brief * * @param[in] tsg * @param[in] data * @param[in] length * @return < 0 on error; 0 if not enough data is available (non blocking mode); > 0 bytes to read */ static int tsg_read(rdpTsg* tsg, BYTE* data, UINT32 length) { rdpRpc* rpc; int status = 0; if (!tsg || !data) return -1; rpc = tsg->rpc; if (rpc->transport->layer == TRANSPORT_LAYER_CLOSED) { WLog_ERR(TAG, "tsg_read error: connection lost"); return -1; } do { status = rpc_client_receive_pipe_read(rpc->client, data, (size_t) length); if (status < 0) return -1; if (!status && !rpc->transport->blocking) return 0; if (rpc->transport->layer == TRANSPORT_LAYER_CLOSED) { WLog_ERR(TAG, "tsg_read error: connection lost"); return -1; } if (status > 0) break; if (rpc->transport->blocking) { while (WaitForSingleObject(rpc->client->PipeEvent, 0) != WAIT_OBJECT_0) { if (!tsg_check_event_handles(tsg)) return -1; WaitForSingleObject(rpc->client->PipeEvent, 100); } } } while (rpc->transport->blocking); return status; } static int tsg_write(rdpTsg* tsg, const BYTE* data, UINT32 length) { int status; if (!tsg || !data || !tsg->rpc || !tsg->rpc->transport) return -1; if (tsg->rpc->transport->layer == TRANSPORT_LAYER_CLOSED) { WLog_ERR(TAG, "error, connection lost"); return -1; } status = TsProxySendToServer((handle_t) tsg, data, 1, &length); if (status < 0) return -1; return length; } rdpTsg* tsg_new(rdpTransport* transport) { rdpTsg* tsg; tsg = (rdpTsg*) calloc(1, sizeof(rdpTsg)); if (!tsg) return NULL; tsg->transport = transport; tsg->settings = transport->settings; tsg->rpc = rpc_new(tsg->transport); if (!tsg->rpc) goto out_free; return tsg; out_free: free(tsg); return NULL; } void tsg_free(rdpTsg* tsg) { if (tsg) { rpc_free(tsg->rpc); free(tsg->Hostname); free(tsg->MachineName); free(tsg); } } static int transport_bio_tsg_write(BIO* bio, const char* buf, int num) { int status; rdpTsg* tsg = (rdpTsg*) BIO_get_data(bio); BIO_clear_flags(bio, BIO_FLAGS_WRITE); status = tsg_write(tsg, (BYTE*) buf, num); if (status < 0) { BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY); return -1; } else if (status == 0) { BIO_set_flags(bio, BIO_FLAGS_WRITE); WSASetLastError(WSAEWOULDBLOCK); } else { BIO_set_flags(bio, BIO_FLAGS_WRITE); } return status >= 0 ? status : -1; } static int transport_bio_tsg_read(BIO* bio, char* buf, int size) { int status; rdpTsg* tsg = (rdpTsg*) BIO_get_data(bio); if (!tsg || (size < 0)) { BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY); return -1; } BIO_clear_flags(bio, BIO_FLAGS_READ); status = tsg_read(tsg, (BYTE*) buf, size); if (status < 0) { BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY); return -1; } else if (status == 0) { BIO_set_flags(bio, BIO_FLAGS_READ); WSASetLastError(WSAEWOULDBLOCK); } else { BIO_set_flags(bio, BIO_FLAGS_READ); } return status > 0 ? status : -1; } static int transport_bio_tsg_puts(BIO* bio, const char* str) { return 1; } static int transport_bio_tsg_gets(BIO* bio, char* str, int size) { return 1; } static long transport_bio_tsg_ctrl(BIO* bio, int cmd, long arg1, void* arg2) { int status = -1; rdpTsg* tsg = (rdpTsg*) BIO_get_data(bio); RpcVirtualConnection* connection = tsg->rpc->VirtualConnection; RpcInChannel* inChannel = connection->DefaultInChannel; RpcOutChannel* outChannel = connection->DefaultOutChannel; switch (cmd) { case BIO_CTRL_FLUSH: (void)BIO_flush(inChannel->common.tls->bio); (void)BIO_flush(outChannel->common.tls->bio); status = 1; break; case BIO_C_GET_EVENT: if (arg2) { *((HANDLE*) arg2) = tsg->rpc->client->PipeEvent; status = 1; } break; case BIO_C_SET_NONBLOCK: status = 1; break; case BIO_C_READ_BLOCKED: { BIO* bio = outChannel->common.bio; status = BIO_read_blocked(bio); } break; case BIO_C_WRITE_BLOCKED: { BIO* bio = inChannel->common.bio; status = BIO_write_blocked(bio); } break; case BIO_C_WAIT_READ: { int timeout = (int) arg1; BIO* bio = outChannel->common.bio; if (BIO_read_blocked(bio)) return BIO_wait_read(bio, timeout); else if (BIO_write_blocked(bio)) return BIO_wait_write(bio, timeout); else status = 1; } break; case BIO_C_WAIT_WRITE: { int timeout = (int) arg1; BIO* bio = inChannel->common.bio; if (BIO_write_blocked(bio)) status = BIO_wait_write(bio, timeout); else if (BIO_read_blocked(bio)) status = BIO_wait_read(bio, timeout); else status = 1; } break; default: break; } return status; } static int transport_bio_tsg_new(BIO* bio) { BIO_set_init(bio, 1); BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY); return 1; } static int transport_bio_tsg_free(BIO* bio) { return 1; } BIO_METHOD* BIO_s_tsg(void) { static BIO_METHOD* bio_methods = NULL; if (bio_methods == NULL) { if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG, "TSGateway"))) return NULL; BIO_meth_set_write(bio_methods, transport_bio_tsg_write); BIO_meth_set_read(bio_methods, transport_bio_tsg_read); BIO_meth_set_puts(bio_methods, transport_bio_tsg_puts); BIO_meth_set_gets(bio_methods, transport_bio_tsg_gets); BIO_meth_set_ctrl(bio_methods, transport_bio_tsg_ctrl); BIO_meth_set_create(bio_methods, transport_bio_tsg_new); BIO_meth_set_destroy(bio_methods, transport_bio_tsg_free); } return bio_methods; } TSG_STATE tsg_get_state(rdpTsg* tsg) { if (!tsg) return TSG_STATE_INITIAL; return tsg->state; } BIO* tsg_get_bio(rdpTsg* tsg) { if (!tsg) return NULL; return tsg->bio; } BOOL tsg_set_state(rdpTsg* tsg, TSG_STATE state) { if (!tsg) return FALSE; tsg->state = state; return TRUE; }
bmiklautz/debian-freerdp2
libfreerdp/core/gateway/tsg.c
C
apache-2.0
61,564
import os import csv def get_value_or_default(value, default=None): result = value.strip() if len(result) == 0: result = default return result def read_csv_file(csv_file_name, delimiter, quote_char='"', skip_header=True, encoding='latin-1'): print(csv_file_name) fd = open(file=csv_file_name, mode='r', encoding=encoding) csv_reader = csv.reader(fd, delimiter=delimiter, quotechar=quote_char) if skip_header: next(csv_reader) for row in csv_reader: yield row fd.close()
CALlanoR/virtual_environments
medical_etls/part1/etls/utils.py
Python
apache-2.0
607
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Copyright (C) 1988-2017 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "Free Software" and "Free Software Needs Free Documentation", with the Front-Cover Texts being "A GNU Manual," and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: "You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom." --> <!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ --> <head> <title>Debugging with GDB: Conditional Init Constructs</title> <meta name="description" content="Debugging with GDB: Conditional Init Constructs"> <meta name="keywords" content="Debugging with GDB: Conditional Init Constructs"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link href="index.html#Top" rel="start" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="Readline-Init-File.html#Readline-Init-File" rel="up" title="Readline Init File"> <link href="Sample-Init-File.html#Sample-Init-File" rel="next" title="Sample Init File"> <link href="Readline-Init-File-Syntax.html#Readline-Init-File-Syntax" rel="prev" title="Readline Init File Syntax"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.indentedblock {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smallindentedblock {margin-left: 3.2em; font-size: smaller} div.smalllisp {margin-left: 3.2em} kbd {font-style:oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:nowrap} span.nolinebreak {white-space:nowrap} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <a name="Conditional-Init-Constructs"></a> <div class="header"> <p> Next: <a href="Sample-Init-File.html#Sample-Init-File" accesskey="n" rel="next">Sample Init File</a>, Previous: <a href="Readline-Init-File-Syntax.html#Readline-Init-File-Syntax" accesskey="p" rel="prev">Readline Init File Syntax</a>, Up: <a href="Readline-Init-File.html#Readline-Init-File" accesskey="u" rel="up">Readline Init File</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="Conditional-Init-Constructs-1"></a> <h4 class="subsection">32.3.2 Conditional Init Constructs</h4> <p>Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be performed as the result of tests. There are four parser directives used. </p> <dl compact="compact"> <dt><code>$if</code></dt> <dd><p>The <code>$if</code> construct allows bindings to be made based on the editing mode, the terminal being used, or the application using Readline. The text of the test extends to the end of the line; no characters are required to isolate it. </p> <dl compact="compact"> <dt><code>mode</code></dt> <dd><p>The <code>mode=</code> form of the <code>$if</code> directive is used to test whether Readline is in <code>emacs</code> or <code>vi</code> mode. This may be used in conjunction with the &lsquo;<samp>set keymap</samp>&rsquo; command, for instance, to set bindings in the <code>emacs-standard</code> and <code>emacs-ctlx</code> keymaps only if Readline is starting out in <code>emacs</code> mode. </p> </dd> <dt><code>term</code></dt> <dd><p>The <code>term=</code> form may be used to include terminal-specific key bindings, perhaps to bind the key sequences output by the terminal&rsquo;s function keys. The word on the right side of the &lsquo;<samp>=</samp>&rsquo; is tested against both the full name of the terminal and the portion of the terminal name before the first &lsquo;<samp>-</samp>&rsquo;. This allows <code>sun</code> to match both <code>sun</code> and <code>sun-cmd</code>, for instance. </p> </dd> <dt><code>application</code></dt> <dd><p>The <var>application</var> construct is used to include application-specific settings. Each program using the Readline library sets the <var>application name</var>, and you can test for a particular value. This could be used to bind key sequences to functions useful for a specific program. For instance, the following command adds a key sequence that quotes the current or previous word in Bash: </p><div class="example"> <pre class="example">$if Bash # Quote the current or previous word &quot;\C-xq&quot;: &quot;\eb\&quot;\ef\&quot;&quot; $endif </pre></div> </dd> </dl> </dd> <dt><code>$endif</code></dt> <dd><p>This command, as seen in the previous example, terminates an <code>$if</code> command. </p> </dd> <dt><code>$else</code></dt> <dd><p>Commands in this branch of the <code>$if</code> directive are executed if the test fails. </p> </dd> <dt><code>$include</code></dt> <dd><p>This directive takes a single filename as an argument and reads commands and bindings from that file. For example, the following directive reads from <samp>/etc/inputrc</samp>: </p><div class="example"> <pre class="example">$include /etc/inputrc </pre></div> </dd> </dl> <hr> <div class="header"> <p> Next: <a href="Sample-Init-File.html#Sample-Init-File" accesskey="n" rel="next">Sample Init File</a>, Previous: <a href="Readline-Init-File-Syntax.html#Readline-Init-File-Syntax" accesskey="p" rel="prev">Readline Init File Syntax</a>, Up: <a href="Readline-Init-File.html#Readline-Init-File" accesskey="u" rel="up">Readline Init File</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>
ATM-HSW/mbed_target
buildtools/gcc-arm-none-eabi-6-2017-q2/share/doc/gcc-arm-none-eabi/html/gdb/Conditional-Init-Constructs.html
HTML
apache-2.0
6,918
package com.faviotorres.pariaguas.utils; import com.faviotorres.pariaguas.Constants; import com.faviotorres.pariaguas.R; import com.faviotorres.pariaguas.model.TempColor; public class TemperatureUtils { private static final float KELVIN = 273.15F; private int getCelsiusFromKelvin(double kelvin){ double celsius = kelvin - KELVIN; return (int) Math.round(celsius); } private int getFahrenheitFromKelvin(double kelvin){ return (int)(((kelvin - KELVIN) * 9d/5) + 32); } private String getCelsiusFromKelvinAsString(double kelvin){ return getCelsiusFromKelvin(kelvin)+"°C"; } private String getFahrenheitFromKelvinAsString(double kelvin){ return getFahrenheitFromKelvin(kelvin)+"°F"; } public String getTemperature(int units, double kelvin){ if(units == 0){ return getCelsiusFromKelvinAsString(kelvin); } return getFahrenheitFromKelvinAsString(kelvin); } public TempColor getColorByIcon(String id) { return Constants.getToolbarColor(id); } public TempColor getColorByKelvin(double kelvin) { if (kelvin >= 305) { return new TempColor(0xfff44336, R.color.md_red_500, R.color.md_red_700); } return new TempColor(0xff64b5f6, R.color.md_blue_300, R.color.md_blue_500); } }
faviotorres/Pariaguas
app/src/main/java/com/faviotorres/pariaguas/utils/TemperatureUtils.java
Java
apache-2.0
1,356
/* * FCKeditor - The text editor for internet * Copyright (C) 2003-2005 Frederico Caldeira Knabben * * Licensed under the terms of the GNU Lesser General Public License: * http://www.opensource.org/licenses/lgpl-license.php * * For further information visit: * http://www.fckeditor.net/ * * "Support Open Source software. What about a donation today?" * * File Name: fckxml.js * Defines the FCKXml object that is used for XML data calls * and XML processing. * This script is shared by almost all pages that compose the * File Browser frameset. * * File Authors: * Frederico Caldeira Knabben (fredck@fckeditor.net) */ var FCKXml = function() {} FCKXml.prototype.GetHttpRequest = function() { if ( window.XMLHttpRequest ) // Gecko return new XMLHttpRequest() ; else if ( window.ActiveXObject ) // IE return new ActiveXObject("MsXml2.XmlHttp") ; } FCKXml.prototype.LoadUrl = function( urlToCall, asyncFunctionPointer ) { var oFCKXml = this ; var bAsync = ( typeof(asyncFunctionPointer) == 'function' ) ; var oXmlHttp = this.GetHttpRequest() ; oXmlHttp.open( "GET", urlToCall, bAsync ) ; if ( bAsync ) { oXmlHttp.onreadystatechange = function() { if ( oXmlHttp.readyState == 4 ) { oFCKXml.DOMDocument = oXmlHttp.responseXML ; if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 ) asyncFunctionPointer( oFCKXml ) ; else alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ; } } } oXmlHttp.send( null ) ; if ( ! bAsync ) { if ( oXmlHttp.status == 200 || oXmlHttp.status == 304 ) this.DOMDocument = oXmlHttp.responseXML ; else { alert( 'XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')' ) ; } } } FCKXml.prototype.SelectNodes = function( xpath ) { if ( document.all ) // IE return this.DOMDocument.selectNodes( xpath ) ; else // Gecko { var aNodeArray = new Array(); var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ; if ( xPathResult ) { var oNode = xPathResult.iterateNext() ; while( oNode ) { aNodeArray[aNodeArray.length] = oNode ; oNode = xPathResult.iterateNext(); } } return aNodeArray ; } } FCKXml.prototype.SelectSingleNode = function( xpath ) { //alert(xpath); if ( document.all ) // IE return this.DOMDocument.selectSingleNode( xpath ) ; else // Gecko { var xPathResult = this.DOMDocument.evaluate( xpath, this.DOMDocument, this.DOMDocument.createNSResolver(this.DOMDocument.documentElement), 9, null); if ( xPathResult && xPathResult.singleNodeValue ) return xPathResult.singleNodeValue ; else return null ; } }
CouleurCitron/cms-2014
lib/FCKeditor/editor/filemanager/browser/default/js/fckxml.js
JavaScript
apache-2.0
2,822
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 09 17:08:24 PDT 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std (jackson-databind 2.1.0 API) </TITLE> <META NAME="date" CONTENT="2012-10-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std (jackson-databind 2.1.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/fasterxml/jackson/databind/introspect//class-useVisibilityChecker.Std.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="VisibilityChecker.Std.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>com.fasterxml.jackson.databind.introspect.VisibilityChecker.Std</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#com.fasterxml.jackson.databind.introspect"><B>com.fasterxml.jackson.databind.introspect</B></A></TD> <TD>Functionality needed for Bean introspection, required for detecting accessors and mutators for Beans, as well as locating and handling method annotations.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="com.fasterxml.jackson.databind.introspect"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A> in <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/package-summary.html">com.fasterxml.jackson.databind.introspect</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/package-summary.html">com.fasterxml.jackson.databind.introspect</A> declared as <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected static&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#DEFAULT">DEFAULT</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is the canonical base instance, configured with default visibility values</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/package-summary.html">com.fasterxml.jackson.databind.introspect</A> that return <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#defaultInstance()">defaultInstance</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#with(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">with</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#with(com.fasterxml.jackson.annotation.JsonAutoDetect)">with</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect</A>&nbsp;ann)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#withCreatorVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">withCreatorVisibility</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#withFieldVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">withFieldVisibility</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#withGetterVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">withGetterVisibility</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#withIsGetterVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">withIsGetterVisibility</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#withSetterVisibility(com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">withSetterVisibility</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect">VisibilityChecker.Std</A></CODE></FONT></TD> <TD><CODE><B>VisibilityChecker.Std.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html#withVisibility(com.fasterxml.jackson.annotation.PropertyAccessor, com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility)">withVisibility</A></B>(<A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/PropertyAccessor.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">PropertyAccessor</A>&nbsp;method, <A HREF="http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonAutoDetect.Visibility.html?is-external=true" title="class or interface in com.fasterxml.jackson.annotation">JsonAutoDetect.Visibility</A>&nbsp;v)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/fasterxml/jackson/databind/introspect/VisibilityChecker.Std.html" title="class in com.fasterxml.jackson.databind.introspect"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?com/fasterxml/jackson/databind/introspect//class-useVisibilityChecker.Std.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="VisibilityChecker.Std.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2012 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved. </BODY> </HTML>
FasterXML/jackson-databind
docs/javadoc/2.1/com/fasterxml/jackson/databind/introspect/class-use/VisibilityChecker.Std.html
HTML
apache-2.0
17,490
# Copyright 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. module Deployment # This exception is raised if you have passed an incorrect object to a method class InvalidArgument < StandardError attr_reader :argument def initialize(object, message='Argument is invalid!', argument=nil) @argument = argument message = "#{object}: #{message}" message += " (#{argument})" if argument super(message) end end # There is no task with such name is the graph class NoSuchTask < StandardError attr_reader :task def initialize(object, message='There is no such task!', task=nil) @task = task message = "#{object}: #{message}" message += " Name: #{task}" if task super(message) end end # You have directly called an abstract method that should be implemented in a subclass class NotImplemented < StandardError end # Loop detected in the graph class LoopDetected < StandardError attr_reader :tasks def initialize(object, message='Loop detected!', tasks=[]) @tasks = tasks message = "#{object}: #{message}" if tasks.any? message += " Path: #{tasks.join ', '}" end super(message) end end end
eayunstack/fuel-astute
lib/fuel_deployment/error.rb
Ruby
apache-2.0
1,776
# -*- coding: utf-8 -*- # Copyright (c) 2015-2022, Exa Analytics Development Team # Distributed under the terms of the Apache License 2.0 from unittest import TestCase import numpy as np import pandas as pd import h5py from exatomic import Universe from exatomic.base import resource from exatomic.molcas.output import Output, Orb, HDF # TODO : change df.shape[0] == num to len(df.index) == num everywhere class TestOutput(TestCase): """Test the Molcas output file editor.""" def setUp(self): self.cdz = Output(resource('mol-carbon-dz.out')) self.uo2sp = Output(resource('mol-uo2-anomb.out')) self.mamcart = Output(resource('mol-ch3nh2-631g.out')) self.mamsphr = Output(resource('mol-ch3nh2-anovdzp.out')) self.c2h6 = Output(resource('mol-c2h6-basis.out')) def test_add_orb(self): """Test adding orbital file functionality.""" self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb')) self.assertTrue(hasattr(self.mamcart, 'momatrix')) self.assertTrue(hasattr(self.mamcart, 'orbital')) with self.assertRaises(ValueError): self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb')) self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb'), mocoefs='same') self.assertTrue('same' in self.mamcart.momatrix.columns) self.assertTrue('same' in self.mamcart.orbital.columns) self.mamcart.add_orb(resource('mol-ch3nh2-631g.scforb'), mocoefs='diff', orbocc='diffocc') self.assertTrue('diff' in self.mamcart.momatrix.columns) self.assertTrue('diffocc' in self.mamcart.orbital.columns) uni = self.mamcart.to_universe() self.assertTrue(hasattr(uni, 'momatrix')) self.assertTrue(hasattr(uni, 'orbital')) def test_add_overlap(self): """Test adding an overlap matrix.""" self.cdz.add_overlap(resource('mol-carbon-dz.overlap')) self.assertTrue(hasattr(self.cdz, 'overlap')) uni = self.cdz.to_universe() self.assertTrue(hasattr(uni, 'overlap')) def test_parse_atom(self): """Test the atom table parser.""" self.uo2sp.parse_atom() self.assertEqual(self.uo2sp.atom.shape[0], 3) self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.uo2sp.atom)))) self.mamcart.parse_atom() self.assertEqual(self.mamcart.atom.shape[0], 7) self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamcart.atom)))) self.mamsphr.parse_atom() self.assertEqual(self.mamsphr.atom.shape[0], 7) self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamsphr.atom)))) def test_parse_basis_set_order(self): """Test the basis set order table parser.""" self.uo2sp.parse_basis_set_order() self.assertEqual(self.uo2sp.basis_set_order.shape[0], 69) cols = list(set(self.uo2sp.basis_set_order._columns)) test = pd.DataFrame(self.uo2sp.basis_set_order[cols]) self.assertTrue(np.all(pd.notnull(test))) self.mamcart.parse_basis_set_order() self.assertEqual(self.mamcart.basis_set_order.shape[0], 28) cols = list(set(self.mamcart.basis_set_order._columns)) test = pd.DataFrame(self.mamcart.basis_set_order[cols]) self.assertTrue(np.all(pd.notnull(test))) self.mamsphr.parse_basis_set_order() self.assertEqual(self.mamsphr.basis_set_order.shape[0], 53) cols = list(set(self.mamsphr.basis_set_order._columns)) test = pd.DataFrame(self.mamsphr.basis_set_order[cols]) self.assertTrue(np.all(pd.notnull(test))) def test_parse_basis_set(self): """Test the gaussian basis set table parser.""" self.uo2sp.parse_basis_set() self.assertEqual(self.uo2sp.basis_set.shape[0], 451) self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.uo2sp.basis_set)))) self.mamcart.parse_basis_set() self.assertEqual(self.mamcart.basis_set.shape[0], 84) self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamcart.basis_set)))) self.mamsphr.parse_basis_set() self.assertEqual(self.mamsphr.basis_set.shape[0], 148) self.assertTrue(np.all(pd.notnull(pd.DataFrame(self.mamsphr.basis_set)))) self.c2h6.parse_basis_set() self.assertTrue(hasattr(self.c2h6, 'basis_set')) def test_to_universe(self): """Test that the Outputs can be converted to universes.""" uni = self.uo2sp.to_universe() self.assertIs(type(uni), Universe) uni = self.mamcart.to_universe() self.assertIs(type(uni), Universe) uni = self.mamsphr.to_universe() self.assertIs(type(uni), Universe) class TestOrb(TestCase): """Test the Molcas Orb file parser.""" def test_parse_old_uhf(self): sym = Orb(resource('mol-c2h6-old-sym.uhforb')) nym = Orb(resource('mol-c2h6-old-nosym.uhforb')) sym.parse_momatrix() nym.parse_momatrix() self.assertTrue(sym.momatrix.shape[0] == 274) self.assertTrue(nym.momatrix.shape[0] == 900) def test_parse_old_orb(self): sym = Orb(resource('mol-c2h6-old-sym.scforb')) nym = Orb(resource('mol-c2h6-old-nosym.scforb')) sym.parse_momatrix() nym.parse_momatrix() self.assertTrue(sym.momatrix.shape[0] == 274) self.assertTrue(nym.momatrix.shape[0] == 900) def test_parse_uhf(self): sym = Orb(resource('mol-c2h6-sym.uhforb')) nym = Orb(resource('mol-c2h6-nosym.uhforb')) sym.parse_momatrix() nym.parse_momatrix() self.assertTrue(sym.momatrix.shape[0] == 274) self.assertTrue(nym.momatrix.shape[0] == 900) def test_parse_orb(self): sym = Orb(resource('mol-c2h6-sym.scforb')) nym = Orb(resource('mol-c2h6-nosym.scforb')) sym.parse_momatrix() nym.parse_momatrix() self.assertTrue(sym.momatrix.shape[0] == 274) self.assertTrue(nym.momatrix.shape[0] == 900) def test_parse_momatrix(self): """Test the momatrix table parser.""" uo2sp = Orb(resource('mol-uo2-anomb.scforb')) uo2sp.parse_momatrix() self.assertEqual(uo2sp.momatrix.shape[0], 4761) self.assertTrue(np.all(pd.notnull(pd.DataFrame(uo2sp.momatrix)))) self.assertTrue(np.all(pd.notnull(pd.DataFrame(uo2sp.orbital)))) mamcart = Orb(resource('mol-ch3nh2-631g.scforb')) mamcart.parse_momatrix() self.assertEqual(mamcart.momatrix.shape[0], 784) self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamcart.momatrix)))) self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamcart.orbital)))) mamsphr = Orb(resource('mol-ch3nh2-anovdzp.scforb')) mamsphr.parse_momatrix() self.assertEqual(mamsphr.momatrix.shape[0], 2809) self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamsphr.momatrix)))) self.assertTrue(np.all(pd.notnull(pd.DataFrame(mamsphr.orbital)))) class TestHDF(TestCase): def setUp(self): self.nym = HDF(resource('mol-c2h6-nosym-scf.hdf5')) self.sym = HDF(resource('mol-c2h6-sym-scf.hdf5')) def test_parse_atom(self): self.sym.parse_atom() self.nym.parse_atom() self.assertTrue(self.sym.atom.shape[0] == 8) self.assertTrue(self.nym.atom.shape[0] == 8) def test_parse_basis_set_order(self): self.sym.parse_basis_set_order() self.nym.parse_basis_set_order() self.assertTrue(self.sym.basis_set_order.shape[0] == 30) self.assertTrue(self.nym.basis_set_order.shape[0] == 30) def test_parse_orbital(self): self.sym.parse_orbital() self.nym.parse_orbital() self.assertTrue(self.sym.orbital.shape[0] == 30) self.assertTrue(self.nym.orbital.shape[0] == 30) def test_parse_overlap(self): self.sym.parse_overlap() self.nym.parse_overlap() self.assertTrue(self.sym.overlap.shape[0]) self.assertTrue(self.nym.overlap.shape[0]) def test_parse_momatrix(self): self.sym.parse_momatrix() self.nym.parse_momatrix() self.assertTrue(self.nym.momatrix.shape[0] == 900) with self.assertRaises(AttributeError): self.assertTrue(self.sym.momatrix) def test_to_universe(self): self.sym.to_universe() self.nym.to_universe()
exa-analytics/exatomic
exatomic/molcas/tests/test_output.py
Python
apache-2.0
8,381
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example29-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-app="FilterInControllerModule"> <div ng-controller="FilterController as ctrl"> <div> All entries: <span ng-repeat="entry in ctrl.array">{{entry.name}} </span> </div> <div> Entries that contain an "a": <span ng-repeat="entry in ctrl.filteredArray">{{entry.name}} </span> </div> </div> </body> </html>
LADOSSIFPB/nutrif
nutrif-web/lib/angular/docs/examples/example-example29/index-production.html
HTML
apache-2.0
624
// ---------------------------------------------------------------------------- // Copyright 2007-2013, GeoTelematic Solutions, Inc. // All rights reserved // ---------------------------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Change History: // 2009/11/10 Martin D. Flynn // -Initial Creation // ---------------------------------------------------------------------------- var MAX_COMMAND_ARGS = 10; var COMMAND_ARG_PREFIX = "rct_"; // Onload function devCommandOnLoad() { devCommandRadioChanged(); }; // Command radio button selection changed function devCommandRadioChanged() { //try { if (document.DeviceCommandForm.cmdRadioSel.length) { var rc = document.DeviceCommandForm.cmdRadioSel.length; //alert("Radio selection changed ... " + rc); for (var i = 0; i < rc; i++) { var cmdName = document.DeviceCommandForm.cmdRadioSel[i].value; var cmdChkd = document.DeviceCommandForm.cmdRadioSel[i].checked; //alert("Command: " + i + " " + cmdName); for (var a = 0; a < MAX_COMMAND_ARGS; a++) { var cmdOptn = document.getElementById(COMMAND_ARG_PREFIX + cmdName + '_' + a); if (!cmdOptn) { continue; } //alert("Radio selection changed ... " + i + " " + cmdChkd); if (cmdChkd) { cmdOptn.disabled = false; cmdOptn.className = "textInput"; } else { cmdOptn.disabled = true; cmdOptn.className = "textReadOnly"; } } } } //} catch (e) { // //} };
vimukthi-git/OpenGTS_2.4.9
war/track/js/DeviceInfo.js
JavaScript
apache-2.0
2,300
package com.pearson.statsagg.network.tcp; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import io.netty.util.CharsetUtil; import com.pearson.statsagg.network.NettyServer; import com.pearson.statsagg.utilities.core_utils.StackTrace; import com.pearson.statsagg.utilities.core_utils.Threads; import io.netty.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ public class TcpServer implements Runnable, NettyServer { private static final Logger logger = LoggerFactory.getLogger(TcpServer.class.getName()); public static final String SERVER_TYPE_STATSD = "STATSD"; public static final String SERVER_TYPE_GRAPHITE_AGGREGATOR = "GRAPHITE_AGGREGATOR"; public static final String SERVER_TYPE_GRAPHITE_PASSTHROUGH = "GRAPHITE_PASSTHROUGH"; public static final String SERVER_TYPE_OPENTSDB_TELNET = "OPENTSDB"; private final int port_; private final String serverType_; private EventLoopGroup bossGroup_ = null; private EventLoopGroup workerGroup_ = null; private boolean initializeSuccess = true; public TcpServer(int port, String serverType) { this.port_ = port; this.serverType_ = serverType; } @Override public void run() { if ((port_ < 0) || (port_ > 65535)) { logger.error("Error running " + serverType_.toLowerCase() + " TCP server. Bad input arguments."); initializeSuccess = false; return; } try { bossGroup_ = new NioEventLoopGroup(); workerGroup_ = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); if (serverType_.equals(SERVER_TYPE_STATSD)) { b.group(bossGroup_, workerGroup_).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(32767), new StringDecoder(CharsetUtil.UTF_8), new TcpServerHandler_Statsd()); } }); } else if (serverType_.equals(SERVER_TYPE_GRAPHITE_AGGREGATOR)) { b.group(bossGroup_, workerGroup_).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(32767), new StringDecoder(CharsetUtil.UTF_8), new TcpServerHandler_GraphiteAggregator()); } }); } else if (serverType_.equals(SERVER_TYPE_GRAPHITE_PASSTHROUGH)) { b.group(bossGroup_, workerGroup_).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(32767), new StringDecoder(CharsetUtil.UTF_8), new TcpServerHandler_GraphitePassthrough()); } }); } else if (serverType_.equals(SERVER_TYPE_OPENTSDB_TELNET)) { b.group(bossGroup_, workerGroup_).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast( new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(32767), new StringDecoder(CharsetUtil.UTF_8), new TcpServerHandler_OpenTsdb()); } }); } b.bind(port_).sync().channel().closeFuture().sync(); } catch (Exception e) { initializeSuccess = false; logger.error(e.toString() + " - Port=" + port_ + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { shutdownServer(); } } @Override public void shutdownServer() { try { if (workerGroup_ != null) { Future futureWorkerGroup = workerGroup_.shutdownGracefully(); futureWorkerGroup.await(); } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } try { if (bossGroup_ != null) { Future futureBossGroup = bossGroup_.shutdownGracefully(); futureBossGroup.await(); } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } try { if (bossGroup_ != null) { while ((bossGroup_ != null) && !bossGroup_.isTerminated()) { Threads.sleepSeconds(1); boolean isGroupTerminated = false; try { isGroupTerminated = bossGroup_.isTerminated(); } catch (Exception e) { isGroupTerminated = true; } logger.info("Is " + serverType_.toLowerCase() + " TCP Server BossGroup Terminated? " + isGroupTerminated); } bossGroup_ = null; } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { bossGroup_ = null; } try { if (workerGroup_ != null) { while ((workerGroup_ != null) && !workerGroup_.isTerminated()) { Threads.sleepSeconds(1); boolean isGroupTerminated = false; try { isGroupTerminated = workerGroup_.isTerminated(); } catch (Exception e) { isGroupTerminated = true; } logger.info("Is " + serverType_.toLowerCase() + " TCP Server WorkerGroup Terminated? " + isGroupTerminated); } workerGroup_ = null; } } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { workerGroup_ = null; } } public boolean isInitializeSuccess() { return initializeSuccess; } }
PearsonEducation/StatsAgg
src/main/java/com/pearson/statsagg/network/tcp/TcpServer.java
Java
apache-2.0
7,937
# Copyright 2010 The Skunkworx. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require File.dirname(__FILE__) + '/base' require 'rest_client' describe SolrMapper::SolrDocument do before(:all) do url = Thing::base_url resource = RestClient::Resource.new("#{url}/update") resource.post("<delete><query>id:[* TO *]</query></delete>", {:content_type => 'text/xml'}) resource.post("<commit/>", {:content_type => 'text/xml'}) thing = Thing.new({:_id => '04787560-bc23-012d-817c-60334b2add60', :content => 'sample content 1', :name => 'sample item 1'}) thing.save thing = Thing.new({:_id => '04787560-bc23-012d-817c-60334b2add61', :content => 'sample content 2', :name => 'sample item 2'}) thing.save end it "should return results" do Thing.query("*:*").count.should > 0 end it "should have identical query and search methods until search is removed" do Thing.query("*:*").count.should == Thing.search("*:*").count Thing.query("name:content").count.should == Thing.search("name:content").count end it "should save new and recall" do id = UUID.new().generate() thing = Thing.new thing._id = id thing.content = 'sample content' thing.save() saved_thing = Thing.find(id) saved_thing.content.should == thing.content end it "should be able to change data" do id = '04787560-bc23-012d-817c-60334b2add60' thing = Thing.find(id) thing.content << ' additional content' thing.save() saved_thing = Thing.find(id) saved_thing.content.should == thing.content end it "should be able to delete" do id = '04787560-bc23-012d-817c-60334b2add61' thing = Thing.find(id) thing.destroy deleted_thing = Thing.find(id) deleted_thing.should be(nil) end it "should be able to update a subset of attributes" do id = '04787560-bc23-012d-817c-60334b2add60' new_content = 'changed content' thing = Thing.find(id) name = thing.name thing.update_attributes({:content => new_content}) saved_thing = Thing.find(id) saved_thing.content.should == new_content # make sure the content HAS changed saved_thing.name.should == name # make sure the name HASN'T changed end end
TheSkunkworx/solr_mapper
spec/query_spec.rb
Ruby
apache-2.0
2,728
<?php if (isset($error)) { ?> <div class="alert alert-danger"><?= $error ?></div> <?php } if (isset($message)) { ?> <div class="alert alert-success"><?= $message ?></div> <?php } $user = new User; if ($user->isLoggedIn()) { ?> <div class="form-group"> <span> <?= t('Attach a community account') ?> </span> <hr> </div> <div class="form-group"> <a href="<?= \URL::to('/ccm/system/authentication/oauth2/community/attempt_attach'); ?>" class="btn btn-primary btn-community btn-block"> <img src="<?= Core::getApplicationURL() ?>/concrete/images/logo.png" class="concrete5-icon"></i> <?= t('Attach a concrete5.org account') ?> </a> </div> <?php } else { ?> <div class="form-group"> <span> <?= t('Sign in with a community account') ?> </span> <hr class="ccm-authentication-type-community"> </div> <div class="form-group"> <a href="<?= \URL::to('/ccm/system/authentication/oauth2/community/attempt_auth'); ?>" class="btn btn-primary btn-community btn-block"> <img src="<?= Core::getApplicationURL() ?>/concrete/images/logo.png" class="concrete5-icon"></i> <?= t('Log in with concrete5.org') ?> </a> </div> <div class="form-group"> <p><?= t('Join the concrete5.org community to setup multiple websites, shop for extensions, and get support.') ?></p> </div> <?php } ?> <style> .ccm-ui .btn-community { border-width: 0px; background: rgb(31,186,232); background: -moz-linear-gradient(top, rgba(31,186,232,1) 0%, rgba(18,155,211,1) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(31,186,232,1)), color-stop(100%,rgba(18,155,211,1))); background: -webkit-linear-gradient(top, rgba(31,186,232,1) 0%,rgba(18,155,211,1) 100%); background: -o-linear-gradient(top, rgba(31,186,232,1) 0%,rgba(18,155,211,1) 100%); background: -ms-linear-gradient(top, rgba(31,186,232,1) 0%,rgba(18,155,211,1) 100%); background: linear-gradient(to bottom, rgba(31,186,232,1) 0%,rgba(18,155,211,1) 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1fbae8', endColorstr='#129bd3',GradientType=0 ); } .ccm-concrete-authentication-type-svg > svg { width: 16px; } img.concrete5-icon { width: 20px; margin-right:5px; } </style> <script> (function() { var svg = $('.ccm-concrete-authentication-type-svg > svg'); if (svg) { var img = new Image(); img.onerror = function() { svg.parent().replaceWith('<i class="fa fa-user"></i>'); }; img.src = svg.parent().data('src'); $(function() { if (svg.closest('li').hasClass('active')) { var color = $('ul.auth-types li.active').css('color'); svg.attr('fill', color); } else { svg.attr('fill', 'rgb(155,155,155)'); } Concrete.event.bind('AuthenticationTypeSelected', function(e, handle) { if (handle === 'community') { var color = $('ul.auth-types li.active').css('color'); svg.attr('fill', color); } else { svg.attr('fill', 'rgb(155,155,155)'); } }); }); } }()); </script>
baardev/lbtb
concrete/authentication/community/form.php
PHP
apache-2.0
3,598
package com.lchtime.safetyexpress.bean; /** * @author Admin * @time 2017/4/7 9:44 * @des ${TODO} */ public class LoginResult { public BasicResult result;//基础结果 public String vc_code;//验证码 public String ub_id;//用户的ID }
simonOrganization/safe
app/src/main/java/com/lchtime/safetyexpress/bean/LoginResult.java
Java
apache-2.0
256
# Gomphandra glabra Merr. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Icacinales/Icacinaceae/Gomphandra/Gomphandra glabra/README.md
Markdown
apache-2.0
173
<!DOCTYPE html> <!--[if IE 8]><html class="ie8"><![endif]--> <!--[if IE 9]><html class="ie9"><![endif]--> <!--[if gt IE 9]><!--> <html> <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="google-site-verification" content="9jyGvNki3NSELTYJ7t_XbF-YQZ8jjfm7LqQQGNq4SSg"> <title>Home | OpenShift Origin Documentation</title> <link href="https://docs.openshift.org/" rel="canonical"> <link href="https://assets.openshift.net/content/subdomain/touch-icon-precomposed.png" rel="apple-touch-icon-precomposed" type="image/png"> <link href="https://assets.openshift.net/content/subdomain/favicon32x32.png" rel="shortcut icon" type="image/png"> <!--[if IE]><link rel="shortcut icon" href="https://assets.openshift.net/content/subdomain/favicon.ico"><![endif]--> <link href="https://assets.openshift.net/content/subdomain.css" rel="stylesheet" media="screen, print"> <link href="_stylesheets/community-home.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://assets.openshift.net/content/html5shiv.js"></script> <script src="https://assets.openshift.net/content/respond.js"></script> <![endif]--> <!-- IE8 requires jQuery and Bootstrap JS to load in head to prevent rendering bugs --> <!-- IE8 requires jQuery v1.x --> <script src="https://assets.openshift.net/content/subdomain.js"></script> <script async src="//www.google-analytics.com/analytics.js" type="text/javascript"></script> <script> window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create', 'UA-40375612-1', 'openshift.org'); ga('set', 'forceSSL', true); ga('send', 'pageview'); </script> </head> <body class="hub hub-home"> <div class="site-wrapper"> <div class="site-wrapper-inner"> <div class="cover-container"> <div class="masthead clearfix"> <div class="inner"> <a href="http://www.openshift.org"><img class="masthead-brand" src="_images/origin_logo.png" alt="OpenShift Logo" /></a> <nav> <ul class="nav masthead-nav"> <li><a href="https://www.openshift.org">Origin Home</a></li> <li><a href="https://www.openshift.org/#contribute">Contribute</a></li> </ul> </nav> </div> </div> <div class="inner cover"> <h1 class="cover-heading">Documentation</h1> <p class="lead"><strong>OpenShift Origin</strong> is an application platform where developers and teams can build, test, deploy, and run their applications. OpenShift Origin also serves as the upstream code base upon which <a href="http://www.openshift.com">OpenShift Online</a> and <a href="https://www.openshift.com/container-platform/">OpenShift Container Platform</a> are built.</p> <div class="btn-group"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Select Version<span class="caret"></span></button> <ul class="dropdown-menu" role="menu"> <li><a href="latest/"><i class="fa fa-arrow-circle-o-right"></i> Origin Latest</a></li> <li><a href="1.2/"><i class="fa fa-arrow-circle-o-right"></i> Origin 1.2</a></li> </ul> </div> </div> <div class="mastfoot"> <div class="inner"> <p> <a href="https://www.redhat.com/"> <img src="https://assets.openshift.net/app/assets/redhat.svg" alt="Red Hat"> </a> <a href="https://hub.openshift.com/quickstarts/92-do-it-yourself-0-1" title="Powered by OpenShift Online with the DIY Cartridge"> <img src="https://www.openshift.com/sites/default/files/images/powered-transparent-white.png" alt="Powered by OpenShift Online"> </a> </p> </div> </div> </div> </div> </div> </body> </html>
xiaoping378/openshift-docs
index-community.html
HTML
apache-2.0
4,235
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path #Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. #Rails.application.config.assets.precompile += %w( search.js ) Rails.application.config.assets.precompile += %w( logo.png )
echoisecho/myapp
config/initializers/assets.rb
Ruby
apache-2.0
546
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/apigatewaymanagementapi/ApiGatewayManagementApiClient.h> #include <aws/apigatewaymanagementapi/ApiGatewayManagementApiEndpoint.h> #include <aws/apigatewaymanagementapi/ApiGatewayManagementApiErrorMarshaller.h> #include <aws/apigatewaymanagementapi/model/DeleteConnectionRequest.h> #include <aws/apigatewaymanagementapi/model/GetConnectionRequest.h> #include <aws/apigatewaymanagementapi/model/PostToConnectionRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::ApiGatewayManagementApi; using namespace Aws::ApiGatewayManagementApi::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "execute-api"; static const char* ALLOCATION_TAG = "ApiGatewayManagementApiClient"; ApiGatewayManagementApiClient::ApiGatewayManagementApiClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<ApiGatewayManagementApiErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } ApiGatewayManagementApiClient::ApiGatewayManagementApiClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<ApiGatewayManagementApiErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } ApiGatewayManagementApiClient::ApiGatewayManagementApiClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, clientConfiguration.region), Aws::MakeShared<ApiGatewayManagementApiErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } ApiGatewayManagementApiClient::~ApiGatewayManagementApiClient() { } void ApiGatewayManagementApiClient::init(const ClientConfiguration& config) { m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + ApiGatewayManagementApiEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void ApiGatewayManagementApiClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } DeleteConnectionOutcome ApiGatewayManagementApiClient::DeleteConnection(const DeleteConnectionRequest& request) const { if (!request.ConnectionIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("DeleteConnection", "Required field: ConnectionId, is not set"); return DeleteConnectionOutcome(Aws::Client::AWSError<ApiGatewayManagementApiErrors>(ApiGatewayManagementApiErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ConnectionId]", false)); } Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/@connections/"; ss << request.GetConnectionId(); uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return DeleteConnectionOutcome(NoResult()); } else { return DeleteConnectionOutcome(outcome.GetError()); } } DeleteConnectionOutcomeCallable ApiGatewayManagementApiClient::DeleteConnectionCallable(const DeleteConnectionRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DeleteConnectionOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteConnection(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void ApiGatewayManagementApiClient::DeleteConnectionAsync(const DeleteConnectionRequest& request, const DeleteConnectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DeleteConnectionAsyncHelper( request, handler, context ); } ); } void ApiGatewayManagementApiClient::DeleteConnectionAsyncHelper(const DeleteConnectionRequest& request, const DeleteConnectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DeleteConnection(request), context); } GetConnectionOutcome ApiGatewayManagementApiClient::GetConnection(const GetConnectionRequest& request) const { if (!request.ConnectionIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("GetConnection", "Required field: ConnectionId, is not set"); return GetConnectionOutcome(Aws::Client::AWSError<ApiGatewayManagementApiErrors>(ApiGatewayManagementApiErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ConnectionId]", false)); } Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/@connections/"; ss << request.GetConnectionId(); uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return GetConnectionOutcome(GetConnectionResult(outcome.GetResult())); } else { return GetConnectionOutcome(outcome.GetError()); } } GetConnectionOutcomeCallable ApiGatewayManagementApiClient::GetConnectionCallable(const GetConnectionRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< GetConnectionOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->GetConnection(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void ApiGatewayManagementApiClient::GetConnectionAsync(const GetConnectionRequest& request, const GetConnectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->GetConnectionAsyncHelper( request, handler, context ); } ); } void ApiGatewayManagementApiClient::GetConnectionAsyncHelper(const GetConnectionRequest& request, const GetConnectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, GetConnection(request), context); } PostToConnectionOutcome ApiGatewayManagementApiClient::PostToConnection(const PostToConnectionRequest& request) const { if (!request.ConnectionIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("PostToConnection", "Required field: ConnectionId, is not set"); return PostToConnectionOutcome(Aws::Client::AWSError<ApiGatewayManagementApiErrors>(ApiGatewayManagementApiErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ConnectionId]", false)); } Aws::Http::URI uri = m_uri; Aws::StringStream ss; ss << "/@connections/"; ss << request.GetConnectionId(); uri.SetPath(uri.GetPath() + ss.str()); JsonOutcome outcome = MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER); if(outcome.IsSuccess()) { return PostToConnectionOutcome(NoResult()); } else { return PostToConnectionOutcome(outcome.GetError()); } } PostToConnectionOutcomeCallable ApiGatewayManagementApiClient::PostToConnectionCallable(const PostToConnectionRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< PostToConnectionOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PostToConnection(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void ApiGatewayManagementApiClient::PostToConnectionAsync(const PostToConnectionRequest& request, const PostToConnectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->PostToConnectionAsyncHelper( request, handler, context ); } ); } void ApiGatewayManagementApiClient::PostToConnectionAsyncHelper(const PostToConnectionRequest& request, const PostToConnectionResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, PostToConnection(request), context); }
cedral/aws-sdk-cpp
aws-cpp-sdk-apigatewaymanagementapi/source/ApiGatewayManagementApiClient.cpp
C++
apache-2.0
10,060
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.rules.modern.builders; import com.facebook.buck.core.cell.Cell; import com.facebook.buck.core.cell.CellPathResolver; import com.facebook.buck.core.cell.Cells; import com.facebook.buck.core.cell.name.CanonicalCellName; import com.facebook.buck.core.config.BuckConfig; import com.facebook.buck.core.exceptions.BuckUncheckedExecutionException; import com.facebook.buck.core.exceptions.WrapsException; import com.facebook.buck.core.filesystems.AbsPath; import com.facebook.buck.core.filesystems.RelPath; import com.facebook.buck.core.rulekey.AddsToRuleKey; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.event.BuckEventBus; import com.facebook.buck.event.PerfEvents; import com.facebook.buck.io.file.GlobPatternMatcher; import com.facebook.buck.io.file.MorePaths; import com.facebook.buck.jvm.java.version.JavaVersion; import com.facebook.buck.remoteexecution.UploadDataSupplier; import com.facebook.buck.remoteexecution.interfaces.Protocol; import com.facebook.buck.remoteexecution.interfaces.Protocol.Digest; import com.facebook.buck.remoteexecution.interfaces.Protocol.Directory; import com.facebook.buck.remoteexecution.interfaces.Protocol.DirectoryNode; import com.facebook.buck.remoteexecution.interfaces.Protocol.FileNode; import com.facebook.buck.remoteexecution.interfaces.Protocol.SymlinkNode; import com.facebook.buck.remoteexecution.proto.WorkerRequirements; import com.facebook.buck.remoteexecution.util.MerkleTreeNodeCache; import com.facebook.buck.remoteexecution.util.MerkleTreeNodeCache.MerkleTreeNode; import com.facebook.buck.remoteexecution.util.MerkleTreeNodeCache.NodeData; import com.facebook.buck.rules.modern.Buildable; import com.facebook.buck.rules.modern.ModernBuildRule; import com.facebook.buck.rules.modern.Serializer; import com.facebook.buck.rules.modern.Serializer.Delegate; import com.facebook.buck.rules.modern.impl.InputsMapBuilder; import com.facebook.buck.rules.modern.impl.InputsMapBuilder.Data; import com.facebook.buck.util.BuckConstant; import com.facebook.buck.util.ConsoleParams; import com.facebook.buck.util.Memoizer; import com.facebook.buck.util.MoreSuppliers; import com.facebook.buck.util.Scope; import com.facebook.buck.util.env.BuckClasspath; import com.facebook.buck.util.function.ThrowingSupplier; import com.facebook.buck.util.hashing.FileHashLoader; import com.google.common.base.Joiner; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.io.ByteStreams; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.management.ManagementFactory; import java.lang.ref.WeakReference; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; /** * ModernBuildRuleRemoteExecutionHelper is used to create remote execution actions for a {@link * ModernBuildRule}. * * <p>To create the remote action, we serialize the MBR (in a graph of serialized {@link * AddsToRuleKey} parts such that different rules will share serialization if they share * references). We then send all the cells BuckConfigs in a serialized form, all of Buck's classpath * (including plugin classpath) and run the action remotely with the {@link * OutOfProcessIsolatedBuilder} (via trampoline.sh). */ public class ModernBuildRuleRemoteExecutionHelper implements RemoteExecutionHelper { private static final Logger LOG = Logger.get(ModernBuildRuleRemoteExecutionHelper.class); private static final Path TRAMPOLINE = Paths.get( System.getProperty( "buck.path_to_isolated_trampoline", "src/com/facebook/buck/rules/modern/builders/trampoline.sh")); private static final String PLUGIN_RESOURCES = System.getProperty("buck.module.resources"); private static final String PLUGIN_ROOT = System.getProperty("pf4j.pluginsDir"); // necessary for isolated buck to work correctly private static final String BASE_BUCK_OUT_DIR = BuckConstant.getBuckOutputPath().toString(); private static final Path TRAMPOLINE_PATH = Paths.get("__trampoline__.sh"); public static final Path METADATA_PATH = Paths.get(".buck.metadata"); private static final String FILE_HASH_VERIFICATION = "hash.verify"; private static final String BUCK_CONFIG_EXPERIMENTS_SECTION_KEY = "experiments"; private static final String BUCK_CONFIG_FILTER_FIELDS_FOR_RE_FLAG_NAME = "filter_buck_config_fields_for_re"; private final InputsMapBuilder inputsMapBuilder; private final ImmutableSet<GlobPatternMatcher> ignorePaths; /** Gets the shared path prefix of all the cells. */ private static AbsPath getCellPathPrefix( CellPathResolver cellResolver, ImmutableSet<CanonicalCellName> cellNames) { return AbsPath.of( MorePaths.splitOnCommonPrefix( cellNames.stream() .map(name -> cellResolver.getNewCellPathResolver().getCellPath(name).getPath()) .collect(ImmutableList.toImmutableList())) .get() .getFirst()); } /** Gets all the canonical cell names. */ private static ImmutableSet<CanonicalCellName> getCellNames(Cells cells) { return cells.getCellProvider().getAllCells().stream() .map(Cell::getCanonicalName) .collect(ImmutableSet.toImmutableSet()); } /** * Used to store information about the common files required by all rules (classpaths, plugin * files, configuration, etc). */ private static class RequiredFile { private final Path path; private final FileNode fileNode; private final UploadDataSupplier dataSupplier; RequiredFile(Path path, FileNode fileNode, UploadDataSupplier dataSupplier) { this.path = path; this.fileNode = fileNode; this.dataSupplier = dataSupplier; } RequiredFile(RelPath path, FileNode fileNode, UploadDataSupplier dataSupplier) { this(path.getPath(), fileNode, dataSupplier); } } private static class ClassPath { private final ImmutableList<RequiredFile> requiredFiles; private final ImmutableList<Path> classpath; ClassPath(ImmutableList<RequiredFile> requiredFiles, ImmutableList<Path> classpath) { this.requiredFiles = requiredFiles; this.classpath = classpath; } } private final ThrowingSupplier<RequiredFile, IOException> trampoline; // TODO(cjhopman): We need to figure out a way to only hash these files once-per-daemon, not // once-per-command. private final ThrowingSupplier<ClassPath, IOException> classPath; private final ThrowingSupplier<ClassPath, IOException> bootstrapClassPath; private final ThrowingSupplier<ClassPath, IOException> pluginFiles; private final ThrowingSupplier<ImmutableList<RequiredFile>, IOException> configFiles; private final ThrowingSupplier<ImmutableList<RequiredFile>, IOException> sharedRequiredFiles; private final ThrowingSupplier<MerkleTreeNode, IOException> sharedFilesNode; private final MerkleTreeNodeCache nodeCache; private final BuckEventBus eventBus; private final SourcePathResolverAdapter pathResolver; private final CellPathResolver cellResolver; private final FileHashLoader fileHasher; private final Serializer serializer; private final Map<Class<?>, Map<String, Boolean>> loggedMessagesByClass = new ConcurrentHashMap<>(); private final AbsPath cellPathPrefix; private final RelPath projectRoot; private final Map<HashCode, Node> nodeMap = new ConcurrentHashMap<>(); private final HashFunction hasher; private final Protocol protocol; private final Memoizer<Digest> emptyDirectoryDigestMemoizer = new Memoizer<>(); private final ConsoleParams consoleParams; public ModernBuildRuleRemoteExecutionHelper( BuckEventBus eventBus, Protocol protocol, SourcePathRuleFinder ruleFinder, Cells cells, FileHashLoader fileHasher, ImmutableSet<GlobPatternMatcher> ignorePaths, ConsoleParams consoleParams, boolean sanitizeBuckConfig) { this.consoleParams = consoleParams; this.ignorePaths = ignorePaths; ImmutableSet<CanonicalCellName> cellNames = getCellNames(cells); this.cellResolver = cells.getRootCell().getCellPathResolver(); this.cellPathPrefix = getCellPathPrefix(cellResolver, cellNames); this.eventBus = eventBus; this.protocol = protocol; this.pathResolver = ruleFinder.getSourcePathResolver(); this.projectRoot = cellPathPrefix.relativize(cells.getRootCell().getRoot().getPath()); this.hasher = protocol.getHashFunction(); this.fileHasher = fileHasher; Delegate delegate = (instance, data, children) -> { HashCode hash = hasher.hashBytes(data); Node node = new Node( instance, data, hash, children.stream() .map(nodeMap::get) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()))); nodeMap.put(hash, node); return hash; }; this.serializer = new Serializer(ruleFinder, cellResolver, delegate); this.nodeCache = new MerkleTreeNodeCache(protocol); this.classPath = prepareClassPath(BuckClasspath::getClasspath); this.bootstrapClassPath = prepareClassPath(BuckClasspath::getBootstrapClasspath); this.trampoline = MoreSuppliers.memoize( () -> { Digest digest = protocol.computeDigest(Files.readAllBytes(TRAMPOLINE)); return new RequiredFile( TRAMPOLINE_PATH, protocol.newFileNode(digest, TRAMPOLINE_PATH.getFileName().toString(), true), new UploadDataSupplier() { @Override public Digest getDigest() { return digest; } @Override public InputStream get() throws IOException { return new FileInputStream(TRAMPOLINE.toFile()); } @Override public String describe() { try { return String.format( "MBR trampoline (path: %s size:%s).", TRAMPOLINE, Files.size(TRAMPOLINE)); } catch (IOException e) { return String.format("failed to describe (%s)", e.getMessage()); } } }); }, IOException.class); if (PLUGIN_RESOURCES == null || PLUGIN_ROOT == null) { pluginFiles = () -> new ClassPath(ImmutableList.of(), ImmutableList.of()); } else { pluginFiles = prepareClassPath(ModernBuildRuleRemoteExecutionHelper::findPlugins); } this.inputsMapBuilder = new InputsMapBuilder(); this.configFiles = MoreSuppliers.memoize( () -> { ImmutableList.Builder<RequiredFile> filesBuilder = ImmutableList.builder(); for (CanonicalCellName cellName : cellNames) { RelPath configPath = getPrefixRelativeCellPath(cellName).resolveRel(".buckconfig"); BuckConfig buckConfig = cells.getCellProvider().getCellByCanonicalCellName(cellName).getBuckConfig(); byte[] bytes = serializeConfig(buckConfig, sanitizeBuckConfig); Digest digest = protocol.computeDigest(bytes); filesBuilder.add( new RequiredFile( configPath, protocol.newFileNode( digest, configPath.getPath().getFileName().toString(), false), new UploadDataSupplier() { @Override public Digest getDigest() { return digest; } @Override public InputStream get() { return new ByteArrayInputStream(bytes); } @Override public String describe() { return String.format( "Serialized .buckconfig (cell: %s size:%s).", cellName.getLegacyName().orElse("root"), bytes.length); } })); } return filesBuilder.build(); }, IOException.class); this.sharedRequiredFiles = MoreSuppliers.memoize( () -> { ImmutableList.Builder<RequiredFile> requiredFiles = ImmutableList.builder(); requiredFiles.addAll(classPath.get().requiredFiles); requiredFiles.addAll(bootstrapClassPath.get().requiredFiles); requiredFiles.addAll(pluginFiles.get().requiredFiles); requiredFiles.add(trampoline.get()); requiredFiles.addAll(configFiles.get()); return requiredFiles.build(); }, IOException.class); this.sharedFilesNode = MoreSuppliers.memoize( () -> { Map<Path, FileNode> sharedRequiredFiles = new HashMap<>(); this.sharedRequiredFiles .get() .forEach(file -> sharedRequiredFiles.put(file.path, file.fileNode)); return nodeCache.createNode( sharedRequiredFiles, ImmutableMap.of(), ImmutableMap.of()); }, IOException.class); } @Override public Path getCellPathPrefix() { return cellPathPrefix.getPath(); } @Override public boolean supportsRemoteExecution(ModernBuildRule<?> rule) { // TODO(cjhopman): We may want to extend this to support returning more information about what // is required from the RE system (i.e. toolchains/platforms/etc). try { // We don't use the result of serialization here, we're just verifying that it succeeds. The // serializer will memoize the results so we won't recompute it when we need it later. serializer.serialize(rule.getBuildable()); return true; } catch (Exception e) { String message = WrapsException.getRootCause(e).getMessage(); loggedMessagesByClass .computeIfAbsent(rule.getClass(), ignored -> new ConcurrentHashMap<>()) .computeIfAbsent( message == null ? "" : message, ignored -> { LOG.warn( e, "Remote Execution not supported for instance of %s due to serialization failure.", rule.getClass()); return true; }); return false; } } @Override public RemoteExecutionActionInfo prepareRemoteExecution( ModernBuildRule<?> rule, BiPredicate<Digest, String> requiredDataPredicate, WorkerRequirements workerRequirements) throws IOException { Set<Path> outputs; HashCode hash; try (Scope ignored = PerfEvents.scope(eventBus, "serializing")) { Buildable original = rule.getBuildable(); hash = serializer.serialize(new BuildableAndTarget(original, rule.getBuildTarget())); } ImmutableList<Path> isolatedClasspath = classPath.get().classpath; ImmutableList<Path> isolatedBootstrapClasspath = bootstrapClassPath.get().classpath; List<MerkleTreeNode> allNodes = new ArrayList<>(); allNodes.add(sharedFilesNode.get()); ImmutableList.Builder<UploadDataSupplier> requiredDataBuilder = ImmutableList.builder(); try (Scope ignored = PerfEvents.scope(eventBus, "constructing_inputs_tree")) { getSharedFilesData(requiredDataPredicate).forEach(requiredDataBuilder::add); allNodes.add( getSerializationTreeAndInputs(hash, requiredDataPredicate, requiredDataBuilder::add)); MerkleTreeNode inputsMerkleTree = resolveInputs(inputsMapBuilder.getInputs(rule)); allNodes.add(inputsMerkleTree); getFileInputs(inputsMerkleTree, requiredDataPredicate, requiredDataBuilder::add); outputs = new HashSet<>(); rule.deriveOutputs( path -> outputs.add( cellPathPrefix.relativize(rule.getProjectFilesystem().resolve(path)).getPath())); // The Buck client expects the METADATA_PATH to be written at the root of the cell of the rule // being built. METADATA_PATH is a relative path within the root of the cell; here we must // explicitly relativize it with the root of the cell. outputs.add( cellPathPrefix.relativize(rule.getProjectFilesystem().resolve(METADATA_PATH)).getPath()); } try (Scope ignored = PerfEvents.scope(eventBus, "constructing_action_info")) { ImmutableList<String> command = getBuilderCommand(projectRoot, hash.toString(), consoleParams); ImmutableSortedMap<String, String> commandEnvironment = getBuilderEnvironmentOverrides( isolatedBootstrapClasspath, isolatedClasspath, cellPathPrefix); Protocol.Command actionCommand = protocol.newCommand(command, commandEnvironment, outputs, workerRequirements); MerkleTreeNode mergedMerkleTree = nodeCache.mergeNodes(allNodes); nodeCache.forAllData( mergedMerkleTree, childData -> { if (requiredDataPredicate.test( childData.getDigest(), childData.getDirectory().toString())) { requiredDataBuilder.add( UploadDataSupplier.of( childData.getDirectory().toString(), childData.getDigest(), () -> new ByteArrayInputStream( protocol.toByteArray(childData.getDirectory())))); } }); NodeData data = nodeCache.getData(mergedMerkleTree); Digest inputsRootDigest = data.getDigest(); byte[] commandData = protocol.toByteArray(actionCommand); Digest commandDigest = protocol.computeDigest(commandData); requiredDataBuilder.add( UploadDataSupplier.of( "command", commandDigest, () -> new ByteArrayInputStream(commandData))); Protocol.Action action = protocol.newAction(commandDigest, inputsRootDigest); byte[] actionData = protocol.toByteArray(action); Digest actionDigest = protocol.computeDigest(actionData); requiredDataBuilder.add( UploadDataSupplier.of( "action", actionDigest, () -> new ByteArrayInputStream(actionData))); return RemoteExecutionActionInfo.of( actionDigest, requiredDataBuilder.build(), data.getTotalSize(), outputs); } } private void getFileInputs( MerkleTreeNode inputsMerkleTree, BiPredicate<Digest, String> requiredDataPredicate, Consumer<UploadDataSupplier> dataConsumer) { inputsMerkleTree.forAllFiles( (path, fileNode) -> { if (requiredDataPredicate.test(fileNode.getDigest(), path.toString())) { dataConsumer.accept( new UploadDataSupplier() { @Override public Digest getDigest() { return fileNode.getDigest(); } @Override public InputStream get() throws IOException { return new FileInputStream(cellPathPrefix.resolve(path).toFile()); } @Override public String describe() { try { HashCode hash = hasher.hashBytes(ByteStreams.toByteArray(get())); String description = String.format( "File (path:%s size:%s). Expected hash: [%s], Calculated hash: [%s]. Cached hash: [%s].", path, Files.size(cellPathPrefix.resolve(path).getPath()), getDigest().getHash(), hash.toString(), fileHasher.get(cellPathPrefix.resolve(path)).toString()); if (cellPathPrefix.resolve(path).getParent() != null) { AbsPath metaInfo = cellPathPrefix .resolve(path) .getParent() .resolve( path.getFileName().toString() + "." + FILE_HASH_VERIFICATION); if (Files.exists(metaInfo.getPath())) { description += String.format( " Meta Data Found: [%s]", String.join(",", Files.readAllLines(metaInfo.getPath()))); } } return description; } catch (IOException e) { LOG.warn(e, "Unable to describe file: " + path); return String.format( "failed to describe (path:%s error:%s)", path, e.getMessage()); } } }); } }); } private Stream<UploadDataSupplier> getSharedFilesData( BiPredicate<Digest, String> requiredDataPredicate) throws IOException { ImmutableList<RequiredFile> requiredFiles = sharedRequiredFiles.get(); return requiredFiles.stream() .map(requiredFile -> requiredFile.dataSupplier) .filter( dataSupplier -> requiredDataPredicate.test(dataSupplier.getDigest(), dataSupplier.describe())); } private final ConcurrentHashMap<Data, MerkleTreeNode> resolvedInputsCache = new ConcurrentHashMap<>(); private MerkleTreeNode resolveInputs(Data inputs) { MerkleTreeNode cached = resolvedInputsCache.get(inputs); if (cached != null) { return cached; } // Ensure the children are computed. inputs.getChildren().forEach(this::resolveInputs); return resolvedInputsCache.computeIfAbsent( inputs, ignored -> { try { Map<Path, FileNode> files = new HashMap<>(); Map<Path, DirectoryNode> emptyDirectories = new HashMap<>(); Map<Path, SymlinkNode> symlinks = new HashMap<>(); FileInputsAdder inputsAdder = new FileInputsAdder( new FileInputsAdder.AbstractDelegate() { @Override public void addFile(AbsPath path) throws IOException { for (GlobPatternMatcher matcher : ignorePaths) { if (matcher.matches(path.getPath())) { LOG.info("Ignoring input: " + path); return; } } files.put( cellPathPrefix.relativize(path).getPath(), protocol.newFileNode( protocol.newDigest( fileHasher.get(path).toString(), (int) Files.size(path.getPath())), path.getFileName().toString(), Files.isExecutable(path.getPath()))); } @Override public void addEmptyDirectory(AbsPath path) { DirectoryNode directoryNode = protocol.newDirectoryNode( path.getFileName().toString(), getEmptyDirectoryDigest()); emptyDirectories.put( cellPathPrefix.relativize(path).getPath(), directoryNode); } @Override public void addSymlink(AbsPath path, Path fixedTarget) { symlinks.put( cellPathPrefix.relativize(path).getPath(), protocol.newSymlinkNode(path.getFileName().toString(), fixedTarget)); } }, cellPathPrefix); for (SourcePath path : inputs.getPaths()) { inputsAdder.addInput(pathResolver.getAbsolutePath(path)); } List<MerkleTreeNode> nodes = new ArrayList<>(); nodes.add(nodeCache.createNode(files, symlinks, emptyDirectories)); inputs.getChildren().forEach(child -> nodes.add(resolveInputs(child))); return nodeCache.mergeNodes(nodes); } catch (IOException e) { throw new BuckUncheckedExecutionException(e); } }); } private Digest getEmptyDirectoryDigest() { return emptyDirectoryDigestMemoizer.get( () -> { Directory emptyDirectory = protocol.newDirectory(ImmutableList.of(), ImmutableList.of(), ImmutableList.of()); return protocol.computeDigest(emptyDirectory); }); } private static ImmutableList<Path> findPlugins() throws IOException { ImmutableList.Builder<Path> pathsBuilder = ImmutableList.builder(); try (Stream<Path> files = Files.walk(Paths.get(PLUGIN_ROOT))) { files.filter(Files::isRegularFile).forEach(pathsBuilder::add); } try (Stream<Path> files = Files.walk(Paths.get(PLUGIN_RESOURCES))) { files.filter(Files::isRegularFile).forEach(pathsBuilder::add); } return pathsBuilder.build(); } private RelPath getPrefixRelativeCellPath(CanonicalCellName name) { return cellPathPrefix.relativize(cellResolver.getNewCellPathResolver().getCellPath(name)); } private static byte[] serializeConfig(BuckConfig config, boolean sanitizeBuckConfig) { StringBuilder builder = new StringBuilder(); getBuckConfigFieldsForSerialization(config, sanitizeBuckConfig) .forEach( (key, value) -> { builder.append(String.format("[%s]\n", key)); value.forEach( (key1, value1) -> builder.append(String.format(" %s=%s\n", key1, value1))); }); return builder.toString().getBytes(StandardCharsets.UTF_8); } private static ImmutableMap<String, ImmutableMap<String, String>> getBuckConfigFieldsForSerialization(BuckConfig config, boolean sanitizeBuckConfig) { // TODO: remove the GK flag if (sanitizeBuckConfig || config.getBooleanValue( BUCK_CONFIG_EXPERIMENTS_SECTION_KEY, BUCK_CONFIG_FILTER_FIELDS_FOR_RE_FLAG_NAME, false)) { return config.prepareConfigForRE(); } return config.getConfig().getSectionToEntries(); } private String relativizePathString(AbsPath prefixRoot, String s) { if (s == null || s.length() == 0) { return ""; } Path path = Paths.get(s); return path.isAbsolute() ? prefixRoot.relativize(path).toString() : path.toString(); } private ImmutableSortedMap<String, String> getBuilderEnvironmentOverrides( ImmutableList<Path> bootstrapClasspath, Iterable<Path> classpath, AbsPath cellPrefixRoot) { // TODO(shivanker): Pass all user environment overrides to remote workers. String relativePluginRoot = relativizePathString(cellPrefixRoot, PLUGIN_ROOT); String relativePluginResources = relativizePathString(cellPrefixRoot, PLUGIN_RESOURCES); return ImmutableSortedMap.<String, String>naturalOrder() .put("CLASSPATH", classpathArg(bootstrapClasspath)) .put("BUCK_CLASSPATH", classpathArg(classpath)) .put( "EXTRA_JAVA_ARGS", ManagementFactory.getRuntimeMXBean().getInputArguments().stream() .filter(ModernBuildRuleRemoteExecutionHelper::isValidJVMArgument) .collect(Collectors.joining(" "))) .put("BUCK_JAVA_VERSION", String.valueOf(JavaVersion.getMajorVersion())) .put("BUCK_PLUGIN_ROOT", relativePluginRoot) .put("BASE_BUCK_OUT_DIR", BASE_BUCK_OUT_DIR) .put("BUCK_PLUGIN_RESOURCES", relativePluginResources) // TODO(cjhopman): This shouldn't be done here, it's not a Buck thing. .put("BUCK_DISTCC", "0") .build(); } private static boolean isValidJVMArgument(String arg) { return arg.startsWith("--illegal-access") || arg.startsWith("--add-opens") || arg.startsWith("--add-exports"); } private static ImmutableList<String> getBuilderCommand( RelPath projectRoot, String hash, ConsoleParams consoleParams) { String rootString = projectRoot.toString(); if (rootString.isEmpty()) { rootString = "./"; } return ImmutableList.of( "./" + TRAMPOLINE_PATH.toString(), rootString, hash, METADATA_PATH.toString(), consoleParams.isAnsiEscapeSequencesEnabled(), consoleParams.getVerbosity()); } private static class Node implements Comparable<Node> { private final AddsToRuleKey instance; private final String hash; private final ImmutableSortedSet<Node> children; private final int dataLength; // We hold the serialized form of the instance in memory only until it is uploaded once. There // might be multiple different rules that reference this that all get scheduled at the same time // and so there's some races in uploading such that all of the rules might need to get a // reference to the serialized data but then only one will actually be uploaded. To handle this, // we hold a strong ref to the data until it is first requested, then we hold a WeakReference to // it. This means that if multiple concurrent rules request it, we'll still have the weak // reference around to give them. // There are a few edge cases where we will still need the data after that point: (1) if the // first upload fails (2) if our blob uploader becomes aware of TTLs such that for very long // builds it may upload the same thing multiple times. To support this, we reserialize the // instance if its requested when we no longer hold any reference to the original serialized // value. @Nullable private volatile byte[] data; private WeakReference<byte[]> dataRef; Node( AddsToRuleKey instance, @Nullable byte[] data, HashCode hash, ImmutableSortedSet<Node> children) { this.instance = instance; this.data = data; this.dataRef = new WeakReference<>(data); this.dataLength = data.length; this.hash = hash.toString(); this.children = children; } public byte[] acquireData(Serializer serializer, HashFunction hasher) throws IOException { // We should only ever need the data once. byte[] current = dataRef.get(); if (current != null) { dropData(); return current; } byte[] reserialized = serializer.reserialize(instance); HashCode recomputedHash = hasher.hashBytes(reserialized); Verify.verify(recomputedHash.toString().equals(hash)); this.dataRef = new WeakReference<>(reserialized); return reserialized; } @Override public int compareTo(Node other) { return hash.compareTo(other.hash); } public void dropData() { this.data = null; } } private MerkleTreeNode getSerializationTreeAndInputs( HashCode hash, BiPredicate<Digest, String> requiredDataPredicate, Consumer<UploadDataSupplier> dataBuilder) throws IOException { Map<Path, FileNode> fileNodes = new HashMap<>(); class DataAdder { void addData(Path root, Node node) throws IOException { String fileName = "__value__"; Path valuePath = root.resolve(node.hash).resolve(fileName); Digest digest = protocol.newDigest(node.hash, node.dataLength); fileNodes.put(valuePath, protocol.newFileNode(digest, fileName, false)); if (!requiredDataPredicate.test(digest, node.instance.getClass().getName())) { node.dropData(); } else { byte[] data = node.acquireData(serializer, hasher); dataBuilder.accept( new UploadDataSupplier() { @Override public InputStream get() { return new ByteArrayInputStream(data); } @Override public Digest getDigest() { return digest; } @Override public String describe() { return String.format( "Serialized java object (class:%s, size:%s).", node.instance.getClass().getName(), node.dataLength); } }); } for (Node value : node.children) { addData(root, value); } } } new DataAdder().addData(Paths.get("__data__"), Objects.requireNonNull(nodeMap.get(hash))); return nodeCache.createNode(fileNodes, ImmutableMap.of(), ImmutableMap.of()); } private ThrowingSupplier<ClassPath, IOException> prepareClassPath( ThrowingSupplier<ImmutableList<Path>, IOException> classpath) { return MoreSuppliers.memoize( () -> { ImmutableList.Builder<Path> pathsBuilder = ImmutableList.builder(); ImmutableList.Builder<RequiredFile> filesBuilder = ImmutableList.builder(); for (Path path : classpath.get()) { if (path.startsWith(cellPathPrefix.getPath())) { RelPath relative = cellPathPrefix.relativize(path); pathsBuilder.add(relative.getPath()); byte[] data = Files.readAllBytes(path); Digest digest = protocol.computeDigest(data); filesBuilder.add( new RequiredFile( relative, protocol.newFileNode(digest, path.getFileName().toString(), false), UploadDataSupplier.of( path.getFileName().toString(), digest, () -> new FileInputStream(path.toFile())))); } else { pathsBuilder.add(path); } } return new ClassPath(filesBuilder.build(), pathsBuilder.build()); }, IOException.class); } private static String classpathArg(Iterable<Path> classpath) { return Joiner.on(File.pathSeparator).join(classpath); } }
JoelMarcey/buck
src/com/facebook/buck/rules/modern/builders/ModernBuildRuleRemoteExecutionHelper.java
Java
apache-2.0
36,277
# Dahlstedtia Malme GENUS #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Dahlstedtia/README.md
Markdown
apache-2.0
173
package uk.co.mmckenzie.visual; import java.util.ArrayList; import javafx.fxml.FXML; import javafx.scene.control.TabPane; public class MainController implements Controller { private static ArrayList<Controller> allControllers = new ArrayList<>(); @FXML private TabPane tabPane; @FXML private void initialize() { } @Override public void update() { for (Controller c: MainController.allControllers) { c.update(); } } public static void addListener(Controller c) { MainController.allControllers.add(c); } public static boolean removeListener(Controller c) { return MainController.allControllers.remove(c); } }
mmckenzie70/visual
src/main/java/uk/co/mmckenzie/visual/MainController.java
Java
apache-2.0
687
/* Document : metamorphosis Created on : 13-Mar-2011, 1:34:28 PM Author : agdarby Description: One of the backgrounds for SubjectdPlus */ body { background: url(../../images/admin/bug_bg.jpg) repeat; }
lalvarezcu/subjectsplus
assets/css/theme/metamorphosis.css
CSS
apache-2.0
232
<nav> <div class="nav-left text-light"><a href='/'>YRM<span class='faded'>2015</span></a></div> <div class="nav-right"> <ul> <li><a href="schedule">Schedule</a></li> <li><a href="location">Location</a></li> <li><a href="speakers">Speakers</a></li> <li id='nav-more'><a href="#more">More&nbsp;&nbsp;<i class="fa fa-navicon faded"></i></a></li> <li><a href="register"><button class='register'>Register</button></a></li> </ul> </div> </nav>
robcalcroft/YRM2015
src/nav.transparent.html
HTML
apache-2.0
459
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Utils::Collector =head1 SYNOPSIS # Inherit this base module in your feature specific Collector # instance: package Bio::EnsEMBL::Funcgen::Collector::ResultFeature; use base('Bio::EnsEMBL::Utils::Collector'); # ... and define package config variables $Bio::EnsEMBL::Funcgen::Collector::bin_model = 'SIMPLE'; $Bio::EnsEMBL::Funcgen::Collector::window_sizes = [ 30, 65, 130, 260, 450, 648, 950, 1296 ]; # Could replace 30 with 0 here for low density data at natural resolution $Bio::EnsEMBL::Utils::Collector::bin_method = 'count'; # only used by collector $Bio::EnsEMBL::Utils::Collector::packed_size = 2; # ... or simply use this module in a script either defining package # config variables, or passing as parameters to the constructor: my $collector = Bio::EnsEMBL::Utils::BaseCollector->new( -pack_template => 'v' ); $Bio::EnsEMBL::Funcgen::Collector::pack_template = 'v'; # Config variables can also be over-ridden by passing a config hash to # the store_window_bins_by_Slice() method: $collector->store_window_bins_by_Slice( $slice, ( -pack_template => 'v', -packed_size => 2 ) ); # NOTE: Over-riding default config variables can cause problems when # storing or fetching data. e.g. Fetch may revert to using defaults or # table partitions may not match window sizes. =head1 DESCRIPTION This package is the base Collector class which contains generic getter/setter methods along with the main 'collecting' methods which perform the majority of the work in generating compressed data collections optimised for web display. The bins produced are aimed at storage in a BLOB representing an entire seq_region i.e. even bins with no features/null data are encoded as a 0 score. Non-BLOB collections are currently not supported. If your Collection class defines a Bio::EnsEMBL::Feature, then its adaptor should inherit from the relevant Collection class. The minimum prerequisites of the input features/data are that they have a start() and end() method. For instance a Bio::EnsEMBL::Features generated from a database or parsed from a flat file. NOTE: This Collector does not have a lightweight mode previously used for dynamic/on the fly collecting i.e. it does not take advantage of bypassing object creation via the related BaseFeatureAdaptor method. =cut package Bio::EnsEMBL::Utils::Collector; use strict; use warnings; use Bio::EnsEMBL::Utils::Argument ('rearrange'); use Bio::EnsEMBL::Utils::Exception ('throw', 'deprecate'); ### Global package config vars # Defaults our $max_view_width = 1000000; # Max bp width in location/detailed view our $max_data_type_size = 16777216; # Default is 16MB for long BLOB # This is really a guide value as this should be set in the inheriting # Collector class by deducting the rest of the row size from this value. # Is is upto the inheritor to handle checking whether this size has been # exceeded. # NOTE: Theoretically the min window size is: slice_length/(16777216/2) # So for human chr1: 249,250,621/(16777216/2) = 29.7 => 30. However, # this size does not seem to directly translate to the MySQL # max_allowed_packet_size. Increasing max_allowed_packet_size to 64MB # solves this issue, and substr operation doesn't appear to incur any of # the potential memory(4*) usage issues. # Others global package variables which are set in the inheriting # Collector class. our ( $bin_model, $bin_method, $pack_template, $packed_size, $window_sizes ); =head2 new Deprecated. Args : None Example : my $collector = Bio::EnsEMBL::XXX::Collector::FEATURE->new(); $collector->store_windows_by_Slice($slice); # Where XXX is, e.g. Compara, FuncGen etc. Description: Simple new method to enable use of collector when not inherited by a descendant of Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor Returntype : Bio::EnsEMBL::XXX::Collector Exceptions : None Caller : Collector script Status : At Risk =cut sub new { deprecate("new is deprecated and will be removed in e100."); return bless {}, $_[0]; # Simply blesses this class as an empty hash. # Do not set anything here, as will not be first in ISA for # FeatureAdaptors. Hence, not guaranteed to be called. } =head2 new_assembly Deprecated. Args : optional - string assembly version e.g. GRCh37 Example : $collector->new_assembly('GRCh37'); Description: Getter/Setter for new assembly version which should be used to project only 0 wsize Collections. Returntype : string Exceptions : None Caller : store_window_bins_by_Slice() or write_collection() in inheriting Collector class. Status : At Risk =cut sub new_assembly { my ( $self, $new_asm ) = @_; deprecate("new_assembly is deprecated and will be removed in e100."); if ( defined($new_asm) ) { $self->{'new_assembly'} = $new_asm; } return $self->{'new_assembly'}; } ### Setter/Getter methods for basic/mandatory config # Can also be set using package variables in the inheriting # Collector/Adaptor or run script. Allows over-riding of defaults set # in Adaptor/Collector. # Package variables used here instead of attrs to enable easy # default config in inheriting class/script method. Provided # for easy/standardised fetch access outside of this package # i.e. Collectors/Adaptors =head2 max_data_type_size Deprecated. Args : optional - int Maximum size of collection in bytes Example : $collector->max_data_type_size($new_max_size); Description: Getter/Setter for max_data_type_size, default is currently set at in this class as 16777216 (16MB), for long BLOB. This is used by the write_collection() method to determine when to build and store a compressed collection. Returntype : int Exceptions : None Caller : bins_per_record() and write_collection() in inheriting Collector class. Status : At Risk =cut sub max_data_type_size { my ( $self, $size ) = @_; deprecate("max_data_type_size is deprecated and will be removed in e100."); # Validate is sensible integer if ( defined($size) ) { if ( $size !~ /^\d+$/ ) { throw("max_data_type_size must be a integer of bytes, not $size"); } $max_data_type_size = $size; } elsif ( !defined($max_data_type_size) ) { # This should never happen as we have defaults in this module. throw( 'You must define a ' . '$Bio::EnsEMBL::Utils::Collector::max_data_type_size ' . 'or pass -max_data_type_size config' ); } return $max_data_type_size; } =head2 max_view_width Deprecated. Args : optional - int Maximum width of view Example : $collector->max_view_width($new_max_width); Description: Getter/Setter for max_view_width, default is currently set at in this class as 500000bp, for maximum level of zoom permitted by location view. Returntype : int Exceptions : None Caller : general Status : At Risk =cut sub max_view_width { my ( $self, $size ) = @_; deprecate("max_data_type_size is deprecated and will be removed in e100."); # Validate is sensible integer if ( defined($size) ) { if ( $size !~ /^\d+$/ ) { throw("max_view_width must be a integer, not $size"); } $max_view_width = $size; } elsif ( !defined $max_view_width ) { # This should never happen as we have defaults in this module. throw( 'You must define a ' . '$Bio::EnsEMBL::Utils::Collector::max_view_width ' . 'or pass -max_view_width config' ); } return $max_view_width; } =head2 bin_method Deprecated. Args[0] : optional - string name of bin method e.g. 'max_magnitude' Args[1] : optional - Bio::EnsEMBL::Funcgen::Parsers::InputSet Example : my $bin_method = $self->bin_method(); Description: Getter/Setter for bin_method, default is normally set in the inheriting Collector class either by package variable or by passing a config hash via the store methods. Returntype : string Exceptions : Throws if cannot set by package variable Caller : general Status : At Risk =cut sub bin_method { my ( $self, $bmethod, $config ) = @_; deprecate("bin_method is deprecated and will be removed in e100."); if ( defined($bmethod) ) { $bin_method = $bmethod; } if ( !defined($bin_method) ) { throw( 'You must define a ' . '$Bio::EnsEMBL::Utils::Collector::bin_method ' . 'or pass -bin_method config' ); } if ( !$self->can( "_calculate_" . $bin_method ) ) { throw("$bin_method is not a valid/available binning method"); } my $set_up_method = "_set_up_" . $bin_method; if ( $self->can($set_up_method) ) { $self->$set_up_method($config); } return $bin_method; } =head2 bin_model Deprecated. Args : optional - string bin model e.g. SIMPLE or COMPLEX Example : my $bin_model = $self->bin_model; Description: Getter/Setter for bin_model, default should be set in inheriting Collector class. Currently only supports 'SIMPLE' bin model. Returntype : string Exceptions : Throws if bin_model is not SIMPLE Caller : general Status : At Risk =cut sub bin_model { my ( $self, $bmodel ) = @_; deprecate("bin_model is deprecated and will be removed in e100."); if ( defined($bmodel) ) { $bin_model = $bmodel; } if ( !defined($bin_model) ) { throw( 'You must define a ' . '$Bio::EnsEMBL::Utils::Collector::bin_model ' . 'or pass -bin_model config' ); } if ( $bin_model ne 'SIMPLE' ) { throw( 'Bio::EnsEMBL::Utils::Collector does not yet support ' . 'non-SIMPLE bin models' ); } return $bin_model; } =head2 window_sizes Deprecated. Args : optional - arrayref of window sizes Example : foreach my $wsize ( @{ $collector->window_sizes } ) { # Do some collecting } Description: Getter/Setter for window_sizes. Default should be set in inheriting Collector (if the config is dynamic), FeatureAdaptor class or script using package variable or this method. NOTE: Redefining these may cause a mismatch with the table partition definition. Returntype : arrayref of ints Exceptions : Throws if cannot set a valid array of int window sizes Caller : general Status : At Risk - rename bin_sizes? =cut sub window_sizes { my ( $self, $sizes ) = @_; deprecate("window_sizes is deprecated and will be removed in e100."); if ( defined($sizes) ) { $window_sizes = $sizes; } if ( !( ref($window_sizes) && ( ref($window_sizes) eq 'ARRAY' ) && ( scalar(@$window_sizes) > 0 ) ) ) { throw('Must pass -windows_sizes in the config ' . 'or define $Bio::EnsEMBL::Utils::Collector::window_sizes ' . 'in your Collector as an array ref of integer window_sizes' ); } return $window_sizes; } =head2 has_window_size Deprecated. Args : int - window size to validate Example : if( $collector->has_window_size('30') ){ #Do something wrt to 30bp window size } Description: Simple utility method to validate whether this Collector has a given window_size Returntype : Boolean Exceptions : Throws if window size not specified Caller : general Status : At Risk =cut sub has_window_size{ my ( $self, $size ) = @_; deprecate("has_window_size is deprecated and will be removed in e100."); if(! defined $size){ throw('You must pass a window size to validate'); } return grep(/$size/, @$window_sizes); } ### Getter/Setters for BLOB collection config # NOTE: Overriding the defaults here may cause a mismatch when the data # is retrieved. =head2 pack_template Deprecated. Args : optional - string perl 'pack' template Example : $self->pack_template('v'); Description: Getter/Setter for pack_template. Default should be set in inheriting Collector (if the config is dynamic), FeatureAdaptor class or script using package variable or this method. Returntype : string Exceptions : Throws if cannot set pack_template from package variable Caller : FeatureAdaptor::_obj_from_sth Status : At Risk =cut sub pack_template { my ( $self, $template ) = @_; deprecate("pack_template is deprecated and will be removed in e100."); if ( defined($template) ) { $pack_template = $template; } if ( !defined($pack_template) ) { throw( 'Must pass a per score ' . '-pack_template in the config ' . 'or define $Bio::EnsEMBL::Utils::Collector::pack_template ' . 'in your Collector' ); } return $pack_template; } =head2 packed_size Deprecated. Args : optional - int size of perl 'pack' template in bytes Example : $self->packed_size(2); Description: Getter/Setter for packed_size. Default should be set in inheriting Collector (if the config is dynamic), FeatureAdaptor class or script using package variable or this method. Returntype : string Exceptions : Throws if cannot set pack_template from pacakge variable Caller : current_packed_size() and FeatureAdaptor::_obj_from_sth() Status : At Risk =cut sub packed_size { my ( $self, $size ) = @_; deprecate("packed_size is deprecated and will be removed in e100."); if ( defined($size) ) { $packed_size = $size; } if ( !defined($packed_size) ) { throw( 'Must pass -packed_size(wrt to pack_template) config ' . 'or define $Bio::EnsEMBL::Utils::Collector::packed_size ' . 'in your Collector' ); } if ( $packed_size !~ /^\d+$/ ) { throw( "$packed_size is not an integer, " . "must pass a size integer for packed_size " . "which specifies size of pack_template:\t" . $pack_template ); } return $packed_size; } =head2 bins_per_record Deprecated. Example : my $bin_per_records = $self->bin_per_record Description: Simple method to calculate the max number of bins allowed per record given the current config. Returntype : int Exceptions : None Caller : Status : At Risk =cut sub bins_per_record { deprecate("bins_per_record is deprecated and will be removed in e100."); return int( $max_data_type_size/$packed_size ); } =head2 current_packed_size Deprecated. Arg[0] : int - window size Example : my $cps = $self->current_packed_size($wsize); Description: Simple method to calculate the max number of bins allowed per record given the current config. Returntype : int Exceptions : None Caller : Status : At Risk =cut sub current_packed_size { my ( $self, $wsize ) = @_; deprecate("current_packed_size is deprecated and will be removed in e100."); return ( scalar( @{ $self->score_cache($wsize) } )*$packed_size ); } =head2 score_cache Deprecated. Arg[0] : int - window size Example : my $cps = $self->current_packed_size($wsize); Description: Handles caching of bin scores for each window size Returntype : arrayref Exceptions : Throws if no window size defined Caller : current_packed_size() and store_collection() methods Status : At Risk =cut sub score_cache { my ( $self, $wsize, $scores ) = @_; deprecate("score_cache is deprecated and will be removed in e100."); if ( !defined($wsize) ) { throw('Must pass a window size argument'); } $self->{'score_cache'}{$wsize} ||= []; if ( defined($scores) ) { push( @{ $self->{'score_cache'}{$wsize} }, @{$scores} ); } return $self->{'score_cache'}{$wsize}; } =head2 collection_start Deprecated. Arg[0] : int - window_size Arg[1] : optional int - seq_region_start Example : my $coll_start->(150); Description: Getter/Setter collection seq_region_start Returntype : int Exceptions : Throws if no window size defined Caller : store_window_bin_by_Slice() and write_collection() Status : At Risk =cut sub collection_start { my ( $self, $wsize, $sr_start ) = @_; deprecate("collection_start is deprecated and will be removed in e100."); if ( !defined($wsize) ) { throw('Must pass a window size argument'); } if ( defined($sr_start) ) { $self->{'collection_start'}{$wsize} = $sr_start; } return $self->{'collection_start'}{$wsize}; } =head2 collection_end Deprecated. Arg[0] : int - window_size Arg[1] : optional int - seq_region_end Example : my $coll_end->(150); Description: Getter/Setter collection seq_region_end Returntype : int Exceptions : Throws if no window size defined Caller : inheriting Collector write_collection method Status : At Risk =cut sub collection_end{ my ($self, $wsize, $sr_end) = @_; deprecate("collection_end is deprecated and will be removed in e100."); throw('Must pass a window size argument') if ! defined $wsize; if(defined $sr_end){ $self->{'collection_end'}{$wsize} = $sr_end; } else{ return $self->{'collection_end'}{$wsize}; } } =head2 collection_strand Deprecated. Arg[0] : int - window_size Arg[1] : optional int - seq_region_strand Example : my $coll_start->(0); Description: Getter/Setter collection seq_region_strand Returntype : int Exceptions : Throws if no window size defined Caller : inheriting Collector write_collection method Status : At Risk - Collections are currently strandless =cut sub collection_strand { my ( $self, $wsize, $strand ) = @_; deprecate("collection_strand is deprecated and will be removed in e100."); if ( !defined($wsize) ) { throw('Must pass a window size argument'); } if ( defined $strand ) { $self->{'collection_strand'}{$wsize} = $strand; } return $self->{'collection_strand'}{$wsize}; } ### Here follows the actual working methods =head2 _get_Slice_chunks Deprecated. Description: Defines the optimal set of slice chunks to use for generating collections such that redundant fetches are minimized. Returntype : hashref of window_size chunk size pairs Exceptions : Throws if no window sizes or max_view_width defined Caller : store_window_bin_by_Slice() Status : At Risk =cut sub _get_Slice_chunks { my $self = shift; deprecate("_get_Slice_chunks is deprecated and will be removed in e100."); if ( !defined($window_sizes) || !defined($max_view_width) ) { throw( 'You must pass both a window_size array ref ' . 'and max_view_width arguments' ); } if ( !defined( $self->{'_slice_chunks'} ) ) { # Calulate sensible slice length based on window sizes my @wsizes = sort { $a <=> $b } @$window_sizes; # Handle calculating only 0 wsize if ( scalar(@wsizes) == 1 && $wsizes[0] == 0 ) { return { $max_view_width => [0] }; } my $multiplier = int( $max_view_width/$wsizes[$#wsizes] ); my $chunk_length = $multiplier*$wsizes[$#wsizes]; my $not_divisible = 1; my %chunk_windows; # Registry of chunk lengths to run with windows my %workable_chunks = map { $_ => {} } @wsizes; # get rid of natural resolution as this will always work delete $workable_chunks{'0'}; while ( $not_divisible && $chunk_length != 0 ) { $not_divisible = 0; foreach my $wsize (@wsizes) { if ( $wsize == 0 ) { # Special wsize for normal data next; } # Set not divisible if modulus is true if ( $chunk_length % $wsize ) { $not_divisible = 1; } else { $workable_chunks{$wsize}{$chunk_length} = []; } } # Gradually shrink the length until we find a workable slice # length for all windows. if ($not_divisible) { $chunk_length -= $wsizes[$#wsizes]; } } my %chunk_sets; if ( $chunk_length == 0 ) { print "Could not find chunk length " . "for all window sizes, " . "attempting to subset windows " . "using alternate slice length\n"; foreach my $wsize ( keys(%workable_chunks) ) { # Loop through windows, seeing if they are workable in the other # windows. foreach my $chunk ( keys( %{ $workable_chunks{$wsize} } ) ) { foreach my $other_wsize ( keys %workable_chunks ) { next if $wsize == $other_wsize; if ( exists( $workable_chunks{$other_wsize}{$chunk} ) ) { # only push it onto the other wsize, as we will do the # reverse later $chunk_sets{$chunk}{$wsize} = undef; } } } } # %chunk_sets represents co-occurence of wsizes with repect to # chunks. Take the set which has the most windows and the longest # chunk. Then get the largest which handles the rest. # define possible set lengths my $i = 0; my %set_lengths; map { $set_lengths{$i} = []; $i++ } @wsizes; # get rid of natural resolution as this will always work delete $set_lengths{'0'}; # Store chunks lengths for each set size foreach my $chunk ( keys(%chunk_sets) ) { my $set_size = scalar( values( %{ $chunk_sets{$chunk} } ) ); push( @{ $set_lengths{$set_size} }, $chunk ); } # Get the biggest set with the longest length; # Scalar here as we are disregarding natural resolution of 0 in # loop. my $largest_size = scalar(@wsizes); my $found_largest_set = 0; while ( !$found_largest_set ) { $largest_size--; if ( scalar( @{ $set_lengths{$largest_size} } ) > 0 ) { $found_largest_set = 1; } } my ($largest_chunk) = sort { $b <=> $a } @{ $set_lengths{$largest_size} }; my @largest_windows = keys %{ $chunk_sets{$largest_chunk} }; @{ $chunk_windows{$largest_chunk} } = @largest_windows; print "Largest chunk $largest_chunk($largest_size) " . "contains windows: @largest_windows\n"; my %remaining_windows = map { $_ => {} } @wsizes; # get rid of natural resolution as this will always work delete $remaining_windows{'0'}; map { delete $remaining_windows{$_} } @largest_windows; my $remaining_set_size = scalar( keys(%remaining_windows) ); # Use array here for practicality, would need to maintain hash if # we need to iterate. my @rwindows = keys(%remaining_windows); # Could be one window, but this will not be in the co-occurence # hash %chunk_sets. my $next_chunk; if ( scalar(@rwindows) == 1 ) { my ($last_window) = @rwindows; # Find a suitably large chunk for this one window. $multiplier = int( 500000/$last_window ); $next_chunk = $multiplier*$last_window; } else { foreach my $chunk ( sort { $b <=> $a } @{ $set_lengths{$remaining_set_size} } ) { my $seen_count = 0; foreach my $rwindow (@rwindows) { if ( grep /$rwindow/, ( values( %{ $chunk_sets{$chunk} } ) ) ) { $seen_count++; } } if ( $seen_count == $remaining_set_size ) { $next_chunk = $chunk; last; } } } @{ $chunk_windows{$next_chunk} } = @rwindows; if ( defined($next_chunk) ) { print "Found next chunk length $next_chunk " . "contains remaining windows:\t@rwindows\n"; } else { warn "Need to write iterative method for set definition"; throw( 'Could not find workable slice length ' . 'for remaining windows: ' . join( ', ', @rwindows ) ); } } else { @{ $chunk_windows{$chunk_length} } = keys(%workable_chunks); print "Found workable chunk length $chunk_length " . "for all window sizes:\t" . join( ' ', @{ $chunk_windows{$chunk_length} } ) . "\n"; } $self->{'_slice_chunks'} = \%chunk_windows; } ## end if ( !defined( $self->...)) return $self->{'_slice_chunks'}; } ## end sub _get_Slice_chunks =head2 set_config Deprecated. Arg[0] : optional hash - parameter hash(see above methods for more info): WINDOW_SIZES => array ref - subset of defined window sizes BIN_METHOD => string MAX_VIEW_WIDTH => int MAX_DATA_TYPE_SIZE => int PACK_TEMPLATE => string PACKED_SIZE => int BIN_MODEL => string NEW_ASSEMBLY => string METHOD_CONFIG => hash of method specific config params SKIP_ZERO_WINDOW => boolean - skips generation of 0 wsize this is used if already generated from an assembly projection. NOTE: Over-riding any of the default config may cause problems when storing or retrieving Collection data, except sub sets of default window sizes. Description: This method replaces the constructor as new will not be called for Adaptor based Collectors. Separating this from the store method is currently redundant as jobs are normally submitetd in Slice based jobs. However, this will be required if the store method is further seaprated into fetch/generate and store methods Returntype : None Exceptions : Throws if no window sizes or max_view_width defined Caller : Inheritor Collector e.g. Bio::EnsEMBL::Funcgen:Collector::ResultFeature or script. Status : At Risk =cut sub set_config { my ( $self, %config ) = @_; deprecate("set_config is deprecated and will be removed in e100."); my ( $wsizes, $bmethod, $mv_width, $md_type_size, $template, $psize, $bmodel, $new_assm, $skip_zero_window, $method_config ) = rearrange( [ 'WINDOW_SIZES', 'BIN_METHOD', 'MAX_VIEW_WIDTH', 'MAX_DATA_TYPE_SIZE', 'PACK_TEMPLATE', 'PACKED_SIZE', 'BIN_MODEL', 'NEW_ASSEMBLY', 'SKIP_ZERO_WINDOW', 'METHOD_CONFIG' ], %config ); ### VAILDATE/SET VARS/CONFIG # Attrs used in this method $self->bin_method( $bmethod, $method_config ); $self->bin_model($bmodel); $self->window_sizes($wsizes); # Set to undef if we have empty array? To change this we need to # pass the config hash -window_sizes conditionally # This currently overwrite the defaults! # if ( ref($window_sizes) eq 'ARRAY' # && scalar( @{$window_sizes} ) == 0 ) # { # $window_sizes = undef; # } # Attrs used in other (store) methods $self->pack_template($template); $self->packed_size($psize); $self->max_data_type_size($md_type_size); $self->max_view_width($mv_width); # Other vars $self->new_assembly($new_assm); $self->{'_only_natural'} = 0; $self->{'_store_natural'} = grep /^0$/, @$window_sizes; ### Set window_sizes if ( $self->new_assembly() ) { print "Assembly projection may cause problems " . "for large Collections, " . "defaulting to window_sizes = (0)\n"; if ( $skip_zero_window ) { throw( "You cannot -skip_zero_window or " . "omit 0 from -window_sizes " . "when projecting to a new assembly($new_assm) " . "which should only be generated using window_size=0" ); } # Then build the bins on the projected 0 level single Features # Test we haven't explicity set window_sizes to be something else if ( defined($wsizes) && !( scalar(@$wsizes) == 1 && $wsizes->[0] == 0 ) ) { throw( "You have set window_sizes config " . "which are not safe when projecting to " . "a new assembly($new_assm), " . "please omit window_sizes config or set to 0" ); } $self->window_sizes( [0] ); } else { if ( $wsizes && $skip_zero_window && ( grep /^0$/, @$wsizes )) { #Only test passed params not default config throw( "You have specied skip_zero_window " . "and window_size 0 in your parameters, " . "please remove one of these" ); } elsif ( defined($window_sizes) && !grep /^0$/, @$window_sizes ) { $skip_zero_window = 1; # re-add 0 window as we need this to build the collections # see ... unshift( @{$window_sizes}, 0 ); } } if ( $self->{'_store_natural'} && scalar( @{$window_sizes} ) == 1 ) { $self->{'_only_natural'} = 1; } if ($skip_zero_window) { $self->{'_store_natural'} = 0; } return; } ## end sub set_config =head2 store_window_bins_by_Slice Deprecated. Arg[0] : Bio::EnsEMBL:Slice Example : $collector->store_window_bins_by_Slice($slice); Description: This is the main run method, it loops through optimal slice chunks from _define_window_chunks, calls _bin_features_by_Slice as appropriate and calls write_collection in the inheriting Collector class/script. Returntype : None Exceptions : Throws if Bio::EnsEMBL::Slice is not defined Caller : store methods in inheriting Collector class/script Status : At Risk =cut sub store_window_bins_by_Slice { my ( $self, $slice ) = @_; deprecate("store_window_bins_by_Slice is deprecated and will be removed in e100."); warn "Need to be careful here " . "about cleaning start end strand caches between " . "serially run slices"; if ( !( defined($slice) && ref($slice) && $slice->isa('Bio::EnsEMBL::Slice') ) ) { throw('You must pass a valid Bio::EnsEMBL::Slice'); } # Rollback previously stored features. # Change 'can' to empty method stubb with pod ??? if ( $self->can('rollback_Features_by_Slice') ) { $self->rollback_Features_by_Slice($slice); } else { warn ref($self) . " cannot rollback_Features_by_Slice. " . "This may result in storage failure " . "or duplicate Collections if there is pre-existing data"; } ### PROCESS CHUNKS my %chunk_windows = %{ $self->_get_Slice_chunks }; my (%counts); my $store_natural = $self->{'_store_natural'}; my $only_natural = $self->{'_only_natural'}; $counts{0} = 0; # Set natural res count to 0 my $slice_end = $slice->end; my $orig_start = $slice->start; my $region = $slice->coord_system_name; my $version = $slice->coord_system->version; my $seq_region_name = $slice->seq_region_name; my $strand = $slice->strand; # Warn if this is not a full slice. Version needed in case we are # projecting from a non-default version slice my $full_slice = $slice->adaptor->fetch_by_region( $region, $seq_region_name, undef, undef, undef, $version ); if ( ( $full_slice->start() != $orig_start ) || ( $full_slice->end() != $slice_end ) ) { warn "Generating collections using sub-Slices " . "can result in data issues/artifacts"; # Last chunk might not be the correct window length. Test # slices less than chunk length can cause failures in # _bin_features_by_window_sizes others? } # Set the initial collection_start to orig_start. This is not the # case for 0 wsize where it must always be the true feature start. for my $wsize (@$window_sizes) { if ( $wsize == 0 ) { next } $self->collection_start( $wsize, $orig_start ); # Also reset collection end and score cache in case we are running # serially. $self->{collection_end}{$wsize} = undef; $self->{'score_cache'}{$wsize} = []; } my $first_chunk_length = 1; foreach my $chunk_length ( sort keys %chunk_windows ) { print "Processing windows " . join( ', ', @{ $chunk_windows{$chunk_length} } ) . " with chunk length $chunk_length\n"; # Set window counts to 0 map $counts{$_} = 0, @{ $chunk_windows{$chunk_length} }; # May need to reset flat file parser handle or other caches via # inheriting Collector if ( !$first_chunk_length ) { # Change 'can' to empty method stubb with pod??? if ( $self->can('reinitialise_input') ) { $self->reinitialise_input(); } } $first_chunk_length = 0; # Now walk through slice using slice length chunks and build all # windows in each chunk. my $in_slice = 1; my $start_adj = 0; my ( $sub_slice, $sub_end, $features, $bins ); my $sub_start = 1; my $slice_length = $slice->length(); # Always create in local coords for fetch # Then change to seq_region coords for store if required while ($in_slice) { $sub_start += $start_adj; $sub_end = $sub_start + $chunk_length - 1; if ( $sub_end >= $slice_length ) { # Surplus bins are removed in store/write_collection in caller $in_slice = 0; } $sub_slice = $slice->adaptor->fetch_by_region( $region, $seq_region_name, $sub_start + $orig_start - 1, $sub_end + $orig_start - 1, $strand, $version ); # Can't subslice as this will not clip if we go over the length of # the slice, unlike normal slice fetching. Will clipping the end # to the slice end cause any problems here? How will this affect # bin clipping? ### Grab features and shift chunk coords $features = $self->get_Features_by_Slice($sub_slice); # warn "Binning " # . scalar(@$features) # . " Features for chunk length $chunk_length, on Slice " # . $sub_slice->name; if ( ( @{$features} ) && ref( $features->[0] ) =~ /Bio::EnsEMBL::Utils::Collection/ ) { # Would need to create base module with generic methods: # window_size, ... # Check that the returned feature/collections support window_size. # All Collections should be able to if ( $features->[0]->can('window_size') ) { if ( $features->[0]->window_size != 0 ) { throw( "You are trying to generated Collections from " . "a non-zero window sized Collection:\t" . $features->[1]->{'window_size'} ); } # This should never happen # if ( !$skip_zero_window ) { # throw( 'You have retrieved data from a Collection ' # . 'which without using -skip_zero_window ' # . 'i.e. you are trying to generate overwrite ' # . 'the data you are generating the Collections from' ); # } } else { throw( 'Something is wrong, ' . 'the Collection you have retrieved ' . 'does not support the method window_size' ); } } ## end if ( ( @{$features} ) ...) # Set collection start here for 0 window_size if ( @{$features} && $store_natural && !defined( $self->collection_start(0) ) ) { $self->collection_start( 0, $features->[0]->start + $sub_start ); } if ($in_slice) { $start_adj = $chunk_length; } # Collect features into wsize bins if ( !$only_natural ) { # Get hashref of wsize=>bin array pairs $bins = $self->_bin_features_by_Slice_window_sizes( -slice => $sub_slice, -window_sizes => $chunk_windows{$chunk_length}, -features => $features, ); } # Handle 0 wsize if ($store_natural) { foreach my $feature ( @{$features} ) { $counts{0}++; if ( $bin_model eq 'SIMPLE' ) { $self->collection_start( 0, $feature->start + $sub_start ); $self->write_collection( 0, $slice, # Pass Slice to sub-slice when storing $feature->end + $sub_start, $feature->strand, # Need to pass strand for 0 resolution $feature->scores, ); } } print "Window size 0 (natural resolution) has " . scalar( @{$features} ) . " feature bins for:\t" . $sub_slice->name . "\n"; } # Now store collections for wsizes >0 my $num_bins; foreach my $wsize ( sort keys( %{$bins} ) ) { $num_bins = scalar( @{ $bins->{$wsize} } ); $counts{$wsize} += $num_bins; if ( $bin_model eq 'SIMPLE' ) { $self->write_collection( $wsize, $slice, #$sub_start, $sub_end, $slice->strand, # This is most likely 1! # Override this woth 0 in descendant Collector if required. $bins->{$wsize}, ); } else { throw( 'Bio::EnsEMBL::Utils::Collector ' . 'does not yet support non-SIMPLE bin models' ); # i.e. More than one score } } } ## end while ($in_slice) # Turn off storing of natural resolution for next chunk length sets $store_natural = 0; } ## end foreach my $chunk_length ( ...) # Write last collections for each wsize foreach my $wsize (@$window_sizes) { if ( ( $wsize == 0 && !$store_natural ) || ( $wsize != 0 && $only_natural ) ) { next; } print "Writing final $wsize window_size collection, " . "this may result in slightly different " . "bin numbers from counts due to removing " . "overhanging bins past end of slice\n"; $self->write_collection( $wsize, $slice ); } # Print some counts foreach my $wsize ( sort ( keys %counts ) ) { print "Generated " . $counts{$wsize} . " bins for window size $wsize for " . $slice->name . "\n"; # Some may have failed to store if we are projecting to a new # assembly. } return; } ## end sub store_window_bins_by_Slice =head2 _bin_features_by_Slice_window_sizes Deprecated. Args[0] : Bio::EnsEMBL::Slice Args[1] : ARRAYREF of window sizes Args[2] : ARRAYREF of features with start and end method e.g. Bio::EnsEMBL::Features Example : $bins = $self->_bin_features_by_window_sizes( -slice => $slice, -window_sizes => $chunk_windows{$chunk_length}, -features => $features, ); Description: Bins feature scores for a given list of window sizes and predefined method. Returntype : HASHREF of scores per bin per window size Exceptions : None Caller : store_window_bins_by_Slice Status : At Risk =cut sub _bin_features_by_Slice_window_sizes { my ( $self, @args ) = @_; deprecate("_bin_features_by_Slice_window_sizes is deprecated and will be removed in e100."); my ( $slice, $wsizes, $features ) = rearrange( [ 'SLICE', 'WINDOW_SIZES', 'FEATURES' ], @args ); # Generate these once in caller? my $calc_method = '_calculate_' . $bin_method; my $post_method = '_post_process_' . $bin_method; # Do this conditional on the Collection type i.e. is # collection seq_region blob then no else yes Would need # $Bio::EnsEMBL::Utils::Collector::collection_format=BLOB|STANDARD # if ( !defined($features) || !@{$features} ) { return {} } # Set up some hashes to store data by window_size my ( %bins, %nbins, %bin_counts ); my $slice_start = $slice->start(); my $slice_length = $slice->length(); # Set up some bin data for the windows foreach my $wsize (@$wsizes) { $nbins{$wsize} = int( $slice_length/$wsize ); # int rounds down # nbins is index of the bin not the 'number' # Unless $slice_length is a multiple! if ( !( $slice_length % $wsize ) ) { $nbins{$wsize}-- } # Create default bins with 0 $bins{$wsize} = []; map { $bins{$wsize}->[$_] = 0 } ( 0 .. $nbins{$wsize} ); # Set bin counts to 0 for each bin $bin_counts{$wsize} = []; # This is adding an undef to the start of the array!? map { $bin_counts{$wsize}->[ ($_) ] = 0 } @{ $bins{$wsize} }; foreach my $bin ( @{ $bins{$wsize} } ) { $bin_counts{$wsize}->[$bin] = 0; } } my $feature_index = 0; my ( $bin_index, @bin_masks ); foreach my $feature ( @{$features} ) { # Set up the bins for each window size foreach my $wsize (@$wsizes) { my $start_bin = int( ( $feature->start )/$wsize ); my $end_bin = int( ( $feature->end )/$wsize ); if ( $end_bin > $nbins{$wsize} ) { $end_bin = $nbins{$wsize}; } $self->$calc_method( $feature, $start_bin, $end_bin, $wsize, \%bins, \%bin_counts ); } } # Now do post processing of bins if required if ( $self->can($post_method) ) { $self->$post_method( \%bins, \%bin_counts ); } return \%bins; } ## end sub _bin_features_by_Slice_window_sizes # end sub _bin_features_by_Slice ### Here follows the bin methods # These may also be defined in the inheriting Collector class. No tests # as these are internal and require speed. =head2 _calculate_count Deprecated. Args[0] : feature e.g. Bio::EnsEMBL::Feature Args[1] : int - start bin Args[2] : int - end bin Args[3] : int - window_size Args[4] : hashref - score bins Example : $self->$calc_method Description: Adds count to bins which this feature overlaps Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _calculate_count { my ( $self, $feature, $start_bin, $end_bin, $wsize, $bins_ref ) = @_; deprecate("_calculate_count is deprecated and will be removed in e100."); my $bin_index; for ( $bin_index = $start_bin; $bin_index <= $end_bin; ++$bin_index ) { $bins_ref->{$wsize}->[$bin_index]++; } return; } =head2 _calculate_average_score Deprecated. Args[0] : feature e.g. Bio::EnsEMBL::Feature Args[1] : int - start bin Args[2] : int - end bin Args[3] : int - window_size Args[4] : hashref - score bins Example : $self->$calc_method Description: Adds score to bins which this feature overlaps Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _calculate_average_score { my ( $self, $feature, $start_bin, $end_bin, $wsize, $bins_ref, $bin_counts_ref ) = @_; deprecate("_calculate_average_score is deprecated and will be removed in e100."); # This is simple an average of all the scores for features which # overlap this bin. No weighting with respect to the bin or the # feature. my $score = $self->get_score_by_Feature($feature); for ( my $bin_index = $start_bin; $bin_index <= $end_bin; ++$bin_index ) { # We should really push onto array here so we can have median or # mean. $bins_ref->{$wsize}->[$bin_index] += $score; $bin_counts_ref->{$wsize}->[$bin_index]++; } return; } =head2 _post_process_average_score Deprecated. Args[0] : hashref - score bins Args[1] : hashref - count bins Example : $self->$post_method Description: Post processes bins to calculate average score Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _post_process_average_score { my ( $self, $bins_ref, $bin_counts_ref ) = @_; deprecate("_post_process_average_score is deprecated and will be removed in e100."); foreach my $wsize ( keys %{$bins_ref} ) { foreach my $bin_index ( 0 .. $#{ $bins_ref->{$wsize} } ) { if ( $bin_counts_ref->{$wsize}->[$bin_index] ) { $bins_ref->{$wsize}->[$bin_index] /= $bin_counts_ref->{$wsize}->[$bin_index]; } } } return; } =head2 _calculate_max_magnitude Deprecated. Args[0] : feature e.g. Bio::EnsEMBL::Feature Args[1] : int - start bin Args[2] : int - end bin Args[3] : int - window_size Args[4] : hashref - score bins Example : $self->$calc_method Description: Sets max +/-ve scores for bins which this feature overlaps Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _calculate_max_magnitude { my ( $self, $feature, $start_bin, $end_bin, $wsize, $bins_ref ) = @_; deprecate("_calculate_max_magnitude is deprecated and will be removed in e100."); my $score = $self->get_score_by_Feature($feature); # Max magnitude # Take the highest value +ve or -ve score for ( my $bin_index = $start_bin; $bin_index <= $end_bin; ++$bin_index ) { # We really need to capture the lowest -ve and higest +ve scores # here and post process to pick between them. $bins_ref->{$wsize}->[$bin_index] ||= [ 0, 0 ]; #-ve, +ve if ( $score < $bins_ref->{$wsize}->[$bin_index]->[0] ) { $bins_ref->{$wsize}->[$bin_index]->[0] = $score; } elsif ( $score > $bins_ref->{$wsize}->[$bin_index][1] ) { $bins_ref->{$wsize}->[$bin_index]->[1] = $score; } } return; } ## end sub _calculate_max_magnitude =head2 _post_process_max_magnitude Deprecated. Args[0] : hashref - score bins Args[1] : hashref - count bins Example : $self->$post_method Description: Post processes bins to pick largest +ve or -ve score Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _post_process_max_magnitude { my ( $self, $bins_ref ) = @_; deprecate("_post_process_max_magnitude is deprecated and will be removed in e100."); # Take the highest value +ve or -ve score foreach my $wsize ( keys %{$bins_ref} ) { foreach my $bin_index ( 0 .. $#{ $bins_ref->{$wsize} } ) { # Have potential for no listref in a given bin # default value if we haven't seen anything is 0 # Actually want an array of -ve +ve values if ( $bins_ref->{$wsize}->[$bin_index] ) { my $tmp_minus = -$bins_ref->{$wsize}->[$bin_index]->[0]; if ( $tmp_minus > $bins_ref->{$wsize}->[$bin_index]->[1] ) { $bins_ref->{$wsize}->[$bin_index] = $bins_ref->{$wsize}->[$bin_index]->[0]; } else { $bins_ref->{$wsize}->[$bin_index] = $bins_ref->{$wsize}->[$bin_index]->[1]; } } } } return; } ## end sub _post_process_max_magnitude =head2 _calculate_RPKM Deprecated. Args[0] : feature e.g. Bio::EnsEMBL::Feature Args[1] : int - start bin Args[2] : int - end bin Args[3] : int - window_size Args[4] : hashref - score bins Example : $self->$calc_method Description: Stores counts to calculate Read Per Kb per Million(RPKM) Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _calculate_RPKM { my ( $self, $feature, $start_bin, $end_bin, $wsize, $bins_ref ) = @_; deprecate("_calculate_RPKM is deprecated and will be removed in e100."); $self->_calculate_count( $feature, $start_bin, $end_bin, $wsize, $bins_ref ); return; } =head2 _post_process_RPKM Deprecated. Args[0] : hashref - score bins Args[1] : hashref - count bins Example : $self->$post_method Description: Post processes bins to calculate average score Returntype : None Exceptions : None Caller : _bin_features_by_window_sizes Status : At Risk =cut sub _post_process_RPKM { my ( $self, $bins_ref ) = @_; deprecate("_post_process_RPKM is deprecated and will be removed in e100."); #10^9 x C / NGB #C = Reads overlapping bin #N = Total reads in the experiment #G = Length of bin in bps #(don't really have to account for non-ref/HAPs or gender here #as should be close enough, CellTypes/gender differences will be miniscule) #B = length of each bin foreach my $wsize(keys %{$bins_ref}){ foreach my $bin_index(0..$#{$bins_ref->{$wsize}}){ $bins_ref->{$wsize}->[$bin_index] = ((10**9) * $bins_ref->{$wsize}->[$bin_index])/(($self->_RPKM_factor($wsize)) * $wsize); } } return; } =head2 _set_up_RPKM Deprecated. Args[0] : hashref - method config e.g { DNADB => Bio::EnsEMBL::DBSQL::DBAdaptor, TOTAL_FEATURE => $total_feature_count, } Example : $self->$set_up_method($config); Description: Sets the RPKM factor Returntype : None Exceptions : Throws is required config params are not set Caller : bin_method Status : At Risk =cut sub _set_up_RPKM{ my ($self, $config) = @_; deprecate("_set_up_RPKM is deprecated and will be removed in e100."); my ($dnadb, $total_features) = rearrange([ 'DNADB', 'TOTAL_FEATURES'], %{$config}); #Test specifically here to notify about config hash if(! $total_features){ throw("For RPKM you must pass a valid 'total_features' ". "as part of the method config hash."); } if(! $dnadb){ throw("For RPKM you must pass 'dnadb' as part of the method config hash."); } foreach my $wsize(@{$self->window_sizes}){ #Should never have 0 here $self->_RPKM_factor($wsize, ($wsize * $total_features)); #N*G warn "setting $wsize RPKM factor($wsize * $total_features) to ". $self->_RPKM_factor($wsize); } return; } ## end sub _set_up_RPKM =head2 _RPKM_factor Deprecated. Args[0] : int - RPKM factor i.e. (Total reads in the experiment * Genome length) Example : $self->_RPKM_factor($wsize, $factor); Description: Gets/Sets the RPKM factor Returntype : int Exceptions : None Caller : _set_up_RPKM, _post_process_RPKM Status : At Risk =cut sub _RPKM_factor{ my ($self, $wsize, $factor) = @_; deprecate("_RPKM_factor is deprecated and will be removed in e100."); if (! defined $wsize){ throw("You must pass at least window_size to get or set the RPKM factor"); } if(defined $factor){ $self->{'RPKM_factor'}{$wsize} = $factor; } elsif(! exists $self->{'RPKM_factor'}{$wsize}){ #This should never happen unless the window sizes #are redefined after initialisation throw("You have requested an RPKM factor for a window_size". " which has not been set:\t$wsize"); } return $self->{'RPKM_factor'}{$wsize}; } =head2 get_diploid_genome_length_by_gender Deprecated. Args[0] : string - RPKM factor i.e. (Total reads in the experiment * Genome length) Args[1] : string - gender e.g. male or female Example : my $glength = $self->get_diploid_genome_length_by_gender( $dnadb, $gender ); Description: Gets the gender specific diploid genome length, including non-ref but not including haplotypes. Only handles species with X/Y sex chromosomes. Returntype : int Exceptions : None Caller : _set_up_RPKM, _post_process_RPKM Status : At Risk - Move to and export from generic Utils Slice module??? =cut sub get_diploid_genome_length_by_gender { my ( $dnadb, $gender ) = @_; deprecate("get_diploid_genome_length_by_gender is deprecated and will be removed in e100."); my %sex_chrs = ( 'Y' => 'male', 'X' => 'female', ); my $dip_length = 0; if (!(( ref($dnadb) && $dnadb->isa('Bio::EnsEMBL::DBSQL::DBAdaptor') ) && $dnadb->grou() eq 'core' && ( defined $gender && $gender =~ /(male|female)/ ) ) ) { throw( "Must provide valid " . "Bio::EnsEMBL::DBSQL::DBAdaptor($dnadb) and " . "gender ($gender) arguments" ); } my @ref_slices = $dnadb->get_SliceAdaptor->fetch_all('toplevel'); # Include non-ref(unassembled), but omit haps/lrgs(i.e. redundant) foreach my $slice ( @{ $dnadb->get_SliceAdaptor->fetch_all( 'toplevel', undef, 1, 1 ) } ) { # Include duplicated region for true diploid length # Skip haps/lrgs if ( ( $slice->coord_system->name() eq 'chromosome' && !$slice->is_reference() ) || $slice->coord_system->name() eq 'lrg' ) { next; } if ( exists( $sex_chrs{ $slice->seq_region_name() } ) ) { if ( $gender eq 'male' ) { $dip_length += $slice->length; } elsif ( $sex_chrs{ $slice->seq_region_name } eq 'male' ) { next; } } $dip_length += 2*$slice->length; } return $dip_length; } ## end sub get_diploid_genome_length_by_gender 1;
muffato/ensembl
modules/Bio/EnsEMBL/Utils/Collector.pm
Perl
apache-2.0
54,184
package com.royalrangers.enums.achivement; public enum TestType { /*0*/ DEFAULT, /*1*/ BLUE, /*2*/ GREEN, /*3*/ YELLOW, /*4*/ LIGHTBLUE, /*5*/ RED, /*6*/ ORANGE, /*7*/ BROWN, /*8*/ PLATINUM }
royalrangers-ck/rr-api
src/main/java/com/royalrangers/enums/achivement/TestType.java
Java
apache-2.0
229
// <copyright file="ExtendedImageRenderer.cs" company="Anura Code"> // All rights reserved. // </copyright> // <author>Alberto Puyana</author> using System; using System.IO; using Xamarin.Forms; namespace Anuracode.Forms.Controls.Renderers { /// <summary> /// Image source binding. /// </summary> public class ImageSourceBinding { /// <summary> /// Default constructor. /// </summary> /// <param name="imageSource">Image source to use.</param> /// <param name="path">Path to use.</param> public ImageSourceBinding(FFImageLoading.Work.ImageSource imageSource, string path) { ImageSource = imageSource; Path = path; } /// <summary> /// Image source. /// </summary> public FFImageLoading.Work.ImageSource ImageSource { get; private set; } /// <summary> /// Path to use. /// </summary> public string Path { get; private set; } /// <summary> /// Equals to use. /// </summary> /// <param name="obj">Object to use.</param> /// <returns>Result to use.</returns> public override bool Equals(object obj) { var item = obj as ImageSourceBinding; if (item == null) { return false; } return this.ImageSource.Equals(item.ImageSource) && this.Path.Equals(item.Path); } /// <summary> /// Get hash code. /// </summary> /// <returns>Code to use.</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + this.ImageSource.GetHashCode(); hash = hash * 23 + Path.GetHashCode(); return hash; } } /// <summary> /// Get binding. /// </summary> /// <param name="source">Source to use.</param> /// <returns>Binding to use.</returns> public static ImageSourceBinding GetImageSourceBinding(ImageSource source) { if (source == null) { return null; } var uriImageSource = source as UriImageSource; if (uriImageSource != null) { return new ImageSourceBinding(FFImageLoading.Work.ImageSource.Url, uriImageSource.Uri.ToString()); } var fileImageSource = source as FileImageSource; if (fileImageSource != null) { if (File.Exists(fileImageSource.File)) return new ImageSourceBinding(FFImageLoading.Work.ImageSource.Filepath, fileImageSource.File); return new ImageSourceBinding(FFImageLoading.Work.ImageSource.CompiledResource, fileImageSource.File); } throw new NotImplementedException("ImageSource type not supported"); } } }
anuracode/forms_controls
Anuracode.Forms.Controls.Droid/ExtendedImage/ImageSourceBinding.cs
C#
apache-2.0
3,002
# Copyright 2011 James McCauley # # This file is part of POX. # # POX is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # POX is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with POX. If not, see <http://www.gnu.org/licenses/>. """ An L2 learning switch. It is derived from one written live for an SDN crash course. It is somwhat similar to NOX's pyswitch in that it installs exact-match rules for each flow. """ from __future__ import division from random import randrange from pox.core import core import pox.openflow.libopenflow_01 as of from pox.lib.util import dpid_to_str from pox.lib.util import str_to_bool import sys, os, commands, time from pox.lib.util import dpidToStr log = core.getLogger() #-------------------------------define flow rate---------- flow_rate = 50 interval = 1/flow_rate print 'current flow modification rate is:', flow_rate global burst burst = {} # We don't want to flood immediately when a switch connects. # Can be overriden on commandline. _flood_delay = 0 class LearningSwitch (object): """ The learning switch "brain" associated with a single OpenFlow switch. When we see a packet, we'd like to output it on a port which will eventually lead to the destination. To accomplish this, we build a table that maps addresses to ports. We populate the table by observing traffic. When we see a packet from some source coming from some port, we know that source is out that port. When we want to forward traffic, we look up the desintation in our table. If we don't know the port, we simply send the message out all ports except the one it came in on. (In the presence of loops, this is bad!). In short, our algorithm looks like this: For each packet from the switch: 1) Use source address and switch port to update address/port table 2) Is transparent = False and either Ethertype is LLDP or the packet's destination address is a Bridge Filtered address? Yes: 2a) Drop packet -- don't forward link-local traffic (LLDP, 802.1x) DONE 3) Is destination multicast? Yes: 3a) Flood the packet DONE 4) Port for destination address in our address/port table? No: 4a) Flood the packet DONE 5) Is output port the same as input port? Yes: 5a) Drop packet and similar ones for a while 6) Install flow table entry in the switch so that this flow goes out the appopriate port 6a) Send the packet out appropriate port """ def __init__ (self, connection, transparent): # Switch we'll be adding L2 learning switch capabilities to self.connection = connection self.transparent = transparent # Our table self.macToPort = {} # We want to hear PacketIn messages, so we listen # to the connection connection.addListeners(self) # We just use this to know when to log a helpful message self.hold_down_expired = _flood_delay == 0 #----------------------- msg = of.ofp_flow_mod(command=of.OFPFC_DELETE) # iterate over all connected switches and delete all their flows connection.send(msg) print "INFO: Clearing all flows..." #for BCM switch only msg = of.ofp_flow_mod() msg.priority = 10 msg.match.dl_type = 0x800 #msg.match.in_port = 5 msg.match.nw_src = '10.0.0.1' msg.idle_timeout = 0 msg.hard_timeout = 0 #msg.actions.append(of.ofp_action_output(port = 1)) self.connection.send(msg) print 'INFO: add a default rule... I am slice 1(BCM only)' for k in xrange(1,65):#the number of rules to install #insert first if k % 2 == 0: msg = of.ofp_flow_mod() #msg.match = of.ofp_match.from_packet(packet, event.port) #msg.priority = 20000 + randrange(1000) msg.priority = 2000 msg.match.dl_type = 0x800 i = int(k / 256) + 56 j = k % 256 dst = '192.168.' + str(i) + '.' + str(j) #msg.match.in_port = 1 msg.match.nw_src = '10.0.0.1' msg.match.nw_dst = dst #print 'INFO',dst, time.time() msg.idle_timeout = 0 msg.hard_timeout = 0 msg.actions.append(of.ofp_action_output(port = 2)) #msg.data = event.ofp # 6a self.connection.send(msg) time.sleep(0.02) #------------------------- # (note that flow_mods match all flows by default) os.system('./simplesniffer eth2 64&') os.system('sudo bash ../pktgen/pktgen.conf.1-1-flow-dist.sh &') time.sleep(5) y = 0 print 'INFO: starting sending flow mod...' for k in xrange(1,65):#the number of rules to install #insert firsti msg = of.ofp_flow_mod() if k % 2 == 0: msg.command = of.OFPFC_MODIFY #msg.match = of.ofp_match.from_packet(packet, event.port) #msg.priority = 20000 + randrange(1000) msg.priority = 2000 msg.match.dl_type = 0x800 i = int(k / 256) + 56 j = k % 256 dst = '192.168.' + str(i) + '.' + str(j) #msg.match.in_port = 1 msg.match.nw_src = '10.0.0.1' msg.match.nw_dst = dst #print 'INFO',dst, time.time() msg.idle_timeout = 0 msg.hard_timeout = 0 msg.actions.append(of.ofp_action_output(port = 5)) #msg.data = event.ofp # 6a self.connection.send(msg) #print 'DATA: 10.0.0.1', dst, '%f' %time.time() #print 'DATA: 10.0.0.1', dst, '%f' %time.time() burst[dst] = time.time() #time.sleep(interval) print 'INFO: flow mod measure finished...' #write file w = open('poxout1','w') for d in burst: w.write('src: 10.0.0.1 dst: %s sec: %f usec: %f\n' %(d, int(burst[d]), (burst[d] - int(burst[d])) * 1000000 )) w.close() os.system('sudo bash cleanpox.sh') #self destrory def _handle_PacketIn (self, event): """ Handle packet in messages from the switch to implement above algorithm. """ packet = event.parsed #print 'PACKET_IN:', event.port, packet.next.dstip,'%f' % time.time() def _handle_flowstats_received (event): stats = flow_stats_to_list(event.stats) print "FlowStatsReceived from %s: %s" % (dpidToStr(event.connection.dpid), stats) class l2_learning (object): """ Waits for OpenFlow switches to connect and makes them learning switches. """ def __init__ (self, transparent): core.openflow.addListeners(self) self.transparent = transparent def _handle_ConnectionUp (self, event): log.debug("Connection %s" % (event.connection,)) LearningSwitch(event.connection, self.transparent) def launch (transparent=False, hold_down=_flood_delay): """ Starts an L2 learning switch. """ try: global _flood_delay _flood_delay = int(str(hold_down), 10) assert _flood_delay >= 0 except: raise RuntimeError("Expected hold-down to be a number") core.registerNew(l2_learning, str_to_bool(transparent))
PrincetonUniversity/AdvNet-OF_Scripts
evaluation/switch/flowmod_test/pox/pox/samples/l2_bell_burst_mod.py
Python
apache-2.0
7,313
// ======================================================================== // Copyright (c) 2010 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.webapp; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Arrays; import javax.servlet.GenericServlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import junit.framework.Assert; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.util.resource.Resource; import org.eclipse.jetty.util.resource.ResourceCollection; import org.junit.Test; public class WebAppContextTest { @Test public void testConfigurationClassesFromDefault () { Server server = new Server(); //test if no classnames set, its the defaults WebAppContext wac = new WebAppContext(); assertNull(wac.getConfigurations()); String[] classNames = wac.getConfigurationClasses(); assertNotNull(classNames); //test if no classname set, and none from server its the defaults wac.setServer(server); assertTrue(Arrays.equals(classNames, wac.getConfigurationClasses())); } @Test public void testConfigurationClassesExplicit () { String[] classNames = {"x.y.z"}; Server server = new Server(); server.setAttribute(WebAppContext.SERVER_CONFIG, classNames); //test an explicitly set classnames list overrides that from the server WebAppContext wac = new WebAppContext(); String[] myClassNames = {"a.b.c", "d.e.f"}; wac.setConfigurationClasses(myClassNames); wac.setServer(server); String[] names = wac.getConfigurationClasses(); assertTrue(Arrays.equals(myClassNames, names)); //test if no explicit classnames, they come from the server WebAppContext wac2 = new WebAppContext(); wac2.setServer(server); assertTrue(Arrays.equals(classNames, wac2.getConfigurationClasses())); } @Test public void testConfigurationInstances () { Configuration[] configs = {new WebInfConfiguration()}; WebAppContext wac = new WebAppContext(); wac.setConfigurations(configs); assertTrue(Arrays.equals(configs, wac.getConfigurations())); //test that explicit config instances override any from server String[] classNames = {"x.y.z"}; Server server = new Server(); server.setAttribute(WebAppContext.SERVER_CONFIG, classNames); wac.setServer(server); assertTrue(Arrays.equals(configs,wac.getConfigurations())); } @Test public void testRealPathDoesNotExist() throws Exception { Server server = new Server(0); WebAppContext context = new WebAppContext(".", "/"); server.setHandler(context); server.start(); // When ServletContext ctx = context.getServletContext(); // Then // This passes: assertNotNull(ctx.getRealPath("/doesnotexist")); // This fails: assertNotNull(ctx.getRealPath("/doesnotexist/")); } /** * tests that the servlet context white list works * * @throws Exception */ @Test public void testContextWhiteList() throws Exception { Server server = new Server(0); HandlerList handlers = new HandlerList(); WebAppContext contextA = new WebAppContext(".", "/A"); contextA.addServlet( ServletA.class, "/s"); handlers.addHandler(contextA); WebAppContext contextB = new WebAppContext(".", "/B"); contextB.addServlet(ServletB.class, "/s"); contextB.setContextWhiteList(new String [] { "/doesnotexist", "/B/s" } ); handlers.addHandler(contextB); server.setHandler(handlers); server.start(); // context A should be able to get both A and B servlet contexts Assert.assertNotNull(contextA.getServletHandler().getServletContext().getContext("/A/s")); Assert.assertNotNull(contextA.getServletHandler().getServletContext().getContext("/B/s")); // context B has a contextWhiteList set and should only be able to get ones that are approved Assert.assertNull(contextB.getServletHandler().getServletContext().getContext("/A/s")); Assert.assertNotNull(contextB.getServletHandler().getServletContext().getContext("/B/s")); } @Test public void testAlias() throws Exception { File dir = File.createTempFile("dir",null); dir.delete(); dir.mkdir(); dir.deleteOnExit(); File webinf = new File(dir,"WEB-INF"); webinf.mkdir(); File classes = new File(dir,"classes"); classes.mkdir(); File someclass = new File(classes,"SomeClass.class"); someclass.createNewFile(); WebAppContext context = new WebAppContext(); context.setBaseResource(new ResourceCollection(dir.getAbsolutePath())); context.setResourceAlias("/WEB-INF/classes/", "/classes/"); assertTrue(Resource.newResource(context.getServletContext().getResource("/WEB-INF/classes/SomeClass.class")).exists()); assertTrue(Resource.newResource(context.getServletContext().getResource("/classes/SomeClass.class")).exists()); } class ServletA extends GenericServlet { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { this.getServletContext().getContext("/A/s"); } } class ServletB extends GenericServlet { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { this.getServletContext().getContext("/B/s"); } } }
thomasbecker/jetty-spdy
jetty-webapp/src/test/java/org/eclipse/jetty/webapp/WebAppContextTest.java
Java
apache-2.0
6,755
// Package apihelper contains some methods which make working with the http // package a bit nicer package apihelper import ( "encoding/json" "fmt" "io" "net/http" "github.com/mediocregopher/mediocre-api/common" "github.com/mediocregopher/mediocre-api/pickyjson" ) // ErrUnlessMethod checks that the given request is using one of the given // HTTP methods. If it is not than an error is sent back to the client and true // is returned func ErrUnlessMethod( w http.ResponseWriter, r *http.Request, methods ...string, ) bool { for i := range methods { if r.Method == methods[i] { return false } } http.Error(w, "invalid method", 400) return false } // Prepare takes in a request and its response, and performs the following // checks/enhancements: // // * If any methods are given, ensure the request is using one of them. // Otherwise send error to client and return false // // * Replace r.Body with a MaxBytesReader which will stop the reading at the // given bodySizeLimit // // * If params isn't nil attempt to json.Unmarshal the request body into it. If // that fails an error is sent to the client and false is returned // func Prepare( w http.ResponseWriter, r *http.Request, params interface{}, bodySizeLimit int64, ) bool { r.Body = http.MaxBytesReader(w, r.Body, bodySizeLimit) if params != nil { if err := json.NewDecoder(r.Body).Decode(params); err != nil { http.Error(w, err.Error(), 400) return false } if err := pickyjson.CheckRequired(params); err != nil { common.HTTPError(w, r, err) return false } if err := pickyjson.CheckRequired(&params); err != nil { common.HTTPError(w, r, err) return false } } return true } // JSONSuccess json encodes the given return value and writes that to the given // io.Writer (presumably an http.ResponseWriter) func JSONSuccess(w io.Writer, i interface{}) { json.NewEncoder(w).Encode(i) fmt.Fprintf(w, "\n") }
mediocregopher/mediocre-api
common/apihelper/apihelper.go
GO
apache-2.0
1,921
// Copyright 2019 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package mock import ( "fmt" "sync" v1 "k8s.io/api/apps/v1" autoscalingv1 "k8s.io/api/autoscaling/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/watch" appsv1 "k8s.io/client-go/kubernetes/typed/apps/v1" ) var _ appsv1.DeploymentInterface = &deploymentImpl{} type deploymentImpl struct { mux sync.Mutex deployments map[string]*v1.Deployment watches Watches } func newAppsInterface() appsv1.DeploymentInterface { return &deploymentImpl{ deployments: make(map[string]*v1.Deployment), } } func (d *deploymentImpl) Create(obj *v1.Deployment) (*v1.Deployment, error) { d.mux.Lock() defer d.mux.Unlock() d.deployments[obj.Name] = obj d.watches.Send(watch.Event{ Type: watch.Added, Object: obj, }) return obj, nil } func (d *deploymentImpl) Update(obj *v1.Deployment) (*v1.Deployment, error) { d.mux.Lock() defer d.mux.Unlock() d.deployments[obj.Name] = obj d.watches.Send(watch.Event{ Type: watch.Modified, Object: obj, }) return obj, nil } func (d *deploymentImpl) UpdateStatus(*v1.Deployment) (*v1.Deployment, error) { panic("not implemented") } func (d *deploymentImpl) Delete(name string, options *metav1.DeleteOptions) error { d.mux.Lock() defer d.mux.Unlock() obj := d.deployments[name] if obj == nil { return fmt.Errorf("unable to delete deployment %s", name) } delete(d.deployments, name) d.watches.Send(watch.Event{ Type: watch.Deleted, Object: obj, }) return nil } func (d *deploymentImpl) DeleteCollection(options *metav1.DeleteOptions, listOptions metav1.ListOptions) error { panic("not implemented") } func (d *deploymentImpl) Get(name string, options metav1.GetOptions) (*v1.Deployment, error) { panic("not implemented") } func (d *deploymentImpl) List(opts metav1.ListOptions) (*v1.DeploymentList, error) { d.mux.Lock() defer d.mux.Unlock() out := &v1.DeploymentList{} for _, v := range d.deployments { out.Items = append(out.Items, *v) } return out, nil } func (d *deploymentImpl) Watch(opts metav1.ListOptions) (watch.Interface, error) { d.mux.Lock() defer d.mux.Unlock() w := NewWatch() d.watches = append(d.watches, w) // Send add events for all current resources. for _, d := range d.deployments { w.Send(watch.Event{ Type: watch.Added, Object: d, }) } return w, nil } func (d *deploymentImpl) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Deployment, err error) { panic("not implemented") } func (d *deploymentImpl) GetScale(deploymentName string, options metav1.GetOptions) (*autoscalingv1.Scale, error) { panic("not implemented") } func (d *deploymentImpl) UpdateScale(deploymentName string, scale *autoscalingv1.Scale) (*autoscalingv1.Scale, error) { panic("not implemented") }
geeknoid/istio
galley/pkg/testing/mock/deployments.go
GO
apache-2.0
3,418
/******************************************************************************* * Copyright 2015 Maximilian Stark | Dakror <mail@dakror.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.dakror.vloxlands.game; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.environment.DirectionalShadowLight; import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; import com.badlogic.gdx.graphics.g3d.utils.DepthShaderProvider; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.math.collision.BoundingBox; import com.badlogic.gdx.math.collision.Ray; import com.badlogic.gdx.utils.Array; import de.dakror.vloxlands.Config; import de.dakror.vloxlands.Vloxlands; import de.dakror.vloxlands.ai.path.BFS; import de.dakror.vloxlands.ai.path.node.BFSNode; import de.dakror.vloxlands.game.entity.Entity; import de.dakror.vloxlands.game.entity.creature.Creature; import de.dakror.vloxlands.game.entity.creature.Human; import de.dakror.vloxlands.game.entity.statics.StaticEntity; import de.dakror.vloxlands.game.entity.structure.Structure; import de.dakror.vloxlands.game.entity.structure.Towncenter; import de.dakror.vloxlands.game.item.Item; import de.dakror.vloxlands.game.item.ItemStack; import de.dakror.vloxlands.game.query.VoxelPos; import de.dakror.vloxlands.game.voxel.Voxel; import de.dakror.vloxlands.game.world.Chunk; import de.dakror.vloxlands.game.world.Island; import de.dakror.vloxlands.game.world.World; import de.dakror.vloxlands.layer.Layer; import de.dakror.vloxlands.render.DDirectionalShadowLight; import de.dakror.vloxlands.render.MeshingThread; import de.dakror.vloxlands.util.Direction; import de.dakror.vloxlands.util.event.SelectionListener; import de.dakror.vloxlands.util.event.VoxelSelection; import de.dakror.vloxlands.util.math.CustomizableFrustum; /** * @author Dakror */ @SuppressWarnings("deprecation") public class Game extends Layer { public static long seed = (long) (Math.random() * Long.MAX_VALUE); public static final float velocity = 10; public static final float rotateSpeed = 0.2f; public static float pickRayMaxDistance = 150f; public static final int dayInTicks = 72020; // 1 ingame day = 72020 ticks = 1200s = 20min public static Game instance; public static World world; public static Camera camera; public static float time = 0.99999999999f; public Environment env; public Array<SelectionListener> listeners = new Array<SelectionListener>(); public Environment minimapEnv; public Camera minimapCamera; public ModelBatch minimapBatch; public StaticEntity cursorEntity; boolean cursorEntityPlacable; boolean cursorEntityContinousPlacing; Array<Material> defaultCursorEntityMaterials; public String activeAction = ""; public Island activeIsland; public DirectionalShadowLight shadowLight; DirectionalLight directionalLight; public CameraInputController controller; ModelBatch modelBatch; ModelBatch shadowBatch; boolean middleDown; boolean doneLoading; ModelInstance sky; int tick; int ticksForTravel; int startTick; public boolean regionSelectionMode = false; boolean regionSelectionLMB; public Vector3 hoveredVoxel = new Vector3(); public Vector3 selectedVoxel = new Vector3(); public Vector3 selectionStartVoxel = new Vector3(-1, 0, 0); Vector3 controllerTarget = new Vector3(); Vector3 cameraPos = new Vector3(); Vector3 target = new Vector3(); Vector3 targetDirection = new Vector3(); Vector3 targetUp = new Vector3(); Vector2 mouseDown = new Vector2(); // -- temp -- // public final Vector3 tmp = new Vector3(); public final Vector3 tmp1 = new Vector3(); public final Vector3 tmp2 = new Vector3(); public final Vector3 tmp3 = new Vector3(); public final Vector3 tmp4 = new Vector3(); public final Vector3 tmp5 = new Vector3(); public final Vector3 tmp6 = new Vector3(); public final Vector3 tmp7 = new Vector3(); public final Vector3 tmp8 = new Vector3(); public final Matrix4 m4 = new Matrix4(); public final BoundingBox bb = new BoundingBox(); public final BoundingBox bb2 = new BoundingBox(); public final BoundingBox bb3 = new BoundingBox(); @Override public void show() { modal = true; instance = this; Gdx.app.log("GameLayer.show", "Seed: " + seed + ""); MathUtils.random = new Random(seed); modelBatch = new ModelBatch(Gdx.files.internal("shader/shader.vs"), Gdx.files.internal("shader/shader.fs")); minimapBatch = new ModelBatch(Gdx.files.internal("shader/shader.vs"), Gdx.files.internal("shader/shader.fs")); camera = new PerspectiveCamera(Config.fov, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); camera.near = 0.1f; camera.far = pickRayMaxDistance; controller = new CameraInputController(camera) { private final Vector3 tmpV1 = new Vector3(); private final Vector3 tmpV2 = new Vector3(); @Override protected boolean process(float deltaX, float deltaY, int button) { if (button == rotateButton && Gdx.input.isKeyPressed(Keys.CONTROL_LEFT)) return false; if (button == rotateButton) { tmpV1.set(camera.direction).crs(camera.up).y = 0f; camera.rotateAround(target, tmpV1.nor(), deltaY * rotateAngle); float dot = camera.direction.dot(Vector3.Y); if (dot < -0.95f) camera.rotateAround(target, tmpV1.nor(), -deltaY * rotateAngle); camera.rotateAround(target, Vector3.Y, deltaX * -rotateAngle); } else if (button == translateButton) { camera.translate(tmpV1.set(camera.direction).crs(camera.up).nor().scl(-deltaX * translateUnits)); camera.translate(tmpV2.set(camera.up).scl(-deltaY * translateUnits)); if (translateTarget) target.add(tmpV1).add(tmpV2); } else if (button == forwardButton) { camera.translate(tmpV1.set(camera.direction).scl(deltaY * translateUnits)); if (forwardTarget) target.add(tmpV1); } if (autoUpdate) camera.update(); return true; } @Override public boolean zoom(float amount) { if (!alwaysScroll && activateKey != 0 && !activatePressed) return false; tmpV1.set(camera.direction).scl(amount); tmpV2.set(camera.position).add(tmpV1); if (tmpV2.dst(target) > 5) { camera.translate(tmpV1); if (scrollTarget) target.add(tmpV1); if (autoUpdate) camera.update(); return true; } return false; } }; controller.translateUnits = 20; controller.rotateLeftKey = -1; controller.rotateRightKey = -1; controller.forwardKey = -1; controller.backwardKey = -1; controller.translateButton = -1; controller.rotateButton = Buttons.MIDDLE; Vloxlands.instance.getMultiplexer().addProcessor(controller); minimapCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); minimapCamera.near = 0.1f; minimapCamera.far = pickRayMaxDistance; minimapEnv = new Environment(); minimapEnv.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f)); minimapEnv.add(new DirectionalLight().set(1f, 1f, 1f, -0.5f, -0.5f, -0.5f)); minimapEnv.add(new DirectionalLight().set(0.5f, 0.5f, 0.5f, -0.5f, -0.5f, -0.5f)); shadowBatch = new ModelBatch(new DepthShaderProvider()); Vloxlands.shapeRenderer = new ShapeRenderer(); new MeshingThread(); env = new Environment(); env.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1.f), new ColorAttribute(ColorAttribute.Fog, 0.5f, 0.8f, 0.85f, 1.f)); env.add(directionalLight = new DirectionalLight().set(0.8f, 0.8f, 0.8f, -0.5f, -0.5f, -0.5f)); env.add((shadowLight = new DDirectionalShadowLight(Config.shadowQuality, 128, 128, camera.near, camera.far)).set(0.6f, 0.6f, 0.6f, 0, -0.5f, time)); env.shadowMap = shadowLight; // int w = MathUtils.random(1, 5); // int d = MathUtils.random(1, 5); world = new World(1, 1); // world = new World(w, d); // Gdx.app.log("GameLayer.show", "World size: " + w + "x" + d); } public void doneLoading() { for (Item item : Item.getAll()) item.onLoaded(); focusIsland(world.getIslands()[0], true); Human human = new Human(Island.SIZE / 2 - 5, Island.SIZE / 4 * 3, Island.SIZE / 2); activeIsland.addEntity(human, false, false); human = new Human(Island.SIZE / 2 - 4, Island.SIZE / 4 * 3, Island.SIZE / 2); activeIsland.addEntity(human, false, false); Towncenter tc = new Towncenter(Island.SIZE / 2 - 2, Island.SIZE / 4 * 3, Island.SIZE / 2 - 2); activeIsland.addEntity(tc, false, true); tc.setBuilt(true); tc.getInnerInventory().add(new ItemStack(Item.get("AXE"), 5)); tc.getInnerInventory().add(new ItemStack(Item.get("PICKAXE"), 5)); tc.getInnerInventory().add(new ItemStack(Item.get("SHOVEL"), 5)); tc.getInnerInventory().add(new ItemStack(Item.get("HAMMER"), 5)); tc.getInnerInventory().add(new ItemStack(Item.get("HOE"), 5)); tc.getInnerInventory().add(new ItemStack(Item.get("WOODEN_LOG"), 40)); tc.getInnerInventory().add(new ItemStack(Item.get("IRON_INGOT"), 5)); doneLoading = true; } public void focusIsland(Island island, boolean initial) { Vector3 islandCenter = new Vector3(island.pos.x + Island.SIZE / 2, island.pos.y + Island.SIZE / 4 * 3, island.pos.z + Island.SIZE / 2); activeIsland = island; selectedVoxel.set(-1, 0, 0); if (!initial) { target.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3); if (target.equals(camera.position)) { camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3); controller.target.set(islandCenter); camera.lookAt(islandCenter); controller.update(); camera.update(); return; } ticksForTravel = (int) camera.position.dst(target) * Config.getGameSpeed(); Vector3 pos = camera.position.cpy(); Vector3 dir = camera.direction.cpy(); Vector3 up = camera.up.cpy(); camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3); controller.target.set(islandCenter); camera.lookAt(islandCenter); targetDirection.set(camera.direction); targetUp.set(camera.up); camera.position.set(pos); camera.direction.set(dir); camera.up.set(up); startTick = tick; } else { camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3); controller.target.set(islandCenter); camera.lookAt(islandCenter); controller.update(); camera.update(); } } @Override public void render(float delta) { if (!doneLoading) return; controller.update(); ((PerspectiveCamera) camera).fieldOfView = Config.fov; Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); shadowLight.begin(controller.target, camera.direction); shadowBatch.begin(shadowLight.getCamera()); world.render(shadowBatch, null); shadowBatch.end(); shadowLight.end(); Gdx.gl.glClearColor(0.5f, 0.8f, 0.85f, 1); modelBatch.begin(camera); world.render(modelBatch, env); if (!Config.paused) world.update(delta); // modelBatch.render(sky, env); if (cursorEntity != null) { cursorEntity.update(delta); cursorEntity.render(modelBatch, env, false); } modelBatch.end(); if (selectionStartVoxel.x > -1 && selectedVoxel.x > -1) { Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl.glEnable(GL20.GL_BLEND); float minX = Math.min(selectionStartVoxel.x, selectedVoxel.x); float maxX = Math.max(selectionStartVoxel.x, selectedVoxel.x); float minY = Math.min(selectionStartVoxel.y, selectedVoxel.y); float maxY = Math.max(selectionStartVoxel.y, selectedVoxel.y); float minZ = Math.min(selectionStartVoxel.z, selectedVoxel.z); float maxZ = Math.max(selectionStartVoxel.z, selectedVoxel.z); Vloxlands.shapeRenderer.begin(ShapeType.Filled); Vloxlands.shapeRenderer.setProjectionMatrix(camera.combined); Vloxlands.shapeRenderer.identity(); Vloxlands.shapeRenderer.translate(activeIsland.pos.x + minX, activeIsland.pos.y + minY, activeIsland.pos.z + maxZ + 1.01f); Vloxlands.shapeRenderer.setColor(0, 1, 0, 0.3f); Vloxlands.shapeRenderer.box(-0.005f, -0.005f, -0.005f, (maxX - minX) + 1.01f, (maxY - minY) + 1.01f, (maxZ - minZ) + 1.01f); Vloxlands.shapeRenderer.end(); } if (Vloxlands.showPathDebug) { Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl.glEnable(GL20.GL_BLEND); Vloxlands.shapeRenderer.begin(ShapeType.Filled); Vloxlands.shapeRenderer.setProjectionMatrix(camera.combined); for (BFSNode node : BFS.visited) { Vloxlands.shapeRenderer.identity(); Vloxlands.shapeRenderer.translate(activeIsland.pos.x + node.x, activeIsland.pos.y + node.y, activeIsland.pos.z + node.z + 1.01f); Vloxlands.shapeRenderer.setColor(1, 1, 1, 0.3f); Vloxlands.shapeRenderer.box(-0.005f, -0.005f, -0.005f, 1.01f, 1.01f, 1.01f); } Vloxlands.shapeRenderer.end(); } } @Override public void tick(int tick) { this.tick = tick; if (!Config.paused) { time -= 0.00002777f; if (time <= -0.99999999999f) time = 0.99999999999f; float t = time * MathUtils.PI; float x = MathUtils.sin(t) * 0.5f; float z = MathUtils.cos(t); float light = MathUtils.cos(t - MathUtils.PI / 2) * 0.5f + 0.3f; shadowLight.set(light - 0.1f, light, light, x, -0.5f, z); directionalLight.set(light, light, light, x, -0.5f, z); world.tick(tick); } if (cursorEntity != null) cursorEntity.tick(tick); if (activeIsland != null && startTick > 0) { camera.position.interpolate(target, (tick - startTick) / (float) (ticksForTravel * Config.getGameSpeed()), Interpolation.linear); camera.direction.interpolate(targetDirection, (tick - startTick) / (float) (ticksForTravel * Config.getGameSpeed()), Interpolation.linear); camera.up.interpolate(new Vector3(0, 1, 0), (tick - startTick) / (float) (ticksForTravel * Config.getGameSpeed()), Interpolation.linear); if (tick >= startTick + ticksForTravel || camera.position.dst(target) < 0.1f) { Vector3 islandCenter = new Vector3(activeIsland.pos.x + Island.SIZE / 2, activeIsland.pos.y + Island.SIZE / 4 * 3, activeIsland.pos.z + Island.SIZE / 2); controller.target.set(islandCenter); camera.position.set(islandCenter).add(-Island.SIZE / 3, Island.SIZE / 3, -Island.SIZE / 3); camera.lookAt(islandCenter); startTick = 0; } controller.update(); camera.update(); } } @Override public void resize(int width, int height) { camera.viewportWidth = width; camera.viewportHeight = height; camera.update(); minimapCamera.viewportWidth = width; minimapCamera.viewportHeight = height; minimapCamera.update(); } public void pickRay(boolean hover, boolean lmb, int x, int y) { Ray ray = camera.getPickRay(x, y); if (hover) { Entity hovered = null; float distance = 0; for (Entity e : activeIsland.getEntities()) { e.hovered = false; if (!e.isVisible()) continue; if (!e.inFrustum) continue; e.getWorldBoundingBox(bb); if (Intersector.intersectRayBounds(ray, bb, tmp)) { float dst = ray.origin.dst(tmp); if (hovered == null || dst < distance) { hovered = e; distance = dst; } } } if (hovered != null) hovered.hovered = true; } else { Entity selectedEntity = null; Chunk selectedChunk = null; Vector3 selVoxel = new Vector3(); float distance = 0; for (Entity e : activeIsland.getEntities()) { e.wasSelected = e.selected; if (lmb) e.selected = false; float dst = ray.origin.dst(e.posCache); if (e.isVisible() && e.inFrustum && e.hovered && (distance == 0 || dst < distance) && dst < pickRayMaxDistance) { distance = dst; selectedEntity = e; } } for (Chunk c : activeIsland.getChunks()) { if (c == null) continue; if (c.inFrustum && !c.isEmpty()) { tmp1.set(activeIsland.pos.x + c.pos.x, activeIsland.pos.y + c.pos.y, activeIsland.pos.z + c.pos.z); tmp2.set(tmp1.cpy().add(Chunk.SIZE, Chunk.SIZE, Chunk.SIZE)); bb.set(tmp1, tmp2); if (Intersector.intersectRayBounds(ray, bb, null) && c.pickVoxel(ray, tmp5, tmp6)) { float dst = ray.origin.dst(tmp5); if ((distance == 0 || dst < distance) && dst <= pickRayMaxDistance) { distance = dst; selVoxel.set(tmp6); selectedChunk = c; } } } } if (selectedChunk != null) { // -- determine selectedVoxelFace -- // Direction dir = null; float distanc = 0; Vector3 is2 = new Vector3(); byte air = Voxel.get("AIR").getId(); for (Direction d : Direction.values()) { tmp7.set(activeIsland.pos.x + selectedChunk.pos.x + selVoxel.x + d.dir.x, activeIsland.pos.y + selectedChunk.pos.y + selVoxel.y + d.dir.y, activeIsland.pos.z + selectedChunk.pos.z + selVoxel.z + d.dir.z); tmp8.set(tmp7.cpy().add(1, 1, 1)); bb3.set(tmp7, tmp8); if (activeIsland.get(selectedChunk.pos.x + selVoxel.x + d.dir.x, selectedChunk.pos.y + selVoxel.y + d.dir.y, selectedChunk.pos.z + selVoxel.z + d.dir.z) != air) continue; if (Intersector.intersectRayBounds(ray, bb3, is2)) { float dist = ray.origin.dst(is2); if (dir == null || dist < distanc) { distanc = dist; dir = d; } } } selectedVoxel.set(selVoxel).add(selectedChunk.pos); for (SelectionListener sl : listeners) sl.onVoxelSelection(new VoxelSelection(activeIsland, new VoxelPos(selVoxel.cpy().add(selectedChunk.pos), selectedChunk.get((int) selVoxel.x, (int) selVoxel.y, (int) selVoxel.z)), dir), lmb); } else if (selectedEntity != null) { selVoxel.set(-1, 0, 0); selectedEntity.selected = true; if (selectedEntity instanceof Structure) { for (SelectionListener sl : listeners) sl.onStructureSelection((Structure) selectedEntity, lmb); } else if (selectedEntity instanceof Creature) { for (SelectionListener sl : listeners) sl.onCreatureSelection((Creature) selectedEntity, lmb); } } else { for (SelectionListener sl : listeners) sl.onNoSelection(lmb); } } } public Chunk pickVoxelRay(Island island, Vector3 selVoxel, boolean lmb, int x, int y) { Chunk selectedChunk = null; Ray ray = camera.getPickRay(x, y); float distance = 0; for (Chunk c : island.getChunks()) { if (c == null) continue; if (c.inFrustum && !c.isEmpty()) { tmp1.set(island.pos.x + c.pos.x, island.pos.y + c.pos.y, island.pos.z + c.pos.z); tmp2.set(tmp1.cpy().add(Chunk.SIZE, Chunk.SIZE, Chunk.SIZE)); bb.set(tmp1, tmp2); if (Intersector.intersectRayBounds(ray, bb, null) && c.pickVoxel(ray, tmp5, tmp6)) { float dst = ray.origin.dst(tmp5); if ((distance == 0 || dst < distance) && dst <= pickRayMaxDistance) { distance = dst; selVoxel.set(tmp6).add(c.pos); selectedChunk = c; } } } } return selectedChunk; } public void selectionBox(Rectangle rectangle) { CustomizableFrustum frustum = new CustomizableFrustum(rectangle); camera.update(); frustum.update(camera.invProjectionView); Vector3 origin = camera.unproject(new Vector3(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0), 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); boolean anyEntitySelected = false; boolean dispatched = false; for (Entity entity : activeIsland.getEntities()) { if (entity instanceof StaticEntity) continue; if (!entity.isVisible()) continue; entity.wasSelected = entity.selected; entity.selected = false; entity.getWorldBoundingBox(bb); float dst = origin.dst(entity.posCache); if (entity.inFrustum && frustum.boundsInFrustum(bb) && dst < pickRayMaxDistance) { entity.selected = true; anyEntitySelected = true; if (!dispatched && entity instanceof Creature) { for (SelectionListener sl : listeners) sl.onCreatureSelection((Creature) entity, true); dispatched = true; } } } if (!anyEntitySelected) { for (Island i : world.getIslands()) { if (i == null) continue; for (Entity e : i.getEntities()) { if (!(e instanceof StaticEntity)) continue; e.wasSelected = e.selected; e.selected = false; e.getWorldBoundingBox(bb); float dst = origin.dst(e.posCache); if (e.inFrustum && frustum.boundsInFrustum(bb) && dst < pickRayMaxDistance) e.selected = true; } } } } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { if (middleDown && Gdx.input.isKeyPressed(Keys.CONTROL_LEFT)) { float f = 0.1f; controller.target.y = controllerTarget.y + (screenY - mouseDown.y) * f; camera.position.y = cameraPos.y + (screenY - mouseDown.y) * f; camera.update(); controller.update(); } return false; } @Override public boolean mouseMoved(int screenX, int screenY) { if (regionSelectionMode) pickVoxelRay(activeIsland, selectedVoxel, false, screenX, screenY); else if (cursorEntity != null) { pickVoxelRay(activeIsland, hoveredVoxel, false, screenX, screenY); cursorEntity.getModelInstance().transform.setToTranslation(activeIsland.pos); cursorEntity.getModelInstance().transform.translate(hoveredVoxel).translate(cursorEntity.getBoundingBox().getDimensions().x <= 1 ? cursorEntity.blockTrn.x : 0, cursorEntity.blockTrn.y, cursorEntity.getBoundingBox().getDimensions().z <= 1 ? cursorEntity.blockTrn.z : 0); cursorEntity.setIsland(activeIsland); cursorEntity.updateVoxelPos(); cursorEntityPlacable = cursorEntity.canBePlaced(); if (defaultCursorEntityMaterials == null) { defaultCursorEntityMaterials = new Array<Material>(); for (Material m : cursorEntity.getModelInstance().materials) defaultCursorEntityMaterials.add(m.copy()); } for (int i = 0; i < cursorEntity.getModelInstance().materials.size; i++) { Material m = cursorEntity.getModelInstance().materials.get(i); if (!cursorEntityPlacable) { m.set(new BlendingAttribute(0.8f), ColorAttribute.createDiffuse(Color.RED)); } else { m.remove(ColorAttribute.Diffuse); BlendingAttribute ba = (BlendingAttribute) defaultCursorEntityMaterials.get(i).get(BlendingAttribute.Type); if (ba == null) m.remove(BlendingAttribute.Type); else m.set(ba); } } } else if (activeIsland != null) pickRay(true, false, screenX, screenY); return false; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { mouseDown.set(screenX, screenY); if (button == Buttons.MIDDLE) { controllerTarget.set(controller.target); cameraPos.set(camera.position); middleDown = true; Gdx.input.setCursorCatched(true); } return false; } @Override public boolean tap(float x, float y, int count, int button) { if (!doneLoading) return false; if (button != Buttons.MIDDLE) { if (!regionSelectionMode) { if (cursorEntity != null) { if (button == Buttons.LEFT) { if (cursorEntityPlacable) { for (int i = 0; i < defaultCursorEntityMaterials.size; i++) { cursorEntity.getModelInstance().materials.set(i, defaultCursorEntityMaterials.get(i)); } if (cursorEntity instanceof Structure) ((Structure) cursorEntity).setBuilt(false); cursorEntity.getModelInstance().transform.translate(-activeIsland.pos.x, -activeIsland.pos.y, -activeIsland.pos.z); activeIsland.addEntity(cursorEntity, true, false); cursorEntity.updateVoxelPos(); if (!cursorEntityContinousPlacing) { cursorEntity = null; defaultCursorEntityMaterials = null; cursorEntityPlacable = false; } else { cursorEntity = (StaticEntity) Entity.getForId(cursorEntity.getId(), cursorEntity.posCache.x, cursorEntity.posCache.y, cursorEntity.posCache.z); cursorEntity.setIsland(activeIsland); cursorEntity.getModelInstance().transform.translate(activeIsland.pos.x, activeIsland.pos.y, activeIsland.pos.z); cursorEntity.updateVoxelPos(); if (cursorEntity instanceof Structure) ((Structure) cursorEntity).setBuilt(true); cursorEntity.setVisible(true); } } } else { cursorEntity = null; defaultCursorEntityMaterials = null; cursorEntityPlacable = false; } } else { selectionStartVoxel.set(-1, 0, 0); pickRay(false, button == Buttons.LEFT, (int) x, (int) y); } } else { if (selectionStartVoxel.x == -1) { selectedVoxel.set(-1, 0, 0); pickVoxelRay(activeIsland, selectionStartVoxel, regionSelectionLMB = button == Buttons.LEFT, (int) x, (int) y); } else if (regionSelectionLMB == (button == Buttons.LEFT)) { pickVoxelRay(activeIsland, selectedVoxel, button == Buttons.LEFT, (int) x, (int) y); for (SelectionListener sl : listeners) sl.onVoxelRangeSelection(activeIsland, selectionStartVoxel, selectedVoxel, regionSelectionLMB); regionSelectionMode = false; } } } return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (button == Buttons.MIDDLE) { middleDown = false; Gdx.input.setCursorCatched(false); } return false; } public void addListener(SelectionListener value) { listeners.insert(0, value); } public boolean removeListener(SelectionListener value) { return listeners.removeValue(value, true); } /* * Only call when @param:action != null */ public void action(String action) { if (action.contains("|region")) { selectionStartVoxel.set(-1, 0, 0); selectedVoxel.set(-1, 0, 0); regionSelectionMode = true; } if (action.contains("entity")) { String[] a = action.split("\\|"); String s = a[0].replace("entity:", ""); Entity e = Entity.getForId((byte) Integer.parseInt(s), 0, 0, 0); if (e instanceof Structure) { ((Structure) e).setBuilt(true); ((Structure) e).tickRequestsEnabled = false; } e.setVisible(true); cursorEntity = (StaticEntity) e; cursorEntityContinousPlacing = a.length > 1 && a[1].equals("cont"); } activeAction = action; } }
Dakror/Vloxlands
core/src/de/dakror/vloxlands/game/Game.java
Java
apache-2.0
28,522
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import unittest from airflow.contrib.hooks.gcp_video_intelligence_hook import CloudVideoIntelligenceHook from google.cloud.videointelligence_v1 import enums from tests.contrib.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id from tests.compat import mock INPUT_URI = "gs://bucket-name/input-file" OUTPUT_URI = "gs://bucket-name/output-file" FEATURES = [enums.Feature.LABEL_DETECTION] ANNOTATE_VIDEO_RESPONSE = {'test': 'test'} class CloudVideoIntelligenceHookTestCase(unittest.TestCase): def setUp(self): with mock.patch( "airflow.contrib.hooks.gcp_video_intelligence_hook.CloudVideoIntelligenceHook.__init__", new=mock_base_gcp_hook_default_project_id, ): self.hook = CloudVideoIntelligenceHook(gcp_conn_id="test") @mock.patch("airflow.contrib.hooks.gcp_video_intelligence_hook.CloudVideoIntelligenceHook.get_conn") def test_annotate_video(self, get_conn): # Given annotate_video_method = get_conn.return_value.annotate_video get_conn.return_value.annotate_video.return_value = ANNOTATE_VIDEO_RESPONSE # When result = self.hook.annotate_video(input_uri=INPUT_URI, features=FEATURES) # Then self.assertIs(result, ANNOTATE_VIDEO_RESPONSE) annotate_video_method.assert_called_once_with( input_uri=INPUT_URI, input_content=None, features=FEATURES, video_context=None, output_uri=None, location_id=None, retry=None, timeout=None, metadata=None, ) @mock.patch("airflow.contrib.hooks.gcp_video_intelligence_hook.CloudVideoIntelligenceHook.get_conn") def test_annotate_video_with_output_uri(self, get_conn): # Given annotate_video_method = get_conn.return_value.annotate_video get_conn.return_value.annotate_video.return_value = ANNOTATE_VIDEO_RESPONSE # When result = self.hook.annotate_video(input_uri=INPUT_URI, output_uri=OUTPUT_URI, features=FEATURES) # Then self.assertIs(result, ANNOTATE_VIDEO_RESPONSE) annotate_video_method.assert_called_once_with( input_uri=INPUT_URI, output_uri=OUTPUT_URI, input_content=None, features=FEATURES, video_context=None, location_id=None, retry=None, timeout=None, metadata=None, )
owlabs/incubator-airflow
tests/contrib/hooks/test_gcp_video_intelligence_hook.py
Python
apache-2.0
3,290
package org.dorkmaster.yasd.where; import org.dorkmaster.yasd.Column; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Author: mjackson * Date: 5/13/15 11:06 PM */ public class Between extends AbstractCondition{ private Column column; private List<Object> params = new ArrayList<Object>(2); public Between(Column column, Object start, Object end) { this.column = column; this.params.add(start); this.params.add(end); } public Between(String column, Object start, Object end) { this(new Column(column), start, end); } @Override public String sql() { // perhaps don't need the parens in here return new StringBuilder().append("(").append(column.sql()).append( " BETWEEN ? AND ?)").toString(); } @Override public Collection<Object> params() { return params; } }
minininja/yasd
src/main/java/org/dorkmaster/yasd/where/Between.java
Java
apache-2.0
910
package controller.implementation; import java.math.BigInteger; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import controller.FuncionarioController; import domain.Funcionario; public class FuncionarioControllerImpl implements FuncionarioController { private static FuncionarioControllerImpl instance; protected EntityManager entityManager; public static FuncionarioController getInstance(){ if (instance == null) instance = new FuncionarioControllerImpl(); return instance; } private FuncionarioControllerImpl() { entityManager = getEntityManager(); } private EntityManager getEntityManager() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("crudHibernate"); if (entityManager == null || !entityManager.isOpen()) entityManager = factory.createEntityManager(); return entityManager; } @Override public Funcionario cadastrar(Funcionario funcionario) { try { entityManager.getTransaction().begin(); entityManager.persist(funcionario); entityManager.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); entityManager.getTransaction().rollback(); } return funcionario; } @Override public Funcionario buscar(BigInteger id) { return entityManager.find(Funcionario.class, id); } @Override public Funcionario alterar(Funcionario funcionario) { try { entityManager.getTransaction().begin(); entityManager.merge(funcionario); entityManager.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); entityManager.getTransaction().rollback(); } return funcionario; } @Override public Boolean excluir(BigInteger id) { try { entityManager.getTransaction().begin(); entityManager.remove(buscar(id)); entityManager.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); entityManager.getTransaction().rollback(); return Boolean.FALSE; } return Boolean.TRUE; } }
a1705164/Restaurante
Restaurante/Web/src/controller/implementation/FuncionarioControllerImpl.java
Java
apache-2.0
2,337
// Copyright 2014 Esri // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.ComponentModel; using System.Windows.Data; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; namespace Localization { internal class DockpaneLocalizedViewModel : DockPane { private const string DockPaneId = "Localization_DockpaneLocalized"; private ICollectionView _sampleRecords; /// <summary> /// Dockpane constructor is used to initialize some sample data /// </summary> internal DockpaneLocalizedViewModel() { SampleRecords = CollectionViewSource.GetDefaultView(SampleRecord.SampleRecords); } /// <summary> /// Sample Records list of sample record objects /// </summary> public ICollectionView SampleRecords { get { return _sampleRecords; } set { SetProperty(ref _sampleRecords, value, () => SampleRecords); } } /// <summary> /// Show the DockPane. /// </summary> internal static void Show() { var pane = FrameworkApplication.DockPaneManager.Find(DockPaneId); if (pane == null) return; pane.Activate(); } /// <summary> /// Text shown near the top of the DockPane. /// </summary> public string Heading { get { return Properties.Resources.DockPaneTitle; } } } /// <summary> /// Button implementation to show the DockPane. /// </summary> internal class DockpaneLocalized_ShowButton : Button { protected override void OnClick() { DockpaneLocalizedViewModel.Show(); } } }
aOrtego/arcgis-pro-sdk-community-samples
Framework/Localization/DockpaneLocalizedViewModel.cs
C#
apache-2.0
2,343
using Shared.Core.Dtos; using Shared.Core.Dtos.References; using Shared.I18n.Utils; using System; using System.Linq.Expressions; using System.Web.Mvc; using System.Web.Mvc.Html; using System.Web.Routing; namespace Client.Core.HtmlHelpers { public static class LocalizedActionLinkExtensions { public static MvcHtmlString LocalizedActionLinkFor<T, U>(this HtmlHelper<T> htmlHelper, Expression<Func<T, U>> expression, string action = "#", string controller = "", object routeValues = null, object htmlAttributes = null) { ModelMetadata expressionModelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); if (expressionModelMetadata.Model == null) { return null; } string resourceKey = expressionModelMetadata.Model.ToString(); if (expressionModelMetadata.Model is ReferenceString) { resourceKey = (expressionModelMetadata.Model as ReferenceString).GetValue(); } return LocalizedActionLink(htmlHelper, resourceKey, action, controller, routeValues, htmlAttributes); } public static MvcHtmlString LocalizedActionLink<T>(this HtmlHelper<T> htmlHelper, string resourceKey, string action = "#", string controller = "", object routeValues = null, object htmlAttributes = null) { string tempName = Guid.NewGuid().ToString(); if (routeValues == null && action != "Index" && action != "#") { action += "/"; } string actionLinkMvcHtmlString = LinkExtensions.ActionLink(htmlHelper, tempName, action, controller, routeValues, htmlAttributes).ToHtmlString(); actionLinkMvcHtmlString = actionLinkMvcHtmlString.Replace(tempName, ResourceUtils.GetString(resourceKey)); return MvcHtmlString.Create(actionLinkMvcHtmlString); } /// <summary> /// Creates the localized link for open the dialog. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="htmlHelper">The html helper</param> /// <param name="resourceKey">The resource key to be localized</param> /// <param name="targetDialog">The html id of the dialog to be opened</param> /// <param name="action">The action to execute</param> /// <param name="controller">The controller of the action</param> /// <param name="routeValues">The route values for the action</param> /// <param name="htmlAttributes">The additional html attributes for the link</param> /// <returns></returns> public static MvcHtmlString DialogActionLink<T>(this HtmlHelper<T> htmlHelper, string resourceKey, string targetDialog, string action, string controller, object routeValues = null, object htmlAttributes = null) { string tempName = Guid.NewGuid().ToString(); RouteValueDictionary attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); attributes.Add("data-toggle", "modal"); attributes.Add("data-target", targetDialog); attributes.Add("data-placement", "top"); attributes["class"] += " show-dialog tooltips"; if (attributes.ContainsKey("title")) { attributes["title"] = ResourceUtils.GetString(attributes["title"].ToString()); } return MvcHtmlString.Create(LinkExtensions.ActionLink(htmlHelper, tempName, action, controller, HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues), attributes).ToHtmlString().Replace(tempName, ResourceUtils.GetString(resourceKey))); } } }
MurielSoftware/MyArt
Client.Core/HtmlHelpers/LocalizedActionLinkExtensions.cs
C#
apache-2.0
3,704
/** * 文件名 : package-info.java * 包 名 : tk.ainiyue.danyuan.application.dbm.tabs * 描 述 : TODO(用一句话描述该文件做什么) * 机能名称: * 技能ID : * 作 者 : wang * 时 间 : 2017年7月12日 下午10:22:30 * 版 本 : V1.0 */ package org.danyuan.application.dbms.tabs;
514840279/danyuan-application
src/main/java/org/danyuan/application/dbms/tabs/package-info.java
Java
apache-2.0
360
// Copyright 2016 DeepFabric, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package redis import ( "strconv" "github.com/deepfabric/elasticell/pkg/pb/raftcmdpb" "github.com/fagongzi/goetty" gredis "github.com/fagongzi/goetty/protocol/redis" "github.com/fagongzi/util/format" "github.com/fagongzi/util/hack" ) const ( pong = "PONG" ) var ( ErrNotSupportCommand = []byte("command is not support") ErrInvalidCommandResp = []byte("invalid command") PongResp = []byte("PONG") OKStatusResp = []byte("OK") ) // WriteFVPairArray write field value pair array resp func WriteFVPairArray(lst []*raftcmdpb.FVPair, buf *goetty.ByteBuf) { buf.WriteByte('*') if len(lst) == 0 { buf.Write(gredis.NullArray) buf.Write(gredis.Delims) } else { buf.Write(hack.StringToSlice(strconv.Itoa(len(lst) * 2))) buf.Write(gredis.Delims) for i := 0; i < len(lst); i++ { gredis.WriteBulk(lst[i].Field, buf) gredis.WriteBulk(lst[i].Value, buf) } } } // WriteScorePairArray write score member pair array resp func WriteScorePairArray(lst []*raftcmdpb.ScorePair, withScores bool, buf *goetty.ByteBuf) { buf.WriteByte('*') if len(lst) == 0 { buf.Write(gredis.NullArray) buf.Write(gredis.Delims) } else { if withScores { buf.Write(hack.StringToSlice(strconv.Itoa(len(lst) * 2))) buf.Write(gredis.Delims) } else { buf.Write(hack.StringToSlice(strconv.Itoa(len(lst)))) buf.Write(gredis.Delims) } for i := 0; i < len(lst); i++ { gredis.WriteBulk(lst[i].Member, buf) if withScores { gredis.WriteBulk(format.Float64ToString(lst[i].Score), buf) } } } }
deepfabric/elasticell
pkg/redis/resp.go
GO
apache-2.0
2,061
<?php require_once '../../../../core/init.php'; chdir(dirname(__FILE__)); ?> <!DOCTYPE html> <html class="no-js" lang="en"> <head> <title>Patient Health</title> <?php include '../../../../includes/php/head.php'; ?> <link rel="stylesheet" type="text/css" href="css/blue-buttons-list.css"> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Year', 'Sales', 'Expenses'], ['2004', 1000, 400], ['2005', 1170, 460], ['2006', 660, 1120], ['2007', 1030, 540] ]); var options = { title: 'Company Performance', curveType: 'function', legend: { position: 'bottom' }, backgroundColor: '#ebebeb' }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } $(window).resize(function(){ drawChart(); }); </script> </head> <body> <div id="container"> <?php include '../../../../includes/php/header.php'; ?> <?php if(Session::exists('home')) { echo '<p>' . Session::flash('home'). '</p>'; } $user = new User(); //Current if($user->isLoggedIn()) { ?> <div class="row"> <h1> Inhaler Usage </h1> <div id="curve_chart" style="width: 100%; height: 500px"></div> <p> <br> <i><a href="">Wikipedia</a></i> </p> </div> <?php } else { ?> <div class="row"> <h1> Error </h1> <p> You are currently not Signed In!<br> Please <a href='sign.php'>Sign In</a> or <a href='register.php'>Register</a> </p> </div> <?php } ?> </div> <?php include '../../../../includes/php/footer.php'; ?> <script src="js/foundation.min.js"></script> <script> $(document).foundation(); </script> </body> </html>
ehosp/eHOSP-Services-CE
src/resources/views/services/patient-med-profile/measurement_includes/Results/inhaler.php
PHP
apache-2.0
2,312
/** GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. */ package jscover.report.lcov; import jscover.report.FileData; import jscover.report.JSONDataMerger; import jscover.util.IoUtils; import org.junit.After; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.util.SortedMap; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class LCovGeneratorIntegrationTest { private LCovGenerator lCovGenerator = new LCovGenerator(); private JSONDataMerger jsonDataMerger = new JSONDataMerger(); private IoUtils ioUtils = IoUtils.getInstance(); private File dest; @After public void tearDown() { //dest.delete(); } @Test @Ignore public void shouldGenerateLCovDataForYUI3() throws Exception { String json = IoUtils.getInstance().loadFromFileSystem(new File("src/test-integration/resources/jscover/report/xml/jscoverage.json")); SortedMap<String, FileData> data = jsonDataMerger.jsonToMap(json); dest = new File("target/yui3.lcov"); lCovGenerator.saveData(data.values(), "c:/js/yui3", dest); } @Test public void shouldGenerateLCovDataFromJSON() throws Exception { String path = new File(".").getCanonicalPath().replaceAll("\\\\","/"); String json = IoUtils.getInstance().loadFromFileSystem(new File("src/test/resources/jscover/report/jscoverage-select-2-4-branch.json")); SortedMap<String, FileData> data = jsonDataMerger.jsonToMap(json); dest = new File("target/test.lcov"); lCovGenerator.saveData(data.values(), path, dest); String result = ioUtils.loadFromFileSystem(dest); String expected = "SF:" + path + "/doc/example" + "/script.js\n" + "BRDA:3,0,1,2\n" + "BRDA:3,0,2,-\n" + "BRDA:6,0,1,1\n" + "BRDA:6,0,2,1\n" + "BRDA:9,0,1,1\n" + "BRDA:9,0,2,-\n" + "BRDA:12,0,1,-\n" + "BRDA:12,0,2,1\n" + "DA:1,2\n" + "DA:2,2\n" + "DA:3,2\n" + "DA:4,0\n" + "DA:6,2\n" + "DA:7,1\n" + "DA:9,1\n" + "DA:10,0\n" + "DA:12,1\n" + "DA:13,1\n" + "DA:15,2\n" + "DA:16,2\n" + "DA:17,2\n" + "DA:18,2\n" + "DA:19,2\n" + "end_of_record\n"; assertThat(result, equalTo(expected)); } }
alfiethomas/datafilters
build/JSCover-0.1.1/src/test-integration/java/jscover/report/lcov/LCovGeneratorIntegrationTest.java
Java
apache-2.0
20,988
/* LzFind.h -- Match finder for LZ algorithms 2009-04-22 : Igor Pavlov : Public domain */ /* Modified by Felix Hanau*/ #ifdef __cplusplus extern "C" { #endif typedef unsigned char Byte; typedef unsigned UInt32; typedef struct _CMatchFinder { const Byte *buffer; const Byte *bufend; UInt32 pos; UInt32 cyclicBufferPos; UInt32 *hash; UInt32 *son; } CMatchFinder; void MatchFinder_Create(CMatchFinder *p); void MatchFinder_Free(CMatchFinder *p); unsigned short Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, unsigned short* distances); void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); void CopyMF(const CMatchFinder *p, CMatchFinder* copy); static const unsigned crc[256] = { 0u, 1996959894u, 3993919788u, 2567524794u, 124634137u, 1886057615u, 3915621685u, 2657392035u, 249268274u, 2044508324u, 3772115230u, 2547177864u, 162941995u, 2125561021u, 3887607047u, 2428444049u, 498536548u, 1789927666u, 4089016648u, 2227061214u, 450548861u, 1843258603u, 4107580753u, 2211677639u, 325883990u, 1684777152u, 4251122042u, 2321926636u, 335633487u, 1661365465u, 4195302755u, 2366115317u, 997073096u, 1281953886u, 3579855332u, 2724688242u, 1006888145u, 1258607687u, 3524101629u, 2768942443u, 901097722u, 1119000684u, 3686517206u, 2898065728u, 853044451u, 1172266101u, 3705015759u, 2882616665u, 651767980u, 1373503546u, 3369554304u, 3218104598u, 565507253u, 1454621731u, 3485111705u, 3099436303u, 671266974u, 1594198024u, 3322730930u, 2970347812u, 795835527u, 1483230225u, 3244367275u, 3060149565u, 1994146192u, 31158534u, 2563907772u, 4023717930u, 1907459465u, 112637215u, 2680153253u, 3904427059u, 2013776290u, 251722036u, 2517215374u, 3775830040u, 2137656763u, 141376813u, 2439277719u, 3865271297u, 1802195444u, 476864866u, 2238001368u, 4066508878u, 1812370925u, 453092731u, 2181625025u, 4111451223u, 1706088902u, 314042704u, 2344532202u, 4240017532u, 1658658271u, 366619977u, 2362670323u, 4224994405u, 1303535960u, 984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u, 2765210733u, 3554079995u, 1131014506u, 879679996u, 2909243462u, 3663771856u, 1141124467u, 855842277u, 2852801631u, 3708648649u, 1342533948u, 654459306u, 3188396048u, 3373015174u, 1466479909u, 544179635u, 3110523913u, 3462522015u, 1591671054u, 702138776u, 2966460450u, 3352799412u, 1504918807u, 783551873u, 3082640443u, 3233442989u, 3988292384u, 2596254646u, 62317068u, 1957810842u, 3939845945u, 2647816111u, 81470997u, 1943803523u, 3814918930u, 2489596804u, 225274430u, 2053790376u, 3826175755u, 2466906013u, 167816743u, 2097651377u, 4027552580u, 2265490386u, 503444072u, 1762050814u, 4150417245u, 2154129355u, 426522225u, 1852507879u, 4275313526u, 2312317920u, 282753626u, 1742555852u, 4189708143u, 2394877945u, 397917763u, 1622183637u, 3604390888u, 2714866558u, 953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u, 3624741850u, 2936675148u, 906185462u, 1090812512u, 3747672003u, 2825379669u, 829329135u, 1181335161u, 3412177804u, 3160834842u, 628085408u, 1382605366u, 3423369109u, 3138078467u, 570562233u, 1426400815u, 3317316542u, 2998733608u, 733239954u, 1555261956u, 3268935591u, 3050360625u, 752459403u, 1541320221u, 2607071920u, 3965973030u, 1969922972u, 40735498u, 2617837225u, 3943577151u, 1913087877u, 83908371u, 2512341634u, 3803740692u, 2075208622u, 213261112u, 2463272603u, 3855990285u, 2094854071u, 198958881u, 2262029012u, 4057260610u, 1759359992u, 534414190u, 2176718541u, 4139329115u, 1873836001u, 414664567u, 2282248934u, 4279200368u, 1711684554u, 285281116u, 2405801727u, 4167216745u, 1634467795u, 376229701u, 2685067896u, 3608007406u, 1308918612u, 956543938u, 2808555105u, 3495958263u, 1231636301u, 1047427035u, 2932959818u, 3654703836u, 1088359270u, 936918000u, 2847714899u, 3736837829u, 1202900863u, 817233897u, 3183342108u, 3401237130u, 1404277552u, 615818150u, 3134207493u, 3453421203u, 1423857449u, 601450431u, 3009837614u, 3294710456u, 1567103746u, 711928724u, 3020668471u, 3272380065u, 1510334235u, 755167117u }; #ifdef __cplusplus } #endif
fhanau/Efficient-Compression-Tool
src/LzFind.h
C
apache-2.0
4,182
/* * Copyright (c) 2015 mgm technology partners GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mgmtp.jfunk.core.ui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Desktop; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.tree.TreePath; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.log4j.Logger; /** * GUI for starting test scripts * */ public final class JFunkFrame extends JFrame { private static final String PATH_TO_MAIL_CONFIG_FILES = "config/email_accounts"; private static final String PROPS_SUFFIX = "properties"; private static final long serialVersionUID = 1L; private final Logger log = Logger.getLogger(getClass()); private JTree tree; private JMenuBar menuBar; private JPopupMenu popup; private JComboBox jFunkPropertyFilesComboBox; private JComboBox testSystemsComboBox; private JComboBox mailConfigurationsComboBox; private JComboBox threadCountComboBox; private JComboBox parallelComboBox; private PropertiesComboBoxModel mailConfigurationsModel; private PropertiesComboBoxModel testSystemsModel; private PropertiesComboBoxModel jFunkPropertyFilesModel; private JPanel jPanelUtilities; private final List<File> roots; private final Action fileOpenScriptsAction = new FileOpenScriptsAction(); private final Action fileEditPropertiesAction = new FileEditPropertiesAction(); private final Action fileExitAction = new FileExitAction(); private final Action toolsRunAction = new ToolsRunAction(); public static void createAndShow(final List<File> roots) { final Runnable r = new Runnable() { @Override public void run() { final JFunkFrame frame = new JFunkFrame(roots); frame.setUpGui(); frame.setVisible(true); frame.tree.requestFocus(); } }; SwingUtilities.invokeLater(r); } public static void main(final String[] args) { List<File> roots = new ArrayList<File>(Math.max(1, args.length)); if (args.length > 0) { for (String arg : args) { File file = new File(arg); if (file.exists()) { roots.add(new File(arg)); } } } else { roots.add(new File("scripts")); } Collections.sort(roots); JFunkFrame.createAndShow(roots); } private JFunkFrame(final List<File> roots) { super("jFunk SkriptRunner UI"); this.roots = roots; setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); } private boolean readState() { ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("jFunkFrame.state")); setBounds((Rectangle) ois.readObject()); setExtendedState(ois.readInt()); tree.setSelectionPaths((TreePath[]) ois.readObject()); jFunkPropertyFilesComboBox.setSelectedIndex(ois.readInt()); testSystemsComboBox.setSelectedIndex(ois.readInt()); mailConfigurationsComboBox.setSelectedIndex(ois.readInt()); threadCountComboBox.setSelectedIndex(ois.readInt()); parallelComboBox.setSelectedIndex(ois.readInt()); return true; } catch (final FileNotFoundException ex) { log.warn("Could not find saved state (which is fine during first start)"); return false; } catch (final Exception ex) { log.error("Error reading state", ex); return false; } finally { IOUtils.closeQuietly(ois); } } private void writeState() { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("jFunkFrame.state")); oos.writeObject(getBounds()); oos.writeInt(getExtendedState()); oos.writeObject(tree.getSelectionPaths()); oos.writeInt(jFunkPropertyFilesComboBox.getSelectedIndex()); oos.writeInt(testSystemsComboBox.getSelectedIndex()); oos.writeInt(mailConfigurationsComboBox.getSelectedIndex()); oos.writeInt(threadCountComboBox.getSelectedIndex()); oos.writeInt(parallelComboBox.getSelectedIndex()); } catch (final IOException ex) { log.error("Error writing prferences.", ex); } finally { IOUtils.closeQuietly(oos); } } private void setUpGui() { buildMenuBar(); buildToolBar(); buildPopup(); buildTree(); BufferedImage image = null; try { image = ImageIO.read(getClass().getResource("/jFunk.png")); setIconImage(image); } catch (Exception e) { log.warn("Could not read icon image, standard icon will be used. Exception was: " + e.getMessage()); } setJMenuBar(menuBar); if (!readState()) { setSize(520, 600); setLocationRelativeTo(null); } final JScrollPane scrollPane = new JScrollPane(tree, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); final Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(jPanelUtilities, BorderLayout.NORTH); contentPane.add(scrollPane, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { exit(); } }); } private void buildMenuBar() { menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); menu.setMnemonic('F'); menu.add(fileOpenScriptsAction); menu.add(fileEditPropertiesAction); menu.addSeparator(); menu.add(fileExitAction); menuBar.add(menu); menu = new JMenu("Tools"); menu.setMnemonic('T'); menu.add(toolsRunAction); menuBar.add(menu); } private void buildPopup() { popup = new JPopupMenu(); popup.add(fileOpenScriptsAction); popup.add(toolsRunAction); } private void buildToolBar() { // Toolbar for the first line JToolBar toolBarFirstLine = new JToolBar("Toolbar"); toolBarFirstLine.setRequestFocusEnabled(false); toolBarFirstLine.setFloatable(false); toolBarFirstLine.add(fileOpenScriptsAction); toolBarFirstLine.add(toolsRunAction); toolBarFirstLine.addSeparator(); // Build component jFunk property files jFunkPropertyFilesModel = new PropertiesComboBoxModel("config", "jfunk", PROPS_SUFFIX, null, true); jFunkPropertyFilesComboBox = new JComboBox(jFunkPropertyFilesModel); jFunkPropertyFilesComboBox.setBorder(BorderFactory.createTitledBorder("jFunk configuration")); // Multi-line tooltip jFunkPropertyFilesComboBox.setToolTipText("<html>List of jFunk property files containing listener and modules" + "<br>Location: all files in directory 'config'</br></html>"); toolBarFirstLine.add(jFunkPropertyFilesComboBox); // Build component testsystems testSystemsModel = new PropertiesComboBoxModel("config/system", null, PROPS_SUFFIX, "baseurl", false); testSystemsComboBox = new JComboBox(testSystemsModel); testSystemsComboBox.setBorder(BorderFactory.createTitledBorder("Test system")); // Multi-line tooltip testSystemsComboBox.setToolTipText("<html>List of test systems" + "<br>Defined by all files in directory 'config/system'</br></html>"); testSystemsComboBox.setSelectedItem(0); toolBarFirstLine.add(testSystemsComboBox); // Toolbar for the second line JToolBar toolBarSecondLine = new JToolBar(); toolBarSecondLine.setRequestFocusEnabled(false); toolBarSecondLine.setFloatable(false); // Build component mail configuration mailConfigurationsModel = new PropertiesComboBoxModel(PATH_TO_MAIL_CONFIG_FILES, null, PROPS_SUFFIX, null, false); mailConfigurationsComboBox = new JComboBox(mailConfigurationsModel); mailConfigurationsComboBox.setBorder(BorderFactory.createTitledBorder("Mail configuration")); // Multi-line tooltip mailConfigurationsComboBox.setToolTipText("<html>List of mail configurations" + "<br>Defined by all files in directory 'config/email_accounts'</br></html>"); toolBarSecondLine.add(mailConfigurationsComboBox); // Build component thread count threadCountComboBox = new JComboBox(createNumberArray(30)); threadCountComboBox.setBorder(BorderFactory.createTitledBorder("Threads")); threadCountComboBox.setToolTipText("Number of threads which will be used for the execution of the selected script files"); toolBarSecondLine.add(threadCountComboBox); // Build component parallel parallelComboBox = new JComboBox(new String[] { "yes", "no" }); parallelComboBox.setSelectedIndex(1); parallelComboBox.setBorder(BorderFactory.createTitledBorder("Parallel?")); parallelComboBox .setToolTipText("If set to 'yes', a single script will be executed " + "multiple times using the specified number of threads"); toolBarSecondLine.add(parallelComboBox); jPanelUtilities = new JPanel(); jPanelUtilities.setLayout(new BorderLayout()); jPanelUtilities.add(toolBarFirstLine, BorderLayout.NORTH); jPanelUtilities.add(toolBarSecondLine, BorderLayout.CENTER); } private Integer[] createNumberArray(final int max) { Integer[] numbers = new Integer[max]; for (int i = 0; i < max; i++) { numbers[i] = i + 1; } return numbers; } private void buildTree() { tree = new JTree(new ScriptsTreeModel(roots)); tree.setCellRenderer(new ScriptsTreeCellRenderer()); tree.setRootVisible(false); tree.setShowsRootHandles(true); tree.addKeyListener(new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { runScripts(); } } }); tree.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (!e.isPopupTrigger() && e.getClickCount() == 2) { if (tree.getModel().isLeaf(tree.getSelectionPath().getLastPathComponent())) { runScripts(); } } } @Override public void mousePressed(final MouseEvent e) { if (e.isPopupTrigger()) { TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); TreePath[] paths = tree.getSelectionPaths(); boolean newPath = true; for (TreePath path : paths) { if (selPath.equals(path)) { newPath = false; break; } } if (newPath) { tree.setSelectionPath(selPath); } popup.show((Component) e.getSource(), e.getX(), e.getY()); } } @Override public void mouseReleased(final MouseEvent e) { if (e.isPopupTrigger()) { TreePath selPath = tree.getPathForLocation(e.getX(), e.getY()); TreePath[] paths = tree.getSelectionPaths(); boolean newPath = true; for (TreePath path : paths) { if (selPath.equals(path)) { newPath = false; break; } } if (newPath) { tree.setSelectionPath(selPath); } popup.show((Component) e.getSource(), e.getX(), e.getY()); } } }); } private void exit() { writeState(); System.exit(0); } private void runScripts() { try { TreePath[] paths = tree.getSelectionPaths(); if (paths == null) { JOptionPane.showMessageDialog(JFunkFrame.this, "No script(s) selected!", "Error", JOptionPane.ERROR_MESSAGE); return; } String testSystem; boolean parallel = false; if (StringUtils.equals((String) parallelComboBox.getSelectedItem(), "yes")) { parallel = true; } testSystem = testSystemsModel.getSelectedItem(); int threads = (Integer) threadCountComboBox.getSelectedItem(); List<String> commandsList = new ArrayList<String>(paths.length + 5); if (SystemUtils.IS_OS_WINDOWS) { commandsList.add("cmd.exe"); commandsList.add("/X"); commandsList.add("/C"); commandsList.add("start"); commandsList.add("run_testskript.bat"); } else if (SystemUtils.IS_OS_LINUX) { commandsList.add("/usr/bin/xterm"); commandsList.add("-e"); commandsList.add("./run_testskript.sh"); } else { JOptionPane.showMessageDialog(JFunkFrame.this, "Routines for running test scripts are only defined for Windows and Linux systems", "Error", JOptionPane.ERROR_MESSAGE); return; } //Threadcount wird als argument weiter gereicht. commandsList.add("-threadcount=" + threads); //Flag parallel wird als Parameter weiter gereicht. if (parallel) { commandsList.add("-parallel"); } if (paths.length == 1) { commandsList.add(((File) paths[0].getLastPathComponent()).getPath()); } else { boolean hasScriptOrDir = false; for (TreePath path : paths) { File file = (File) path.getLastPathComponent(); if (file.isFile()) { commandsList.add(file.getPath()); hasScriptOrDir = true; } } if (!hasScriptOrDir) { // Es wurden nur Verzeichnisse ausgewählt. // Erstes Verzeichnis nehmen! commandsList.add(((File) paths[0].getLastPathComponent()).getPath()); } } final ProcessBuilder pb = new ProcessBuilder(commandsList); pb.environment().put("EXIT_AFTER_RUNNING", "true"); StringBuilder opts = new StringBuilder("-Djfunk.props.file=" + jFunkPropertyFilesModel.getSelectedItem()); opts.append(" -Dtestsystem=" + testSystem); String mailConfig = mailConfigurationsModel.getSelectedItem(); if (!StringUtils.equals(mailConfig, "default")) { opts.append(" -Dsystem.properties.mailconfig=email_accounts/" + mailConfig + "." + PROPS_SUFFIX); } pb.environment().put("APP_OPTS", opts.toString()); pb.start(); } catch (final Exception ex) { log.error(ex.getMessage(), ex); JOptionPane.showMessageDialog(JFunkFrame.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } private class FileOpenScriptsAction extends AbstractAction { private static final long serialVersionUID = 1L; public FileOpenScriptsAction() { super("Open script(s)"); final URL url = getClass().getResource("/Open16.gif"); putValue(SMALL_ICON, new ImageIcon(url)); putValue(SHORT_DESCRIPTION, "Open script(s)"); putValue(MNEMONIC_KEY, KeyEvent.VK_S); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); } @Override public void actionPerformed(final ActionEvent e) { try { TreePath[] paths = tree.getSelectionPaths(); if (paths == null) { return; } for (TreePath path : paths) { File file = (File) path.getLastPathComponent(); if (file.isFile()) { if (System.getProperty("os.name").toLowerCase().contains("windows")) { String cmd = "rundll32 url.dll,FileProtocolHandler " + file.getCanonicalPath(); Runtime.getRuntime().exec(cmd); } else { Desktop.getDesktop().edit(file); } } } } catch (final Exception ex) { log.error(ex.getMessage(), ex); JOptionPane.showMessageDialog(JFunkFrame.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private class FileEditPropertiesAction extends AbstractAction { private static final long serialVersionUID = 1L; public FileEditPropertiesAction() { super("Edit properties file"); final URL url = getClass().getResource("/Edit16.gif"); putValue(SMALL_ICON, new ImageIcon(url)); putValue(SHORT_DESCRIPTION, "Edit properties file"); putValue(MNEMONIC_KEY, KeyEvent.VK_E); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK)); } @Override public void actionPerformed(final ActionEvent e) { try { File f = new File("config/" + jFunkPropertyFilesModel.getSelectedItem() + (jFunkPropertyFilesModel.isIncludeSuffix() ? "" : "." + PROPS_SUFFIX)); if (System.getProperty("os.name").toLowerCase().contains("windows")) { String cmd = "rundll32 url.dll,FileProtocolHandler " + f.getCanonicalPath(); Runtime.getRuntime().exec(cmd); } else { Desktop.getDesktop().edit(f); } } catch (final Exception ex) { log.error(ex.getMessage(), ex); JOptionPane.showMessageDialog(JFunkFrame.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } } private class FileExitAction extends AbstractAction { private static final long serialVersionUID = 1L; public FileExitAction() { super("Exit"); putValue(MNEMONIC_KEY, KeyEvent.VK_X); } @Override public void actionPerformed(final ActionEvent e) { exit(); } } private class ToolsRunAction extends AbstractAction { private static final long serialVersionUID = 1L; public ToolsRunAction() { super("Run script(s)"); final URL url = getClass().getResource("/Play16.gif"); putValue(SMALL_ICON, new ImageIcon(url)); putValue(SHORT_DESCRIPTION, "Run script(s)"); putValue(MNEMONIC_KEY, KeyEvent.VK_R); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0)); } @Override public void actionPerformed(final ActionEvent e) { runScripts(); } } }
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/ui/JFunkFrame.java
Java
apache-2.0
18,651
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2021 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.oracle.model; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.data.DBDInsertReplaceMethod; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.struct.DBSAttributeBase; import org.jkiss.dbeaver.model.struct.DBSEntityConstraintType; import org.jkiss.dbeaver.model.struct.rdb.DBSTable; import org.jkiss.dbeaver.model.struct.rdb.DBSTableConstraint; import org.jkiss.utils.CommonUtils; import java.util.Collection; import java.util.Optional; public class OracleInsertReplaceMethodIgnore implements DBDInsertReplaceMethod { private static final Log log = Log.getLog(OracleInsertReplaceMethodIgnore.class); @NotNull @Override public String getOpeningClause(DBSTable table, DBRProgressMonitor monitor) { if (table != null) { try { Collection<? extends DBSTableConstraint> constraints = table.getConstraints(monitor); if (!CommonUtils.isEmpty(constraints)) { Optional<? extends DBSTableConstraint> tableConstraint = constraints .stream().filter(key -> key.getConstraintType() == DBSEntityConstraintType.PRIMARY_KEY).findFirst(); if (tableConstraint.isPresent()) { DBSTableConstraint constraint = tableConstraint.get(); return "INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(" + table.getName() + ", " + constraint.getName() + ") */ INTO"; } } } catch (DBException e) { log.debug("Can't read table constraints list"); } } return "INSERT INTO"; } @Override public String getTrailingClause(DBSTable table, DBRProgressMonitor monitor, DBSAttributeBase[] attributes) { return null; } }
Sargul/dbeaver
plugins/org.jkiss.dbeaver.ext.oracle/src/org/jkiss/dbeaver/ext/oracle/model/OracleInsertReplaceMethodIgnore.java
Java
apache-2.0
2,574
/* * Copyright 2013 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package org.openntf.domino; import java.util.Vector; import org.openntf.domino.types.DatabaseDescendant; import org.openntf.domino.types.FactorySchema; /** * The Interface ViewEntry. */ public interface ViewEntry extends lotus.domino.ViewEntry, org.openntf.domino.ext.ViewEntry, Base<lotus.domino.ViewEntry>, DatabaseDescendant { public static class Schema extends FactorySchema<ViewEntry, lotus.domino.ViewEntry, View> { @Override public Class<ViewEntry> typeClass() { return ViewEntry.class; } @Override public Class<lotus.domino.ViewEntry> delegateClass() { return lotus.domino.ViewEntry.class; } @Override public Class<View> parentClass() { return View.class; } }; public static final Schema SCHEMA = new Schema(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getChildCount() */ @Override public int getChildCount(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getColumnIndentLevel() */ @Override public int getColumnIndentLevel(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getColumnValues() */ @Override public Vector<Object> getColumnValues(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getDescendantCount() */ @Override public int getDescendantCount(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getDocument() */ @Override public Document getDocument(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getFTSearchScore() */ @Override public int getFTSearchScore(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getIndentLevel() */ @Override public int getIndentLevel(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getNoteID() */ @Override public String getNoteID(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getNoteIDAsInt() */ @Override public int getNoteIDAsInt(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getParent() */ @Override public Base<?> getParent(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getPosition(char) */ @Override public String getPosition(final char separator); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getRead() */ @Override public boolean getRead(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getRead(java.lang.String) */ @Override public boolean getRead(final String userName); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getSiblingCount() */ @Override public int getSiblingCount(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#getUniversalID() */ @Override public String getUniversalID(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#isCategory() */ @Override public boolean isCategory(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#isConflict() */ @Override public boolean isConflict(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#isDocument() */ @Override public boolean isDocument(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#isPreferJavaDates() */ @Override public boolean isPreferJavaDates(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#isTotal() */ @Override public boolean isTotal(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#isValid() */ @Override public boolean isValid(); /* * (non-Javadoc) * * @see lotus.domino.ViewEntry#setPreferJavaDates(boolean) */ @Override public void setPreferJavaDates(final boolean flag); }
rPraml/org.openntf.domino
domino/core/src/main/java/org/openntf/domino/ViewEntry.java
Java
apache-2.0
4,134
/* * Licensed Materials - Property of IBM * (C) Copyright IBM Corp. 2010, 2017 * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */ define({ // NLS_CHARSET=UTF-8 // configuration configuration_pane_aspera_url: "Adresa URL servera IBM Aspera", configuration_pane_aspera_url_hover: "Zadajte adresu URL servera IBM Aspera. Napríklad: https://názov_hostiteľa:číslo_portu/aspera/faspex", configuration_pane_aspera_url_prompt: "Dôrazne odporúčame, aby ste používali protokol HTTPS.", configuration_pane_max_docs_to_send: "Maximálny počet odoslaných položiek", configuration_pane_max_docs_to_send_hover: "Zadajte maximálny počet položiek, ktoré môžu užívatelia naraz odoslať.", configuration_pane_max_procs_to_send: "Maximálny počet súbežných požiadaviek", configuration_pane_max_procs_to_send_hover: "Zadajte maximálny počet požiadaviek, ktoré môžu byť súčasne spustené.", configuration_pane_target_transfer_rate: "Cieľová prenosová rýchlosť (v Mb/s)", configuration_pane_target_transfer_rate_hover: "Zadajte cieľovú prenosovú rýchlosť ako Mb/s. Maximálna rýchlosť je obmedzená licenčnými oprávneniami.", configuration_pane_speed_info: "Vaša aktuálna základná licencia umožňuje maximálnu prenosovú rýchlosť 20 Mb/s. Ak chcete vykonať inováciu na rýchlejšiu skúšobnú licenciu (podporujúcu prenosovú rýchlosť až do 10 Gb/s) pre softvér Aspera Faspex, požiadajte o novú licenciu na stránke <a target='_blank' href='https://ibm.biz/BdjYHq'>Aspera Evaluation Request</a>.", // runtime send_dialog_sender_title: "Odosielateľ: ${0}", send_dialog_not_set: "Nenastavené", send_dialog_send_one: "Poslať '${0}'.", send_dialog_send_more: "Poslať súbory: ${0}.", send_dialog_sender: "Meno užívateľa:", send_dialog_password: "Heslo:", send_dialog_missing_sender_message: "Je potrebné zadať meno užívateľa pre prihlásenie na server IBM Aspera.", send_dialog_missing_password_message: "Je potrebné zadať heslo pre prihlásenie na server IBM Aspera.", send_dialog_title: "Poslať cez IBM Aspera", send_dialog_missing_title_message: "Musíte zadať názov.", send_dialog_info: "Posielajte súbory cez server IBM Aspera a upozornite užívateľov, že si môžu stiahnuť súbory.", send_dialog_recipients_label: "Príjemcovia:", send_dialog_recipients_textfield_hover_help: "E-mailové adresy alebo mená užívateľov oddeľte čiarkou. Napríklad, zadajte: 'adresa1, adresa2, meno_užívateľa1, meno_užívateľa2'.", send_dialog_missing_recipients_message: "Zadajte aspoň jednu e-mailovú adresu alebo meno užívateľa.", send_dialog_title_label: "Názov:", send_dialog_note_label: "Pridajte správu.", send_dialog_earPassphrase_label: "Heslo pre šifrovanie:", send_dialog_earPassphrase_textfield_hover_help: "Zadajte heslo pre zašifrovanie súborov na serveri. Toto heslo budú musieť príjemcovia zadať, aby mohli dešifrovať chránené súbory po stiahnutí.", send_dialog_notify_title: "Upozornenie: ${0}", send_dialog_notifyOnUpload_label: "Upozorniť ma na nahratie súboru", send_dialog_notifyOnDownload_label: "Upozorniť ma na stiahnutie súboru", send_dialog_notifyOnUploadDownload: "Upozorniť ma na nahratie a stiahnutie súboru", send_dialog_send_button_label: "Odoslať", send_dialog_started: "Balík ${0} sa posiela.", status_started: "Stav balíka: ${0} - prebieha (${1} %)", status_stopped: "Stav balíka: ${0} - zastavené", status_failed: "Stav balíka: ${0} - neúspešné", status_completed: "Stav balíka: ${0} - dokončené", // error send_dialog_too_many_items_error: "Nepodarilo sa odoslať položky.", send_dialog_too_many_items_error_explanation: "Môžete odoslať najviac ${0} položiek naraz. Pokúšate sa odoslať ${1} položiek.", send_dialog_too_many_items_error_userResponse: "Vyberte menší počet položiek a znova sa ich pokúste odoslať. Taktiež sa môžete obrátiť na správcu systému a požiadať ho, aby zvýšil maximálny počet súbežne odosielaných položiek.", send_dialog_too_many_items_error_0: "maximum_number_of_items", send_dialog_too_many_items_error_1: "number_of_items", send_dialog_too_many_items_error_number: 5050, });
ibm-ecm/ibm-navigator-aspera-sample
src/main/resources/com/ibm/ecm/extension/aspera/WebContent/aspera/nls/sk/messages.js
JavaScript
apache-2.0
4,353
<?php // Code for Session Cookie workaround if (isset($_POST["PHPSESSID"])) { session_id($_POST["PHPSESSID"]); } else if (isset($_GET["PHPSESSID"])) { session_id($_GET["PHPSESSID"]); } session_start(); $POST_MAX_SIZE = ini_get('post_max_size'); $unit = strtoupper(substr($POST_MAX_SIZE, -1)); $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1))); if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) { header("HTTP/1.1 500 Internal Server Error"); echo "POST exceeded maximum allowed size."; exit(0); } // Settings $save_path = getcwd() . "/file/"; $upload_name = "Filedata"; $max_file_size_in_bytes = 2147483647; // 2GB in bytes $extension_whitelist = array("doc", "txt", "jpg", "gif", "png"); //ÔÊÐíµÄÎļþ $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-'; //ÔÊÐíµÄÎļþÃû×Ö·û // Other variables $MAX_FILENAME_LENGTH = 260; $file_name = ""; $file_extension = ""; $uploadErrors = array( 0=>"ÎļþÉÏ´«³É¹¦", 1=>"ÉÏ´«µÄÎļþ³¬¹ýÁË php.ini ÎļþÖÐµÄ upload_max_filesize directive ÀïµÄÉèÖÃ", 2=>"ÉÏ´«µÄÎļþ³¬¹ýÁË HTML form ÎļþÖÐµÄ MAX_FILE_SIZE directive ÀïµÄÉèÖÃ", 3=>"ÉÏ´«µÄÎļþ½öΪ²¿·ÖÎļþ", 4=>"ûÓÐÎļþÉÏ´«", 6=>"ȱÉÙÁÙʱÎļþ¼Ð" ); if (!isset($_FILES[$upload_name])) { HandleError("No upload found in \$_FILES for " . $upload_name); exit(0); } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) { HandleError($uploadErrors[$_FILES[$upload_name]["error"]]); exit(0); } else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) { HandleError("Upload failed is_uploaded_file test."); exit(0); } else if (!isset($_FILES[$upload_name]['name'])) { HandleError("File has no name."); exit(0); } $file_size = @filesize($_FILES[$upload_name]["tmp_name"]); if (!$file_size || $file_size > $max_file_size_in_bytes) { HandleError("File exceeds the maximum allowed size"); exit(0); } if ($file_size <= 0) { HandleError("File size outside allowed lower bound"); exit(0); } $file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name'])); if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) { HandleError("Invalid file name"); exit(0); } if (file_exists($save_path . $file_name)) { HandleError("File with this name already exists"); exit(0); } // Validate file extension $path_info = pathinfo($_FILES[$upload_name]['name']); $file_extension = $path_info["extension"]; $is_valid_extension = false; foreach ($extension_whitelist as $extension) { if (strcasecmp($file_extension, $extension) == 0) { $is_valid_extension = true; break; } } if (!$is_valid_extension) { HandleError("Invalid file extension"); exit(0); } if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) { HandleError("ÎļþÎÞ·¨±£´æ."); exit(0); }else{ } echo "File Received"; exit(0); function HandleError($message) { header("HTTP/1.1 500 Internal Server Error"); echo $message; } ?>
SailingLRH/sailing
sailing/src/main/webapp/resources/SWFUpload v2.2.0/upload.php
PHP
apache-2.0
3,306
<!-- BEGIN MUNGE: UNVERSIONED_WARNING --> <!-- BEGIN STRIP_FOR_RELEASE --> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <img src="http://kubernetes.io/img/warning.png" alt="WARNING" width="25" height="25"> <h2>PLEASE NOTE: This document applies to the HEAD of the source tree</h2> If you are using a released version of Kubernetes, you should refer to the docs that go with that version. <strong> The latest 1.0.x release of this document can be found [here](http://releases.k8s.io/release-1.0/docs/user-guide/logging.md). Documentation for other releases can be found at [releases.k8s.io](http://releases.k8s.io). </strong> -- <!-- END STRIP_FOR_RELEASE --> <!-- END MUNGE: UNVERSIONED_WARNING --> # Logging ## Logging by Kubernetes Components Kubernetes components, such as kubelet and apiserver, use the [glog](https://godoc.org/github.com/golang/glog) logging library. Developer conventions for logging severity are described in [docs/devel/logging.md](../devel/logging.md). ## Examining the logs of running containers The logs of a running container may be fetched using the command `kubectl logs`. For example, given this pod specification [counter-pod.yaml](../../examples/blog-logging/counter-pod.yaml), which has a container which writes out some text to standard output every second. (You can find different pod specifications [here](logging-demo/).) ```yaml apiVersion: v1 kind: Pod metadata: name: counter spec: containers: - name: count image: ubuntu:14.04 args: [bash, -c, 'for ((i = 0; ; i++)); do echo "$i: $(date)"; sleep 1; done'] ``` we can run the pod: ```console $ kubectl create -f ./counter-pod.yaml pods/counter ``` and then fetch the logs: ```console $ kubectl logs counter 0: Tue Jun 2 21:37:31 UTC 2015 1: Tue Jun 2 21:37:32 UTC 2015 2: Tue Jun 2 21:37:33 UTC 2015 3: Tue Jun 2 21:37:34 UTC 2015 4: Tue Jun 2 21:37:35 UTC 2015 5: Tue Jun 2 21:37:36 UTC 2015 ... ``` If a pod has more than one container then you need to specify which container's log files should be fetched e.g. ```console $ kubectl logs kube-dns-v3-7r1l9 etcd 2015/06/23 00:43:10 etcdserver: start to snapshot (applied: 30003, lastsnap: 20002) 2015/06/23 00:43:10 etcdserver: compacted log at index 30003 2015/06/23 00:43:10 etcdserver: saved snapshot at index 30003 2015/06/23 02:05:42 etcdserver: start to snapshot (applied: 40004, lastsnap: 30003) 2015/06/23 02:05:42 etcdserver: compacted log at index 40004 2015/06/23 02:05:42 etcdserver: saved snapshot at index 40004 2015/06/23 03:28:31 etcdserver: start to snapshot (applied: 50005, lastsnap: 40004) 2015/06/23 03:28:31 etcdserver: compacted log at index 50005 2015/06/23 03:28:31 etcdserver: saved snapshot at index 50005 2015/06/23 03:28:56 filePurge: successfully removed file default.etcd/member/wal/0000000000000000-0000000000000000.wal 2015/06/23 04:51:03 etcdserver: start to snapshot (applied: 60006, lastsnap: 50005) 2015/06/23 04:51:03 etcdserver: compacted log at index 60006 2015/06/23 04:51:03 etcdserver: saved snapshot at index 60006 ... ``` ## Cluster level logging to Google Cloud Logging The getting started guide [Cluster Level Logging to Google Cloud Logging](../getting-started-guides/logging.md) explains how container logs are ingested into [Google Cloud Logging](https://cloud.google.com/logging/docs/) and shows how to query the ingested logs. ## Cluster level logging with Elasticsearch and Kibana The getting started guide [Cluster Level Logging with Elasticsearch and Kibana](../getting-started-guides/logging-elasticsearch.md) describes how to ingest cluster level logs into Elasticsearch and view them using Kibana. ## Ingesting Application Log Files Cluster level logging only collects the standard output and standard error output of the applications running in containers. The guide [Collecting log files within containers with Fluentd](http://releases.k8s.io/HEAD/contrib/logging/fluentd-sidecar-gcp/README.md) explains how the log files of applications can also be ingested into Google Cloud logging. ## Known issues Kubernetes does log rotation for kubernetes components and docker containers. The command `kubectl logs` currently only read the latest logs, not all historical ones. <!-- BEGIN MUNGE: GENERATED_ANALYTICS --> [![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/docs/user-guide/logging.md?pixel)]() <!-- END MUNGE: GENERATED_ANALYTICS -->
evandbrown/kubernetes
docs/user-guide/logging.md
Markdown
apache-2.0
4,760
#include "base/geo_object_id.hpp" #include "base/assert.hpp" #include <iostream> #include <sstream> namespace { // todo(@m) Uncomment when the transition from osm::Id to base::GeoObjectId is complete // and add assertions about the highest bit. // The old scheme used the highest bit and the new one does not. // uint64_t const kTypeMask = 0x7F00000000000000; uint64_t const kTypeMask = 0xFF00000000000000; uint64_t const kReservedMask = 0x00FF000000000000; uint64_t const kSerialMask = 0x0000FFFFFFFFFFFF; } // namespace namespace base { GeoObjectId::GeoObjectId(uint64_t encodedId) : m_encodedId(encodedId) {} GeoObjectId::GeoObjectId(GeoObjectId::Type type, uint64_t id) : m_encodedId((static_cast<uint64_t>(type) << 56) | id) {} uint64_t GeoObjectId::GetSerialId() const { CHECK_NOT_EQUAL(m_encodedId & kTypeMask, 0, ()); CHECK_EQUAL(m_encodedId & kReservedMask, 0, ()); return m_encodedId & kSerialMask; } uint64_t GeoObjectId::GetEncodedId() const { return m_encodedId; } GeoObjectId::Type GeoObjectId::GetType() const { CHECK_EQUAL(m_encodedId & kReservedMask, 0, ()); uint64_t const typeBits = (m_encodedId & kTypeMask) >> 56; switch (typeBits) { case 0x00: return GeoObjectId::Type::Invalid; case 0x01: return GeoObjectId::Type::OsmNode; case 0x02: return GeoObjectId::Type::OsmWay; case 0x03: return GeoObjectId::Type::OsmRelation; case 0x04: return GeoObjectId::Type::BookingComNode; case 0x05: return GeoObjectId::Type::OsmSurrogate; case 0x06: return GeoObjectId::Type::Fias; case 0x40: return GeoObjectId::Type::ObsoleteOsmNode; case 0x80: return GeoObjectId::Type::ObsoleteOsmWay; case 0xC0: return GeoObjectId::Type::ObsoleteOsmRelation; } CHECK_SWITCH(); } GeoObjectId MakeOsmNode(uint64_t id) { return GeoObjectId(GeoObjectId::Type::ObsoleteOsmNode, id); } GeoObjectId MakeOsmWay(uint64_t id) { return GeoObjectId(GeoObjectId::Type::ObsoleteOsmWay, id); } GeoObjectId MakeOsmRelation(uint64_t id) { return GeoObjectId(GeoObjectId::Type::ObsoleteOsmRelation, id); } std::ostream & operator<<(std::ostream & os, GeoObjectId const & geoObjectId) { os << geoObjectId.GetEncodedId(); return os; } std::string DebugPrint(GeoObjectId::Type const & t) { switch (t) { case GeoObjectId::Type::Invalid: return "Invalid"; case GeoObjectId::Type::OsmNode: return "Osm Node"; case GeoObjectId::Type::OsmWay: return "Osm Way"; case GeoObjectId::Type::OsmRelation: return "Osm Relation"; case GeoObjectId::Type::BookingComNode: return "Booking.com"; case GeoObjectId::Type::OsmSurrogate: return "Osm Surrogate"; case GeoObjectId::Type::Fias: return "FIAS"; case GeoObjectId::Type::ObsoleteOsmNode: return "Osm Node"; case GeoObjectId::Type::ObsoleteOsmWay: return "Osm Way"; case GeoObjectId::Type::ObsoleteOsmRelation: return "Osm Relation"; } CHECK_SWITCH(); } std::string DebugPrint(GeoObjectId const & id) { std::ostringstream oss; // GetSerialId() does not work for invalid ids but we may still want to print them. oss << DebugPrint(id.GetType()) << " " << (id.GetEncodedId() & kSerialMask); return oss.str(); } } // namespace base
ygorshenin/omim
base/geo_object_id.cpp
C++
apache-2.0
3,159
/** * */ package org.minnal.security.auth; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.Response.StatusType; import org.glassfish.jersey.message.internal.OutboundJaxrsResponse; import org.glassfish.jersey.message.internal.OutboundMessageContext; import org.minnal.core.MinnalException; import org.minnal.security.session.Session; import org.pac4j.core.context.WebContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Charsets; /** * @author ganeshs * */ public class JaxrsWebContext implements WebContext { private ContainerRequestContext request; private Response response; private OutboundMessageContext context; private Session session; private static final Logger logger = LoggerFactory.getLogger(JaxrsWebContext.class); /** * @param request * @param response * @param session */ public JaxrsWebContext(ContainerRequestContext request, OutboundMessageContext context, Session session) { this.request = request; this.context = context; this.session = session; this.response = new OutboundJaxrsResponse.Builder(context).build(); } /** * @return the request */ public ContainerRequestContext getRequest() { return request; } /** * @return the response */ public Response getResponse() { return response; } /** * @return the session */ public Session getSession() { return session; } @Override public String getRequestParameter(String name) { return request.getUriInfo().getQueryParameters().getFirst(name); } @Override public Map<String, String[]> getRequestParameters() { Set<Entry<String, List<String>>> entries = request.getUriInfo().getQueryParameters().entrySet(); Map<String, String[]> params = new HashMap<String, String[]>(); for (Entry<String, List<String>> entry : entries) { params.put(entry.getKey(), entry.getValue().toArray(new String[0])); } return params; } @Override public String getRequestHeader(String name) { return request.getHeaderString(name); } @Override public void setSessionAttribute(String name, Object value) { session.addAttribute(name, value); } @Override public Object getSessionAttribute(String name) { return session.getAttribute(name); } @Override public String getRequestMethod() { return request.getMethod(); } @Override public void writeResponseContent(String content) { try { context.getEntityStream().write(content.getBytes(Charsets.UTF_8)); } catch (IOException e) { logger.error("Failed while writing the response content", e); throw new MinnalException("Failed while writing the response content", e); } } @Override public void setResponseStatus(final int code) { StatusType type = Response.Status.fromStatusCode(code); if (type == null) { type = new StatusType() { @Override public int getStatusCode() { return code; } @Override public String getReasonPhrase() { return null; } @Override public Family getFamily() { return Family.familyOf(code); } }; } response = new OutboundJaxrsResponse(type, context); } @Override public void setResponseHeader(String name, String value) { response.getHeaders().add(name, value); } public String getServerName() { return request.getUriInfo().getRequestUri().getHost(); } @Override public int getServerPort() { return request.getUriInfo().getRequestUri().getPort(); } @Override public String getScheme() { return request.getUriInfo().getRequestUri().getScheme(); } @Override public String getFullRequestURL() { return request.getUriInfo().getRequestUri().toASCIIString(); } }
minnal/minnal
minnal-security/src/main/java/org/minnal/security/auth/JaxrsWebContext.java
Java
apache-2.0
3,914
package opts // import "github.com/tiborvass/docker/opts" // QuotedString is a string that may have extra quotes around the value. The // quotes are stripped from the value. type QuotedString struct { value *string } // Set sets a new value func (s *QuotedString) Set(val string) error { *s.value = trimQuotes(val) return nil } // Type returns the type of the value func (s *QuotedString) Type() string { return "string" } func (s *QuotedString) String() string { return *s.value } func trimQuotes(value string) string { lastIndex := len(value) - 1 for _, char := range []byte{'\'', '"'} { if value[0] == char && value[lastIndex] == char { return value[1:lastIndex] } } return value } // NewQuotedString returns a new quoted string option func NewQuotedString(value *string) *QuotedString { return &QuotedString{value: value} }
tiborvass/docker
opts/quotedstring.go
GO
apache-2.0
851
function New-VSNetworkManagerDevice { <# .SYNOPSIS Adds an AWS::NetworkManager::Device resource to the template. Specifies a device. .DESCRIPTION Adds an AWS::NetworkManager::Device resource to the template. Specifies a device. .LINK http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html .PARAMETER LogicalId The logical ID must be alphanumeric (A-Za-z0-9) and unique within the template. Use the logical name to reference the resource in other parts of the template. For example, if you want to map an Amazon Elastic Block Store volume to an Amazon EC2 instance, you reference the logical IDs to associate the block stores with the instance. .PARAMETER Description A description of the device. Length Constraints: Maximum length of 256 characters. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-description UpdateType: Mutable PrimitiveType: String .PARAMETER Tags The tags for the device. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-tags UpdateType: Mutable Type: List ItemType: Tag .PARAMETER GlobalNetworkId The ID of the global network. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-globalnetworkid UpdateType: Immutable PrimitiveType: String .PARAMETER Location The site location. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-location UpdateType: Mutable Type: Location .PARAMETER Model The model of the device. Length Constraints: Maximum length of 128 characters. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-model UpdateType: Mutable PrimitiveType: String .PARAMETER SerialNumber The serial number of the device. Length Constraints: Maximum length of 128 characters. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-serialnumber UpdateType: Mutable PrimitiveType: String .PARAMETER SiteId The site ID. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-siteid UpdateType: Mutable PrimitiveType: String .PARAMETER Type The device type. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-type UpdateType: Mutable PrimitiveType: String .PARAMETER Vendor The vendor of the device. Length Constraints: Maximum length of 128 characters. Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-networkmanager-device.html#cfn-networkmanager-device-vendor UpdateType: Mutable PrimitiveType: String .PARAMETER DeletionPolicy With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted. You specify a DeletionPolicy attribute for each resource that you want to control. If a resource has no DeletionPolicy attribute, AWS CloudFormation deletes the resource by default. To keep a resource when its stack is deleted, specify Retain for that resource. You can use retain for any resource. For example, you can retain a nested stack, S3 bucket, or EC2 instance so that you can continue to use or modify those resources after you delete their stacks. You must use one of the following options: "Delete","Retain","Snapshot" .PARAMETER UpdateReplacePolicy Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation. When you initiate a stack update, AWS CloudFormation updates resources based on differences between what you submit and the stack's current template and parameters. If you update a resource property that requires that the resource be replaced, AWS CloudFormation recreates the resource during the update. Recreating the resource generates a new physical ID. AWS CloudFormation creates the replacement resource first, and then changes references from other dependent resources to point to the replacement resource. By default, AWS CloudFormation then deletes the old resource. Using the UpdateReplacePolicy, you can specify that AWS CloudFormation retain or (in some cases) create a snapshot of the old resource. For resources that support snapshots, such as AWS::EC2::Volume, specify Snapshot to have AWS CloudFormation create a snapshot before deleting the old resource instance. You can apply the UpdateReplacePolicy attribute to any resource. UpdateReplacePolicy is only executed if you update a resource property whose update behavior is specified as Replacement, thereby causing AWS CloudFormation to replace the old resource with a new one with a new physical ID. For example, if you update the Engine property of an AWS::RDS::DBInstance resource type, AWS CloudFormation creates a new resource and replaces the current DB instance resource with the new one. The UpdateReplacePolicy attribute would then dictate whether AWS CloudFormation deleted, retained, or created a snapshot of the old DB instance. The update behavior for each property of a resource is specified in the reference topic for that resource in the AWS Resource and Property Types Reference. For more information on resource update behavior, see Update Behaviors of Stack Resources. The UpdateReplacePolicy attribute applies to stack updates you perform directly, as well as stack updates performed using change sets. Note Resources that are retained continue to exist and continue to incur applicable charges until you delete those resources. Snapshots that are created with this policy continue to exist and continue to incur applicable charges until you delete those snapshots. UpdateReplacePolicy retains the old physical resource or snapshot, but removes it from AWS CloudFormation's scope. UpdateReplacePolicy differs from the DeletionPolicy attribute in that it only applies to resources replaced during stack updates. Use DeletionPolicy for resources deleted when a stack is deleted, or when the resource definition itself is deleted from the template as part of a stack update. You must use one of the following options: "Delete","Retain","Snapshot" .PARAMETER DependsOn With the DependsOn attribute you can specify that the creation of a specific resource follows another. When you add a DependsOn attribute to a resource, that resource is created only after the creation of the resource specified in the DependsOn attribute. This parameter takes a string or list of strings representing Logical IDs of resources that must be created prior to this resource being created. .PARAMETER Metadata The Metadata attribute enables you to associate structured data with a resource. By adding a Metadata attribute to a resource, you can add data in JSON or YAML to the resource declaration. In addition, you can use intrinsic functions (such as GetAtt and Ref), parameters, and pseudo parameters within the Metadata attribute to add those interpreted values. You must use a PSCustomObject containing key/value pairs here. This will be returned when describing the resource using AWS CLI. .PARAMETER UpdatePolicy Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource. AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a scheduled action is associated with the Auto Scaling group. You must use the "Add-UpdatePolicy" function here. .PARAMETER Condition Logical ID of the condition that this resource needs to be true in order for this resource to be provisioned. .FUNCTIONALITY Vaporshell #> [OutputType('Vaporshell.Resource.NetworkManager.Device')] [cmdletbinding()] Param ( [parameter(Mandatory = $true,Position = 0)] [ValidateScript( { if ($_ -match "^[a-zA-Z0-9]*$") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String 'The LogicalID must be alphanumeric (a-z, A-Z, 0-9) and unique within the template.')) } })] [System.String] $LogicalId, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Description, [VaporShell.Core.TransformTag()] [parameter(Mandatory = $false)] $Tags, [parameter(Mandatory = $true)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $GlobalNetworkId, [parameter(Mandatory = $false)] $Location, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Model, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $SerialNumber, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $SiteId, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Type, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.String","Vaporshell.Function","Vaporshell.Condition" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Vendor, [ValidateSet("Delete","Retain","Snapshot")] [System.String] $DeletionPolicy, [ValidateSet("Delete","Retain","Snapshot")] [System.String] $UpdateReplacePolicy, [parameter(Mandatory = $false)] [System.String[]] $DependsOn, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "System.Management.Automation.PSCustomObject" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "The UpdatePolicy parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $Metadata, [parameter(Mandatory = $false)] [ValidateScript( { $allowedTypes = "Vaporshell.Resource.UpdatePolicy" if ([string]$($_.PSTypeNames) -match "($(($allowedTypes|ForEach-Object{[RegEx]::Escape($_)}) -join '|'))") { $true } else { $PSCmdlet.ThrowTerminatingError((New-VSError -String "This parameter only accepts the following types: $($allowedTypes -join ", "). The current types of the value are: $($_.PSTypeNames -join ", ").")) } })] $UpdatePolicy, [parameter(Mandatory = $false)] $Condition ) Begin { $ResourceParams = @{ LogicalId = $LogicalId Type = "AWS::NetworkManager::Device" } $commonParams = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') } Process { foreach ($key in $PSBoundParameters.Keys | Where-Object {$commonParams -notcontains $_}) { switch ($key) { LogicalId {} DeletionPolicy { $ResourceParams.Add("DeletionPolicy",$DeletionPolicy) } UpdateReplacePolicy { $ResourceParams.Add("UpdateReplacePolicy",$UpdateReplacePolicy) } DependsOn { $ResourceParams.Add("DependsOn",$DependsOn) } Metadata { $ResourceParams.Add("Metadata",$Metadata) } UpdatePolicy { $ResourceParams.Add("UpdatePolicy",$UpdatePolicy) } Condition { $ResourceParams.Add("Condition",$Condition) } Tags { if (!($ResourceParams["Properties"])) { $ResourceParams.Add("Properties",([PSCustomObject]@{})) } $ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name Tags -Value @($Tags) } Default { if (!($ResourceParams["Properties"])) { $ResourceParams.Add("Properties",([PSCustomObject]@{})) } $ResourceParams["Properties"] | Add-Member -MemberType NoteProperty -Name $key -Value $PSBoundParameters[$key] } } } } End { $obj = New-VaporResource @ResourceParams $obj | Add-ObjectDetail -TypeName 'Vaporshell.Resource.NetworkManager.Device' Write-Verbose "Resulting JSON from $($MyInvocation.MyCommand): `n`n$(@{$obj.LogicalId = $obj.Props} | ConvertTo-Json -Depth 5)`n" } }
scrthq/Vaporshell
VaporShell/Public/Resource Types/New-VSNetworkManagerDevice.ps1
PowerShell
apache-2.0
17,490
/* Copyright 2020 The cert-manager Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This file defines methods used for PKCS#12 support. // This is an experimental feature and the contents of this file are intended // to be absorbed into a more fully fledged implementing ahead of the v0.15 // release. // This should hopefully not exist by the next time you come to read this :) package secretsmanager import ( "bytes" "crypto/rand" "crypto/x509" "time" jks "github.com/pavel-v-chernykh/keystore-go" "software.sslmate.com/src/go-pkcs12" "github.com/jetstack/cert-manager/pkg/util/pki" ) const ( // pkcs12SecretKey is the name of the data entry in the Secret resource // used to store the p12 file. pkcs12SecretKey = "keystore.p12" // Data Entry Name in the Secret resource for PKCS12 containing Certificate Authority pkcs12TruststoreKey = "truststore.p12" // jksSecretKey is the name of the data entry in the Secret resource // used to store the jks file. jksSecretKey = "keystore.jks" // Data Entry Name in the Secret resource for JKS containing Certificate Authority jksTruststoreKey = "truststore.jks" ) // encodePKCS12Keystore will encode a PKCS12 keystore using the password provided. // The key, certificate and CA data must be provided in PKCS1 or PKCS8 PEM format. // If the certificate data contains multiple certificates, the first will be used // as the keystores 'certificate' and the remaining certificates will be prepended // to the list of CAs in the resulting keystore. func encodePKCS12Keystore(password string, rawKey []byte, certPem []byte, caPem []byte) ([]byte, error) { key, err := pki.DecodePrivateKeyBytes(rawKey) if err != nil { return nil, err } certs, err := pki.DecodeX509CertificateChainBytes(certPem) if err != nil { return nil, err } var cas []*x509.Certificate if len(caPem) > 0 { cas, err = pki.DecodeX509CertificateChainBytes(caPem) if err != nil { return nil, err } } // prepend the certificate chain to the list of certificates as the PKCS12 // library only allows setting a single certificate. if len(certs) > 1 { cas = append(certs[1:], cas...) } return pkcs12.Encode(rand.Reader, key, certs[0], cas, password) } func encodePKCS12Truststore(password string, caPem []byte) ([]byte, error) { ca, err := pki.DecodeX509CertificateBytes(caPem) if err != nil { return nil, err } var cas = []*x509.Certificate{ca} return pkcs12.EncodeTrustStore(rand.Reader, cas, password) } func encodeJKSKeystore(password []byte, rawKey []byte, certPem []byte, caPem []byte) ([]byte, error) { // encode the private key to PKCS8 key, err := pki.DecodePrivateKeyBytes(rawKey) if err != nil { return nil, err } keyDER, err := x509.MarshalPKCS8PrivateKey(key) if err != nil { return nil, err } // encode the certificate chain chain, err := pki.DecodeX509CertificateChainBytes(certPem) if err != nil { return nil, err } certs := make([]jks.Certificate, len(chain)) for i, cert := range chain { certs[i] = jks.Certificate{ Type: "X509", Content: cert.Raw, } } ks := jks.KeyStore{ "certificate": &jks.PrivateKeyEntry{ Entry: jks.Entry{ CreationDate: time.Now(), }, PrivKey: keyDER, CertChain: certs, }, } // add the CA certificate, if set if len(caPem) > 0 { ca, err := pki.DecodeX509CertificateBytes(caPem) if err != nil { return nil, err } ks["ca"] = &jks.TrustedCertificateEntry{ Entry: jks.Entry{ CreationDate: time.Now(), }, Certificate: jks.Certificate{ Type: "X509", Content: ca.Raw, }, } } buf := &bytes.Buffer{} if err := jks.Encode(buf, ks, password); err != nil { return nil, err } return buf.Bytes(), nil } func encodeJKSTruststore(password []byte, caPem []byte) ([]byte, error) { ca, err := pki.DecodeX509CertificateBytes(caPem) if err != nil { return nil, err } ks := jks.KeyStore{ "ca": &jks.TrustedCertificateEntry{ Entry: jks.Entry{ CreationDate: time.Now(), }, Certificate: jks.Certificate{ Type: "X509", Content: ca.Raw, }, }, } buf := &bytes.Buffer{} if err := jks.Encode(buf, ks, password); err != nil { return nil, err } return buf.Bytes(), nil }
jetstack-experimental/cert-manager
pkg/controller/certificates/internal/secretsmanager/keystore.go
GO
apache-2.0
4,691
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2010 The ZAP Development team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.extension.anticsrf; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.HTMLElementName; import net.htmlparser.jericho.Source; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.control.Control.Mode; import org.parosproxy.paros.db.DatabaseException; import org.parosproxy.paros.extension.ExtensionAdaptor; import org.parosproxy.paros.extension.ExtensionHook; import org.parosproxy.paros.extension.SessionChangedListener; import org.parosproxy.paros.extension.encoder.Encoder; import org.parosproxy.paros.extension.history.ExtensionHistory; import org.parosproxy.paros.extension.history.HistoryFilter; import org.parosproxy.paros.model.HistoryReference; import org.parosproxy.paros.model.Session; import org.parosproxy.paros.network.HtmlParameter; import org.parosproxy.paros.network.HttpMalformedHeaderException; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.extension.pscan.ExtensionPassiveScan; /** * An {@code Extension} that handles anti-csrf tokens. * <p> * Extracts and tracks anti-csrf tokens, allowing to refresh and send them in new requests. * * @since 1.3.0 */ public class ExtensionAntiCSRF extends ExtensionAdaptor implements SessionChangedListener { public static final String NAME = "ExtensionAntiCSRF"; public static final String TAG = "AntiCSRF"; private Map<String, AntiCsrfToken> valueToToken = new HashMap<>(); private OptionsAntiCsrfPanel optionsAntiCsrfPanel = null; private PopupMenuGenerateForm popupMenuGenerateForm = null; private Encoder encoder = new Encoder(); private static Logger log = Logger.getLogger(ExtensionAntiCSRF.class); private AntiCsrfParam antiCsrfParam; private AntiCsrfDetectScanner antiCsrfDetectScanner; private HistoryReferenceFactory historyReferenceFactory; public ExtensionAntiCSRF() { super(); initialize(); } private void initialize() { this.setName(NAME); this.setOrder(50); } @Override public boolean supportsDb(String type) { return true; } @Override public void init() { antiCsrfParam = new AntiCsrfParam(); antiCsrfDetectScanner = new AntiCsrfDetectScanner(this); } @Override public String getUIName() { return Constant.messages.getString("acsrf.name"); } @Override public void hook(ExtensionHook extensionHook) { super.hook(extensionHook); extensionHook.addOptionsParamSet(antiCsrfParam); final ExtensionHistory extensionHistory = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.class); if (extensionHistory != null) { historyReferenceFactory = new HistoryReferenceFactory() { @Override public HistoryReference createHistoryReference(int id) { return extensionHistory.getHistoryReference(id); } }; } else { historyReferenceFactory = new HistoryReferenceFactory() { @Override public HistoryReference createHistoryReference(int id) throws HttpMalformedHeaderException, DatabaseException { return new HistoryReference(id); } }; } AntiCsrfToken.setHistoryReferenceFactory(historyReferenceFactory); extensionHook.addSessionListener(this); if (getView() != null) { extensionHook.getHookView().addOptionPanel(getOptionsAntiCsrfPanel()); extensionHook.getHookMenu().addPopupMenuItem(this.getPopupMenuGenerateForm()); } ExtensionPassiveScan extensionPassiveScan = Control.getSingleton().getExtensionLoader().getExtension(ExtensionPassiveScan.class); if (extensionPassiveScan != null) { extensionPassiveScan.addPassiveScanner(antiCsrfDetectScanner); } AntiCsrfAPI api = new AntiCsrfAPI(this); api.addApiOptions(getParam()); extensionHook.addApiImplementor(api); } @Override public void unload() { ExtensionPassiveScan extensionPassiveScan = Control.getSingleton().getExtensionLoader().getExtension(ExtensionPassiveScan.class); if (extensionPassiveScan != null) { extensionPassiveScan.removePassiveScanner(antiCsrfDetectScanner); } super.unload(); } private PopupMenuGenerateForm getPopupMenuGenerateForm() { if (popupMenuGenerateForm == null) { this.popupMenuGenerateForm = new PopupMenuGenerateForm(Constant.messages.getString("anticsrf.genForm.popup")); } return popupMenuGenerateForm; } private OptionsAntiCsrfPanel getOptionsAntiCsrfPanel() { if (optionsAntiCsrfPanel == null) { optionsAntiCsrfPanel = new OptionsAntiCsrfPanel(); } return optionsAntiCsrfPanel; } protected AntiCsrfParam getParam() { return antiCsrfParam; } /** * Gets the names of the anti-csrf tokens handled by this extension. * * @return the names of the anti-csrf tokens. * @see #addAntiCsrfTokenName(String) * @since 1.4.0 */ public List<String> getAntiCsrfTokenNames() { return this.getParam().getTokensNames(); } /** * Adds the given token name, enabled by default. * <p> * The call to this method has no effect if the given name is null or empty, or a token with the given name already exist. * * @param token the token name to add. * @see #removeAntiCsrfTokenName(String) * @see #getAntiCsrfTokenNames() * @since 1.4.0 */ public void addAntiCsrfTokenName(String token) { this.getParam().addToken(token); } /** * Removes the given token name. * <p> * The call to this method has no effect if the given name is null or empty, or if the token with the given name does not * exist. * * @param token the token name to remove. * @see #addAntiCsrfTokenName(String) * @since 1.4.0 */ public void removeAntiCsrfTokenName(String token) { this.getParam().removeToken(token); } public void registerAntiCsrfToken(AntiCsrfToken token) { log.debug("registerAntiCsrfToken " + token.getMsg().getRequestHeader().getURI().toString() + " " + token.getValue()); synchronized (valueToToken) { try { HistoryReference hRef = token.getMsg().getHistoryRef(); if (hRef == null) { hRef = new HistoryReference(getModel().getSession(), HistoryReference.TYPE_TEMPORARY, token.getMsg()); token.getMsg().setHistoryRef(null); } token.setHistoryReferenceId(hRef.getHistoryId()); valueToToken.put(encoder.getURLEncode(token.getValue()), token); } catch (HttpMalformedHeaderException | DatabaseException e) { log.error("Failed to persist the message: ", e); } } } public boolean requestHasToken(HttpMessage msg) { return this.requestHasToken(msg.getRequestBody().toString()); } public boolean requestHasToken(String reqBody) { Set<String> values; synchronized (valueToToken) { values = Collections.unmodifiableSet(new HashSet<String>(valueToToken.keySet())); } for (String token : values) { if (reqBody.indexOf(token) >= 0) { return true; } } return false; } public List<AntiCsrfToken> getTokens(HttpMessage msg) { return this.getTokens(msg.getRequestBody().toString(), msg.getRequestHeader().getURI().toString()); } private List<AntiCsrfToken> getTokens(String reqBody, String targetUrl) { List<AntiCsrfToken> tokens = new ArrayList<>(); Set<String> values; synchronized (valueToToken) { values = Collections.unmodifiableSet(new HashSet<String>(valueToToken.keySet())); } for (String value : values) { if (reqBody.indexOf(value) >= 0) { AntiCsrfToken token = valueToToken.get(value).clone(); token.setTargetURL(targetUrl); tokens.add(token); } } return tokens; } public String getTokenValue(HttpMessage tokenMsg, String tokenName) { Source source = new Source(tokenMsg.getResponseBody().toString()); List<Element> formElements = source.getAllElements(HTMLElementName.FORM); if (formElements != null && formElements.size() > 0) { // Loop through all of the FORM tags for (Element formElement : formElements) { List<Element> inputElements = formElement.getAllElements(HTMLElementName.INPUT); if (inputElements != null && inputElements.size() > 0) { // Loop through all of the INPUT elements for (Element inputElement : inputElements) { String id = inputElement.getAttributeValue("ID"); if (id != null && id.equalsIgnoreCase(tokenName)) { return inputElement.getAttributeValue("VALUE"); } String name = inputElement.getAttributeValue("NAME"); if (name != null && name.equalsIgnoreCase(tokenName)) { return inputElement.getAttributeValue("VALUE"); } } } } } return null; } /** * Convenience method that calls {@link #getTokensFromResponse(HttpMessage, Source)} with a {@code Source} built from the * response of the given HTTP message. * * @param msg from where the tokens should be extracted. * @return the extracted anti-csrf tokens. * @since TODO add version */ public List<AntiCsrfToken> getTokensFromResponse(HttpMessage msg) { return getTokensFromResponse(msg, new Source(msg.getResponseBody().toString())); } /** * Gets the {@link #getAntiCsrfTokenNames() known} anti-csrf tokens from the given response. * * @param msg from where the tokens should be extracted. * @param source the HTML source document of the response. * @return the extracted anti-csrf tokens. * @since 2.2.0 */ public List<AntiCsrfToken> getTokensFromResponse(HttpMessage msg, Source source) { List<AntiCsrfToken> list = new ArrayList<>(); List<Element> formElements = source.getAllElements(HTMLElementName.FORM); if (formElements != null && formElements.size() > 0) { // Loop through all of the FORM tags log.debug("Found " + formElements.size() + " forms"); int formIndex = 0; for (Element formElement : formElements) { List<Element> inputElements = formElement.getAllElements(HTMLElementName.INPUT); if (inputElements != null && inputElements.size() > 0) { // Loop through all of the INPUT elements log.debug("Found " + inputElements.size() + " inputs"); for (Element inputElement : inputElements) { String value = inputElement.getAttributeValue("VALUE"); if (value == null) { continue; } String attId = inputElement.getAttributeValue("ID"); boolean found = false; if (attId != null) { for (String tokenName : this.getAntiCsrfTokenNames()) { if (tokenName.equalsIgnoreCase(attId)) { list.add(new AntiCsrfToken(msg, attId, value, formIndex)); found = true; break; } } } if (!found) { String name = inputElement.getAttributeValue("NAME"); if (name != null) { for (String tokenName : this.getAntiCsrfTokenNames()) { if (tokenName.equalsIgnoreCase(name)) { list.add(new AntiCsrfToken(msg, name, value, formIndex)); break; } } } } } } formIndex++; } } return list; } @Override public void sessionChanged(Session session) { if (session == null) { // Closedown return; } synchronized (valueToToken) { valueToToken.clear(); } // search for tokens... try { List<Integer> list = getModel().getDb().getTableHistory().getHistoryIdsOfHistType( session.getSessionId(), HistoryReference.TYPE_PROXIED, HistoryReference.TYPE_ZAP_USER); HistoryFilter filter = new HistoryFilter(); filter.setTags(Arrays.asList(new String[] {TAG})); AntiCsrfDetectScanner antiCsrfDetectScanner = new AntiCsrfDetectScanner(this); for (Integer i : list) { HistoryReference hRef = historyReferenceFactory.createHistoryReference(i); if (filter.matches(hRef)) { HttpMessage msg = hRef.getHttpMessage(); Source src = new Source(msg.getResponseBody().toString()); if (msg.isResponseFromTargetHost()) { antiCsrfDetectScanner.scanHttpResponseReceive(msg, hRef.getHistoryId(), src); } } } } catch (DatabaseException | HttpMalformedHeaderException e) { log.error(e.getMessage(), e); } } public boolean isAntiCsrfToken(String name) { if (name == null) { return false; } return this.getParam().getTokensNames().contains(name.toLowerCase()); } @Override public void sessionAboutToChange(Session session) { } @Override public void sessionScopeChanged(Session session) { } @Override public String getAuthor() { return Constant.ZAP_TEAM; } @Override public String getDescription() { return Constant.messages.getString("anticsrf.desc"); } @Override public URL getURL() { try { return new URL(Constant.ZAP_HOMEPAGE); } catch (MalformedURLException e) { return null; } } @Override public void sessionModeChanged(Mode mode) { // Ignore } public String generateForm(int hrefId) throws Exception { ExtensionHistory extHist = Control.getSingleton().getExtensionLoader().getExtension(ExtensionHistory.class); if (extHist != null) { HistoryReference hr = extHist.getHistoryReference(hrefId); if (hr != null) { return generateForm(hr.getHttpMessage()); } } return null; } /** * Generates a HTML form from the given message. * * @param msg the message used to generate the HTML form, must not be {@code null}. * @return a string containing the HTML form, never {@code null}. * @throws UnsupportedEncodingException if an error occurred while encoding the values of the form. * @since 2.7.0 */ public String generateForm(HttpMessage msg) throws UnsupportedEncodingException { String requestUri = msg.getRequestHeader().getURI().toString(); StringBuilder sb = new StringBuilder(300); sb.append("<html>\n"); sb.append("<body>\n"); sb.append("<h3>"); sb.append(requestUri); sb.append("</h3>"); sb.append("<form id=\"f1\" method=\"POST\" action=\"").append(requestUri).append("\">\n"); sb.append("<table>\n"); TreeSet<HtmlParameter> params = msg.getFormParams(); Iterator<HtmlParameter> iter = params.iterator(); while (iter.hasNext()) { HtmlParameter htmlParam = iter.next(); String name = URLDecoder.decode(htmlParam.getName(), "UTF-8"); String value = URLDecoder.decode(htmlParam.getValue(), "UTF-8"); sb.append("<tr><td>\n"); sb.append(name); sb.append("<td>"); sb.append("<input name=\""); sb.append(name); sb.append("\" value=\""); sb.append(value); sb.append("\" size=\"100\">"); sb.append("</tr>\n"); } sb.append("</table>\n"); sb.append("<input id=\"submit\" type=\"submit\" value=\"Submit\"/>\n"); sb.append("</form>\n"); sb.append("</body>\n"); sb.append("</html>\n"); return sb.toString(); } static interface HistoryReferenceFactory { HistoryReference createHistoryReference(int id) throws DatabaseException, HttpMalformedHeaderException; } }
zapbot/zaproxy
src/org/zaproxy/zap/extension/anticsrf/ExtensionAntiCSRF.java
Java
apache-2.0
15,949
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ghidra.file.formats.sparseimage; import static ghidra.formats.gfilesystem.fileinfo.FileAttributeType.*; import java.io.IOException; import java.util.List; import ghidra.app.util.bin.ByteProvider; import ghidra.app.util.bin.ByteProviderWrapper; import ghidra.formats.gfilesystem.*; import ghidra.formats.gfilesystem.annotations.FileSystemInfo; import ghidra.formats.gfilesystem.fileinfo.FileAttributes; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; /** * A pseudo filesystem that contains a single file that is the decompressed contents * of the sparse container file. */ @FileSystemInfo(type = "simg", description = "Android Sparse Image (simg)", factory = SparseImageFileSystemFactory.class) public class SparseImageFileSystem implements GFileSystem { private final FSRLRoot fsFSRL; private final FileSystemRefManager refManager = new FileSystemRefManager(this); private final FileSystemService fsService; private ByteProvider byteProvider; private ByteProvider payloadProvider; private SingleFileSystemIndexHelper fsIndexHelper; public SparseImageFileSystem(FSRLRoot fsFSRL, ByteProvider byteProvider, FileSystemService fsService, TaskMonitor monitor) throws CancelledException, IOException { this.fsFSRL = fsFSRL; this.fsService = fsService; this.byteProvider = byteProvider; this.payloadProvider = getPayload(null, monitor); FSRL containerFSRL = byteProvider.getFSRL(); String payloadName = containerFSRL.getName() + ".raw"; this.fsIndexHelper = new SingleFileSystemIndexHelper(this, fsFSRL, payloadName, payloadProvider.length(), payloadProvider.getFSRL().getMD5()); } @Override public void close() throws IOException { refManager.onClose(); fsIndexHelper.clear(); if (byteProvider != null) { byteProvider.close(); byteProvider = null; } if (payloadProvider != null) { payloadProvider.close(); payloadProvider = null; } } @Override public boolean isClosed() { return fsIndexHelper.isClosed(); } @Override public String getName() { return fsFSRL.getContainer().getName(); } @Override public FSRLRoot getFSRL() { return fsFSRL; } @Override public FileSystemRefManager getRefManager() { return refManager; } @Override public GFile lookup(String path) throws IOException { return fsIndexHelper.lookup(path); } private ByteProvider getPayload(FSRL payloadFSRL, TaskMonitor monitor) throws CancelledException, IOException { return fsService.getDerivedByteProviderPush(byteProvider.getFSRL(), payloadFSRL, "sparse", -1, os -> { SparseImageDecompressor sid = new SparseImageDecompressor(byteProvider, os); sid.decompress(monitor); }, monitor); } @Override public ByteProvider getByteProvider(GFile file, TaskMonitor monitor) throws IOException, CancelledException { if (fsIndexHelper.isPayloadFile(file)) { return new ByteProviderWrapper(payloadProvider, file.getFSRL()); } return null; } @Override public List<GFile> getListing(GFile directory) throws IOException { return fsIndexHelper.getListing(directory); } @Override public FileAttributes getFileAttributes(GFile file, TaskMonitor monitor) { FileAttributes result = new FileAttributes(); if (fsIndexHelper.isPayloadFile(file)) { try { result.add(SIZE_ATTR, payloadProvider.length()); result.add(COMPRESSED_SIZE_ATTR, byteProvider.length()); } catch (IOException e) { // ignore and continue } result.add("MD5", fsIndexHelper.getPayloadFile().getFSRL().getMD5()); } return result; } }
NationalSecurityAgency/ghidra
Ghidra/Features/FileFormats/src/main/java/ghidra/file/formats/sparseimage/SparseImageFileSystem.java
Java
apache-2.0
4,153
package com.darrensun.timus; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Timus 1881 - Long problem statement * Created by Darren on 14-7-9. */ public class Q1881 { public static void main(String[] args) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { StringTokenizer tokenizer = new StringTokenizer(in.readLine()); int h = Integer.parseInt(tokenizer.nextToken()); int w = Integer.parseInt(tokenizer.nextToken()); int n = Integer.parseInt(tokenizer.nextToken()); int remainingSpaceInALine = 0, linesUsed = 0; for (int i = 0; i < n; i++) { int wordLength = in.readLine().length(); if (wordLength <= remainingSpaceInALine) { remainingSpaceInALine -= wordLength + 1; } else { linesUsed++; remainingSpaceInALine = w - (wordLength + 1); } } System.out.println((linesUsed+h-1)/h); } catch (IOException e) { e.printStackTrace(); } } }
darrensun/OJ-Solutions
src/com/darrensun/timus/Q1881.java
Java
apache-2.0
1,228
# Getting started with Liberty on Bluemix By following this guide, you'll set up a development environment, deploy an app locally and on Bluemix, and integrate a Bluemix database service in your app. ## Prerequisites You'll need [Git](https://git-scm.com/downloads), [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads), [Maven](https://maven.apache.org/download.cgi) and a [Bluemix account](https://console.ng.bluemix.net/registration/), ## 1. Clone the sample app Now you're ready to start working with the app. Clone the repo and change the directory to where the sample app is located. ```bash git clone https://github.com/IBM-Bluemix/get-started-java cd get-started-java ``` ## 2. Run the app locally using command line Use Maven to install dependencies and build the .war file. ``` mvn clean install ``` Run the app locally on Liberty. ``` mvn install liberty:run-server ``` View your app at: http://localhost:9080/GetStartedJava ## 3. Deploy to Bluemix using command line To deploy to Bluemix using command line, it can be helpful to set up a manifest.yml file. The manifest.yml includes basic information about your app, such as the name, the location of your app, how much memory to allocate for each instance, and how many instances to create on startup. This is also where you'll choose your URL. [Learn more...](/docs/manageapps/depapps.html#appmanifest) The manifest.yml is provided in the sample. ``` applications: - path: target/GetStartedJava.war memory: 512M instances: 1 name: your-appname-here host: your-appname-here ``` Change both the *name* and *host* to a single unique name of your choice. Note that the *host* value will be used in your public url, for example, http://your-appname-here.mybluemix.net. If you already created an app from the Bluemix UI but haven't pushed your code to it, you can use the same name value. Make sure the path points to the built application, for this example the location is `target/JavaHelloWorldApp.war`. Choose your API endpoint ``` cf api <API-endpoint> ``` Replace the *API-endpoint* in the command with an API endpoint from the following list. * https://api.ng.bluemix.net # US South * https://api.eu-gb.bluemix.net # United Kingdom * https://api.au-syd.bluemix.net # Sydney Login to your Bluemix account ``` cf login ``` Push your application to Bluemix. ``` cf push ``` This can take around two minutes. If there is an error in the deployment process you can use the command `cf logs <Your-App-Name> --recent` to troubleshoot. ## 4. Developing and Deploying using Eclipse IBM® Eclipse Tools for Bluemix provides plug-ins that can be installed into an existing Eclipse environment to assist in integrating the developer's integrated development environment (IDE) with Bluemix. 1. Download and install [IBM Eclipse Tools for Bluemix](https://developer.ibm.com/wasdev/downloads/#asset/tools-IBM_Eclipse_Tools_for_Bluemix). 2. Import this sample into Eclipse using `File` -> `Import` -> `Maven` -> `Existing Maven Projects` option. 3. Create a Liberty server definition: - In the `Servers` view right-click -> `New` -> `Server` - Select `IBM` -> `WebSphere Application Server Liberty` - Choose `Install from an archive or a repository` - Enter a destination path (/Users/username/liberty) - Choose `WAS Liberty with Java EE 7 Web Profile` - Continue the wizard with default options to Finish 4. Run your application locally on Liberty: - Right click on the `GetStartedJava` sample and select `Run As` -> `Run on Server` option - Find and select the localhost Liberty server and press `Finish` - In a few seconds, your application should be running at http://localhost:9080/GetStartedJava/ 5. Create a Bluemix server definition: - In the `Servers` view, right-click -> `New` -> `Server` - Select `IBM` -> `IBM Bluemix` and follow the steps in the wizard.\ - Enter your credentials and click `Next` - Select your `org` and `space` and click `Finish` 6. Run your application on Bluemix: - Right click on the `GetStartedJava` sample and select `Run As` -> `Run on Server` option - Find and select the `IBM Bluemix` and press `Finish` - A wizard will guide you with the deployment options. Be sure to choose a unique `Name` for your application - In a few minutes, your application should be running at the URL you chose. Now you have your code running locally and on the cloud! The `IBM Eclipse Tools for Bluemix` provides many powerful features such as incremental updates, remote debugging, pushing packaged servers, etc. [Learn more](/docs/manageapps/eclipsetools/eclipsetools.html) ## 5. Add a database Next, we'll add a NoSQL database to this application and set up the application so that it can run locally and on Bluemix. 1. Log in to Bluemix in your Browser. Select your application and click on `Connect new` under `Connections`. 2. Select `Cloudant NoSQL DB` and Create the service. 3. Select `Restage` when prompted. Bluemix will restart your application and provide the database credentials to your application using the `VCAP_SERVICES` environment variable. This environment variable is only available to the application when it is running on Bluemix. ## 6. Use the database We're now going to update your local code to point to this database. We'll store the credentials for the services in a properties file. This file will get used ONLY when the application is running locally. When running in Bluemix, the credentials will be read from the VCAP_SERVICES environment variable. 1. In Eclipse, open the file src/main/resources/cloudant.properties: ``` cloudant_url= ``` 2. In your browser open the Bluemix UI, select your App -> Connections -> Cloudant -> View Credentials 3. Copy and paste just the `url` from the credentials to the `url` field of the `cloudant.properties` file. 4. Your Liberty server in Eclipse should automatically pick up the changes and restart the application. View your app at: http://localhost:9080/GetStartedJava/. Any names you enter into the app will now get added to the database. Make any changes you want and re-deploy to Bluemix!
markroberts0830/SimpleJavaApp-MR01
README.md
Markdown
apache-2.0
6,202
package com.turn.ttorrent.client.network; import com.turn.ttorrent.client.Context; import com.turn.ttorrent.client.Handshake; import com.turn.ttorrent.client.LoadedTorrent; import com.turn.ttorrent.client.SharedTorrent; import com.turn.ttorrent.client.peer.SharingPeer; import com.turn.ttorrent.common.LoggerUtils; import com.turn.ttorrent.common.PeerUID; import com.turn.ttorrent.common.TorrentLoggerFactory; import org.slf4j.Logger; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.text.ParseException; import java.util.Arrays; import java.util.concurrent.RejectedExecutionException; public class HandshakeReceiver implements DataProcessor { private static final Logger logger = TorrentLoggerFactory.getLogger(); private final Context myContext; private final String myHostAddress; private final int myPort; private final boolean myIsOutgoingConnection; private ByteBuffer messageBytes; private int pstrLength; HandshakeReceiver(Context context, String hostAddress, int port, boolean isOutgoingListener) { myContext = context; myHostAddress = hostAddress; myPort = port; this.pstrLength = -1; this.myIsOutgoingConnection = isOutgoingListener; } @Override public DataProcessor processAndGetNext(ByteChannel socketChannel) throws IOException { if (pstrLength == -1) { ByteBuffer len = ByteBuffer.allocate(1); int readBytes = -1; try { readBytes = socketChannel.read(len); } catch (IOException ignored) { } if (readBytes == -1) { return new ShutdownProcessor().processAndGetNext(socketChannel); } if (readBytes == 0) { return this; } len.rewind(); byte pstrLen = len.get(); this.pstrLength = pstrLen; messageBytes = ByteBuffer.allocate(this.pstrLength + Handshake.BASE_HANDSHAKE_LENGTH); messageBytes.put(pstrLen); } int readBytes = -1; try { readBytes = socketChannel.read(messageBytes); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "unable to read data from {}", socketChannel, e); } if (readBytes == -1) { return new ShutdownProcessor().processAndGetNext(socketChannel); } if (messageBytes.remaining() != 0) { return this; } Handshake hs = parseHandshake(socketChannel.toString()); if (hs == null) { return new ShutdownProcessor().processAndGetNext(socketChannel); } final LoadedTorrent announceableTorrent = myContext.getTorrentsStorage().getLoadedTorrent(hs.getHexInfoHash()); if (announceableTorrent == null) { logger.debug("Announceable torrent {} is not found in storage", hs.getHexInfoHash()); return new ShutdownProcessor().processAndGetNext(socketChannel); } SharedTorrent torrent; try { torrent = myContext.getTorrentLoader().loadTorrent(announceableTorrent); } catch (IllegalStateException e) { return new ShutdownProcessor().processAndGetNext(socketChannel); } catch(Exception e) { LoggerUtils.warnWithMessageAndDebugDetails(logger, "cannot load torrent {}", hs.getHexInfoHash(), e); return new ShutdownProcessor().processAndGetNext(socketChannel); } logger.trace("got handshake {} from {}", Arrays.toString(messageBytes.array()), socketChannel); String clientTypeVersion = new String(Arrays.copyOf(hs.getPeerId(), 8)); String clientType = clientTypeVersion.substring(1, 3); int clientVersion = 0; try { clientVersion = Integer.parseInt(clientTypeVersion.substring(3, 7)); } catch (NumberFormatException ignored) {} final SharingPeer sharingPeer = myContext.createSharingPeer(myHostAddress, myPort, ByteBuffer.wrap(hs.getPeerId()), torrent, socketChannel, clientType, clientVersion); PeerUID peerUID = new PeerUID(sharingPeer.getAddress(), hs.getHexInfoHash()); SharingPeer old = myContext.getPeersStorage().putIfAbsent(peerUID, sharingPeer); if (old != null) { logger.debug("Already connected to old peer {}, close current connection with {}", old, sharingPeer); return new ShutdownProcessor().processAndGetNext(socketChannel); } // If I am not a leecher if (!myIsOutgoingConnection) { logger.trace("send handshake to {}", socketChannel); try { final Handshake craft = Handshake.craft(hs.getInfoHash(), myContext.getPeersStorage().getSelf().getPeerIdArray()); socketChannel.write(craft.getData()); } catch (IOException e) { LoggerUtils.warnAndDebugDetails(logger, "error in sending handshake to {}", socketChannel, e); return new ShutdownAndRemovePeerProcessor(peerUID, myContext); } } logger.debug("setup new connection with {}", sharingPeer); try { myContext.getExecutor().submit(new Runnable() { @Override public void run() { try { sharingPeer.onConnectionEstablished(); } catch (Throwable e) { LoggerUtils.warnAndDebugDetails(logger, "unhandled exception {} in executor task (onConnectionEstablished)", e.toString(), e); } } }); torrent.addConnectedPeer(sharingPeer); } catch (RejectedExecutionException e) { LoggerUtils.warnAndDebugDetails(logger, "task 'onConnectionEstablished' submit is failed. Reason: {}", e.getMessage(), e); return new ShutdownAndRemovePeerProcessor(peerUID, myContext).processAndGetNext(socketChannel); } return new WorkingReceiver(peerUID, myContext); } private Handshake parseHandshake(String socketChannelForLog) throws IOException { try { messageBytes.rewind(); return Handshake.parse(messageBytes, pstrLength); } catch (ParseException e) { logger.info("incorrect handshake message from " + socketChannelForLog, e); } return null; } @Override public DataProcessor handleError(ByteChannel socketChannel, Throwable e) throws IOException { return new ShutdownProcessor().processAndGetNext(socketChannel); } }
JetBrains/ttorrent-lib
ttorrent-client/src/main/java/com/turn/ttorrent/client/network/HandshakeReceiver.java
Java
apache-2.0
6,252
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; using HiddenSound.API.Identity; using Newtonsoft.Json; namespace HiddenSound.API.Areas.Shared.Models { public class Device { [Key] [Required] public Guid Id { get; set; } [Required] public string Name { get; set; } [Required] public string IMEI { get; set; } [ForeignKey("User")] public Guid? UserId { get; set; } public HiddenSoundUser User { get; set; } } }
hidden-sound-team/Hidden-Sound-API
HiddenSound.API/Areas/Shared/Models/Device.cs
C#
apache-2.0
678
package am.foodi.popularmovies; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class ReviewAdapter extends ArrayAdapter<Review> { Context mContext; public ReviewAdapter(Context context) { super(context, R.layout.grid_content); this.mContext = context; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v==null) { LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v=vi.inflate(R.layout.review_content, null); } Review review = getItem(position); TextView reviewView = (TextView)v.findViewById(R.id.review); reviewView.setText( review.content ); return v; } }
dougchestnut/udacity-movies-app
app/src/main/java/am/foodi/popularmovies/ReviewAdapter.java
Java
apache-2.0
1,001
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.core.file; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import org.apache.accumulo.core.WithTestNames; import org.apache.accumulo.core.conf.ConfigurationCopy; import org.apache.accumulo.core.conf.DefaultConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.crypto.CryptoServiceFactory; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.PartialKey; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.file.keyfunctor.ColumnFamilyFunctor; import org.apache.accumulo.core.file.rfile.RFile; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.Text; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "paths not set by user input") public class BloomFilterLayerLookupTest extends WithTestNames { private static final Logger log = LoggerFactory.getLogger(BloomFilterLayerLookupTest.class); private static final SecureRandom random = new SecureRandom(); @TempDir private final File tempDir = new File(System.getProperty("user.dir") + "/target", BloomFilterLayerLookupTest.class.getSimpleName() + "/"); @Test public void test() throws IOException { HashSet<Integer> valsSet = new HashSet<>(); for (int i = 0; i < 100000; i++) { valsSet.add(random.nextInt(Integer.MAX_VALUE)); } ArrayList<Integer> vals = new ArrayList<>(valsSet); Collections.sort(vals); ConfigurationCopy acuconf = new ConfigurationCopy(DefaultConfiguration.getInstance()); acuconf.set(Property.TABLE_BLOOM_ENABLED, "true"); acuconf.set(Property.TABLE_BLOOM_KEY_FUNCTOR, ColumnFamilyFunctor.class.getName()); acuconf.set(Property.TABLE_FILE_TYPE, RFile.EXTENSION); acuconf.set(Property.TABLE_BLOOM_LOAD_THRESHOLD, "1"); acuconf.set(Property.TSERV_BLOOM_LOAD_MAXCONCURRENT, "1"); Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); // get output file name String suffix = FileOperations.getNewFileExtension(acuconf); String fname = new File(tempDir, testName() + "." + suffix).getAbsolutePath(); FileSKVWriter bmfw = FileOperations.getInstance().newWriterBuilder() .forFile(fname, fs, conf, CryptoServiceFactory.newDefaultInstance()) .withTableConfiguration(acuconf).build(); // write data to file long t1 = System.currentTimeMillis(); bmfw.startDefaultLocalityGroup(); for (Integer i : vals) { String fi = String.format("%010d", i); bmfw.append(new Key(new Text("r" + fi), new Text("cf1")), new Value("v" + fi)); bmfw.append(new Key(new Text("r" + fi), new Text("cf2")), new Value("v" + fi)); } long t2 = System.currentTimeMillis(); log.debug(String.format("write rate %6.2f%n", vals.size() / ((t2 - t1) / 1000.0))); bmfw.close(); t1 = System.currentTimeMillis(); FileSKVIterator bmfr = FileOperations.getInstance().newReaderBuilder() .forFile(fname, fs, conf, CryptoServiceFactory.newDefaultInstance()) .withTableConfiguration(acuconf).build(); t2 = System.currentTimeMillis(); log.debug("Opened {} in {}", fname, (t2 - t1)); int hits = 0; t1 = System.currentTimeMillis(); for (int i = 0; i < 5000; i++) { int row = random.nextInt(Integer.MAX_VALUE); seek(bmfr, row); if (valsSet.contains(row)) { hits++; assertTrue(bmfr.hasTop()); } } t2 = System.currentTimeMillis(); double rate1 = 5000 / ((t2 - t1) / 1000.0); log.debug(String.format("random lookup rate : %6.2f%n", rate1)); log.debug("hits = {}", hits); int count = 0; t1 = System.currentTimeMillis(); for (Integer row : valsSet) { seek(bmfr, row); assertTrue(bmfr.hasTop()); count++; if (count >= 500) { break; } } t2 = System.currentTimeMillis(); double rate2 = 500 / ((t2 - t1) / 1000.0); log.debug(String.format("existing lookup rate %6.2f%n", rate2)); log.debug("expected hits 500. Receive hits: {}", count); bmfr.close(); assertTrue(rate1 > rate2); } private void seek(FileSKVIterator bmfr, int row) throws IOException { String fi = String.format("%010d", row); // bmfr.seek(new Range(new Text("r"+fi))); Key k1 = new Key(new Text("r" + fi), new Text("cf1")); bmfr.seek(new Range(k1, true, k1.followingKey(PartialKey.ROW_COLFAM), false), new ArrayList<>(), false); } }
milleruntime/accumulo
core/src/test/java/org/apache/accumulo/core/file/BloomFilterLayerLookupTest.java
Java
apache-2.0
5,732
# Pseudellipsoidion Neustupa & Nemcova, 2001 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in Beih Nova Hedwigia 123: 375. #### Original name null ### Remarks null
mdoering/backbone
life/Chromista/Ochrophyta/Eustigmatophyceae/Eustigmataceae/Pseudellipsoidion/README.md
Markdown
apache-2.0
230
# Peperomia gorgonillana var. hirsutula Trel. & Yunck. VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Piperales/Piperaceae/Peperomia/Peperomia gorgonillana/Peperomia gorgonillana hirsutula/README.md
Markdown
apache-2.0
202
/** * */ package org.crazyit.auction.client.util; import org.crazyit.auction.client.AuctionClientActivity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.view.View; /** * Description: * <br/>ÍøÕ¾: <a href="http://www.crazyit.org">·è¿ñJavaÁªÃË</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class DialogUtil { // ¶¨ÒåÒ»¸öÏÔʾÏûÏ¢µÄ¶Ô»°¿ò public static void showDialog(final Context ctx , String msg , boolean goHome) { // ´´½¨Ò»¸öAlertDialog.Builder¶ÔÏó AlertDialog.Builder builder = new AlertDialog.Builder(ctx) .setMessage(msg).setCancelable(false); if(goHome) { builder.setPositiveButton("È·¶¨", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(ctx , AuctionClientActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); ctx.startActivity(i); } }); } else { builder.setPositiveButton("È·¶¨", null); } builder.create().show(); } // ¶¨ÒåÒ»¸öÏÔʾָ¶¨×é¼þµÄ¶Ô»°¿ò public static void showDialog(Context ctx , View view) { new AlertDialog.Builder(ctx) .setView(view).setCancelable(false) .setPositiveButton("È·¶¨", null) .create() .show(); } }
00wendi00/MyProject
W_eclipse1_2/AuctionClient/src/org/crazyit/auction/client/util/DialogUtil.java
Java
apache-2.0
1,524
/* * Copyright (c) 2016, https://github.com/nebula-im/nebula * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PROTO_TELEGRAM_SCHEMA_TL_H #define PROTO_TELEGRAM_SCHEMA_TL_H #include "nebula/base/crypto_util/crypto_util.h" #include "nebula/net/telegram/core/tl_object.h" #include "nebula/net/telegram/core/tl_vector.h" #include "nebula/base/self_register_factory_manager.h" // req_pq#60469778 nonce:int128 = ResPQ; class TL_req_pq : public TLObject { public: enum { CLASS_ID = 0x60469778, }; // static constexpr TLClassID CLASS_ID = 0x60469778; TLClassID GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("req_pq#0x60469778: {{nonce = {}}}", ToHexStr(nonce_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } private: TLInt128 nonce_; }; // resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector<long> = ResPQ; class TL_resPQ : public TLObject { public: enum { CLASS_ID = 0x05162463, }; // static constexpr TLClassID CLASS_ID = 0x05162463; TLClassID GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("resPQ#0x05162463: {{nonce:{}, server_nonce:{}, pq:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), ToHexStr(pq_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLString& pq() const { return pq_; } inline TLString* mutable_pq() { return &pq_; } inline void set_pq(const TLString & v) { pq_ = v; } inline size_t server_public_key_fingerprints_size() const { return server_public_key_fingerprints_.size(); } inline const TLInt64Vector& server_public_key_fingerprints() const { return server_public_key_fingerprints_; } inline int64_t server_public_key_fingerprints(int idx) const { return server_public_key_fingerprints_.vector()[idx]; } inline void add_server_public_key_fingerprints( int64_t val ) { server_public_key_fingerprints_.mutable_vector()->push_back(val); } inline TLInt64Vector* mutable_server_public_key_fingerprints() { return &server_public_key_fingerprints_; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLString pq_; TLInt64Vector server_public_key_fingerprints_; }; // p_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data; class TL_p_q_inner_data : public TLObject { public: enum { CLASS_ID = 0x83c95aec, }; // static constexpr TLClassID CLASS_ID = 0x83c95aec; uint32_t GetClassID() const override { return CLASS_ID; } size_t GetObjectSize() const override { return CalcObjSize(pq_) + CalcObjSize(p_) + CalcObjSize(q_) + CalcObjSize(nonce_) + CalcObjSize(server_nonce_) + CalcObjSize(new_nonce_); } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("p_q_inner_data#83c95aec: {{pq:{}, p:{}, q:{}, nonce:{}, server_nonce:{}, new_nonce:{}}}", ToHexStr(pq_), ToHexStr(p_), ToHexStr(q_), ToHexStr(nonce_), ToHexStr(server_nonce_), ToHexStr(new_nonce_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLString& pq() const { return pq_; } inline TLString* mutable_pq() { return &pq_; } inline void set_pq(const TLString & v) { pq_ = v; } inline const TLString& p() const { return p_; } inline TLString* mutable_p() { return &p_; } inline void set_p(const TLString & v) { p_ = v; } inline const TLString& q() const { return q_; } inline TLString* mutable_q() { return &q_; } inline void set_q(const TLString & v) { q_ = v; } inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLInt256& new_nonce() const { return new_nonce_; } inline TLInt256* mutable_new_nonce() { return &new_nonce_; } private: TLString pq_; TLString p_; TLString q_; TLInt128 nonce_; TLInt128 server_nonce_; TLInt256 new_nonce_; }; // req_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params; class TL_req_DH_params : public TLObject { public: enum { CLASS_ID = 0xd712e4be, }; // static constexpr TLClassID CLASS_ID = 0xd712e4be; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("req_DH_params#0xd712e4be: {{nonce:{}, server_nonce:{}, p:{}, q:{}, public_key_fingerprint_:{}, encrypted_data_:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), ToHexStr(p_), ToHexStr(q_), public_key_fingerprint_, ToHexStr(encrypted_data_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLString& p() const { return p_; } inline TLString* mutable_p() { return &p_; } inline void set_p(const TLString & v) { p_ = v; } inline const TLString& q() const { return q_; } inline TLString* mutable_q() { return &q_; } inline void set_q(const TLString & v) { q_ = v; } inline int64_t public_key_fingerprint() const { return public_key_fingerprint_; } inline void set_public_key_fingerprint(int64_t v) { public_key_fingerprint_ = v; } inline const TLString& encrypted_data() const { return encrypted_data_; } inline TLString* mutable_encrypted_data() { return &encrypted_data_; } inline void set_encrypted_data(const TLString & v) { encrypted_data_ = v; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLString p_; TLString q_; int64_t public_key_fingerprint_; TLString encrypted_data_; }; // server_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data; class TL_server_DH_inner_data : public TLObject { public: enum { CLASS_ID = 0xb5890dba, }; // static constexpr TLClassID CLASS_ID = 0xb5890dba; uint32_t GetClassID() const override { return CLASS_ID; } size_t GetObjectSize() const override { return CalcObjSize(nonce_) + CalcObjSize(server_nonce_) + 4 + CalcObjSize(dh_prime_) + CalcObjSize(g_a_) + 4; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("server_DH_inner_data#b5890dba: {{nonce:{}, server_nonce:{}, g:{}, dh_prime_:{}, g_a_:{}, server_time_:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), g_, ToHexStr(dh_prime_), ToHexStr(g_a_), server_time_); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline int32_t g() const { return g_; } inline void set_g(int32_t v) { g_ = v; } inline const TLString& dh_prime() const { return dh_prime_; } inline TLString* mutable_dh_prime() { return &dh_prime_; } inline void set_dh_prime(const TLString & v) { dh_prime_ = v; } inline const TLString& g_a() const { return g_a_; } inline TLString* mutable_g_a() { return &g_a_; } inline void set_g_a(const TLString & v) { g_a_ = v; } inline int32_t server_time() const { return server_time_; } inline void set_server_time(int32_t v) { server_time_ = v; } private: TLInt128 nonce_; TLInt128 server_nonce_; int32_t g_; TLString dh_prime_; TLString g_a_; int32_t server_time_; }; // server_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params; // server_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params; class Server_DH_Params : public TLObject { public: virtual ~Server_DH_Params() override = default; }; class TL_server_DH_params_fail : public Server_DH_Params { public: enum { CLASS_ID = 0x79cb045d, }; // static constexpr TLClassID CLASS_ID = 0x79cb045d; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "TL_server_DH_params_fail#79cb045d"; } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLInt128& new_nonce_hash() const { return new_nonce_hash_; } inline TLInt128* mutable_new_nonce_hash() { return &new_nonce_hash_; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLInt128 new_nonce_hash_; }; class TL_server_DH_params_ok : public Server_DH_Params { public: enum { CLASS_ID = 0xd0e8075c, }; // static constexpr TLClassID CLASS_ID = 0xd0e8075c; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("server_DH_inner_data#b5890dba: {{nonce:{}, server_nonce:{}, encrypted_answer_:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), ToHexStr(encrypted_answer_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLString& encrypted_answer() const { return encrypted_answer_; } inline TLString* mutable_encrypted_answer() { return &encrypted_answer_; } inline void set_encrypted_answer(const TLString & v) { encrypted_answer_ = v; } private: TLInt128 nonce_; TLInt128 server_nonce_; // TLInt128 new_nonce_hash_; TLString encrypted_answer_; }; // client_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data; class TL_client_DH_inner_data : public TLObject { public: enum { CLASS_ID = 0x6643b654, }; // static constexpr TLClassID CLASS_ID = 0x6643b654; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("client_DH_inner_data#6643b654: {{nonce:{}, server_nonce:{}, retry_id:{}, g_b:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), retry_id_, ToHexStr(g_b_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline int64_t retry_id() const { return retry_id_; } inline void set_retry_id(int64_t v) { retry_id_ = v; } inline const TLString& g_b() const { return g_b_; } inline TLString* mutable_g_b() { return &g_b_; } inline void set_g_b(const TLString & v) { g_b_ = v; } private: TLInt128 nonce_; TLInt128 server_nonce_; int64_t retry_id_; TLString g_b_; }; // set_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer; class TL_set_client_DH_params : public TLObject { public: enum { CLASS_ID = 0xf5045f1f, }; // static constexpr TLClassID CLASS_ID = 0xf5045f1f; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return folly::sformat("set_client_DH_params#f5045f1f: {{nonce:{}, server_nonce:{}, encrypted_data:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), ToHexStr(encrypted_data_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLString& encrypted_data() const { return encrypted_data_; } inline TLString* mutable_encrypted_data() { return &encrypted_data_; } inline void set_encrypted_data(const TLString & v) { encrypted_data_ = v; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLString encrypted_data_; }; // dh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer; // dh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer; // dh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer; class Set_client_DH_params_answer : public TLObject { public: virtual ~Set_client_DH_params_answer() override = default; }; class TL_dh_gen_retry : public Set_client_DH_params_answer { public: enum { CLASS_ID = 0x46dc1fb9, }; // static constexpr TLClassID CLASS_ID = 0x46dc1fb9; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "set_client_DH_params#f5045f1f"; } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLInt128& new_nonce_hash2() const { return new_nonce_hash2_; } inline TLInt128* mutable_new_nonce_hash2() { return &new_nonce_hash2_; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLInt128 new_nonce_hash2_; }; class TL_dh_gen_fail : public Set_client_DH_params_answer { public: enum { CLASS_ID = 0xa69dae02, }; // static constexpr TLClassID CLASS_ID = 0xa69dae02; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "set_client_DH_params#a69dae02"; } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLInt128& new_nonce_hash3() const { return new_nonce_hash3_; } inline TLInt128* mutable_new_nonce_hash3() { return &new_nonce_hash3_; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLInt128 new_nonce_hash3_; }; class TL_dh_gen_ok : public Set_client_DH_params_answer { public: enum { CLASS_ID = 0x3bcbf734, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { // return "set_client_DH_params#3bcbf734"; return folly::sformat("TL_dh_gen_ok#0x3bcbf734: {{nonce:{}, server_nonce:{}, new_nonce_hash1:{}}}", ToHexStr(nonce_), ToHexStr(server_nonce_), ToHexStr(new_nonce_hash1_)); } /////////////////////////////////////////////////////////////////////////////// inline const TLInt128& nonce() const { return nonce_; } inline TLInt128* mutable_nonce() { return &nonce_; } inline const TLInt128& server_nonce() const { return server_nonce_; } inline TLInt128* mutable_server_nonce() { return &server_nonce_; } inline const TLInt128& new_nonce_hash1() const { return new_nonce_hash1_; } inline TLInt128* mutable_new_nonce_hash1() { return &new_nonce_hash1_; } private: TLInt128 nonce_; TLInt128 server_nonce_; TLInt128 new_nonce_hash1_; }; class TL_msgs_ack : public TLObject { public: enum { CLASS_ID = 0x62d6b459, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "msgs_ack#0x62d6b459"; } inline size_t msg_ids_size() const { return msg_ids_.size(); } inline const TLInt64Vector& msg_ids() const { return msg_ids_; } inline int64_t msg_ids(int idx) const { return msg_ids_.vector()[idx]; } inline void add_msg_ids( int64_t val ) { msg_ids_.mutable_vector()->push_back(val); } inline TLInt64Vector* mutable_msg_ids() { return &msg_ids_; } private: TLInt64Vector msg_ids_; /* public: static const uint32_t constructor = 0x62d6b459; std::vector<int64_ msg_ids; static TL_msgs_ack *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); void readParams(NativeByteBuffer *stream, bool &error); void serializeToStream(NativeByteBuffer *stream); */ }; //message#0x5bb8e511 msg_id:long seqno:int bytes:int body:Object = Message; // parsed manually class TL_message : public TLObject { public: enum { CLASS_ID = 0x5bb8e511, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "message#0x5bb8e511"; } private: int64_t msg_id_; int seqno_; int bytes_; std::shared_ptr<TLObject> body_; }; //msg_container#73f1f8dc messages:vector<message> = MessageContainer; // parsed manually class TL_msg_container : public TLObject { public: enum { CLASS_ID = 0x73f1f8dc, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "msg_container#73f1f8dc"; } private: std::vector<std::shared_ptr<TL_message>> messages_; }; //msg_copy#e06046b2 orig_message:Message = MessageCopy; // parsed manually, not used - use msg_container class TL_msg_copy : public TLObject { public: enum { CLASS_ID = 0xe06046b2, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "msg_copy#e06046b2"; } private: std::shared_ptr<TL_message> orig_message_; }; //gzip_packed#3072cfa1 packed_data:string = Object; // parsed manually class TL_gzip_packed : public TLObject { public: enum { CLASS_ID = 0x3072cfa1, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "TL_gzip_packed#3072cfa1"; } private: TLString packed_data_; }; // destroy_session#e7512126 session_id:long = DestroySessionRes; class TL_destroy_session : public TLObject { public: enum { CLASS_ID = 0xe7512126, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "destroy_session#e7512126"; } private: int64_t session_id_; }; // destroy_session_ok#e22045fc session_id:long = DestroySessionRes; // destroy_session_none#62d350c9 session_id:long = DestroySessionRes; class DestroySessionRes : public TLObject { public: virtual ~DestroySessionRes() override = default; }; class TL_destroy_session_ok : public DestroySessionRes { public: enum { CLASS_ID = 0xe22045fc, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "destroy_session_ok#e22045fc"; } private: int64_t session_id_; }; class TL_destroy_session_none : public DestroySessionRes { public: enum { CLASS_ID = 0x62d350c9, }; // static constexpr TLClassID CLASS_ID = 0x3bcbf734; uint32_t GetClassID() const override { return CLASS_ID; } bool Decode(IOBufReader& iobr) override; bool Encode(IOBufWriter& iobw) const override; std::string ToString() const override { return "destroy_session_none#62d350c9"; } private: int64_t session_id_; }; using TLObjectFactory = nebula::SelfRegisterFactoryManager<TLObject, uint32_t>; #endif
nebula-im/imengine
proto/mtproto/schema2.tl.h
C
apache-2.0
24,384
class ActionNotifier def initialize(action) @action = action end def notify Notification.transaction do users.each do |user| Notification.create(action: action, user: user) end end end private attr_reader :action def users @users ||= User.joins(:profile).where(profiles: { id: action.receivers_ids }) end end class ActionNotifierJob < ApplicationJob queue_as :notifications def perform(action) ActionNotifier.new(action).notify end end
foliea/deckie-api
app/jobs/action_notifier_job.rb
Ruby
apache-2.0
504
using System; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Collections; using System.Threading; using System.Linq.Expressions; using System.Reflection; using System.Web.SessionState; namespace ManagerShop.Infrastructure.Core { /// <summary> /// ページを処理する共通クラス /// </summary> public class WebHelper : IRequiresSessionState { //public void ProcessRequest(HttpContext context) //{ //} //public bool IsReusable //{ // get { return true; } //} #region 絶対的なパス /// <summary> /// 相対的なパスを絶対的なパスに変更する /// </summary> /// <param name="relativeUrl"></param> /// <returns></returns> public static string ResolveUrl(string relativeUrl) { if (string.IsNullOrWhiteSpace(relativeUrl)) return string.Empty; relativeUrl = relativeUrl.Replace("\\", "/"); if (relativeUrl.StartsWith("/")) return relativeUrl; if (relativeUrl.Contains("://")) return relativeUrl; return VirtualPathUtility.ToAbsolute(relativeUrl); } #endregion #region HtmlString文字化 /// <summary> /// HtmlString文字列のエンコード /// </summary> /// <param name="html"></param> /// <returns></returns> public static string HtmlEncode(string HtmlString) { return HttpUtility.HtmlEncode(HtmlString); } /// <summary> /// HtmlString文字列のデコード /// </summary> /// <param name="html"></param> /// <returns></returns> public static string HtmlDecode(string HtmlString) { return HttpUtility.HtmlDecode(HtmlString); } #endregion #region URLのエンコード・デコード /// <summary> /// URLのエンコード /// </summary> /// <param name="url"></param> /// <param name="isUpper"></param> /// <returns></returns> public static string UrlEncode(string url, bool isUpper = false) { var result = HttpUtility.UrlEncode(url, Encoding.UTF8); if (!isUpper) return result; return GetUpperEncode(result); } /// <summary> /// URLのエンコードは大文字に変更する /// </summary> /// <param name="encode"></param> /// <returns></returns> private static string GetUpperEncode(string encode) { var result = new StringBuilder(); int index = int.MinValue; for (int i = 0; i < encode.Length; i++) { string character = encode[i].ToString(); if (character == "%") index = i; if (i - index == 1 || i - index == 2) character = character.ToUpper(); result.Append(character); } return result.ToString(); } /// <summary> /// URLのデコード /// </summary> /// <param name="url"></param> /// <returns></returns> public static string UrlDecode(string url) { return HttpUtility.UrlDecode(url); } /// <summary> /// URLのデコード /// </summary> /// <param name="url"></param> /// <param name="encoding"></param> /// <returns></returns> public static string UrlDecode(string url, Encoding encoding) { return HttpUtility.UrlDecode(url, encoding); } #endregion #region cacheの操作 /// <summary> /// cacheの追加 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> public static void SetCache(string key, dynamic value) { if (key.IsEmpty()) return; System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(key, value); } /// <summary> /// cacheの取得 /// </summary> /// <param name="key"></param> public static T GetCache<T>(string key) { if (key.IsEmpty()) return default(T); System.Web.Caching.Cache objCache = HttpRuntime.Cache; return (T)objCache.Get(key); } /// <summary> /// cacheの更新 /// </summary> /// <param name="key"></param> public static void UpdateCache(string key, dynamic value) { if (key.IsEmpty()) return; System.Web.Caching.Cache objCache = HttpRuntime.Cache; RemoveCache(key); SetCache(key, value); } /// <summary> /// cacheの削除 /// </summary> /// <param name="key"></param> public static void RemoveCache(string key) { if (key.IsEmpty()) return; System.Web.Caching.Cache _cache = HttpRuntime.Cache; _cache.Remove(key); } /// <summary> /// 全部Cacheを削除 /// </summary> public static void RemoveAllCache() { System.Web.Caching.Cache _cache = HttpRuntime.Cache; IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); while (CacheEnum.MoveNext()) { _cache.Remove(CacheEnum.Key.ToString()); } } #endregion #region Sessionの操作 /// <summary> /// Sessionの追加 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> public static void SetSession<T>(string key, T value) { if (key.IsEmpty()) return; HttpContext.Current.Session[key] = value; } /// <summary> /// Sessionの追加 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void SetSession(string key, string value) { SetSession<string>(key, value); } /// <summary> /// Sessionの取得 /// </summary> /// <param name="key"></param> /// <returns></returns> public static string GetSession(string key) { if (key.IsEmpty()) return string.Empty; return HttpContext.Current.Session[key] as string; } /// <summary> /// Sessionの取得 /// </summary> /// <param name="key"></param> /// <returns></returns> public static T GetSession<T>(string key) { if (key.IsEmpty()) return default(T); return (T)HttpContext.Current.Session[key]; } /// <summary> /// Sessionの削除 /// </summary> /// <param name="key"></param> public static void RemoveSession(string key) { if (key.IsEmpty()) return; HttpContext.Current.Session.Contents.Remove(key); } #endregion #region Cookieの操作 /// <summary> /// Cookieの追加 /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> public static void SetCookie(string strName, string strValue) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } cookie.Value = strValue; HttpContext.Current.Response.AppendCookie(cookie); } /// <summary> /// Cookieの追加(TimeOut設定できる) /// </summary> /// <param name="strName"></param> /// <param name="strValue"></param> /// <param name="expires">TimeOut(Minute)</param> public static void SetCookie(string strName, string strValue, int expires) { HttpCookie cookie = HttpContext.Current.Request.Cookies[strName]; if (cookie == null) { cookie = new HttpCookie(strName); } cookie.Value = strValue; cookie.Expires = DateTime.Now.AddHours(expires); HttpContext.Current.Response.Cookies.Add(cookie); } /// <summary> /// Cookieの取得 /// </summary> /// <param name="strName"></param> /// <returns></returns> public static string GetCookie(string strName) { if (HttpContext.Current != null && HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null) { return Convert.ToString(HttpContext.Current.Request.Cookies[strName].Value); } return null; } /// <summary> /// Cookieの削除 /// </summary> /// <param name="CookiesName"></param> public static void RemoveCookie(string CookiesName) { HttpCookie objCookie = new HttpCookie(CookiesName.Trim()); objCookie.Expires = DateTime.Now.AddYears(-5); HttpContext.Current.Response.Cookies.Add(objCookie); } #endregion #region HttpRequestの操作 /// <summary> /// URLによりHttpRequestを取得 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string HttpWebRequest(string url) { return HttpWebRequest(url, string.Empty, Encoding.Default); } /// <summary> /// URLによりHttpRequestを取得 /// </summary> /// <param name="url"></param> /// <param name="parameters">parm1=a&(&amp;)parm2=b</param> /// <returns></returns> public static string HttpWebRequest(string url, string parameters) { return HttpWebRequest(url, parameters, Encoding.GetEncoding("utf-8"), true); } /// <summary> /// URLによりHttpRequestを取得 /// </summary> /// <param name="url"></param> /// <param name="parameters">parm1=a&(&amp;)parm2=b</param> /// <param name="encoding"></param> /// <param name="isPost"></param> /// <param name="contentType">HTML内容タイプ</param> /// <param name="cookie">CookieContainer</param> /// <param name="timeout"></param> /// <returns></returns> public static string HttpWebRequest(string url, string parameters, Encoding encoding, bool isPost = false, string contentType = "application/x-www-form-urlencoded", CookieContainer cookie = null, int timeout = 120000) { var request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = timeout; request.CookieContainer = cookie; if (isPost) { byte[] postData = encoding.GetBytes(parameters); request.Method = "POST"; request.ContentType = contentType; request.ContentLength = postData.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(postData, 0, postData.Length); } } var response = (HttpWebResponse)request.GetResponse(); string result; using (Stream stream = response.GetResponseStream()) { if (stream == null) return string.Empty; using (var reader = new StreamReader(stream, encoding)) { result = reader.ReadToEnd(); } } return result; } #endregion #region HTMLタグを削除 /// <summary> /// HTMLタグを削除 /// </summary> /// <param name="Htmlstring"></param> /// <returns></returns> public static string NoHtml(string Htmlstring) { Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&hellip;", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&mdash;", "", RegexOptions.IgnoreCase); Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "", RegexOptions.IgnoreCase); Htmlstring.Replace("<", ""); Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "", RegexOptions.IgnoreCase); Htmlstring.Replace(">", ""); Htmlstring.Replace("\r\n", ""); Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim(); return Htmlstring; } #endregion } }
dawutao/ManagerShop
ManagerShop.UI/ManagerShop.Core/Web/WebHelper.cs
C#
apache-2.0
14,626
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.primitives.resources.impl; import java.util.Collection; import java.util.List; import java.util.Timer; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import com.google.common.collect.ImmutableList; import io.atomix.protocols.raft.proxy.RaftProxy; import org.onlab.util.AbstractAccumulator; import org.onlab.util.Accumulator; import org.onlab.util.KryoNamespace; import org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.Add; import org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.Complete; import org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.Take; import org.onosproject.store.serializers.KryoNamespaces; import org.onosproject.store.service.Serializer; import org.onosproject.store.service.Task; import org.onosproject.store.service.WorkQueue; import org.onosproject.store.service.WorkQueueStats; import org.slf4j.Logger; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.onlab.util.Tools.groupedThreads; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueEvents.TASK_AVAILABLE; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.ADD; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.CLEAR; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.COMPLETE; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.REGISTER; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.STATS; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.TAKE; import static org.onosproject.store.primitives.resources.impl.AtomixWorkQueueOperations.UNREGISTER; import static org.slf4j.LoggerFactory.getLogger; /** * Distributed resource providing the {@link WorkQueue} primitive. */ public class AtomixWorkQueue extends AbstractRaftPrimitive implements WorkQueue<byte[]> { private static final Serializer SERIALIZER = Serializer.using(KryoNamespace.newBuilder() .register(KryoNamespaces.BASIC) .register(AtomixWorkQueueOperations.NAMESPACE) .register(AtomixWorkQueueEvents.NAMESPACE) .build()); private final Logger log = getLogger(getClass()); private final ExecutorService executor = newSingleThreadExecutor(groupedThreads("AtomixWorkQueue", "%d", log)); private final AtomicReference<TaskProcessor> taskProcessor = new AtomicReference<>(); private final Timer timer = new Timer("atomix-work-queue-completer"); private final AtomicBoolean isRegistered = new AtomicBoolean(false); public AtomixWorkQueue(RaftProxy proxy) { super(proxy); proxy.addStateChangeListener(state -> { if (state == RaftProxy.State.CONNECTED && isRegistered.get()) { proxy.invoke(REGISTER); } }); proxy.addEventListener(TASK_AVAILABLE, this::resumeWork); } @Override public CompletableFuture<Void> destroy() { executor.shutdown(); timer.cancel(); return proxy.invoke(CLEAR); } @Override public CompletableFuture<Void> addMultiple(Collection<byte[]> items) { if (items.isEmpty()) { return CompletableFuture.completedFuture(null); } return proxy.invoke(ADD, SERIALIZER::encode, new Add(items)); } @Override public CompletableFuture<Collection<Task<byte[]>>> take(int maxTasks) { if (maxTasks <= 0) { return CompletableFuture.completedFuture(ImmutableList.of()); } return proxy.invoke(TAKE, SERIALIZER::encode, new Take(maxTasks), SERIALIZER::decode); } @Override public CompletableFuture<Void> complete(Collection<String> taskIds) { if (taskIds.isEmpty()) { return CompletableFuture.completedFuture(null); } return proxy.invoke(COMPLETE, SERIALIZER::encode, new Complete(taskIds)); } @Override public CompletableFuture<Void> registerTaskProcessor(Consumer<byte[]> callback, int parallelism, Executor executor) { Accumulator<String> completedTaskAccumulator = new CompletedTaskAccumulator(timer, 50, 50); // TODO: make configurable taskProcessor.set(new TaskProcessor(callback, parallelism, executor, completedTaskAccumulator)); return register().thenCompose(v -> take(parallelism)) .thenAccept(taskProcessor.get()); } @Override public CompletableFuture<Void> stopProcessing() { return unregister(); } @Override public CompletableFuture<WorkQueueStats> stats() { return proxy.invoke(STATS, SERIALIZER::decode); } private void resumeWork() { TaskProcessor activeProcessor = taskProcessor.get(); if (activeProcessor == null) { return; } this.take(activeProcessor.headRoom()) .whenCompleteAsync((tasks, e) -> activeProcessor.accept(tasks), executor); } private CompletableFuture<Void> register() { return proxy.invoke(REGISTER).thenRun(() -> isRegistered.set(true)); } private CompletableFuture<Void> unregister() { return proxy.invoke(UNREGISTER).thenRun(() -> isRegistered.set(false)); } // TaskId accumulator for paced triggering of task completion calls. private class CompletedTaskAccumulator extends AbstractAccumulator<String> { CompletedTaskAccumulator(Timer timer, int maxTasksToBatch, int maxBatchMillis) { super(timer, maxTasksToBatch, maxBatchMillis, Integer.MAX_VALUE); } @Override public void processItems(List<String> items) { complete(items); } } private class TaskProcessor implements Consumer<Collection<Task<byte[]>>> { private final AtomicInteger headRoom; private final Consumer<byte[]> backingConsumer; private final Executor executor; private final Accumulator<String> taskCompleter; public TaskProcessor(Consumer<byte[]> backingConsumer, int parallelism, Executor executor, Accumulator<String> taskCompleter) { this.backingConsumer = backingConsumer; this.headRoom = new AtomicInteger(parallelism); this.executor = executor; this.taskCompleter = taskCompleter; } public int headRoom() { return headRoom.get(); } @Override public void accept(Collection<Task<byte[]>> tasks) { if (tasks == null) { return; } headRoom.addAndGet(-1 * tasks.size()); tasks.forEach(task -> executor.execute(() -> { try { backingConsumer.accept(task.payload()); taskCompleter.add(task.taskId()); } catch (Exception e) { log.debug("Task execution failed", e); } finally { headRoom.incrementAndGet(); resumeWork(); } })); } } }
osinstom/onos
core/store/primitives/src/main/java/org/onosproject/store/primitives/resources/impl/AtomixWorkQueue.java
Java
apache-2.0
8,304
/* * Copyright (C) 2014 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger2.internal.codegen; import dagger2.MapKey; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import static dagger2.internal.codegen.ErrorMessages.MAPKEY_WITHOUT_FIELDS; /** * A {@link Validator} for {@link MapKey} Annotation. * * @author Chenying Hou * @since 2.0 */ final class MapKeyValidator implements Validator<Element> { @Override public ValidationReport<Element> validate(Element element) { ValidationReport.Builder<Element> builder = ValidationReport.Builder.about(element); if (((TypeElement) element).getEnclosedElements().isEmpty()) { builder.addItem(MAPKEY_WITHOUT_FIELDS, element); } return builder.build(); } }
goinstant/dagger
compiler/src/main/java/dagger2/internal/codegen/MapKeyValidator.java
Java
apache-2.0
1,307
# AUTOGENERATED FILE FROM balenalib/imx8m-var-dart-ubuntu:cosmic-run # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # install python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ netbase \ && rm -rf /var/lib/apt/lists/* # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.6.12 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.0.1 ENV SETUPTOOLS_VERSION 56.0.0 RUN set -x \ && buildDeps=' \ curl \ ' \ && apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" \ && echo "f44f5617a7cd5593250bb8ad02044c37b433293343eacc84d78acae6490b7c53 Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu cosmic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.12, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
nghiant2710/base-images
balena-base-images/python/imx8m-var-dart/ubuntu/cosmic/3.6.12/run/Dockerfile
Dockerfile
apache-2.0
4,075
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.examples.mllib import scala.reflect.runtime.universe._ /** * Abstract class for parameter case classes. * 抽象参数的类 * This overrides the [[toString]] method to print all case class fields by name and value. * 这将重写toString方法打印实例类所有的字段名和值 * @tparam T Concrete parameter class. */ abstract class AbstractParams[T: TypeTag] { private def tag: TypeTag[T] = typeTag[T] /** * Finds all case class fields in concrete class instance, and outputs them in JSON-style format: * 在实例类中查找所字段,输出JSON风格的格式 * { * [field name]:\t[field value]\n * [field name]:\t[field value]\n * ... * } */ override def toString: String = { val tpe = tag.tpe val allAccessors = tpe.declarations.collect { //Symbol符号 case m: MethodSymbol if m.isCaseAccessor => m //访问器或者访问器方法 } val mirror = runtimeMirror(getClass.getClassLoader) val instanceMirror = mirror.reflect(this) allAccessors.map { f => val paramName = f.name.toString val fieldMirror = instanceMirror.reflectField(f) val paramValue = fieldMirror.get s" $paramName:\t$paramValue" }.mkString("{\n", ",\n", "\n}") } }
tophua/spark1.52
examples/src/main/scala/org/apache/spark/examples/mllib/AbstractParams.scala
Scala
apache-2.0
2,086
--- title: Wire Serializer summary: How to use the Wire serializer in an endpoint. related: - nservicebus/serialization --- ## NServiceBus.Wire This samples uses the community run serializer [NServiceBus.Wire](https://github.com/hmemcpy/NServiceBus.Wire) to serialize messages with the [Wire](https://github.com/rogeralsing/Wire) binary format. ## Configuring to use Wire <!-- import config --> ## The message send <!-- import message --> ## The Output Since Wire is a binary format there is not much human readable in the message body. ![](wirebinary.png)
eclaus/docs.particular.net
samples/serializers/wire/sample.md
Markdown
apache-2.0
570