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 |
|---|---|---|---|---|---|
using System;
namespace JetBrains.ReSharper.Koans.Inspections
{
// Solution Wide Analysis
//
// Analyses whole solution. Can find multiple code issues, and highlights code that isn't used.
// Takes up additional resources, so disabled by default
//
// Enable by right clicking circular indicator in the status bar
//
// Navigate between highlights in files:
//
// <shortcut id="Next Error">Shift+Alt+PageUp</shortcut> and <shortcut id="Previous Error">Shift+Alt+PageDn</shortcut> (VS)
//
public class SolutionWideAnalysis
{
// 1. Enable solution wide analysis
// 2. Once complete, notice that this class and method are marked unused
public void UnusedMethod()
{
}
// 3. Navigate between warnings
// 4. Uncomment the failing code below
// Open the Solution Errors Window (ReSharper → Inspect → Solution Errors Window)
// Double click the error in the window to navigate back
// Hide errors with right click or toolbar
// Show hidden errors with toolbar
// Comment code to fix errors again
//public void FailingCode()
//{
// int i = "hello";
// UnusedMethod(undefinedVariable);
// return new Exception();
//}
}
} | JetBrains/resharper-workshop | localized/ja/03-Inspections/1-As_you_type/1.8-Solution_wide_analysis.cs | C# | apache-2.0 | 1,349 |
<!--
Copyright 2005-2011 The Kuali Foundation
Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Editing
New Course Request
(NewCourseRequest)
document
</title>
<!--
Meta data block for automation/testing
[var editable_value=true]
[var annotatable_value=true]
[var readonly=false]
[var annotatable=true]
[var annotation=EDocLiteTest 'approve' of NewCourseRequest as user 'user2']
REDACTED TRANSIENT DATA
[var doctype=NewCourseRequest]
[var def=NewCourseRequestSimpleStyle]
[var style=Default]
-->
<link href="css/screen.css" rel="stylesheet" type="text/css">
<link href="css/edoclite1.css" rel="stylesheet" type="text/css">
<script src="scripts/edoclite1.js" type="text/javascript"></script>
</head>
<body onload="onPageLoad()">
<table border="0" cellpadding="0" cellspacing="0" class="headertable" width="100%">
<tr>
<td align="left" valign="top" width="10%"><img alt="Workflow" height="21" hspace="5" src="images/wf-logo.gif" vspace="5" width="150"></td><td align="right">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="right" class="thnormal">Document Type Name:</td><td align="left" class="datacell1">NewCourseRequest</td>
</tr>
<tr>
<td align="right" class="thnormal">Document Status:</td><td align="left" class="datacell1" width="50">ENROUTE</td>
</tr>
<tr>
<td align="right" class="thnormal">Create Date:</td><td align="left" class="datacell1">
<!--REDACTED TRANSIENT DATA--></td>
</tr>
<tr>
<td align="right" class="thnormal">Document ID:</td><td align="left" class="datacell1">
<!--REDACTED TRANSIENT DATA--></td>
</tr>
</table>
</td>
</tr>
</table>
<table align="center" border="0" cellpadding="10" cellspacing="0" width="80%">
<tr>
<td><strong>
Editing
New Course Request
(NewCourseRequest)
</strong></td>
</tr>
<tr>
<td>** Review the Course Request.</td>
</tr>
</table>
<table align="center" border="0" cellpadding="10" cellspacing="0" width="80%"></table>
<form action="EDocLite" enctype="multipart/form-data" id="edoclite" method="post" onsubmit="return validateOnSubmit(this)">
<!--hide this nastiness so we can concentrate on formating above-->
<div style="display: none">
<!--input name="docId" type="hidden"-->
<!--REDACTED TRANSIENT DATA-->
</div>
<table align="center" border="0" cellpadding="0" cellspacing="0" class="bord-r-t" width="80%" xmlns:wf="http://xml.apache.org/xalan/java/org.kuali.rice.kew.edoclite.WorkflowFunctions">
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Department</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><select name="department"><option title="African American/African Diaspora Studies" value="AAAD COAS">African American/African Diaspora Studies</option><option title="African Studies" value="AFRI COAS">African Studies</option><option title="American Studies" value="AMST COAS" selected>American Studies</option><option title="Ancient Studies" value="ANCS COAS">Ancient Studies</option></select><span class="emptyMessage" id="department_messageHeaderCell">empty</span><span class="emptyMessage" id="department_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Check Appropriate Boxes</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input xmlns="http://www.w3.org/1999/xhtml" name="creditType" title="Undergraduate credit" type="radio" value="undergraduateCredit" checked>Undergraduate credit <input name="creditType" title="Graduate credit" type="radio" value="graduateCredit">Graduate credit <input name="creditType" title="Professional credit" type="radio" value="professionCredit">Professional credit <span class="emptyMessage" id="creditType_messageHeaderCell">empty</span><span class="emptyMessage" id="creditType_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Academic Subject Code</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="bogus academic subject code" type="text" name="academicSubjectCode"><span class="emptyMessage" id="academicSubjectCode_messageHeaderCell">empty</span><span class="emptyMessage" id="academicSubjectCode_message"></span><script type="text/javascript">
// register field
register("academicSubjectCode","Academic Subject Code","","","true");
// end comment
</script></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message: Course Number must be of for A123
message: Course Number must be of for A123-->Course Number (must be cleared with University Enrollment Services)</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message: Course Number must be of for A123
message: Course Number must be of for A123--><input value="A123" type="text" name="courseNumber" size="4"><span class="emptyMessage" id="courseNumber_messageHeaderCell">empty</span><span class="emptyMessage" id="courseNumber_message">Course Number must be of for A123</span><script type="text/javascript">
// register field
register("courseNumber","Course Number (must be cleared with University Enrollment Services)","\\D\\d\\d\\d?","Course Number must be of for A123","true");
// end comment
</script></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message: [JS] Javascript SHOULD NOT enforce instructor to be specified
message: [JS] Javascript SHOULD NOT enforce instructor to be specified-->Instructor</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message: [JS] Javascript SHOULD NOT enforce instructor to be specified
message: [JS] Javascript SHOULD NOT enforce instructor to be specified--><input value="" type="text" name="instructor" size="4"><span class="emptyMessage" id="instructor_messageHeaderCell">empty</span><span class="emptyMessage" id="instructor_message">[JS] Javascript SHOULD NOT enforce instructor to be specified</span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Course Title</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="courseTitle" size="4"><span class="emptyMessage" id="courseTitle_messageHeaderCell">empty</span><span class="emptyMessage" id="courseTitle_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Course Title Abbreviation (32 Characters including spaces)</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="courseTitleAbbreviation" size="4"><span class="emptyMessage" id="courseTitleAbbreviation_messageHeaderCell">empty</span><span class="emptyMessage" id="courseTitleAbbreviation_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->First time this course is to be offered (Semester/Year)</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="courseOfferTimeline"><span class="emptyMessage" id="courseOfferTimeline_messageHeaderCell">empty</span><span class="emptyMessage" id="courseOfferTimeline_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Credit Hours: Fixed at</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="creditHoursFixed"><span class="emptyMessage" id="creditHoursFixed_messageHeaderCell">empty</span><span class="emptyMessage" id="creditHoursFixed_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->or Variable from</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="creditHoursVariableFrom"><span class="emptyMessage" id="creditHoursVariableFrom_messageHeaderCell">empty</span><span class="emptyMessage" id="creditHoursVariableFrom_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->to</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="creditHoursVariableTo"><span class="emptyMessage" id="creditHoursVariableTo_messageHeaderCell">empty</span><span class="emptyMessage" id="creditHoursVariableTo_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Is this course to be graded S-F (only)?</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input name="courseGradedSFOnly" title="Yes" type="radio" value="yes" checked>Yes <input name="courseGradedSFOnly" title="No" type="radio" value="no">No <span class="emptyMessage" id="courseGradedSFOnly_messageHeaderCell">empty</span><span class="emptyMessage" id="courseGradedSFOnly_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Is variable title approval being requested?</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input name="variableTitleApproveRequested" title="Yes" type="radio" value="yes" checked>Yes <input name="variableTitleApproveRequested" title="No" type="radio" value="no">No <span class="emptyMessage" id="variableTitleApproveRequested_messageHeaderCell">empty</span><span class="emptyMessage" id="variableTitleApproveRequested_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Course Description (not to exceed 50 words) for Bulletin publication</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><textarea cols="50" name="courseDescription" rows="5"> </textarea><span class="emptyMessage" id="courseDescription_messageHeaderCell">empty</span><span class="emptyMessage" id="courseDescription_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Lecture Contact Hours: Fixed at</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="lectureContactHoursFixed"><span class="emptyMessage" id="lectureContactHoursFixed_messageHeaderCell">empty</span><span class="emptyMessage" id="lectureContactHoursFixed_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->or Variable from</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="lectureContactHoursVariableFrom"><span class="emptyMessage" id="lectureContactHoursVariableFrom_messageHeaderCell">empty</span><span class="emptyMessage" id="lectureContactHoursVariableFrom_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->to</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="lectureContactHoursVariableTo"><span class="emptyMessage" id="lectureContactHoursVariableTo_messageHeaderCell">empty</span><span class="emptyMessage" id="lectureContactHoursVariableTo_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Non-Lecture Contact Hours: Fixed at</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="nonlectureContactHoursFixed"><span class="emptyMessage" id="nonlectureContactHoursFixed_messageHeaderCell">empty</span><span class="emptyMessage" id="nonlectureContactHoursFixed_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->or Variable from</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="nonlectureContactHoursVariableFrom"><span class="emptyMessage" id="nonlectureContactHoursVariableFrom_messageHeaderCell">empty</span><span class="emptyMessage" id="nonlectureContactHoursVariableFrom_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->to</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="nonlectureContactHoursVariableTo"><span class="emptyMessage" id="nonlectureContactHoursVariableTo_messageHeaderCell">empty</span><span class="emptyMessage" id="nonlectureContactHoursVariableTo_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Estimated enrollment</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="estimatedEnrollment"><span class="emptyMessage" id="estimatedEnrollment_messageHeaderCell">empty</span><span class="emptyMessage" id="estimatedEnrollment_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Estimated enrollment percent expected to be graduate students</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="estimatedEnrollmentPercentGradStudents"><span class="emptyMessage" id="estimatedEnrollmentPercentGradStudents_messageHeaderCell">empty</span><span class="emptyMessage" id="estimatedEnrollmentPercentGradStudents_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Frequency of Schedule</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input value="" type="text" name="schedulingFrequency"><span class="emptyMessage" id="schedulingFrequency_messageHeaderCell">empty</span><span class="emptyMessage" id="schedulingFrequency_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Will this course be required for majors?</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input name="requiredForMajors" title="Yes" type="radio" value="yes" checked>Yes <input name="requiredForMajors" title="No" type="radio" value="no">No <span class="emptyMessage" id="requiredForMajors_messageHeaderCell">empty</span><span class="emptyMessage" id="requiredForMajors_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Justification for new course</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><textarea cols="50" name="courseJustification" rows="5"> </textarea><span class="emptyMessage" id="courseJustification_messageHeaderCell">empty</span><span class="emptyMessage" id="courseJustification_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Are the necessary reading materials currently available in the appropriate library?</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><input name="readingMaterialsAvailable" title="Yes" type="radio" value="yes" checked>Yes <input name="readingMaterialsAvailable" title="No" type="radio" value="no">No <span class="emptyMessage" id="readingMaterialsAvailable_messageHeaderCell">empty</span><span class="emptyMessage" id="readingMaterialsAvailable_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->Please append a complete outline of the proposed course, and indicate instructor (if known), textbooks, and other materials.</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><textarea cols="50" name="courseOutline" rows="5"> </textarea><span class="emptyMessage" id="courseOutline_messageHeaderCell">empty</span><span class="emptyMessage" id="courseOutline_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->If this course overlaps with existing courses, please explain with which courses it overlaps and whether this overlap is necessary, desirable, or unimportant</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><textarea cols="50" name="courseOverlapExplanation" rows="5"> </textarea><span class="emptyMessage" id="courseOverlapExplanation_messageHeaderCell">empty</span><span class="emptyMessage" id="courseOverlapExplanation_message"></span></td>
</tr>
<tr>
<td class="thnormal" width="30%">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: -->A copy of every new course proposal must be submitted to departments, schools, or divisions in which there may be overlap of the new course with existing courses or areas of strong concern, with instructions that they send comments directly to the originating Curriculum Committee. Please append a list of departments, schools, or divisions thus consulted.</td><td class="datacell">
<!-- For JavaScript validation-->
<!--
custom message: NONE
validation/message:
message: --><textarea cols="50" name="overlapDepts" rows="5"> </textarea><span class="emptyMessage" id="overlapDepts_messageHeaderCell">empty</span><span class="emptyMessage" id="overlapDepts_message"></span></td>
</tr>
</table>
<table align="center" border="0" cellpadding="0" cellspacing="0" class="bord-r-t" width="80%">
<tr>
<td align="center" class="thnormal" colspan="2">
Current annotation: EDocLiteTest 'approve' of NewCourseRequest as user 'user2'<br>
Set annotation:<br>
<textarea name="annotation"></textarea></td>
</tr>
</table>
<table align="center" border="0" cellpadding="0" cellspacing="0" class="bord-r-t" width="80%">
<tr>
<td align="center" class="thnormal" colspan="2">
<input name="action" title="Approve" type="submit" value="approve">
<input name="action" title="Disapprove" type="submit" value="disapprove">
<input name="action" title="ReturnToPrevious" type="submit" value="returnToPrevious">
<select name="previousNode"><option value="Department">Department</option></select>
</td>
</tr>
</table>
<br>
<input name="showEdit" type="hidden" value="no"><input name="showAdd" type="hidden" value="true"><input name="methodToCall" type="hidden"><input name="sortNotes" type="hidden" value=""><input name="noteIdNumber" type="hidden" value="">
<table align="center" border="0" cellpadding="0" cellspacing="0" class="bord-r-t" width="80%">
<tr>
<td align="center" class="thnormal2" colspan="4" scope="col"><b>Create Note </b></td>
</tr>
<tr>
<td class="thnormal" scope="col">
<div align="center">Author</div>
</td><td class="thnormal" scope="col">
<div align="center">Date</div>
</td><td class="thnormal" scope="col">
<div align="center">Note</div>
</td><td class="thnormal" scope="col">
<div align="center">Action</div>
</td>
</tr>
<tr valign="top">
<td class="datacell">User Three</td><td class="datacell">
<!--[transient start]-->06/01/2006<!--[transient end]--></td><td class="datacell"><textarea cols="60" name="addText" rows="3"></textarea></td><td class="datacell">
<div align="center">
<img border="0" height="15" hspace="3" onclick="document.forms[0].methodToCall.value='save'; document.forms[0].submit();" src="images/tinybutton-save.gif" vspace="3" width="45"></div>
</td>
</tr>
</table>
</form>
<center>
User
Quick Start
standing in for user
User Three</center>
</body>
</html>
| ua-eas/ua-rice-2.1.9 | it/kew/src/test/resources/org/kuali/rice/kew/edl/AfterSecondPickup.html | HTML | apache-2.0 | 22,316 |
package com.smartbear.ready.plugin.template.factories;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.plugins.auto.PluginResponseEditorView;
import com.eviware.soapui.support.editor.Editor;
import com.eviware.soapui.support.editor.views.AbstractXmlEditorView;
import com.eviware.soapui.support.editor.xml.XmlEditor;
import javax.swing.JComponent;
import javax.swing.JLabel;
/**
* Created by ole on 18/06/14.
*/
@PluginResponseEditorView(viewId = "SampleResponseEditorView")
public class SampleResponseEditorView extends AbstractXmlEditorView {
private ModelItem modelItem;
public SampleResponseEditorView(Editor<?> editor, ModelItem modelItem) {
super("Sample Response Editor View", (XmlEditor) editor, "SampleResponseEditorView");
this.modelItem = modelItem;
}
@Override
public JComponent getComponent() {
return new JLabel(modelItem.getName());
}
@Override
public void setEditable(boolean enabled) {
}
@Override
public boolean saveDocument(boolean validate) {
return true;
}
}
| olensmar/ready-api-plugin-template | src/main/java/com/smartbear/ready/plugin/template/factories/SampleResponseEditorView.java | Java | apache-2.0 | 1,092 |
<!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_20) on Tue Jun 01 14:31:55 BST 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.hp.hpl.jena.graph.query.ExpressionSet (Jena Framework)
</TITLE>
<META NAME="date" CONTENT="2010-06-01">
<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.hp.hpl.jena.graph.query.ExpressionSet (Jena Framework)";
}
}
</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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?com/hp/hpl/jena/graph/query/\class-useExpressionSet.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExpressionSet.html" target="_top"><B>NO FRAMES</B></A>
<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.hp.hpl.jena.graph.query.ExpressionSet</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/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.hp.hpl.jena.graph.query"><B>com.hp.hpl.jena.graph.query</B></A></TD>
<TD>Defines the graph-level Query classes, allowing multi-pattern query
over arbitrary graphs. </TD>
</TR>
</TABLE>
<P>
<A NAME="com.hp.hpl.jena.graph.query"><!-- --></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/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> in <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/package-summary.html">com.hp.hpl.jena.graph.query</A></FONT></TH>
</TR>
</TABLE>
<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/hp/hpl/jena/graph/query/package-summary.html">com.hp.hpl.jena.graph.query</A> that return <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A></CODE></FONT></TD>
<TD><CODE><B>ExpressionSet.</B><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html#add(com.hp.hpl.jena.graph.query.Expression)">add</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Expression.html" title="interface in com.hp.hpl.jena.graph.query">Expression</A> e)</CODE>
<BR>
Answer this expressionset after e has been anded into it.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A></CODE></FONT></TD>
<TD><CODE><B>Query.</B><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Query.html#getConstraints()">getConstraints</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<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/hp/hpl/jena/graph/query/package-summary.html">com.hp.hpl.jena.graph.query</A> with parameters of type <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ValuatorSet.html" title="class in com.hp.hpl.jena.graph.query">ValuatorSet</A>[]</CODE></FONT></TD>
<TD><CODE><B>GuardArranger.</B><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/GuardArranger.html#makeGuards(com.hp.hpl.jena.graph.query.Mapping, com.hp.hpl.jena.graph.query.ExpressionSet)">makeGuards</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Mapping.html" title="class in com.hp.hpl.jena.graph.query">Mapping</A> map,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraints)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Stage.html" title="class in com.hp.hpl.jena.graph.query">Stage</A></CODE></FONT></TD>
<TD><CODE><B>SimpleQueryHandler.</B><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/SimpleQueryHandler.html#patternStage(com.hp.hpl.jena.graph.query.Mapping, com.hp.hpl.jena.graph.query.ExpressionSet, com.hp.hpl.jena.graph.Triple[])">patternStage</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Mapping.html" title="class in com.hp.hpl.jena.graph.query">Mapping</A> map,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraints,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</A>[] t)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Stage.html" title="class in com.hp.hpl.jena.graph.query">Stage</A></CODE></FONT></TD>
<TD><CODE><B>QueryHandler.</B><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/QueryHandler.html#patternStage(com.hp.hpl.jena.graph.query.Mapping, com.hp.hpl.jena.graph.query.ExpressionSet, com.hp.hpl.jena.graph.Triple[])">patternStage</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Mapping.html" title="class in com.hp.hpl.jena.graph.query">Mapping</A> map,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraints,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</A>[] p)</CODE>
<BR>
produce a single Stage which will probe the underlying graph for triples
matching p and inject all the resulting bindings into the processing stream
(see Stage for details)</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/package-summary.html">com.hp.hpl.jena.graph.query</A> with parameters of type <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ConstraintStage.html#ConstraintStage(com.hp.hpl.jena.graph.query.Mapping, com.hp.hpl.jena.graph.query.ExpressionSet)">ConstraintStage</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Mapping.html" title="class in com.hp.hpl.jena.graph.query">Mapping</A> map,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraint)</CODE>
<BR>
Initialise this ConstraintStage with the mapping [from names to indexes] and
ExpressionSet [the constraint expressions] that will be evaluated when the
constraint stage runs.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/PatternStage.html#PatternStage(com.hp.hpl.jena.graph.Graph, com.hp.hpl.jena.graph.query.Mapping, com.hp.hpl.jena.graph.query.ExpressionSet, com.hp.hpl.jena.graph.Triple[])">PatternStage</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/Graph.html" title="interface in com.hp.hpl.jena.graph">Graph</A> graph,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Mapping.html" title="class in com.hp.hpl.jena.graph.query">Mapping</A> map,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraints,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</A>[] triples)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/PatternStageBase.html#PatternStageBase(com.hp.hpl.jena.graph.query.QueryNodeFactory, com.hp.hpl.jena.graph.Graph, com.hp.hpl.jena.graph.query.Mapping, com.hp.hpl.jena.graph.query.ExpressionSet, com.hp.hpl.jena.graph.Triple[])">PatternStageBase</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/QueryNodeFactory.html" title="interface in com.hp.hpl.jena.graph.query">QueryNodeFactory</A> factory,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/Graph.html" title="interface in com.hp.hpl.jena.graph">Graph</A> graph,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/Mapping.html" title="class in com.hp.hpl.jena.graph.query">Mapping</A> map,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraints,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</A>[] triples)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/SimpleQueryEngine.html#SimpleQueryEngine(java.util.List, com.hp.hpl.jena.graph.query.TripleSorter, com.hp.hpl.jena.graph.query.ExpressionSet)">SimpleQueryEngine</A></B>(java.util.List<<A HREF="../../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</A>> pattern,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/TripleSorter.html" title="interface in com.hp.hpl.jena.graph.query">TripleSorter</A> sorter,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraints)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../com/hp/hpl/jena/graph/query/SimpleQueryEngine.html#SimpleQueryEngine(com.hp.hpl.jena.graph.query.NamedTripleBunches, com.hp.hpl.jena.graph.query.TripleSorter, com.hp.hpl.jena.graph.query.ExpressionSet)">SimpleQueryEngine</A></B>(<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/NamedTripleBunches.html" title="class in com.hp.hpl.jena.graph.query">NamedTripleBunches</A> triples,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/TripleSorter.html" title="interface in com.hp.hpl.jena.graph.query">TripleSorter</A> ts,
<A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query">ExpressionSet</A> constraint)</CODE>
<BR>
<B>Deprecated.</B> <I>NamedTripleBunches are not supported. Use SimpleQueryEngine
( List, TripleSorter, ExpressionSet ) instead.</I></TD>
</TR>
</TABLE>
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../com/hp/hpl/jena/graph/query/ExpressionSet.html" title="class in com.hp.hpl.jena.graph.query"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?com/hp/hpl/jena/graph/query/\class-useExpressionSet.html" target="_top"><B>FRAMES</B></A>
<A HREF="ExpressionSet.html" target="_top"><B>NO FRAMES</B></A>
<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 © 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
</BODY>
</HTML>
| jianglili007/pretty-printer | Jenna-2.6.3/doc/javadoc/com/hp/hpl/jena/graph/query/class-use/ExpressionSet.html | HTML | apache-2.0 | 18,498 |
/* Copyright 2017 The TensorFlow 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.
==============================================================================*/
#include <string.h>
#include <algorithm>
#include <cmath>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/runtime/types.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"
namespace toco {
namespace {
// Using the function reducer, reduce input along all axes in axes.
// Put the reduced data in output, which should aleady be appropriately sized.
// check_output_shape is set to what this code computes the final shape
// to be, so it can be cross checked with the shape computation logic.
void ReduceGeneric(bool keep_dims, const std::vector<int>& axes,
const Shape& input_shape, const std::vector<float>& input,
Shape* check_output_shape, std::vector<float>* output,
const std::function<float(float, float)>& reducer) {
if (!IsNonEmpty(input_shape)) {
// Zero-dimensions will break the NextIndices() logic, so just early out if
// we have an empty shape.
return;
}
// Set up output_shape to be the same length as input_shape, with
// appropriate dimensions squashed to 1. If keep_dims is false, we'll strip
// out the one dimensions at the end, but it's convenient to leave them for
// now. We recompute the shape because we need the output shape to have
// 1-dims in all the squashed dimensions; the shape from shape computation may
// remove those squashed dimensions, depending on the options used.
Shape output_shape = input_shape;
// Reduction mask will be elementwise multiplied against the input
// indices to figure out the output index for the element.
std::vector<int> reduction_mask(input_shape.dimensions_count(), 1);
for (int axis : axes) {
CHECK_GE(axis, 0);
CHECK_LT(axis, input_shape.dimensions_count());
reduction_mask[axis] = 0;
output_shape.mutable_dims()->at(axis) = 1;
}
std::vector<int> output_indices(input_shape.dimensions_count());
for (int input_offset = 0; input_offset < input.size(); ++input_offset) {
std::vector<int> input_indices = ReverseOffset(input_shape, input_offset);
// Calculate the output location by squashing input indices to 0
// in reduced axes.
for (int i = 0; i < input_shape.dimensions_count(); ++i) {
output_indices[i] = input_indices[i] * reduction_mask[i];
}
int output_offset = Offset(output_shape, output_indices);
if (input_indices == output_indices) {
// Base element for the reduced axes
output->at(output_offset) = input.at(input_offset);
} else {
// Reduce with existing element.
output->at(output_offset) =
reducer(output->at(output_offset), input.at(input_offset));
}
}
if (!keep_dims) {
// Strip out the dims from output_shape.
std::vector<int> new_dims;
for (int i = 0; i < output_shape.dimensions_count(); ++i) {
if (reduction_mask[i]) {
new_dims.push_back(output_shape.dims(i));
}
}
output_shape.mutable_dims()->swap(new_dims);
}
*check_output_shape = output_shape;
}
} // namespace
bool CopyMinMaxFromFirstInput(const Operator& op, Model* model) {
auto& output_array = model->GetArray(op.outputs[0]);
if (output_array.minmax) {
return false;
}
const auto& input_array = model->GetArray(op.inputs[0]);
if (!input_array.minmax) {
return false;
}
const auto& input_minmax = input_array.GetMinMax();
CHECK(!output_array.minmax);
auto& output_minmax = output_array.GetOrCreateMinMax();
output_minmax.min = input_minmax.min;
output_minmax.max = input_minmax.max;
return true;
}
::tensorflow::Status ResolveConstantUnaryOperator::Run(Model* model,
std::size_t op_index,
bool* modified) {
*modified = false;
const auto unary_it = model->operators.begin() + op_index;
const auto* unary_op = unary_it->get();
// Test for unary ops of types that we know how to resolve.
switch (unary_op->type) {
case OperatorType::kCast:
case OperatorType::kExp:
case OperatorType::kLog:
case OperatorType::kNeg:
case OperatorType::kRsqrt:
case OperatorType::kSqrt:
case OperatorType::kSquare:
case OperatorType::kSum:
case OperatorType::kReduceMin: // Reduction Min
case OperatorType::kReduceMax: // Reduction Max
case OperatorType::kReshape:
case OperatorType::kRelu6:
case OperatorType::kRelu1:
case OperatorType::kRelu:
break;
default:
return ::tensorflow::Status::OK();
}
// Check if the input is a constant parameter.
if (!IsConstantParameterArray(*model, unary_op->inputs[0])) {
return ::tensorflow::Status::OK();
}
// if the unary op involves a tensor required by a rnn state, ignore it
for (const auto& rnn_state : model->flags.rnn_states()) {
if (unary_op->inputs[0] == rnn_state.back_edge_source_array()) {
return ::tensorflow::Status::OK();
}
if (unary_op->inputs[0] == rnn_state.state_array()) {
return ::tensorflow::Status::OK();
}
}
auto& output_array = model->GetArray(unary_op->outputs[0]);
if (!output_array.has_shape()) {
// Yield until the output array dims have been resolved.
return ::tensorflow::Status::OK();
}
// At the moment we don't want to care about fused activation functions.
// The idea is that we should do the present constants-propagation before
// activation functions get fused.
if (unary_op->fused_activation_function !=
FusedActivationFunctionType::kNone) {
AddMessageF(
"Not resolving constant %s "
" because it has a fused activation function",
LogName(*unary_op));
return ::tensorflow::Status::OK();
}
// The min-max is only copied for ops that copy data without arithmetic.
// In future trivial transpose, etc, can be handled here.
if (unary_op->type == OperatorType::kReshape) {
CopyMinMaxFromFirstInput(*unary_op, model);
}
const auto& input_array = model->GetArray(unary_op->inputs[0]);
// We have already tested above for existence of buffers (synonymous to being
// a constant param).
CHECK(input_array.buffer);
std::vector<DataType<ArrayDataType::kFloat>> const* input_float_data;
if (unary_op->type == OperatorType::kCast) {
CastOperator const* cast_op = static_cast<CastOperator const*>(unary_op);
if (cast_op->dst_data_type != ArrayDataType::kFloat) {
AddMessageF(
"Not resolving constant %s because we currently only support casting "
"to float",
LogName(*unary_op));
return ::tensorflow::Status::OK();
}
if (cast_op->src_data_type != input_array.buffer->type) {
AddMessageF(
"Not resolving constant %s because cast op source type does not "
"match input type",
LogName(*unary_op));
}
} else {
if (input_array.buffer->type != ArrayDataType::kFloat) {
return ::tensorflow::Status::OK();
}
input_float_data = &(input_array.GetBuffer<ArrayDataType::kFloat>().data);
}
// Create a float buffer on the output array, which are always constant.
const Shape& output_shape = output_array.shape();
const int output_dims_count = output_shape.dimensions_count();
const int output_buffer_size = RequiredBufferSizeForShape(output_shape);
auto& output_float_data =
output_array.GetMutableBuffer<ArrayDataType::kFloat>().data;
output_float_data.resize(output_buffer_size);
const Shape& input_shape = input_array.shape();
const int input_buffer_size = RequiredBufferSizeForShape(input_shape);
if (unary_op->type == OperatorType::kCast) {
for (int i = 0; i < output_buffer_size; i++) {
float outval = 0.0f;
if (input_array.buffer->type == ArrayDataType::kFloat) {
outval = static_cast<float>(
input_array.GetBuffer<ArrayDataType::kFloat>().data[i]);
} else if (input_array.buffer->type == ArrayDataType::kUint8) {
outval = static_cast<float>(
input_array.GetBuffer<ArrayDataType::kUint8>().data[i]);
} else if (input_array.buffer->type == ArrayDataType::kInt32) {
outval = static_cast<float>(
input_array.GetBuffer<ArrayDataType::kInt32>().data[i]);
} else if (input_array.buffer->type == ArrayDataType::kInt64) {
outval = static_cast<float>(
input_array.GetBuffer<ArrayDataType::kInt64>().data[i]);
} else {
LOG(FATAL) << "Unsupported cast op input type";
}
output_float_data[i] = outval;
}
} else if (unary_op->type == OperatorType::kReshape) {
CHECK(input_buffer_size == output_buffer_size);
output_float_data = *input_float_data;
} else if (unary_op->type == OperatorType::kSum) {
CHECK_EQ(unary_op->inputs.size(), 2) << "Sum needs 2 inputs";
if (!IsConstantParameterArray(*model, unary_op->inputs[1])) {
AddMessageF("Axis input is non-constant");
return ::tensorflow::Status::OK();
}
auto& axis_array = model->GetArray(unary_op->inputs[1]);
CHECK(axis_array.data_type == ArrayDataType::kInt32);
// We only support keep_dims=true; shape prop will need to change otherwise.
auto sum_op = static_cast<const TensorFlowSumOperator*>(unary_op);
Shape check_output_shape;
ReduceGeneric(
sum_op->keep_dims, axis_array.GetBuffer<ArrayDataType::kInt32>().data,
input_shape, *input_float_data, &check_output_shape, &output_float_data,
[](float existing, float current) -> float {
return existing + current;
});
CHECK(check_output_shape == output_shape)
<< "Shape propagation output shape doesn't match output shape from op";
} else if (unary_op->type == OperatorType::kReduceMin) {
// At the moment only full reduction across all dimensions is supported.
// TODO(starka): Output should not be padded.
for (int i = 0; i < output_dims_count; i++) {
CHECK_EQ(output_shape.dims(i), 1);
}
float min = (*input_float_data)[0];
for (int i = 0; i < input_buffer_size; i++) {
min = std::min(min, (*input_float_data)[i]);
}
output_float_data[0] = min;
} else if (unary_op->type == OperatorType::kReduceMax) {
// At the moment only full reduction across all dimensions is supported.
// TODO(starka): Output should not be padded.
for (int i = 0; i < output_dims_count; i++) {
CHECK_EQ(output_shape.dims(i), 1);
}
float max = (*input_float_data)[0];
for (int i = 0; i < input_buffer_size; i++) {
max = std::max(max, (*input_float_data)[i]);
}
output_float_data[0] = max;
} else if (unary_op->type == OperatorType::kExp ||
unary_op->type == OperatorType::kNeg ||
unary_op->type == OperatorType::kLog ||
unary_op->type == OperatorType::kRsqrt ||
unary_op->type == OperatorType::kSqrt ||
unary_op->type == OperatorType::kSquare) {
// Element-wise ops. Should have perfectly matching sizes here.
for (int i = 0; i < output_dims_count; i++) {
CHECK_EQ(output_shape.dims(i), input_shape.dims(i));
}
for (int i = 0; i < output_buffer_size; i++) {
const float val = (*input_float_data)[i];
float outval = 0.f;
if (unary_op->type == OperatorType::kExp) {
outval = std::exp(val);
} else if (unary_op->type == OperatorType::kNeg) {
outval = -val;
} else if (unary_op->type == OperatorType::kLog) {
outval = std::log(val);
} else if (unary_op->type == OperatorType::kRsqrt) {
outval = 1.0f / std::sqrt(val);
} else if (unary_op->type == OperatorType::kSqrt) {
outval = std::sqrt(val);
} else if (unary_op->type == OperatorType::kSquare) {
outval = val * val;
} else {
LOG(FATAL) << "should not get here.";
}
output_float_data[i] = outval;
}
} else if (unary_op->type == OperatorType::kRelu6 ||
unary_op->type == OperatorType::kRelu1 ||
unary_op->type == OperatorType::kRelu) {
for (size_t i = 0; i < output_buffer_size; ++i) {
const float value = (*input_float_data)[i];
float new_value = 0.0f;
switch (unary_op->type) {
case OperatorType::kRelu: {
static constexpr float kLower = 0;
new_value = value < kLower ? kLower : value;
break;
}
case OperatorType::kRelu1: {
static constexpr float kUpper = 1;
static constexpr float kLower = -1;
new_value = value > kUpper ? kUpper : value < kLower ? kLower : value;
break;
}
case OperatorType::kRelu6: {
static constexpr float kUpper = 6;
static constexpr float kLower = 0;
new_value = value > kUpper ? kUpper : value < kLower ? kLower : value;
break;
}
default:
LOG(FATAL) << "Unsupported activation function "
<< LogName(*unary_op);
return ::tensorflow::Status::OK();
}
output_float_data[i] = new_value;
}
} else {
LOG(FATAL) << "should not get here.";
}
for (const auto& input : unary_op->inputs) {
if (CountOpsWithInput(*model, input) == 1) {
model->EraseArray(input);
}
}
AddMessageF("Resolved constant %s to the equivalent constant array",
LogName(*unary_op));
model->operators.erase(unary_it);
*modified = true;
return ::tensorflow::Status::OK();
}
} // namespace toco
| alshedivat/tensorflow | tensorflow/contrib/lite/toco/graph_transformations/resolve_constant_unary.cc | C++ | apache-2.0 | 14,346 |
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: file.dot.proto
/*
Package filedotname is a generated protocol buffer package.
It is generated from these files:
file.dot.proto
It has these top-level messages:
M
*/
package filedotname
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
import github_com_gogo_protobuf_protoc_gen_gogo_descriptor "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
import compress_gzip "compress/gzip"
import bytes "bytes"
import io_ioutil "io/ioutil"
import strings "strings"
import reflect "reflect"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
type M struct {
A *string `protobuf:"bytes,1,opt,name=a" json:"a,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *M) Reset() { *m = M{} }
func (*M) ProtoMessage() {}
func (*M) Descriptor() ([]byte, []int) { return fileDescriptorFileDot, []int{0} }
func init() {
proto.RegisterType((*M)(nil), "filedotname.M")
}
func (this *M) Description() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
return FileDotDescription()
}
func FileDotDescription() (desc *github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet) {
d := &github_com_gogo_protobuf_protoc_gen_gogo_descriptor.FileDescriptorSet{}
var gzipped = []byte{
// 3657 bytes of a gzipped FileDescriptorSet
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x5a, 0x5d, 0x70, 0x1b, 0xd7,
0x75, 0xe6, 0xe2, 0x87, 0x04, 0x0e, 0x40, 0x70, 0xb9, 0xa4, 0x29, 0x88, 0x8e, 0x21, 0x8a, 0xb1,
0x63, 0xda, 0x6e, 0xa8, 0x8c, 0x6c, 0xc9, 0xf2, 0xaa, 0x89, 0x06, 0x04, 0x21, 0x06, 0x2a, 0x49,
0x20, 0x0b, 0x32, 0x96, 0xd2, 0x87, 0x9d, 0xe5, 0xee, 0x05, 0xb8, 0xd2, 0x62, 0x17, 0xd9, 0x5d,
0x48, 0xa2, 0x9e, 0xd4, 0x71, 0x7f, 0x26, 0xd3, 0xe9, 0x7f, 0x67, 0x9a, 0xb8, 0x8e, 0xdb, 0x66,
0xa6, 0x75, 0x9a, 0x34, 0x6d, 0xd2, 0x9f, 0x34, 0xd3, 0xa7, 0xbc, 0xa4, 0xf5, 0x53, 0x27, 0x79,
0xeb, 0x43, 0x1f, 0x2c, 0xc6, 0x33, 0x75, 0x5b, 0xb5, 0x75, 0x1b, 0xcd, 0x34, 0x33, 0x7a, 0xc9,
0xdc, 0xbf, 0xc5, 0x2e, 0x00, 0x72, 0xc1, 0xcc, 0x38, 0x7e, 0x22, 0xef, 0xb9, 0xe7, 0xfb, 0xf6,
0xec, 0xb9, 0xe7, 0x9e, 0x73, 0xee, 0x5d, 0xc0, 0x0f, 0x2f, 0xc0, 0x52, 0xdb, 0x71, 0xda, 0x16,
0x3a, 0xd7, 0x75, 0x1d, 0xdf, 0xd9, 0xeb, 0xb5, 0xce, 0x19, 0xc8, 0xd3, 0x5d, 0xb3, 0xeb, 0x3b,
0xee, 0x2a, 0x91, 0x49, 0x33, 0x54, 0x63, 0x95, 0x6b, 0x2c, 0x6f, 0xc1, 0xec, 0x55, 0xd3, 0x42,
0xeb, 0x81, 0x62, 0x13, 0xf9, 0xd2, 0x25, 0x48, 0xb5, 0x4c, 0x0b, 0x15, 0x85, 0xa5, 0xe4, 0x4a,
0xee, 0xfc, 0xd3, 0xab, 0x03, 0xa0, 0xd5, 0x28, 0xa2, 0x81, 0xc5, 0x0a, 0x41, 0x2c, 0xbf, 0x9b,
0x82, 0xb9, 0x11, 0xb3, 0x92, 0x04, 0x29, 0x5b, 0xeb, 0x60, 0x46, 0x61, 0x25, 0xab, 0x90, 0xff,
0xa5, 0x22, 0x4c, 0x75, 0x35, 0xfd, 0x96, 0xd6, 0x46, 0xc5, 0x04, 0x11, 0xf3, 0xa1, 0x54, 0x02,
0x30, 0x50, 0x17, 0xd9, 0x06, 0xb2, 0xf5, 0x83, 0x62, 0x72, 0x29, 0xb9, 0x92, 0x55, 0x42, 0x12,
0xe9, 0x05, 0x98, 0xed, 0xf6, 0xf6, 0x2c, 0x53, 0x57, 0x43, 0x6a, 0xb0, 0x94, 0x5c, 0x49, 0x2b,
0x22, 0x9d, 0x58, 0xef, 0x2b, 0x3f, 0x0b, 0x33, 0x77, 0x90, 0x76, 0x2b, 0xac, 0x9a, 0x23, 0xaa,
0x05, 0x2c, 0x0e, 0x29, 0x56, 0x20, 0xdf, 0x41, 0x9e, 0xa7, 0xb5, 0x91, 0xea, 0x1f, 0x74, 0x51,
0x31, 0x45, 0xde, 0x7e, 0x69, 0xe8, 0xed, 0x07, 0xdf, 0x3c, 0xc7, 0x50, 0x3b, 0x07, 0x5d, 0x24,
0x95, 0x21, 0x8b, 0xec, 0x5e, 0x87, 0x32, 0xa4, 0x8f, 0xf0, 0x5f, 0xd5, 0xee, 0x75, 0x06, 0x59,
0x32, 0x18, 0xc6, 0x28, 0xa6, 0x3c, 0xe4, 0xde, 0x36, 0x75, 0x54, 0x9c, 0x24, 0x04, 0xcf, 0x0e,
0x11, 0x34, 0xe9, 0xfc, 0x20, 0x07, 0xc7, 0x49, 0x15, 0xc8, 0xa2, 0xbb, 0x3e, 0xb2, 0x3d, 0xd3,
0xb1, 0x8b, 0x53, 0x84, 0xe4, 0x99, 0x11, 0xab, 0x88, 0x2c, 0x63, 0x90, 0xa2, 0x8f, 0x93, 0x2e,
0xc2, 0x94, 0xd3, 0xf5, 0x4d, 0xc7, 0xf6, 0x8a, 0x99, 0x25, 0x61, 0x25, 0x77, 0xfe, 0x23, 0x23,
0x03, 0xa1, 0x4e, 0x75, 0x14, 0xae, 0x2c, 0xd5, 0x40, 0xf4, 0x9c, 0x9e, 0xab, 0x23, 0x55, 0x77,
0x0c, 0xa4, 0x9a, 0x76, 0xcb, 0x29, 0x66, 0x09, 0xc1, 0x99, 0xe1, 0x17, 0x21, 0x8a, 0x15, 0xc7,
0x40, 0x35, 0xbb, 0xe5, 0x28, 0x05, 0x2f, 0x32, 0x96, 0x16, 0x60, 0xd2, 0x3b, 0xb0, 0x7d, 0xed,
0x6e, 0x31, 0x4f, 0x22, 0x84, 0x8d, 0x96, 0xff, 0x3f, 0x0d, 0x33, 0xe3, 0x84, 0xd8, 0x65, 0x48,
0xb7, 0xf0, 0x5b, 0x16, 0x13, 0x27, 0xf1, 0x01, 0xc5, 0x44, 0x9d, 0x38, 0xf9, 0x53, 0x3a, 0xb1,
0x0c, 0x39, 0x1b, 0x79, 0x3e, 0x32, 0x68, 0x44, 0x24, 0xc7, 0x8c, 0x29, 0xa0, 0xa0, 0xe1, 0x90,
0x4a, 0xfd, 0x54, 0x21, 0x75, 0x1d, 0x66, 0x02, 0x93, 0x54, 0x57, 0xb3, 0xdb, 0x3c, 0x36, 0xcf,
0xc5, 0x59, 0xb2, 0x5a, 0xe5, 0x38, 0x05, 0xc3, 0x94, 0x02, 0x8a, 0x8c, 0xa5, 0x75, 0x00, 0xc7,
0x46, 0x4e, 0x4b, 0x35, 0x90, 0x6e, 0x15, 0x33, 0x47, 0x78, 0xa9, 0x8e, 0x55, 0x86, 0xbc, 0xe4,
0x50, 0xa9, 0x6e, 0x49, 0xaf, 0xf4, 0x43, 0x6d, 0xea, 0x88, 0x48, 0xd9, 0xa2, 0x9b, 0x6c, 0x28,
0xda, 0x76, 0xa1, 0xe0, 0x22, 0x1c, 0xf7, 0xc8, 0x60, 0x6f, 0x96, 0x25, 0x46, 0xac, 0xc6, 0xbe,
0x99, 0xc2, 0x60, 0xf4, 0xc5, 0xa6, 0xdd, 0xf0, 0x50, 0xfa, 0x28, 0x04, 0x02, 0x95, 0x84, 0x15,
0x90, 0x2c, 0x94, 0xe7, 0xc2, 0x6d, 0xad, 0x83, 0x16, 0x2f, 0x41, 0x21, 0xea, 0x1e, 0x69, 0x1e,
0xd2, 0x9e, 0xaf, 0xb9, 0x3e, 0x89, 0xc2, 0xb4, 0x42, 0x07, 0x92, 0x08, 0x49, 0x64, 0x1b, 0x24,
0xcb, 0xa5, 0x15, 0xfc, 0xef, 0xe2, 0xcb, 0x30, 0x1d, 0x79, 0xfc, 0xb8, 0xc0, 0xe5, 0x2f, 0x4e,
0xc2, 0xfc, 0xa8, 0x98, 0x1b, 0x19, 0xfe, 0x0b, 0x30, 0x69, 0xf7, 0x3a, 0x7b, 0xc8, 0x2d, 0x26,
0x09, 0x03, 0x1b, 0x49, 0x65, 0x48, 0x5b, 0xda, 0x1e, 0xb2, 0x8a, 0xa9, 0x25, 0x61, 0xa5, 0x70,
0xfe, 0x85, 0xb1, 0xa2, 0x7a, 0x75, 0x13, 0x43, 0x14, 0x8a, 0x94, 0x3e, 0x05, 0x29, 0x96, 0xe2,
0x30, 0xc3, 0xf3, 0xe3, 0x31, 0xe0, 0x58, 0x54, 0x08, 0x4e, 0x7a, 0x12, 0xb2, 0xf8, 0x2f, 0xf5,
0xed, 0x24, 0xb1, 0x39, 0x83, 0x05, 0xd8, 0xaf, 0xd2, 0x22, 0x64, 0x48, 0x98, 0x19, 0x88, 0x97,
0x86, 0x60, 0x8c, 0x17, 0xc6, 0x40, 0x2d, 0xad, 0x67, 0xf9, 0xea, 0x6d, 0xcd, 0xea, 0x21, 0x12,
0x30, 0x59, 0x25, 0xcf, 0x84, 0x9f, 0xc5, 0x32, 0xe9, 0x0c, 0xe4, 0x68, 0x54, 0x9a, 0xb6, 0x81,
0xee, 0x92, 0xec, 0x93, 0x56, 0x68, 0xa0, 0xd6, 0xb0, 0x04, 0x3f, 0xfe, 0xa6, 0xe7, 0xd8, 0x7c,
0x69, 0xc9, 0x23, 0xb0, 0x80, 0x3c, 0xfe, 0xe5, 0xc1, 0xc4, 0xf7, 0xd4, 0xe8, 0xd7, 0x1b, 0x8c,
0xc5, 0xe5, 0x6f, 0x27, 0x20, 0x45, 0xf6, 0xdb, 0x0c, 0xe4, 0x76, 0x6e, 0x34, 0xaa, 0xea, 0x7a,
0x7d, 0x77, 0x6d, 0xb3, 0x2a, 0x0a, 0x52, 0x01, 0x80, 0x08, 0xae, 0x6e, 0xd6, 0xcb, 0x3b, 0x62,
0x22, 0x18, 0xd7, 0xb6, 0x77, 0x2e, 0xbe, 0x24, 0x26, 0x03, 0xc0, 0x2e, 0x15, 0xa4, 0xc2, 0x0a,
0x2f, 0x9e, 0x17, 0xd3, 0x92, 0x08, 0x79, 0x4a, 0x50, 0xbb, 0x5e, 0x5d, 0xbf, 0xf8, 0x92, 0x38,
0x19, 0x95, 0xbc, 0x78, 0x5e, 0x9c, 0x92, 0xa6, 0x21, 0x4b, 0x24, 0x6b, 0xf5, 0xfa, 0xa6, 0x98,
0x09, 0x38, 0x9b, 0x3b, 0x4a, 0x6d, 0x7b, 0x43, 0xcc, 0x06, 0x9c, 0x1b, 0x4a, 0x7d, 0xb7, 0x21,
0x42, 0xc0, 0xb0, 0x55, 0x6d, 0x36, 0xcb, 0x1b, 0x55, 0x31, 0x17, 0x68, 0xac, 0xdd, 0xd8, 0xa9,
0x36, 0xc5, 0x7c, 0xc4, 0xac, 0x17, 0xcf, 0x8b, 0xd3, 0xc1, 0x23, 0xaa, 0xdb, 0xbb, 0x5b, 0x62,
0x41, 0x9a, 0x85, 0x69, 0xfa, 0x08, 0x6e, 0xc4, 0xcc, 0x80, 0xe8, 0xe2, 0x4b, 0xa2, 0xd8, 0x37,
0x84, 0xb2, 0xcc, 0x46, 0x04, 0x17, 0x5f, 0x12, 0xa5, 0xe5, 0x0a, 0xa4, 0x49, 0x74, 0x49, 0x12,
0x14, 0x36, 0xcb, 0x6b, 0xd5, 0x4d, 0xb5, 0xde, 0xd8, 0xa9, 0xd5, 0xb7, 0xcb, 0x9b, 0xa2, 0xd0,
0x97, 0x29, 0xd5, 0xcf, 0xec, 0xd6, 0x94, 0xea, 0xba, 0x98, 0x08, 0xcb, 0x1a, 0xd5, 0xf2, 0x4e,
0x75, 0x5d, 0x4c, 0x2e, 0xeb, 0x30, 0x3f, 0x2a, 0xcf, 0x8c, 0xdc, 0x19, 0xa1, 0x25, 0x4e, 0x1c,
0xb1, 0xc4, 0x84, 0x6b, 0x68, 0x89, 0xbf, 0x22, 0xc0, 0xdc, 0x88, 0x5c, 0x3b, 0xf2, 0x21, 0x57,
0x20, 0x4d, 0x43, 0x94, 0x56, 0x9f, 0xe7, 0x46, 0x26, 0x6d, 0x12, 0xb0, 0x43, 0x15, 0x88, 0xe0,
0xc2, 0x15, 0x38, 0x79, 0x44, 0x05, 0xc6, 0x14, 0x43, 0x46, 0xbe, 0x26, 0x40, 0xf1, 0x28, 0xee,
0x98, 0x44, 0x91, 0x88, 0x24, 0x8a, 0xcb, 0x83, 0x06, 0x9c, 0x3d, 0xfa, 0x1d, 0x86, 0xac, 0x78,
0x4b, 0x80, 0x85, 0xd1, 0x8d, 0xca, 0x48, 0x1b, 0x3e, 0x05, 0x93, 0x1d, 0xe4, 0xef, 0x3b, 0xbc,
0x58, 0x7f, 0x6c, 0x44, 0x09, 0xc0, 0xd3, 0x83, 0xbe, 0x62, 0xa8, 0x70, 0x0d, 0x49, 0x1e, 0xd5,
0x6d, 0x50, 0x6b, 0x86, 0x2c, 0xfd, 0x42, 0x02, 0x9e, 0x18, 0x49, 0x3e, 0xd2, 0xd0, 0xa7, 0x00,
0x4c, 0xbb, 0xdb, 0xf3, 0x69, 0x41, 0xa6, 0xf9, 0x29, 0x4b, 0x24, 0x64, 0xef, 0xe3, 0xdc, 0xd3,
0xf3, 0x83, 0xf9, 0x24, 0x99, 0x07, 0x2a, 0x22, 0x0a, 0x97, 0xfa, 0x86, 0xa6, 0x88, 0xa1, 0xa5,
0x23, 0xde, 0x74, 0xa8, 0xd6, 0x7d, 0x02, 0x44, 0xdd, 0x32, 0x91, 0xed, 0xab, 0x9e, 0xef, 0x22,
0xad, 0x63, 0xda, 0x6d, 0x92, 0x80, 0x33, 0x72, 0xba, 0xa5, 0x59, 0x1e, 0x52, 0x66, 0xe8, 0x74,
0x93, 0xcf, 0x62, 0x04, 0xa9, 0x32, 0x6e, 0x08, 0x31, 0x19, 0x41, 0xd0, 0xe9, 0x00, 0xb1, 0xfc,
0xf5, 0x29, 0xc8, 0x85, 0xda, 0x3a, 0xe9, 0x2c, 0xe4, 0x6f, 0x6a, 0xb7, 0x35, 0x95, 0xb7, 0xea,
0xd4, 0x13, 0x39, 0x2c, 0x6b, 0xb0, 0x76, 0xfd, 0x13, 0x30, 0x4f, 0x54, 0x9c, 0x9e, 0x8f, 0x5c,
0x55, 0xb7, 0x34, 0xcf, 0x23, 0x4e, 0xcb, 0x10, 0x55, 0x09, 0xcf, 0xd5, 0xf1, 0x54, 0x85, 0xcf,
0x48, 0x17, 0x60, 0x8e, 0x20, 0x3a, 0x3d, 0xcb, 0x37, 0xbb, 0x16, 0x52, 0xf1, 0xe1, 0xc1, 0x23,
0x89, 0x38, 0xb0, 0x6c, 0x16, 0x6b, 0x6c, 0x31, 0x05, 0x6c, 0x91, 0x27, 0xad, 0xc3, 0x53, 0x04,
0xd6, 0x46, 0x36, 0x72, 0x35, 0x1f, 0xa9, 0xe8, 0xf3, 0x3d, 0xcd, 0xf2, 0x54, 0xcd, 0x36, 0xd4,
0x7d, 0xcd, 0xdb, 0x2f, 0xce, 0x63, 0x82, 0xb5, 0x44, 0x51, 0x50, 0x4e, 0x63, 0xc5, 0x0d, 0xa6,
0x57, 0x25, 0x6a, 0x65, 0xdb, 0xf8, 0xb4, 0xe6, 0xed, 0x4b, 0x32, 0x2c, 0x10, 0x16, 0xcf, 0x77,
0x4d, 0xbb, 0xad, 0xea, 0xfb, 0x48, 0xbf, 0xa5, 0xf6, 0xfc, 0xd6, 0xa5, 0xe2, 0x93, 0xe1, 0xe7,
0x13, 0x0b, 0x9b, 0x44, 0xa7, 0x82, 0x55, 0x76, 0xfd, 0xd6, 0x25, 0xa9, 0x09, 0x79, 0xbc, 0x18,
0x1d, 0xf3, 0x1e, 0x52, 0x5b, 0x8e, 0x4b, 0x2a, 0x4b, 0x61, 0xc4, 0xce, 0x0e, 0x79, 0x70, 0xb5,
0xce, 0x00, 0x5b, 0x8e, 0x81, 0xe4, 0x74, 0xb3, 0x51, 0xad, 0xae, 0x2b, 0x39, 0xce, 0x72, 0xd5,
0x71, 0x71, 0x40, 0xb5, 0x9d, 0xc0, 0xc1, 0x39, 0x1a, 0x50, 0x6d, 0x87, 0xbb, 0xf7, 0x02, 0xcc,
0xe9, 0x3a, 0x7d, 0x67, 0x53, 0x57, 0x59, 0x8b, 0xef, 0x15, 0xc5, 0x88, 0xb3, 0x74, 0x7d, 0x83,
0x2a, 0xb0, 0x18, 0xf7, 0xa4, 0x57, 0xe0, 0x89, 0xbe, 0xb3, 0xc2, 0xc0, 0xd9, 0xa1, 0xb7, 0x1c,
0x84, 0x5e, 0x80, 0xb9, 0xee, 0xc1, 0x30, 0x50, 0x8a, 0x3c, 0xb1, 0x7b, 0x30, 0x08, 0x7b, 0x86,
0x1c, 0xdb, 0x5c, 0xa4, 0x6b, 0x3e, 0x32, 0x8a, 0xa7, 0xc2, 0xda, 0xa1, 0x09, 0xe9, 0x1c, 0x88,
0xba, 0xae, 0x22, 0x5b, 0xdb, 0xb3, 0x90, 0xaa, 0xb9, 0xc8, 0xd6, 0xbc, 0xe2, 0x99, 0xb0, 0x72,
0x41, 0xd7, 0xab, 0x64, 0xb6, 0x4c, 0x26, 0xa5, 0xe7, 0x61, 0xd6, 0xd9, 0xbb, 0xa9, 0xd3, 0xc8,
0x52, 0xbb, 0x2e, 0x6a, 0x99, 0x77, 0x8b, 0x4f, 0x13, 0x37, 0xcd, 0xe0, 0x09, 0x12, 0x57, 0x0d,
0x22, 0x96, 0x9e, 0x03, 0x51, 0xf7, 0xf6, 0x35, 0xb7, 0x4b, 0x4a, 0xbb, 0xd7, 0xd5, 0x74, 0x54,
0x7c, 0x86, 0xaa, 0x52, 0xf9, 0x36, 0x17, 0xe3, 0xc8, 0xf6, 0xee, 0x98, 0x2d, 0x9f, 0x33, 0x3e,
0x4b, 0x23, 0x9b, 0xc8, 0x18, 0xdb, 0x75, 0x98, 0xef, 0xd9, 0xa6, 0xed, 0x23, 0xb7, 0xeb, 0x22,
0xdc, 0xc4, 0xd3, 0x9d, 0x58, 0xfc, 0xb7, 0xa9, 0x23, 0xda, 0xf0, 0xdd, 0xb0, 0x36, 0x0d, 0x00,
0x65, 0xae, 0x37, 0x2c, 0x5c, 0x96, 0x21, 0x1f, 0x8e, 0x0b, 0x29, 0x0b, 0x34, 0x32, 0x44, 0x01,
0xd7, 0xd8, 0x4a, 0x7d, 0x1d, 0x57, 0xc7, 0xcf, 0x55, 0xc5, 0x04, 0xae, 0xd2, 0x9b, 0xb5, 0x9d,
0xaa, 0xaa, 0xec, 0x6e, 0xef, 0xd4, 0xb6, 0xaa, 0x62, 0xf2, 0xf9, 0x6c, 0xe6, 0xbd, 0x29, 0xf1,
0xfe, 0xfd, 0xfb, 0xf7, 0x13, 0xcb, 0xdf, 0x4b, 0x40, 0x21, 0xda, 0x19, 0x4b, 0x3f, 0x0f, 0xa7,
0xf8, 0x31, 0xd6, 0x43, 0xbe, 0x7a, 0xc7, 0x74, 0x49, 0xa8, 0x76, 0x34, 0xda, 0x5b, 0x06, 0x5e,
0x9e, 0x67, 0x5a, 0x4d, 0xe4, 0xbf, 0x6a, 0xba, 0x38, 0x10, 0x3b, 0x9a, 0x2f, 0x6d, 0xc2, 0x19,
0xdb, 0x51, 0x3d, 0x5f, 0xb3, 0x0d, 0xcd, 0x35, 0xd4, 0xfe, 0x05, 0x82, 0xaa, 0xe9, 0x3a, 0xf2,
0x3c, 0x87, 0x96, 0x88, 0x80, 0xe5, 0x23, 0xb6, 0xd3, 0x64, 0xca, 0xfd, 0xdc, 0x59, 0x66, 0xaa,
0x03, 0x11, 0x91, 0x3c, 0x2a, 0x22, 0x9e, 0x84, 0x6c, 0x47, 0xeb, 0xaa, 0xc8, 0xf6, 0xdd, 0x03,
0xd2, 0xcf, 0x65, 0x94, 0x4c, 0x47, 0xeb, 0x56, 0xf1, 0xf8, 0x83, 0x5b, 0x83, 0xb0, 0x1f, 0xff,
0x35, 0x09, 0xf9, 0x70, 0x4f, 0x87, 0x5b, 0x64, 0x9d, 0xe4, 0x6f, 0x81, 0xec, 0xf0, 0x8f, 0x1e,
0xdb, 0x01, 0xae, 0x56, 0x70, 0x62, 0x97, 0x27, 0x69, 0xa7, 0xa5, 0x50, 0x24, 0x2e, 0xaa, 0x78,
0x4f, 0x23, 0xda, 0xbf, 0x67, 0x14, 0x36, 0x92, 0x36, 0x60, 0xf2, 0xa6, 0x47, 0xb8, 0x27, 0x09,
0xf7, 0xd3, 0xc7, 0x73, 0x5f, 0x6b, 0x12, 0xf2, 0xec, 0xb5, 0xa6, 0xba, 0x5d, 0x57, 0xb6, 0xca,
0x9b, 0x0a, 0x83, 0x4b, 0xa7, 0x21, 0x65, 0x69, 0xf7, 0x0e, 0xa2, 0x25, 0x80, 0x88, 0xc6, 0x75,
0xfc, 0x69, 0x48, 0xdd, 0x41, 0xda, 0xad, 0x68, 0xe2, 0x25, 0xa2, 0x0f, 0x30, 0xf4, 0xcf, 0x41,
0x9a, 0xf8, 0x4b, 0x02, 0x60, 0x1e, 0x13, 0x27, 0xa4, 0x0c, 0xa4, 0x2a, 0x75, 0x05, 0x87, 0xbf,
0x08, 0x79, 0x2a, 0x55, 0x1b, 0xb5, 0x6a, 0xa5, 0x2a, 0x26, 0x96, 0x2f, 0xc0, 0x24, 0x75, 0x02,
0xde, 0x1a, 0x81, 0x1b, 0xc4, 0x09, 0x36, 0x64, 0x1c, 0x02, 0x9f, 0xdd, 0xdd, 0x5a, 0xab, 0x2a,
0x62, 0x22, 0xbc, 0xbc, 0x1e, 0xe4, 0xc3, 0xed, 0xdc, 0xcf, 0x26, 0xa6, 0xfe, 0x41, 0x80, 0x5c,
0xa8, 0x3d, 0xc3, 0x8d, 0x81, 0x66, 0x59, 0xce, 0x1d, 0x55, 0xb3, 0x4c, 0xcd, 0x63, 0x41, 0x01,
0x44, 0x54, 0xc6, 0x92, 0x71, 0x17, 0xed, 0x67, 0x62, 0xfc, 0x9b, 0x02, 0x88, 0x83, 0xad, 0xdd,
0x80, 0x81, 0xc2, 0x87, 0x6a, 0xe0, 0x1b, 0x02, 0x14, 0xa2, 0xfd, 0xdc, 0x80, 0x79, 0x67, 0x3f,
0x54, 0xf3, 0xde, 0x49, 0xc0, 0x74, 0xa4, 0x8b, 0x1b, 0xd7, 0xba, 0xcf, 0xc3, 0xac, 0x69, 0xa0,
0x4e, 0xd7, 0xf1, 0x91, 0xad, 0x1f, 0xa8, 0x16, 0xba, 0x8d, 0xac, 0xe2, 0x32, 0x49, 0x14, 0xe7,
0x8e, 0xef, 0x13, 0x57, 0x6b, 0x7d, 0xdc, 0x26, 0x86, 0xc9, 0x73, 0xb5, 0xf5, 0xea, 0x56, 0xa3,
0xbe, 0x53, 0xdd, 0xae, 0xdc, 0x50, 0x77, 0xb7, 0x7f, 0x61, 0xbb, 0xfe, 0xea, 0xb6, 0x22, 0x9a,
0x03, 0x6a, 0x1f, 0xe0, 0x56, 0x6f, 0x80, 0x38, 0x68, 0x94, 0x74, 0x0a, 0x46, 0x99, 0x25, 0x4e,
0x48, 0x73, 0x30, 0xb3, 0x5d, 0x57, 0x9b, 0xb5, 0xf5, 0xaa, 0x5a, 0xbd, 0x7a, 0xb5, 0x5a, 0xd9,
0x69, 0xd2, 0x83, 0x73, 0xa0, 0xbd, 0x13, 0xdd, 0xd4, 0xaf, 0x27, 0x61, 0x6e, 0x84, 0x25, 0x52,
0x99, 0xf5, 0xec, 0xf4, 0x18, 0xf1, 0xf1, 0x71, 0xac, 0x5f, 0xc5, 0x5d, 0x41, 0x43, 0x73, 0x7d,
0xd6, 0xe2, 0x3f, 0x07, 0xd8, 0x4b, 0xb6, 0x6f, 0xb6, 0x4c, 0xe4, 0xb2, 0x7b, 0x06, 0xda, 0xc8,
0xcf, 0xf4, 0xe5, 0xf4, 0xaa, 0xe1, 0xe7, 0x40, 0xea, 0x3a, 0x9e, 0xe9, 0x9b, 0xb7, 0x91, 0x6a,
0xda, 0xfc, 0x52, 0x02, 0x37, 0xf6, 0x29, 0x45, 0xe4, 0x33, 0x35, 0xdb, 0x0f, 0xb4, 0x6d, 0xd4,
0xd6, 0x06, 0xb4, 0x71, 0x02, 0x4f, 0x2a, 0x22, 0x9f, 0x09, 0xb4, 0xcf, 0x42, 0xde, 0x70, 0x7a,
0xb8, 0x4d, 0xa2, 0x7a, 0xb8, 0x5e, 0x08, 0x4a, 0x8e, 0xca, 0x02, 0x15, 0xd6, 0xc7, 0xf6, 0x6f,
0x43, 0xf2, 0x4a, 0x8e, 0xca, 0xa8, 0xca, 0xb3, 0x30, 0xa3, 0xb5, 0xdb, 0x2e, 0x26, 0xe7, 0x44,
0xb4, 0x33, 0x2f, 0x04, 0x62, 0xa2, 0xb8, 0x78, 0x0d, 0x32, 0xdc, 0x0f, 0xb8, 0x24, 0x63, 0x4f,
0xa8, 0x5d, 0x7a, 0x27, 0x95, 0x58, 0xc9, 0x2a, 0x19, 0x9b, 0x4f, 0x9e, 0x85, 0xbc, 0xe9, 0xa9,
0xfd, 0xcb, 0xd1, 0xc4, 0x52, 0x62, 0x25, 0xa3, 0xe4, 0x4c, 0x2f, 0xb8, 0x0d, 0x5b, 0x7e, 0x2b,
0x01, 0x85, 0xe8, 0xe5, 0xae, 0xb4, 0x0e, 0x19, 0xcb, 0xd1, 0x35, 0x12, 0x5a, 0xf4, 0xcb, 0xc2,
0x4a, 0xcc, 0x7d, 0xf0, 0xea, 0x26, 0xd3, 0x57, 0x02, 0xe4, 0xe2, 0x3f, 0x0b, 0x90, 0xe1, 0x62,
0x69, 0x01, 0x52, 0x5d, 0xcd, 0xdf, 0x27, 0x74, 0xe9, 0xb5, 0x84, 0x28, 0x28, 0x64, 0x8c, 0xe5,
0x5e, 0x57, 0xb3, 0x49, 0x08, 0x30, 0x39, 0x1e, 0xe3, 0x75, 0xb5, 0x90, 0x66, 0x90, 0xb6, 0xdf,
0xe9, 0x74, 0x90, 0xed, 0x7b, 0x7c, 0x5d, 0x99, 0xbc, 0xc2, 0xc4, 0xd2, 0x0b, 0x30, 0xeb, 0xbb,
0x9a, 0x69, 0x45, 0x74, 0x53, 0x44, 0x57, 0xe4, 0x13, 0x81, 0xb2, 0x0c, 0xa7, 0x39, 0xaf, 0x81,
0x7c, 0x4d, 0xdf, 0x47, 0x46, 0x1f, 0x34, 0x49, 0x6e, 0x0e, 0x4f, 0x31, 0x85, 0x75, 0x36, 0xcf,
0xb1, 0xcb, 0x3f, 0x10, 0x60, 0x96, 0x1f, 0x54, 0x8c, 0xc0, 0x59, 0x5b, 0x00, 0x9a, 0x6d, 0x3b,
0x7e, 0xd8, 0x5d, 0xc3, 0xa1, 0x3c, 0x84, 0x5b, 0x2d, 0x07, 0x20, 0x25, 0x44, 0xb0, 0xd8, 0x01,
0xe8, 0xcf, 0x1c, 0xe9, 0xb6, 0x33, 0x90, 0x63, 0x37, 0xf7, 0xe4, 0xf3, 0x0f, 0x3d, 0xda, 0x02,
0x15, 0xe1, 0x13, 0x8d, 0x34, 0x0f, 0xe9, 0x3d, 0xd4, 0x36, 0x6d, 0x76, 0x9f, 0x48, 0x07, 0xfc,
0x96, 0x32, 0x15, 0xdc, 0x52, 0xae, 0x5d, 0x87, 0x39, 0xdd, 0xe9, 0x0c, 0x9a, 0xbb, 0x26, 0x0e,
0x1c, 0xaf, 0xbd, 0x4f, 0x0b, 0x9f, 0x83, 0x7e, 0x8b, 0xf9, 0x95, 0x44, 0x72, 0xa3, 0xb1, 0xf6,
0xb5, 0xc4, 0xe2, 0x06, 0xc5, 0x35, 0xf8, 0x6b, 0x2a, 0xa8, 0x65, 0x21, 0x1d, 0x9b, 0x0e, 0x3f,
0xfa, 0x18, 0x7c, 0xbc, 0x6d, 0xfa, 0xfb, 0xbd, 0xbd, 0x55, 0xdd, 0xe9, 0x9c, 0x6b, 0x3b, 0x6d,
0xa7, 0xff, 0xb9, 0x0b, 0x8f, 0xc8, 0x80, 0xfc, 0xc7, 0x3e, 0x79, 0x65, 0x03, 0xe9, 0x62, 0xec,
0xf7, 0x31, 0x79, 0x1b, 0xe6, 0x98, 0xb2, 0x4a, 0xee, 0xdc, 0xe9, 0xd1, 0x40, 0x3a, 0xf6, 0xde,
0xa5, 0xf8, 0xad, 0x77, 0x49, 0xad, 0x56, 0x66, 0x19, 0x14, 0xcf, 0xd1, 0x03, 0x84, 0xac, 0xc0,
0x13, 0x11, 0x3e, 0xba, 0x2f, 0x91, 0x1b, 0xc3, 0xf8, 0x3d, 0xc6, 0x38, 0x17, 0x62, 0x6c, 0x32,
0xa8, 0x5c, 0x81, 0xe9, 0x93, 0x70, 0xfd, 0x23, 0xe3, 0xca, 0xa3, 0x30, 0xc9, 0x06, 0xcc, 0x10,
0x12, 0xbd, 0xe7, 0xf9, 0x4e, 0x87, 0x24, 0xbd, 0xe3, 0x69, 0xfe, 0xe9, 0x5d, 0xba, 0x51, 0x0a,
0x18, 0x56, 0x09, 0x50, 0xb2, 0x0c, 0xe4, 0x33, 0x83, 0x81, 0x74, 0x2b, 0x86, 0xe1, 0x6d, 0x66,
0x48, 0xa0, 0x2f, 0x7f, 0x16, 0xe6, 0xf1, 0xff, 0x24, 0x27, 0x85, 0x2d, 0x89, 0xbf, 0x65, 0x2a,
0xfe, 0xe0, 0x35, 0xba, 0x17, 0xe7, 0x02, 0x82, 0x90, 0x4d, 0xa1, 0x55, 0x6c, 0x23, 0xdf, 0x47,
0xae, 0xa7, 0x6a, 0xd6, 0x28, 0xf3, 0x42, 0xc7, 0xf4, 0xe2, 0x97, 0x1e, 0x46, 0x57, 0x71, 0x83,
0x22, 0xcb, 0x96, 0x25, 0xef, 0xc2, 0xa9, 0x11, 0x51, 0x31, 0x06, 0xe7, 0xeb, 0x8c, 0x73, 0x7e,
0x28, 0x32, 0x30, 0x6d, 0x03, 0xb8, 0x3c, 0x58, 0xcb, 0x31, 0x38, 0xff, 0x90, 0x71, 0x4a, 0x0c,
0xcb, 0x97, 0x14, 0x33, 0x5e, 0x83, 0xd9, 0xdb, 0xc8, 0xdd, 0x73, 0x3c, 0x76, 0x35, 0x32, 0x06,
0xdd, 0x1b, 0x8c, 0x6e, 0x86, 0x01, 0xc9, 0x5d, 0x09, 0xe6, 0x7a, 0x05, 0x32, 0x2d, 0x4d, 0x47,
0x63, 0x50, 0x7c, 0x99, 0x51, 0x4c, 0x61, 0x7d, 0x0c, 0x2d, 0x43, 0xbe, 0xed, 0xb0, 0xb2, 0x14,
0x0f, 0x7f, 0x93, 0xc1, 0x73, 0x1c, 0xc3, 0x28, 0xba, 0x4e, 0xb7, 0x67, 0xe1, 0x9a, 0x15, 0x4f,
0xf1, 0x47, 0x9c, 0x82, 0x63, 0x18, 0xc5, 0x09, 0xdc, 0xfa, 0xc7, 0x9c, 0xc2, 0x0b, 0xf9, 0xf3,
0x0a, 0xe4, 0x1c, 0xdb, 0x3a, 0x70, 0xec, 0x71, 0x8c, 0xf8, 0x13, 0xc6, 0x00, 0x0c, 0x82, 0x09,
0x2e, 0x43, 0x76, 0xdc, 0x85, 0xf8, 0xd3, 0x87, 0x7c, 0x7b, 0xf0, 0x15, 0xd8, 0x80, 0x19, 0x9e,
0xa0, 0x4c, 0xc7, 0x1e, 0x83, 0xe2, 0xcf, 0x18, 0x45, 0x21, 0x04, 0x63, 0xaf, 0xe1, 0x23, 0xcf,
0x6f, 0xa3, 0x71, 0x48, 0xde, 0xe2, 0xaf, 0xc1, 0x20, 0xcc, 0x95, 0x7b, 0xc8, 0xd6, 0xf7, 0xc7,
0x63, 0xf8, 0x2a, 0x77, 0x25, 0xc7, 0x60, 0x8a, 0x0a, 0x4c, 0x77, 0x34, 0xd7, 0xdb, 0xd7, 0xac,
0xb1, 0x96, 0xe3, 0xcf, 0x19, 0x47, 0x3e, 0x00, 0x31, 0x8f, 0xf4, 0xec, 0x93, 0xd0, 0x7c, 0x8d,
0x7b, 0x24, 0x04, 0x63, 0x5b, 0xcf, 0xf3, 0xc9, 0x05, 0xd4, 0x49, 0xd8, 0xbe, 0xce, 0xb7, 0x1e,
0xc5, 0x6e, 0x85, 0x19, 0x2f, 0x43, 0xd6, 0x33, 0xef, 0x8d, 0x45, 0xf3, 0x17, 0x7c, 0xa5, 0x09,
0x00, 0x83, 0x6f, 0xc0, 0xe9, 0x91, 0x65, 0x62, 0x0c, 0xb2, 0x6f, 0x30, 0xb2, 0x85, 0x11, 0xa5,
0x82, 0xa5, 0x84, 0x93, 0x52, 0xfe, 0x25, 0x4f, 0x09, 0x68, 0x80, 0xab, 0x81, 0x0f, 0x0a, 0x9e,
0xd6, 0x3a, 0x99, 0xd7, 0xfe, 0x8a, 0x7b, 0x8d, 0x62, 0x23, 0x5e, 0xdb, 0x81, 0x05, 0xc6, 0x78,
0xb2, 0x75, 0xfd, 0x26, 0x4f, 0xac, 0x14, 0xbd, 0x1b, 0x5d, 0xdd, 0x5f, 0x84, 0xc5, 0xc0, 0x9d,
0xbc, 0x23, 0xf5, 0xd4, 0x8e, 0xd6, 0x1d, 0x83, 0xf9, 0x5b, 0x8c, 0x99, 0x67, 0xfc, 0xa0, 0xa5,
0xf5, 0xb6, 0xb4, 0x2e, 0x26, 0xbf, 0x0e, 0x45, 0x4e, 0xde, 0xb3, 0x5d, 0xa4, 0x3b, 0x6d, 0xdb,
0xbc, 0x87, 0x8c, 0x31, 0xa8, 0xff, 0x7a, 0x60, 0xa9, 0x76, 0x43, 0x70, 0xcc, 0x5c, 0x03, 0x31,
0xe8, 0x55, 0x54, 0xb3, 0xd3, 0x75, 0x5c, 0x3f, 0x86, 0xf1, 0x6f, 0xf8, 0x4a, 0x05, 0xb8, 0x1a,
0x81, 0xc9, 0x55, 0x28, 0x90, 0xe1, 0xb8, 0x21, 0xf9, 0xb7, 0x8c, 0x68, 0xba, 0x8f, 0x62, 0x89,
0x43, 0x77, 0x3a, 0x5d, 0xcd, 0x1d, 0x27, 0xff, 0xfd, 0x1d, 0x4f, 0x1c, 0x0c, 0xc2, 0x12, 0x87,
0x7f, 0xd0, 0x45, 0xb8, 0xda, 0x8f, 0xc1, 0xf0, 0x6d, 0x9e, 0x38, 0x38, 0x86, 0x51, 0xf0, 0x86,
0x61, 0x0c, 0x8a, 0xbf, 0xe7, 0x14, 0x1c, 0x83, 0x29, 0x3e, 0xd3, 0x2f, 0xb4, 0x2e, 0x6a, 0x9b,
0x9e, 0xef, 0xd2, 0x3e, 0xf8, 0x78, 0xaa, 0xef, 0x3c, 0x8c, 0x36, 0x61, 0x4a, 0x08, 0x2a, 0x5f,
0x83, 0x99, 0x81, 0x16, 0x43, 0x8a, 0xfb, 0xcd, 0x42, 0xf1, 0x97, 0x1e, 0xb1, 0x64, 0x14, 0xed,
0x30, 0xe4, 0x4d, 0xbc, 0xee, 0xd1, 0x3e, 0x20, 0x9e, 0xec, 0xb5, 0x47, 0xc1, 0xd2, 0x47, 0xda,
0x00, 0xf9, 0x2a, 0x4c, 0x47, 0x7a, 0x80, 0x78, 0xaa, 0x5f, 0x66, 0x54, 0xf9, 0x70, 0x0b, 0x20,
0x5f, 0x80, 0x14, 0xae, 0xe7, 0xf1, 0xf0, 0x5f, 0x61, 0x70, 0xa2, 0x2e, 0x7f, 0x12, 0x32, 0xbc,
0x8e, 0xc7, 0x43, 0x7f, 0x95, 0x41, 0x03, 0x08, 0x86, 0xf3, 0x1a, 0x1e, 0x0f, 0xff, 0x35, 0x0e,
0xe7, 0x10, 0x0c, 0x1f, 0xdf, 0x85, 0xdf, 0xfd, 0xf5, 0x14, 0xcb, 0xc3, 0xdc, 0x77, 0x97, 0x61,
0x8a, 0x15, 0xef, 0x78, 0xf4, 0x17, 0xd8, 0xc3, 0x39, 0x42, 0x7e, 0x19, 0xd2, 0x63, 0x3a, 0xfc,
0x37, 0x18, 0x94, 0xea, 0xcb, 0x15, 0xc8, 0x85, 0x0a, 0x76, 0x3c, 0xfc, 0x37, 0x19, 0x3c, 0x8c,
0xc2, 0xa6, 0xb3, 0x82, 0x1d, 0x4f, 0xf0, 0x5b, 0xdc, 0x74, 0x86, 0xc0, 0x6e, 0xe3, 0xb5, 0x3a,
0x1e, 0xfd, 0xdb, 0xdc, 0xeb, 0x1c, 0x22, 0x5f, 0x81, 0x6c, 0x90, 0x7f, 0xe3, 0xf1, 0xbf, 0xc3,
0xf0, 0x7d, 0x0c, 0xf6, 0x40, 0x28, 0xff, 0xc7, 0x53, 0xfc, 0x2e, 0xf7, 0x40, 0x08, 0x85, 0xb7,
0xd1, 0x60, 0x4d, 0x8f, 0x67, 0xfa, 0x3d, 0xbe, 0x8d, 0x06, 0x4a, 0x3a, 0x5e, 0x4d, 0x92, 0x06,
0xe3, 0x29, 0x7e, 0x9f, 0xaf, 0x26, 0xd1, 0xc7, 0x66, 0x0c, 0x16, 0xc9, 0x78, 0x8e, 0x3f, 0xe0,
0x66, 0x0c, 0xd4, 0x48, 0xb9, 0x01, 0xd2, 0x70, 0x81, 0x8c, 0xe7, 0xfb, 0x22, 0xe3, 0x9b, 0x1d,
0xaa, 0x8f, 0xf2, 0xab, 0xb0, 0x30, 0xba, 0x38, 0xc6, 0xb3, 0x7e, 0xe9, 0xd1, 0xc0, 0x71, 0x26,
0x5c, 0x1b, 0xe5, 0x9d, 0x7e, 0x96, 0x0d, 0x17, 0xc6, 0x78, 0xda, 0xd7, 0x1f, 0x45, 0x13, 0x6d,
0xb8, 0x2e, 0xca, 0x65, 0x80, 0x7e, 0x4d, 0x8a, 0xe7, 0x7a, 0x83, 0x71, 0x85, 0x40, 0x78, 0x6b,
0xb0, 0x92, 0x14, 0x8f, 0xff, 0x32, 0xdf, 0x1a, 0x0c, 0x81, 0xb7, 0x06, 0xaf, 0x46, 0xf1, 0xe8,
0x37, 0xf9, 0xd6, 0xe0, 0x10, 0xf9, 0x32, 0x64, 0xec, 0x9e, 0x65, 0xe1, 0xd8, 0x92, 0x8e, 0xff,
0x19, 0x51, 0xf1, 0xdf, 0x1f, 0x33, 0x30, 0x07, 0xc8, 0x17, 0x20, 0x8d, 0x3a, 0x7b, 0xc8, 0x88,
0x43, 0xfe, 0xc7, 0x63, 0x9e, 0x4f, 0xb0, 0xb6, 0x7c, 0x05, 0x80, 0x1e, 0xa6, 0xc9, 0x57, 0xa2,
0x18, 0xec, 0x7f, 0x3e, 0x66, 0xbf, 0x50, 0xe8, 0x43, 0xfa, 0x04, 0xf4, 0xf7, 0x0e, 0xc7, 0x13,
0x3c, 0x8c, 0x12, 0x90, 0x03, 0xf8, 0x2b, 0x30, 0x75, 0xd3, 0x73, 0x6c, 0x5f, 0x6b, 0xc7, 0xa1,
0xff, 0x8b, 0xa1, 0xb9, 0x3e, 0x76, 0x58, 0xc7, 0x71, 0x91, 0xaf, 0xb5, 0xbd, 0x38, 0xec, 0x7f,
0x33, 0x6c, 0x00, 0xc0, 0x60, 0x5d, 0xf3, 0xfc, 0x71, 0xde, 0xfb, 0x7f, 0x38, 0x98, 0x03, 0xb0,
0xd1, 0xf8, 0xff, 0x5b, 0xe8, 0x20, 0x0e, 0xfb, 0x3e, 0x37, 0x9a, 0xe9, 0xcb, 0x9f, 0x84, 0x2c,
0xfe, 0x97, 0xfe, 0x6a, 0x27, 0x06, 0xfc, 0xbf, 0x0c, 0xdc, 0x47, 0xe0, 0x27, 0x7b, 0xbe, 0xe1,
0x9b, 0xf1, 0xce, 0xfe, 0x3f, 0xb6, 0xd2, 0x5c, 0x5f, 0x2e, 0x43, 0xce, 0xf3, 0x0d, 0xa3, 0xc7,
0x3a, 0x9a, 0x18, 0xf8, 0x8f, 0x1e, 0x07, 0x87, 0xdc, 0x00, 0xb3, 0x76, 0x76, 0xf4, 0x65, 0x1d,
0x6c, 0x38, 0x1b, 0x0e, 0xbd, 0xa6, 0x83, 0x6f, 0x08, 0x50, 0x68, 0x99, 0x16, 0x5a, 0x35, 0x1c,
0x9f, 0x5d, 0xab, 0xe5, 0xf0, 0xd8, 0x70, 0x7c, 0xbc, 0xde, 0x8b, 0x27, 0xbb, 0x92, 0x5b, 0x9e,
0x05, 0x61, 0x4b, 0xca, 0x83, 0xa0, 0xb1, 0x5f, 0x93, 0x08, 0xda, 0xda, 0xe6, 0xdb, 0x0f, 0x4a,
0x13, 0xdf, 0x7f, 0x50, 0x9a, 0xf8, 0x97, 0x07, 0xa5, 0x89, 0x77, 0x1e, 0x94, 0x84, 0xf7, 0x1e,
0x94, 0x84, 0xf7, 0x1f, 0x94, 0x84, 0x1f, 0x3f, 0x28, 0x09, 0xf7, 0x0f, 0x4b, 0xc2, 0x57, 0x0f,
0x4b, 0xc2, 0x37, 0x0f, 0x4b, 0xc2, 0x77, 0x0e, 0x4b, 0xc2, 0x77, 0x0f, 0x4b, 0xc2, 0xdb, 0x87,
0xa5, 0x89, 0xef, 0x1f, 0x96, 0x26, 0xde, 0x39, 0x2c, 0x09, 0xef, 0x1d, 0x96, 0x26, 0xde, 0x3f,
0x2c, 0x09, 0x3f, 0x3e, 0x2c, 0x4d, 0xdc, 0xff, 0x61, 0x69, 0xe2, 0x27, 0x01, 0x00, 0x00, 0xff,
0xff, 0x7c, 0xbe, 0x1b, 0xf8, 0x0c, 0x2f, 0x00, 0x00,
}
r := bytes.NewReader(gzipped)
gzipr, err := compress_gzip.NewReader(r)
if err != nil {
panic(err)
}
ungzipped, err := io_ioutil.ReadAll(gzipr)
if err != nil {
panic(err)
}
if err := github_com_gogo_protobuf_proto.Unmarshal(ungzipped, d); err != nil {
panic(err)
}
return d
}
func (this *M) VerboseEqual(that interface{}) error {
if that == nil {
if this == nil {
return nil
}
return fmt.Errorf("that == nil && this != nil")
}
that1, ok := that.(*M)
if !ok {
that2, ok := that.(M)
if ok {
that1 = &that2
} else {
return fmt.Errorf("that is not of type *M")
}
}
if that1 == nil {
if this == nil {
return nil
}
return fmt.Errorf("that is type *M but is nil && this != nil")
} else if this == nil {
return fmt.Errorf("that is type *M but is not nil && this == nil")
}
if this.A != nil && that1.A != nil {
if *this.A != *that1.A {
return fmt.Errorf("A this(%v) Not Equal that(%v)", *this.A, *that1.A)
}
} else if this.A != nil {
return fmt.Errorf("this.A == nil && that.A != nil")
} else if that1.A != nil {
return fmt.Errorf("A this(%v) Not Equal that(%v)", this.A, that1.A)
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that1.XXX_unrecognized)
}
return nil
}
func (this *M) Equal(that interface{}) bool {
if that == nil {
if this == nil {
return true
}
return false
}
that1, ok := that.(*M)
if !ok {
that2, ok := that.(M)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
if this == nil {
return true
}
return false
} else if this == nil {
return false
}
if this.A != nil && that1.A != nil {
if *this.A != *that1.A {
return false
}
} else if this.A != nil {
return false
} else if that1.A != nil {
return false
}
if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) {
return false
}
return true
}
type MFace interface {
Proto() github_com_gogo_protobuf_proto.Message
GetA() *string
}
func (this *M) Proto() github_com_gogo_protobuf_proto.Message {
return this
}
func (this *M) TestProto() github_com_gogo_protobuf_proto.Message {
return NewMFromFace(this)
}
func (this *M) GetA() *string {
return this.A
}
func NewMFromFace(that MFace) *M {
this := &M{}
this.A = that.GetA()
return this
}
func (this *M) GoString() string {
if this == nil {
return "nil"
}
s := make([]string, 0, 5)
s = append(s, "&filedotname.M{")
if this.A != nil {
s = append(s, "A: "+valueToGoStringFileDot(this.A, "string")+",\n")
}
if this.XXX_unrecognized != nil {
s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n")
}
s = append(s, "}")
return strings.Join(s, "")
}
func valueToGoStringFileDot(v interface{}, typ string) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv)
}
func NewPopulatedM(r randyFileDot, easy bool) *M {
this := &M{}
if r.Intn(10) != 0 {
v1 := string(randStringFileDot(r))
this.A = &v1
}
if !easy && r.Intn(10) != 0 {
this.XXX_unrecognized = randUnrecognizedFileDot(r, 2)
}
return this
}
type randyFileDot interface {
Float32() float32
Float64() float64
Int63() int64
Int31() int32
Uint32() uint32
Intn(n int) int
}
func randUTF8RuneFileDot(r randyFileDot) rune {
ru := r.Intn(62)
if ru < 10 {
return rune(ru + 48)
} else if ru < 36 {
return rune(ru + 55)
}
return rune(ru + 61)
}
func randStringFileDot(r randyFileDot) string {
v2 := r.Intn(100)
tmps := make([]rune, v2)
for i := 0; i < v2; i++ {
tmps[i] = randUTF8RuneFileDot(r)
}
return string(tmps)
}
func randUnrecognizedFileDot(r randyFileDot, maxFieldNumber int) (dAtA []byte) {
l := r.Intn(5)
for i := 0; i < l; i++ {
wire := r.Intn(4)
if wire == 3 {
wire = 5
}
fieldNumber := maxFieldNumber + r.Intn(100)
dAtA = randFieldFileDot(dAtA, r, fieldNumber, wire)
}
return dAtA
}
func randFieldFileDot(dAtA []byte, r randyFileDot, fieldNumber int, wire int) []byte {
key := uint32(fieldNumber)<<3 | uint32(wire)
switch wire {
case 0:
dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key))
v3 := r.Int63()
if r.Intn(2) == 0 {
v3 *= -1
}
dAtA = encodeVarintPopulateFileDot(dAtA, uint64(v3))
case 1:
dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
case 2:
dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key))
ll := r.Intn(100)
dAtA = encodeVarintPopulateFileDot(dAtA, uint64(ll))
for j := 0; j < ll; j++ {
dAtA = append(dAtA, byte(r.Intn(256)))
}
default:
dAtA = encodeVarintPopulateFileDot(dAtA, uint64(key))
dAtA = append(dAtA, byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)))
}
return dAtA
}
func encodeVarintPopulateFileDot(dAtA []byte, v uint64) []byte {
for v >= 1<<7 {
dAtA = append(dAtA, uint8(uint64(v)&0x7f|0x80))
v >>= 7
}
dAtA = append(dAtA, uint8(v))
return dAtA
}
func (m *M) Size() (n int) {
var l int
_ = l
if m.A != nil {
l = len(*m.A)
n += 1 + l + sovFileDot(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovFileDot(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozFileDot(x uint64) (n int) {
return sovFileDot(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *M) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{`&M{`,
`A:` + valueToStringFileDot(this.A) + `,`,
`XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`,
`}`,
}, "")
return s
}
func valueToStringFileDot(v interface{}) string {
rv := reflect.ValueOf(v)
if rv.IsNil() {
return "nil"
}
pv := reflect.Indirect(rv).Interface()
return fmt.Sprintf("*%v", pv)
}
func init() { proto.RegisterFile("file.dot.proto", fileDescriptorFileDot) }
var fileDescriptorFileDot = []byte{
// 179 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x24, 0xcb, 0xaf, 0x6e, 0xc2, 0x50,
0x1c, 0xc5, 0xf1, 0xdf, 0x91, 0xeb, 0x96, 0x25, 0xab, 0x5a, 0x26, 0x4e, 0x96, 0xa9, 0x99, 0xb5,
0xef, 0x30, 0x0d, 0x86, 0x37, 0x68, 0xe9, 0x1f, 0x9a, 0x50, 0x2e, 0x21, 0xb7, 0xbe, 0x8f, 0x83,
0x44, 0x22, 0x91, 0x95, 0x95, 0xc8, 0xde, 0x1f, 0xa6, 0xb2, 0xb2, 0x92, 0x70, 0x71, 0xe7, 0x93,
0x9c, 0x6f, 0xf0, 0x5e, 0x54, 0xdb, 0x3c, 0xca, 0x8c, 0x8d, 0xf6, 0x07, 0x63, 0x4d, 0xf8, 0xfa,
0x70, 0x66, 0xec, 0x2e, 0xa9, 0xf3, 0xaf, 0xbf, 0xb2, 0xb2, 0x9b, 0x26, 0x8d, 0xd6, 0xa6, 0x8e,
0x4b, 0x53, 0x9a, 0xd8, 0x7f, 0xd2, 0xa6, 0xf0, 0xf2, 0xf0, 0xeb, 0xd9, 0xfe, 0x7c, 0x04, 0x58,
0x86, 0x6f, 0x01, 0x92, 0x4f, 0x7c, 0xe3, 0xf7, 0x65, 0x85, 0xe4, 0x7f, 0xd1, 0x39, 0x4a, 0xef,
0x28, 0x57, 0x47, 0x19, 0x1c, 0x31, 0x3a, 0x62, 0x72, 0xc4, 0xec, 0x88, 0x56, 0x89, 0xa3, 0x12,
0x27, 0x25, 0xce, 0x4a, 0x5c, 0x94, 0xe8, 0x94, 0xd2, 0x2b, 0x65, 0x50, 0x62, 0x54, 0xca, 0xa4,
0xc4, 0xac, 0x94, 0xf6, 0x46, 0xb9, 0x07, 0x00, 0x00, 0xff, 0xff, 0x3f, 0x59, 0x32, 0x8a, 0xad,
0x00, 0x00, 0x00,
}
| tangfeixiong/go-for-docker | vendor/github.com/gogo/protobuf/test/filedotname/file.dot.pb.go | GO | apache-2.0 | 31,616 |
/*
* Copyright 2019 Red Hat, Inc. and/or 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 org.jbpm.workbench.ht.backend.server;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import org.dashbuilder.dataset.impl.SQLDataSetDefBuilderImpl;
import org.jbpm.workbench.ks.integration.AbstractDataSetDefsBootstrap;
import org.jbpm.workbench.ks.integration.event.QueryDefinitionLoaded;
import static org.jbpm.workbench.ht.model.TaskDataSetConstants.*;
@ApplicationScoped
public class DataSetDefsBootstrap extends AbstractDataSetDefsBootstrap {
public void registerDataSetDefinitions(@Observes QueryDefinitionLoaded event) {
if (event.getDefinition().getName().equals(HUMAN_TASKS_DATASET)) {
registerDataSetDefinition(event.getDefinition(),
builder ->
addBuilderCommonColumns(builder)
);
} else if (event.getDefinition().getName().equals(HUMAN_TASKS_WITH_USER_DATASET)) {
registerDataSetDefinition(event.getDefinition(),
builder ->
addBuilderCommonColumns(builder)
.label(COLUMN_ORGANIZATIONAL_ENTITY)
.label(COLUMN_EXCLUDED_OWNER)
);
} else if (event.getDefinition().getName().equals(HUMAN_TASKS_WITH_ADMIN_DATASET)) {
registerDataSetDefinition(event.getDefinition(),
builder ->
addBuilderCommonColumns(builder)
.label(COLUMN_ORGANIZATIONAL_ENTITY)
.number(COLUMN_ERROR_COUNT)
);
} else if (event.getDefinition().getName().equals(HUMAN_TASKS_WITH_VARIABLES_DATASET)) {
registerDataSetDefinition(event.getDefinition(),
builder ->
builder.number(COLUMN_TASK_VARIABLE_TASK_ID)
.label(COLUMN_TASK_VARIABLE_NAME)
.label(COLUMN_TASK_VARIABLE_VALUE)
);
}
}
private SQLDataSetDefBuilderImpl addBuilderCommonColumns(SQLDataSetDefBuilderImpl builder) {
return builder
.date(COLUMN_ACTIVATION_TIME)
.label(COLUMN_ACTUAL_OWNER)
.label(COLUMN_CREATED_BY)
.date(COLUMN_CREATED_ON)
.label(COLUMN_DEPLOYMENT_ID)
.text(COLUMN_DESCRIPTION)
.date(COLUMN_DUE_DATE)
.label(COLUMN_NAME)
.number(COLUMN_PARENT_ID)
.number(COLUMN_PRIORITY)
.label(COLUMN_PROCESS_ID)
.number(COLUMN_PROCESS_INSTANCE_ID)
.number(COLUMN_PROCESS_SESSION_ID)
.label(COLUMN_STATUS)
.number(COLUMN_TASK_ID)
.number(COLUMN_WORK_ITEM_ID)
.date(COLUMN_LAST_MODIFICATION_DATE)
.label(COLUMN_PROCESS_INSTANCE_CORRELATION_KEY)
.text(COLUMN_PROCESS_INSTANCE_DESCRIPTION)
.date(COLUMN_SLA_DUE_DATE)
.number(COLUMN_SLA_COMPLIANCE);
}
}
| droolsjbpm/jbpm-console-ng | jbpm-wb-human-tasks/jbpm-wb-human-tasks-backend/src/main/java/org/jbpm/workbench/ht/backend/server/DataSetDefsBootstrap.java | Java | apache-2.0 | 4,017 |
<?php
/*
* Copyright 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.
*/
namespace Google\Service\Document;
class GoogleCloudDocumentaiV1SetDefaultProcessorVersionResponse extends \Google\Model
{
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDocumentaiV1SetDefaultProcessorVersionResponse::class, 'Google_Service_Document_GoogleCloudDocumentaiV1SetDefaultProcessorVersionResponse');
| googleapis/google-api-php-client-services | src/Document/GoogleCloudDocumentaiV1SetDefaultProcessorVersionResponse.php | PHP | apache-2.0 | 971 |
// Copyright 2017 PingCAP, 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 owner
import (
"fmt"
"math"
"os"
"strconv"
"sync/atomic"
"time"
"unsafe"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/clientv3/concurrency"
"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
"github.com/coreos/etcd/mvcc/mvccpb"
"github.com/pingcap/errors"
"github.com/pingcap/parser/terror"
"github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/util"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
const (
newSessionRetryInterval = 200 * time.Millisecond
logIntervalCnt = int(3 * time.Second / newSessionRetryInterval)
)
// Manager is used to campaign the owner and manage the owner information.
type Manager interface {
// ID returns the ID of the manager.
ID() string
// IsOwner returns whether the ownerManager is the owner.
IsOwner() bool
// RetireOwner make the manager to be a not owner. It's exported for testing.
RetireOwner()
// GetOwnerID gets the owner ID.
GetOwnerID(ctx context.Context) (string, error)
// CampaignOwner campaigns the owner.
CampaignOwner(ctx context.Context) error
// ResignOwner lets the owner start a new election.
ResignOwner(ctx context.Context) error
// Cancel cancels this etcd ownerManager campaign.
Cancel()
}
const (
// NewSessionDefaultRetryCnt is the default retry times when create new session.
NewSessionDefaultRetryCnt = 3
// NewSessionRetryUnlimited is the unlimited retry times when create new session.
NewSessionRetryUnlimited = math.MaxInt64
keyOpDefaultTimeout = 5 * time.Second
)
// DDLOwnerChecker is used to check whether tidb is owner.
type DDLOwnerChecker interface {
// IsOwner returns whether the ownerManager is the owner.
IsOwner() bool
}
// ownerManager represents the structure which is used for electing owner.
type ownerManager struct {
id string // id is the ID of the manager.
key string
prompt string
logPrefix string
etcdCli *clientv3.Client
cancel context.CancelFunc
elec unsafe.Pointer
}
// NewOwnerManager creates a new Manager.
func NewOwnerManager(etcdCli *clientv3.Client, prompt, id, key string, cancel context.CancelFunc) Manager {
return &ownerManager{
etcdCli: etcdCli,
id: id,
key: key,
prompt: prompt,
cancel: cancel,
logPrefix: fmt.Sprintf("[%s] %s ownerManager %s", prompt, key, id),
}
}
// ID implements Manager.ID interface.
func (m *ownerManager) ID() string {
return m.id
}
// IsOwner implements Manager.IsOwner interface.
func (m *ownerManager) IsOwner() bool {
return atomic.LoadPointer(&m.elec) != unsafe.Pointer(nil)
}
// Cancel implements Manager.Cancel interface.
func (m *ownerManager) Cancel() {
m.cancel()
}
// ManagerSessionTTL is the etcd session's TTL in seconds. It's exported for testing.
var ManagerSessionTTL = 60
// setManagerSessionTTL sets the ManagerSessionTTL value, it's used for testing.
func setManagerSessionTTL() error {
ttlStr := os.Getenv("tidb_manager_ttl")
if len(ttlStr) == 0 {
return nil
}
ttl, err := strconv.Atoi(ttlStr)
if err != nil {
return errors.Trace(err)
}
ManagerSessionTTL = ttl
return nil
}
// NewSession creates a new etcd session.
func NewSession(ctx context.Context, logPrefix string, etcdCli *clientv3.Client, retryCnt, ttl int) (*concurrency.Session, error) {
var err error
var etcdSession *concurrency.Session
failedCnt := 0
for i := 0; i < retryCnt; i++ {
if err = contextDone(ctx, err); err != nil {
return etcdSession, errors.Trace(err)
}
// gofail: var closeClient bool
// if closeClient {
// etcdCli.Close()
// }
// gofail: var closeGrpc bool
// if closeGrpc {
// etcdCli.ActiveConnection().Close()
// }
startTime := time.Now()
etcdSession, err = concurrency.NewSession(etcdCli,
concurrency.WithTTL(ttl), concurrency.WithContext(ctx))
metrics.NewSessionHistogram.WithLabelValues(logPrefix, metrics.RetLabel(err)).Observe(time.Since(startTime).Seconds())
if err == nil {
break
}
if failedCnt%logIntervalCnt == 0 {
log.Warnf("%s failed to new session to etcd, err %v", logPrefix, err)
}
time.Sleep(newSessionRetryInterval)
failedCnt++
}
return etcdSession, errors.Trace(err)
}
// CampaignOwner implements Manager.CampaignOwner interface.
func (m *ownerManager) CampaignOwner(ctx context.Context) error {
logPrefix := fmt.Sprintf("[%s] %s", m.prompt, m.key)
session, err := NewSession(ctx, logPrefix, m.etcdCli, NewSessionDefaultRetryCnt, ManagerSessionTTL)
if err != nil {
return errors.Trace(err)
}
cancelCtx, _ := context.WithCancel(ctx)
go m.campaignLoop(cancelCtx, session)
return nil
}
// ResignOwner lets the owner start a new election.
func (m *ownerManager) ResignOwner(ctx context.Context) error {
elec := (*concurrency.Election)(atomic.LoadPointer(&m.elec))
if elec == nil {
return errors.Errorf("This node is not a ddl owner, can't be resigned.")
}
childCtx, cancel := context.WithTimeout(ctx, keyOpDefaultTimeout)
err := elec.Resign(childCtx)
cancel()
if err != nil {
return errors.Trace(err)
}
log.Warnf("%s Resign ddl owner success!", m.logPrefix)
return nil
}
func (m *ownerManager) toBeOwner(elec *concurrency.Election) {
atomic.StorePointer(&m.elec, unsafe.Pointer(elec))
}
// RetireOwner make the manager to be a not owner.
func (m *ownerManager) RetireOwner() {
atomic.StorePointer(&m.elec, nil)
}
func (m *ownerManager) campaignLoop(ctx context.Context, etcdSession *concurrency.Session) {
defer func() {
if r := recover(); r != nil {
buf := util.GetStack()
log.Errorf("[%s] recover panic:%v, %s", m.prompt, r, buf)
metrics.PanicCounter.WithLabelValues(metrics.LabelDDLOwner).Inc()
}
}()
logPrefix := m.logPrefix
var err error
for {
if err != nil {
metrics.CampaignOwnerCounter.WithLabelValues(m.prompt, err.Error()).Inc()
}
select {
case <-etcdSession.Done():
log.Infof("%s etcd session is done, creates a new one", logPrefix)
leaseID := etcdSession.Lease()
etcdSession, err = NewSession(ctx, logPrefix, m.etcdCli, NewSessionRetryUnlimited, ManagerSessionTTL)
if err != nil {
log.Infof("%s break campaign loop, NewSession err %v", logPrefix, err)
m.revokeSession(logPrefix, leaseID)
return
}
case <-ctx.Done():
m.revokeSession(logPrefix, etcdSession.Lease())
return
default:
}
// If the etcd server turns clocks forward,the following case may occur.
// The etcd server deletes this session's lease ID, but etcd session doesn't find it.
// In this time if we do the campaign operation, the etcd server will return ErrLeaseNotFound.
if terror.ErrorEqual(err, rpctypes.ErrLeaseNotFound) {
if etcdSession != nil {
err = etcdSession.Close()
log.Infof("%s etcd session encounters the error of lease not found, closes it err %s", logPrefix, err)
}
continue
}
elec := concurrency.NewElection(etcdSession, m.key)
err = elec.Campaign(ctx, m.id)
if err != nil {
log.Infof("%s failed to campaign, err %v", logPrefix, err)
continue
}
ownerKey, err := GetOwnerInfo(ctx, elec, logPrefix, m.id)
if err != nil {
continue
}
m.toBeOwner(elec)
m.watchOwner(ctx, etcdSession, ownerKey)
m.RetireOwner()
metrics.CampaignOwnerCounter.WithLabelValues(m.prompt, metrics.NoLongerOwner).Inc()
log.Warnf("%s isn't the owner", logPrefix)
}
}
func (m *ownerManager) revokeSession(logPrefix string, leaseID clientv3.LeaseID) {
// Revoke the session lease.
// If revoke takes longer than the ttl, lease is expired anyway.
cancelCtx, cancel := context.WithTimeout(context.Background(),
time.Duration(ManagerSessionTTL)*time.Second)
_, err := m.etcdCli.Revoke(cancelCtx, leaseID)
cancel()
log.Infof("%s break campaign loop, revoke err %v", logPrefix, err)
}
// GetOwnerID implements Manager.GetOwnerID interface.
func (m *ownerManager) GetOwnerID(ctx context.Context) (string, error) {
resp, err := m.etcdCli.Get(ctx, m.key, clientv3.WithFirstCreate()...)
if err != nil {
return "", errors.Trace(err)
}
if len(resp.Kvs) == 0 {
return "", concurrency.ErrElectionNoLeader
}
return string(resp.Kvs[0].Value), nil
}
// GetOwnerInfo gets the owner information.
func GetOwnerInfo(ctx context.Context, elec *concurrency.Election, logPrefix, id string) (string, error) {
resp, err := elec.Leader(ctx)
if err != nil {
// If no leader elected currently, it returns ErrElectionNoLeader.
log.Infof("%s failed to get leader, err %v", logPrefix, err)
return "", errors.Trace(err)
}
ownerID := string(resp.Kvs[0].Value)
log.Infof("%s, owner is %v", logPrefix, ownerID)
if ownerID != id {
log.Warnf("%s isn't the owner", logPrefix)
return "", errors.New("ownerInfoNotMatch")
}
return string(resp.Kvs[0].Key), nil
}
func (m *ownerManager) watchOwner(ctx context.Context, etcdSession *concurrency.Session, key string) {
logPrefix := fmt.Sprintf("[%s] ownerManager %s watch owner key %v", m.prompt, m.id, key)
log.Debugf("%s", logPrefix)
watchCh := m.etcdCli.Watch(ctx, key)
for {
select {
case resp, ok := <-watchCh:
if !ok {
metrics.WatchOwnerCounter.WithLabelValues(m.prompt, metrics.WatcherClosed).Inc()
log.Infof("%s watcher is closed, no owner", logPrefix)
return
}
if resp.Canceled {
metrics.WatchOwnerCounter.WithLabelValues(m.prompt, metrics.Cancelled).Inc()
log.Infof("%s canceled, no owner", logPrefix)
return
}
for _, ev := range resp.Events {
if ev.Type == mvccpb.DELETE {
metrics.WatchOwnerCounter.WithLabelValues(m.prompt, metrics.Deleted).Inc()
log.Infof("%s failed, owner is deleted", logPrefix)
return
}
}
case <-etcdSession.Done():
metrics.WatchOwnerCounter.WithLabelValues(m.prompt, metrics.SessionDone).Inc()
return
case <-ctx.Done():
metrics.WatchOwnerCounter.WithLabelValues(m.prompt, metrics.CtxDone).Inc()
return
}
}
}
func init() {
err := setManagerSessionTTL()
if err != nil {
log.Warnf("set manager session TTL failed %v", err)
}
}
func contextDone(ctx context.Context, err error) error {
select {
case <-ctx.Done():
return errors.Trace(ctx.Err())
default:
}
// Sometime the ctx isn't closed, but the etcd client is closed,
// we need to treat it as if context is done.
// TODO: Make sure ctx is closed with etcd client.
if terror.ErrorEqual(err, context.Canceled) ||
terror.ErrorEqual(err, context.DeadlineExceeded) ||
terror.ErrorEqual(err, grpc.ErrClientConnClosing) {
return errors.Trace(err)
}
return nil
}
| tiancaiamao/tidb | owner/manager.go | GO | apache-2.0 | 10,972 |
@echo off
rem Set Quartz to the base directory of the Quartz Distribution
@SET WD=%~d0%~p0
@SET QUARTZ=%WD%..\..
@rem setup the class path...
CALL "%WD%"..\bin\buildcp.bat
SET QUARTZ_CP=%TMP_CP%
rem !!!!!!! Please read important information. !!!!!!
rem If "java" is not in your path, please set the path
rem for Java 2 Runtime Environment in the path variable below
rem for example :
rem @SET PATH=D:\jdk1.6.0_18;%PATH%
rem
rem a configuration file for log4j logging
@SET LOG4J_PROPS="-Dlog4j.configuration=file:%WD%log4j.xml"
"java" -cp %QUARTZ_CP% %LOG4J_PROPS% org.quartz.examples.example4.JobStateExample
| suthat/signal | vendor/quartz-2.2.0/examples/example4/example4.bat | Batchfile | apache-2.0 | 637 |
<eq name="type" value="personal">
<div class="form-group">
<label for="expand_{$field_id}" class="col-sm-2 control-label" style="text-align: right;">
<eq name="required" value="1"><span style="color: #FF0047;vertical-align: middle;">* </span></eq>{$field_name}
</label>
<div class="col-sm-6">
<ul class="expandinfo-ul" id="expand_{$field_id}" style="-webkit-padding-start: 0px;">
<volist name="items" id="vl">
<li class="expandinfo-li">
<!--增加编辑扩展资料关联字段数据显示-->
<label><input class="checkbox-inline" style="margin: -2px 3px 0 0" type="checkbox" name="expand_{$field_id}[]" value="<eq name="vl.join" value="1">{$vl.id}<else/>{$vl.value}</eq>" <eq name="vl.selected" value="1">checked</eq>>{$vl.value}</label>
</li>
</volist>
</ul>
<div class="clearfix"></div>
<neq name="input_tips" value=""> <span class="help-block">{$input_tips}</span></neq>
</div>
</div>
<else/>
<dt class="expandinfo-dt">
{$field_name}:
</dt>
<dd class="expandinfo-dd">
<ul class="expandinfo-ul" style="-webkit-padding-start: 0;">
<volist name="checked" id="vl">
<li class="expandinfo-li">
{$vl}
</li>
</volist>
<if condition="($checked eq null)||($checked[0] eq '')">
无
</if>
</ul>
<div class="clearfix"></div>
</dd>
</eq>
<div class="clearfix"></div> | kylinlxl/kylin | Application/Ucenter/View/default/Widget/InputRender/checkbox.html | HTML | apache-2.0 | 1,650 |
/* Copyright 2007-2015 QReal Research Group
*
* 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 "qrtext/lua/ast/expression.h"
namespace qrtext {
namespace lua {
namespace ast {
/// Represents Lua string literal.
class QRTEXT_EXPORT String : public Expression
{
public:
/// Constructor.
/// @param string - value of a literal (without quotes).
String(const QString &string)
: mString(string)
{
}
/// Returns value of a string (without quotes).
const QString &string() const {
return mString;
}
private:
void accept(core::AstVisitorInterface &visitor) const override
{
static_cast<LuaAstVisitorInterface *>(&visitor)->visit(*this);
}
QString mString;
};
}
}
}
| tara-sova/qreal | qrtext/include/qrtext/lua/ast/string.h | C | apache-2.0 | 1,215 |
'use strict';
/* jshint -W110 */
var Utils = require('../../utils')
, util = require('util')
, DataTypes = require('../../data-types')
, AbstractQueryGenerator = require('../abstract/query-generator')
, primaryKeys = {}
, semver = require('semver')
, _ = require('lodash');
var QueryGenerator = {
options: {},
dialect: 'postgres',
setSearchPath: function(searchPath) {
var query = 'SET search_path to <%= searchPath%>;';
return Utils._.template(query)({searchPath: searchPath});
},
createSchema: function(schema) {
var query = 'CREATE SCHEMA <%= schema%>;';
return Utils._.template(query)({schema: schema});
},
dropSchema: function(schema) {
var query = 'DROP SCHEMA IF EXISTS <%= schema%> CASCADE;';
return Utils._.template(query)({schema: schema});
},
showSchemasQuery: function() {
return "SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema' AND schema_name != 'public' AND schema_name !~ E'^pg_';";
},
versionQuery: function() {
return 'SHOW SERVER_VERSION';
},
createTableQuery: function(tableName, attributes, options) {
var self = this;
options = Utils._.extend({
}, options || {});
primaryKeys[tableName] = [];
var databaseVersion = Utils._.get(self, 'sequelize.options.databaseVersion', 0);
//Postgres 9.0 does not support CREATE TABLE IF NOT EXISTS, 9.1 and above do
var query = 'CREATE TABLE ' +
( (databaseVersion === 0 || semver.gte(databaseVersion, '9.1.0')) ? 'IF NOT EXISTS ' : '') +
'<%= table %> (<%= attributes%>)<%= comments %>'
, comments = ''
, attrStr = []
, i;
if (options.comment && Utils._.isString(options.comment)) {
comments += '; COMMENT ON TABLE <%= table %> IS ' + this.escape(options.comment);
}
for (var attr in attributes) {
if ((i = attributes[attr].indexOf('COMMENT')) !== -1) {
// Move comment to a separate query
comments += '; ' + attributes[attr].substring(i);
attributes[attr] = attributes[attr].substring(0, i);
}
var dataType = this.pgDataTypeMapping(tableName, attr, attributes[attr]);
attrStr.push(this.quoteIdentifier(attr) + ' ' + dataType);
}
var values = {
table: this.quoteTable(tableName),
attributes: attrStr.join(', '),
comments: Utils._.template(comments)({ table: this.quoteTable(tableName)})
};
if (!!options.uniqueKeys) {
Utils._.each(options.uniqueKeys, function(columns) {
if (!columns.singleField) { // If it's a single field its handled in column def, not as an index
values.attributes += ', UNIQUE (' + columns.fields.map(function(f) { return self.quoteIdentifiers(f); }).join(', ') + ')';
}
});
}
var pks = primaryKeys[tableName].map(function(pk) {
return this.quoteIdentifier(pk);
}.bind(this)).join(',');
if (pks.length > 0) {
values.attributes += ', PRIMARY KEY (' + pks + ')';
}
return Utils._.template(query)(values).trim() + ';';
},
dropTableQuery: function(tableName, options) {
options = options || {};
var query = 'DROP TABLE IF EXISTS <%= table %><%= cascade %>;';
return Utils._.template(query)({
table: this.quoteTable(tableName),
cascade: options.cascade ? ' CASCADE' : ''
});
},
showTablesQuery: function() {
return "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type LIKE '%TABLE' AND table_name != 'spatial_ref_sys';";
},
describeTableQuery: function(tableName, schema) {
if (!schema) {
schema = 'public';
}
var query = 'SELECT tc.constraint_type as "Constraint", c.column_name as "Field", c.column_default as "Default", c.is_nullable as "Null", ' +
"CASE WHEN c.udt_name = 'hstore' " +
'THEN c.udt_name ELSE c.data_type END as "Type", (SELECT array_agg(e.enumlabel) ' +
'FROM pg_catalog.pg_type t JOIN pg_catalog.pg_enum e ON t.oid=e.enumtypid WHERE t.typname=c.udt_name) AS "special" ' +
'FROM information_schema.columns c ' +
'LEFT JOIN information_schema.key_column_usage cu ON c.table_name = cu.table_name AND cu.column_name = c.column_name ' +
'LEFT JOIN information_schema.table_constraints tc ON c.table_name = tc.table_name AND cu.column_name = c.column_name AND tc.constraint_type = \'PRIMARY KEY\' ' +
' WHERE c.table_name = <%= table %> AND c.table_schema = <%= schema %> ';
return Utils._.template(query)({
table: this.escape(tableName),
schema: this.escape(schema)
});
},
// A recursive parser for nested where conditions
parseConditionObject: function(_conditions, path) {
var self = this;
path = path || [];
return Utils._.reduce(_conditions, function (r, v, k) { // result, key, value
if (Utils._.isObject(v)) {
r = r.concat(self.parseConditionObject(v, path.concat(k))); // Recursively parse objects
} else {
r.push({ path: path.concat(k), value: v });
}
return r;
}, []);
},
handleSequelizeMethod: function (smth, tableName, factory, options, prepend) {
if (smth instanceof Utils.json) {
// Parse nested object
if (smth.conditions) {
var conditions = _.map(this.parseConditionObject(smth.conditions), function generateSql(condition) {
return util.format("%s#>>'{%s}' = '%s'",
_.first(condition.path),
_.tail(condition.path).join(','),
condition.value);
});
return conditions.join(' and ');
} else if (smth.path) {
var str;
// Allow specifying conditions using the postgres json syntax
if (_.some(['->', '->>', '#>'], _.partial(_.includes, smth.path))) {
str = smth.path;
} else {
// Also support json dot notation
var path = smth.path.split('.');
str = util.format("%s#>>'{%s}'",
_.first(path),
_.tail(path).join(','));
}
if (smth.value) {
str += util.format(' = %s', this.escape(smth.value));
}
return str;
}
} else {
return AbstractQueryGenerator.handleSequelizeMethod.call(this, smth, tableName, factory, options, prepend);
}
},
addColumnQuery: function(table, key, dataType) {
var query = 'ALTER TABLE <%= table %> ADD COLUMN <%= attribute %>;'
, dbDataType = this.attributeToSQL(dataType, {context: 'addColumn'})
, attribute;
if (dataType.type && dataType.type instanceof DataTypes.ENUM || dataType instanceof DataTypes.ENUM) {
query = this.pgEnum(table, key, dataType) + query;
}
attribute = Utils._.template('<%= key %> <%= definition %>')({
key: this.quoteIdentifier(key),
definition: this.pgDataTypeMapping(table, key, dbDataType)
});
return Utils._.template(query)({
table: this.quoteTable(table),
attribute: attribute
});
},
removeColumnQuery: function(tableName, attributeName) {
var query = 'ALTER TABLE <%= tableName %> DROP COLUMN <%= attributeName %>;';
return Utils._.template(query)({
tableName: this.quoteTable(tableName),
attributeName: this.quoteIdentifier(attributeName)
});
},
changeColumnQuery: function(tableName, attributes) {
var query = 'ALTER TABLE <%= tableName %> ALTER COLUMN <%= query %>;'
, sql = [];
for (var attributeName in attributes) {
var definition = this.pgDataTypeMapping(tableName, attributeName, attributes[attributeName]);
var attrSql = '';
if (definition.indexOf('NOT NULL') > 0) {
attrSql += Utils._.template(query)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' SET NOT NULL'
});
definition = definition.replace('NOT NULL', '').trim();
} else if (!definition.match(/REFERENCES/)) {
attrSql += Utils._.template(query)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' DROP NOT NULL'
});
}
if (definition.indexOf('DEFAULT') > 0) {
attrSql += Utils._.template(query)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' SET DEFAULT ' + definition.match(/DEFAULT ([^;]+)/)[1]
});
definition = definition.replace(/(DEFAULT[^;]+)/, '').trim();
} else if (!definition.match(/REFERENCES/)) {
attrSql += Utils._.template(query)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' DROP DEFAULT'
});
}
if (attributes[attributeName].match(/^ENUM\(/)) {
query = this.pgEnum(tableName, attributeName, attributes[attributeName]) + query;
definition = definition.replace(/^ENUM\(.+\)/, this.quoteIdentifier('enum_' + tableName + '_' + attributeName));
definition += ' USING (' + this.quoteIdentifier(attributeName) + '::' + this.quoteIdentifier(definition) + ')';
}
if (definition.match(/UNIQUE;*$/)) {
definition = definition.replace(/UNIQUE;*$/, '');
attrSql += Utils._.template(query.replace('ALTER COLUMN', ''))({
tableName: this.quoteTable(tableName),
query: 'ADD CONSTRAINT ' + this.quoteIdentifier(attributeName + '_unique_idx') + ' UNIQUE (' + this.quoteIdentifier(attributeName) + ')'
});
}
if (definition.match(/REFERENCES/)) {
definition = definition.replace(/.+?(?=REFERENCES)/,'');
attrSql += Utils._.template(query.replace('ALTER COLUMN', ''))({
tableName: this.quoteTable(tableName),
query: 'ADD CONSTRAINT ' + this.quoteIdentifier(attributeName + '_foreign_idx') + ' FOREIGN KEY (' + this.quoteIdentifier(attributeName) + ') ' + definition
});
} else {
attrSql += Utils._.template(query)({
tableName: this.quoteTable(tableName),
query: this.quoteIdentifier(attributeName) + ' TYPE ' + definition
});
}
sql.push(attrSql);
}
return sql.join('');
},
renameColumnQuery: function(tableName, attrBefore, attributes) {
var query = 'ALTER TABLE <%= tableName %> RENAME COLUMN <%= attributes %>;';
var attrString = [];
for (var attributeName in attributes) {
attrString.push(Utils._.template('<%= before %> TO <%= after %>')({
before: this.quoteIdentifier(attrBefore),
after: this.quoteIdentifier(attributeName)
}));
}
return Utils._.template(query)({
tableName: this.quoteTable(tableName),
attributes: attrString.join(', ')
});
},
fn: function(fnName, tableName, body, returns, language) {
fnName = fnName || 'testfunc';
language = language || 'plpgsql';
returns = returns || 'SETOF ' + this.quoteTable(tableName);
var query = 'CREATE OR REPLACE FUNCTION pg_temp.<%= fnName %>() RETURNS <%= returns %> AS $func$ BEGIN <%= body %> END; $func$ LANGUAGE <%= language %>; SELECT * FROM pg_temp.<%= fnName %>();';
return Utils._.template(query)({
fnName: fnName,
returns: returns,
language: language,
body: body
});
},
exceptionFn: function(fnName, tableName, main, then, when, returns, language) {
when = when || 'unique_violation';
var body = '<%= main %> EXCEPTION WHEN <%= when %> THEN <%= then %>;';
body = Utils._.template(body)({
main: main,
when: when,
then: then
});
return this.fn(fnName, tableName, body, returns, language);
},
// http://www.maori.geek.nz/post/postgres_upsert_update_or_insert_in_ger_using_knex_js
upsertQuery: function (tableName, insertValues, updateValues, where, rawAttributes, options) {
var insert = this.insertQuery(tableName, insertValues, rawAttributes, options);
var update = this.updateQuery(tableName, updateValues, where, options, rawAttributes);
// The numbers here are selected to match the number of affected rows returned by MySQL
return this.exceptionFn(
'sequelize_upsert',
tableName,
insert + ' RETURN 1;',
update + '; RETURN 2',
'unique_violation',
'integer'
);
},
deleteQuery: function(tableName, where, options, model) {
var query;
options = options || {};
tableName = Utils.removeTicks(this.quoteTable(tableName), '"');
if (options.truncate === true) {
query = 'TRUNCATE ' + QueryGenerator.quoteIdentifier(tableName);
if (options.cascade) {
query += ' CASCADE';
}
return query;
}
if (Utils._.isUndefined(options.limit)) {
options.limit = 1;
}
primaryKeys[tableName] = primaryKeys[tableName] || [];
if (!!model && primaryKeys[tableName].length < 1) {
primaryKeys[tableName] = Utils._.map(Object.keys(model.primaryKeys), function(k){
return model.primaryKeys[k].field;
});
}
if (options.limit) {
query = 'DELETE FROM <%= table %> WHERE <%= primaryKeys %> IN (SELECT <%= primaryKeysSelection %> FROM <%= table %><%= where %><%= limit %>)';
} else {
query = 'DELETE FROM <%= table %><%= where %>';
}
var pks;
if (primaryKeys[tableName] && primaryKeys[tableName].length > 0) {
pks = primaryKeys[tableName].map(function(pk) {
return this.quoteIdentifier(pk);
}.bind(this)).join(',');
} else {
pks = this.quoteIdentifier('id');
}
var replacements = {
table: this.quoteIdentifiers(tableName),
where: this.getWhereConditions(where, null, model, options),
limit: !!options.limit ? ' LIMIT ' + this.escape(options.limit) : '',
primaryKeys: primaryKeys[tableName].length > 1 ? '(' + pks + ')' : pks,
primaryKeysSelection: pks
};
if (replacements.where) {
replacements.where = ' WHERE ' + replacements.where;
}
return Utils._.template(query)(replacements);
},
showIndexesQuery: function(tableName) {
var schemaJoin = '', schemaWhere = '';
if (!Utils._.isString(tableName)) {
schemaJoin = ', pg_namespace s';
schemaWhere = Utils._.template(" AND s.oid = t.relnamespace AND s.nspname = '<%= schemaName %>'")({schemaName: tableName.schema});
tableName = tableName.tableName;
}
// This is ARCANE!
var query = 'SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, ' +
'array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) ' +
'AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a<%= schemaJoin%> ' +
'WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND ' +
"t.relkind = 'r' and t.relname = '<%= tableName %>'<%= schemaWhere%> " +
'GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;';
return Utils._.template(query)({tableName: tableName, schemaJoin: schemaJoin, schemaWhere: schemaWhere});
},
removeIndexQuery: function(tableName, indexNameOrAttributes) {
var sql = 'DROP INDEX IF EXISTS <%= indexName %>'
, indexName = indexNameOrAttributes;
if (typeof indexName !== 'string') {
indexName = Utils.inflection.underscore(tableName + '_' + indexNameOrAttributes.join('_'));
}
return Utils._.template(sql)({
tableName: this.quoteIdentifiers(tableName),
indexName: this.quoteIdentifiers(indexName)
});
},
addLimitAndOffset: function(options) {
var fragment = '';
if (options.limit) fragment += ' LIMIT ' + this.escape(options.limit);
if (options.offset) fragment += ' OFFSET ' + this.escape(options.offset);
return fragment;
},
attributeToSQL: function(attribute) {
if (!Utils._.isPlainObject(attribute)) {
attribute = {
type: attribute
};
}
var template = '<%= type %>'
, replacements = {};
if (attribute.type instanceof DataTypes.ENUM) {
if (attribute.type.values && !attribute.values) attribute.values = attribute.type.values;
if (Array.isArray(attribute.values) && (attribute.values.length > 0)) {
replacements.type = 'ENUM(' + Utils._.map(attribute.values, function(value) {
return this.escape(value);
}.bind(this)).join(', ') + ')';
} else {
throw new Error("Values for ENUM haven't been defined.");
}
}
if (!replacements.type) {
replacements.type = attribute.type;
}
if (attribute.hasOwnProperty('allowNull') && (!attribute.allowNull)) {
template += ' NOT NULL';
}
if (attribute.autoIncrement) {
template += ' SERIAL';
}
if (Utils.defaultValueSchemable(attribute.defaultValue)) {
template += ' DEFAULT <%= defaultValue %>';
replacements.defaultValue = this.escape(attribute.defaultValue, attribute);
}
if (attribute.unique === true) {
template += ' UNIQUE';
}
if (attribute.primaryKey) {
template += ' PRIMARY KEY';
}
if (attribute.references) {
attribute = Utils.formatReferences(attribute);
template += ' REFERENCES <%= referencesTable %> (<%= referencesKey %>)';
replacements.referencesTable = this.quoteTable(attribute.references.model);
if (attribute.references.key) {
replacements.referencesKey = this.quoteIdentifiers(attribute.references.key);
} else {
replacements.referencesKey = this.quoteIdentifier('id');
}
if (attribute.onDelete) {
template += ' ON DELETE <%= onDeleteAction %>';
replacements.onDeleteAction = attribute.onDelete.toUpperCase();
}
if (attribute.onUpdate) {
template += ' ON UPDATE <%= onUpdateAction %>';
replacements.onUpdateAction = attribute.onUpdate.toUpperCase();
}
if (attribute.references.deferrable) {
template += ' <%= deferrable %>';
replacements.deferrable = attribute.references.deferrable.toString(this);
}
}
return Utils._.template(template)(replacements);
},
deferConstraintsQuery: function (options) {
return options.deferrable.toString(this);
},
setConstraintQuery: function (columns, type) {
var columnFragment = 'ALL';
if (columns) {
columnFragment = columns.map(function (column) {
return this.quoteIdentifier(column);
}.bind(this)).join(', ');
}
return 'SET CONSTRAINTS ' + columnFragment + ' ' + type;
},
setDeferredQuery: function (columns) {
return this.setConstraintQuery(columns, 'DEFERRED');
},
setImmediateQuery: function (columns) {
return this.setConstraintQuery(columns, 'IMMEDIATE');
},
attributesToSQL: function(attributes, options) {
var result = {}
, key
, attribute;
for (key in attributes) {
attribute = attributes[key];
result[attribute.field || key] = this.attributeToSQL(attribute, options);
}
return result;
},
findAutoIncrementField: function(factory) {
var fields = [];
for (var name in factory.attributes) {
var definition = factory.attributes[name];
if (definition && definition.autoIncrement) {
fields.push(name);
}
}
return fields;
},
createTrigger: function(tableName, triggerName, eventType, fireOnSpec, functionName, functionParams, optionsArray) {
var sql = [
'CREATE <%= constraintVal %>TRIGGER <%= triggerName %>'
, '<%= eventType %> <%= eventSpec %>'
, 'ON <%= tableName %>'
, '<%= optionsSpec %>'
, 'EXECUTE PROCEDURE <%= functionName %>(<%= paramList %>);'
].join('\n\t');
return Utils._.template(sql)({
constraintVal: this.triggerEventTypeIsConstraint(eventType),
triggerName: triggerName,
eventType: this.decodeTriggerEventType(eventType),
eventSpec: this.expandTriggerEventSpec(fireOnSpec),
tableName: tableName,
optionsSpec: this.expandOptions(optionsArray),
functionName: functionName,
paramList: this.expandFunctionParamList(functionParams)
});
},
dropTrigger: function(tableName, triggerName) {
var sql = 'DROP TRIGGER <%= triggerName %> ON <%= tableName %> RESTRICT;';
return Utils._.template(sql)({
triggerName: triggerName,
tableName: tableName
});
},
renameTrigger: function(tableName, oldTriggerName, newTriggerName) {
var sql = 'ALTER TRIGGER <%= oldTriggerName %> ON <%= tableName %> RENAME TO <%= newTriggerName%>;';
return Utils._.template(sql)({
tableName: tableName,
oldTriggerName: oldTriggerName,
newTriggerName: newTriggerName
});
},
createFunction: function(functionName, params, returnType, language, body, options) {
var sql = ['CREATE FUNCTION <%= functionName %>(<%= paramList %>)'
, 'RETURNS <%= returnType %> AS $func$'
, 'BEGIN'
, '\t<%= body %>'
, 'END;'
, "$func$ language '<%= language %>'<%= options %>;"
].join('\n');
return Utils._.template(sql)({
functionName: functionName,
paramList: this.expandFunctionParamList(params),
returnType: returnType,
body: body.replace('\n', '\n\t'),
language: language,
options: this.expandOptions(options)
});
},
dropFunction: function(functionName, params) {
// RESTRICT is (currently, as of 9.2) default but we'll be explicit
var sql = 'DROP FUNCTION <%= functionName %>(<%= paramList %>) RESTRICT;';
return Utils._.template(sql)({
functionName: functionName,
paramList: this.expandFunctionParamList(params)
});
},
renameFunction: function(oldFunctionName, params, newFunctionName) {
var sql = 'ALTER FUNCTION <%= oldFunctionName %>(<%= paramList %>) RENAME TO <%= newFunctionName %>;';
return Utils._.template(sql)({
oldFunctionName: oldFunctionName,
paramList: this.expandFunctionParamList(params),
newFunctionName: newFunctionName
});
},
databaseConnectionUri: function(config) {
var template = '<%= protocol %>://<%= user %>:<%= password %>@<%= host %><% if(port) { %>:<%= port %><% } %>/<%= database %><% if(ssl) { %>?ssl=<%= ssl %><% } %>';
return Utils._.template(template)({
user: config.username,
password: config.password,
database: config.database,
host: config.host,
port: config.port,
protocol: config.protocol,
ssl: config.ssl
});
},
pgEscapeAndQuote: function(val) {
return this.quoteIdentifier(Utils.removeTicks(this.escape(val), "'"));
},
expandFunctionParamList: function expandFunctionParamList(params) {
if (Utils._.isUndefined(params) || !Utils._.isArray(params)) {
throw new Error('expandFunctionParamList: function parameters array required, including an empty one for no arguments');
}
var paramList = Utils._.each(params, function expandParam(curParam) {
var paramDef = [];
if (Utils._.has(curParam, 'type')) {
if (Utils._.has(curParam, 'direction')) { paramDef.push(curParam.direction); }
if (Utils._.has(curParam, 'name')) { paramDef.push(curParam.name); }
paramDef.push(curParam.type);
} else {
throw new Error('createFunction called with a parameter with no type');
}
return paramDef.join(' ');
});
return paramList.join(', ');
},
expandOptions: function expandOptions(options) {
return Utils._.isUndefined(options) || Utils._.isEmpty(options) ?
'' : '\n\t' + options.join('\n\t');
},
decodeTriggerEventType: function decodeTriggerEventType(eventSpecifier) {
var EVENT_DECODER = {
'after': 'AFTER',
'before': 'BEFORE',
'instead_of': 'INSTEAD OF',
'after_constraint': 'AFTER'
};
if (!Utils._.has(EVENT_DECODER, eventSpecifier)) {
throw new Error('Invalid trigger event specified: ' + eventSpecifier);
}
return EVENT_DECODER[eventSpecifier];
},
triggerEventTypeIsConstraint: function triggerEventTypeIsConstraint(eventSpecifier) {
return eventSpecifier === 'after_constrain' ? 'CONSTRAINT ' : '';
},
expandTriggerEventSpec: function expandTriggerEventSpec(fireOnSpec) {
if (Utils._.isEmpty(fireOnSpec)) {
throw new Error('no table change events specified to trigger on');
}
return Utils._.map(fireOnSpec, function parseTriggerEventSpec(fireValue, fireKey) {
var EVENT_MAP = {
'insert': 'INSERT',
'update': 'UPDATE',
'delete': 'DELETE',
'truncate': 'TRUNCATE'
};
if (!Utils._.has(EVENT_MAP, fireKey)) {
throw new Error('parseTriggerEventSpec: undefined trigger event ' + fireKey);
}
var eventSpec = EVENT_MAP[fireKey];
if (eventSpec === 'UPDATE') {
if (Utils._.isArray(fireValue) && fireValue.length > 0) {
eventSpec += ' OF ' + fireValue.join(', ');
}
}
return eventSpec;
}).join(' OR ');
},
pgEnumName: function (tableName, attr, options) {
options = options || {};
var tableDetails = this.extractTableDetails(tableName, options)
, enumName = '"enum_' + tableDetails.tableName + '_' + attr + '"';
// pgListEnums requires the enum name only, without the schema
if (options.schema !== false && tableDetails.schema) {
enumName = this.quoteIdentifier(tableDetails.schema) + tableDetails.delimiter + enumName;
}
return enumName;
},
pgListEnums: function(tableName, attrName, options) {
var enumName = ''
, tableDetails = this.extractTableDetails(tableName, options);
if (tableDetails.tableName && attrName) {
enumName = ' AND t.typname=' + this.pgEnumName(tableDetails.tableName, attrName, { schema: false }).replace(/"/g, "'");
}
var query = 'SELECT t.typname enum_name, array_agg(e.enumlabel ORDER BY enumsortorder) enum_value FROM pg_type t ' +
'JOIN pg_enum e ON t.oid = e.enumtypid ' +
'JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace ' +
"WHERE n.nspname = '" + tableDetails.schema + "'" + enumName + ' GROUP BY 1';
return query;
},
pgEnum: function(tableName, attr, dataType, options) {
var enumName = this.pgEnumName(tableName, attr, options)
, values;
if (dataType.values) {
values = "ENUM('" + dataType.values.join("', '") + "')";
} else {
values = dataType.toString().match(/^ENUM\(.+\)/)[0];
}
var sql = 'CREATE TYPE ' + enumName + ' AS ' + values + ';';
if (!!options && options.force === true) {
sql = this.pgEnumDrop(tableName, attr) + sql;
}
return sql;
},
pgEnumAdd: function(tableName, attr, value, options) {
var enumName = this.pgEnumName(tableName, attr)
, sql = 'ALTER TYPE ' + enumName + ' ADD VALUE ';
if (semver.gte(this.sequelize.options.databaseVersion, '9.3.0')) {
sql += 'IF NOT EXISTS ';
}
sql += this.escape(value);
if (!!options.before) {
sql += ' BEFORE ' + this.escape(options.before);
} else if (!!options.after) {
sql += ' AFTER ' + this.escape(options.after);
}
return sql;
},
pgEnumDrop: function(tableName, attr, enumName) {
enumName = enumName || this.pgEnumName(tableName, attr);
return 'DROP TYPE IF EXISTS ' + enumName + '; ';
},
fromArray: function(text) {
text = text.replace(/^{/, '').replace(/}$/, '');
var matches = text.match(/("(?:\\.|[^"\\\\])*"|[^,]*)(?:\s*,\s*|\s*$)/ig);
if (matches.length < 1) {
return [];
}
matches = matches.map(function(m) {
return m.replace(/",$/, '').replace(/,$/, '').replace(/(^"|"$)/, '');
});
return matches.slice(0, -1);
},
padInt: function(i) {
return (i < 10) ? '0' + i.toString() : i.toString();
},
pgDataTypeMapping: function(tableName, attr, dataType) {
return this.dataTypeMapping(tableName, attr, dataType);
},
dataTypeMapping: function(tableName, attr, dataType) {
if (Utils._.includes(dataType, 'PRIMARY KEY')) {
primaryKeys[tableName].push(attr);
dataType = dataType.replace(/PRIMARY KEY/, '');
}
if (Utils._.includes(dataType, 'SERIAL')) {
if (Utils._.includes(dataType, 'BIGINT')) {
dataType = dataType.replace(/SERIAL/, 'BIGSERIAL');
dataType = dataType.replace(/BIGINT/, '');
} else {
dataType = dataType.replace(/INTEGER/, '');
}
dataType = dataType.replace(/NOT NULL/, '');
}
if (dataType.match(/^ENUM\(/)) {
dataType = dataType.replace(/^ENUM\(.+\)/, this.pgEnumName(tableName, attr));
}
return dataType;
},
quoteIdentifier: function(identifier, force) {
if (identifier === '*') return identifier;
if (!force && this.options && this.options.quoteIdentifiers === false) { // default is `true`
// In Postgres, if tables or attributes are created double-quoted,
// they are also case sensitive. If they contain any uppercase
// characters, they must always be double-quoted. This makes it
// impossible to write queries in portable SQL if tables are created in
// this way. Hence, we strip quotes if we don't want case sensitivity.
return Utils.removeTicks(identifier, '"');
} else {
return Utils.addTicks(identifier, '"');
}
},
/*
/**
* Generates an SQL query that returns all foreign keys of a table.
*
* @param {String} tableName The name of the table.
* @param {String} schemaName The name of the schema.
* @return {String} The generated sql query.
*/
getForeignKeysQuery: function(tableName, schemaName) {
return 'SELECT conname as constraint_name, pg_catalog.pg_get_constraintdef(r.oid, true) as condef FROM pg_catalog.pg_constraint r ' +
"WHERE r.conrelid = (SELECT oid FROM pg_class WHERE relname = '" + tableName + "' LIMIT 1) AND r.contype = 'f' ORDER BY 1;";
},
/**
* Generates an SQL query that removes a foreign key from a table.
*
* @param {String} tableName The name of the table.
* @param {String} foreignKey The name of the foreign key constraint.
* @return {String} The generated sql query.
*/
dropForeignKeyQuery: function(tableName, foreignKey) {
return 'ALTER TABLE ' + this.quoteTable(tableName) + ' DROP CONSTRAINT ' + this.quoteIdentifier(foreignKey) + ';';
},
setAutocommitQuery: function(value, options) {
if (options.parent) {
return;
}
// POSTGRES does not support setting AUTOCOMMIT = OFF as of 9.4.0
// Additionally it does not support AUTOCOMMIT at all starting at v9.5
// The assumption is that it won't be returning in future versions either
// If you are on a Pg version that is not semver compliant e.g. '9.5.0beta2', which fails due to the 'beta' qualification, then you need to pass
// the database version as "9.5.0" explicitly through the options param passed when creating the Sequelize instance under the key "databaseVersion"
// otherwise Pg version "9.4.0" is assumed by default as per Sequelize 3.14.2.
// For Pg versions that are semver compliant, this is auto-detected upon the first connection.
if (!value || semver.gte(this.sequelize.options.databaseVersion, '9.4.0')) {
return;
}
return AbstractQueryGenerator.setAutocommitQuery.call(this, value, options);
}
};
module.exports = Utils._.extend(Utils._.clone(AbstractQueryGenerator), QueryGenerator);
| Brechard/practica5.2 | node_modules/sequelize/lib/dialects/postgres/query-generator.js | JavaScript | apache-2.0 | 31,456 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "base/arena_allocator.h"
#include "bounds_check_elimination.h"
#include "builder.h"
#include "gvn.h"
#include "induction_var_analysis.h"
#include "instruction_simplifier.h"
#include "nodes.h"
#include "optimizing_unit_test.h"
#include "side_effects_analysis.h"
#include "gtest/gtest.h"
namespace art {
/**
* Fixture class for the BoundsCheckElimination tests.
*/
class BoundsCheckEliminationTest : public testing::Test {
public:
BoundsCheckEliminationTest() : pool_(), allocator_(&pool_) {
graph_ = CreateGraph(&allocator_);
graph_->SetHasBoundsChecks(true);
}
~BoundsCheckEliminationTest() { }
void RunBCE() {
graph_->BuildDominatorTree();
InstructionSimplifier(graph_).Run();
SideEffectsAnalysis side_effects(graph_);
side_effects.Run();
GVNOptimization(graph_, side_effects).Run();
HInductionVarAnalysis induction(graph_);
induction.Run();
BoundsCheckElimination(graph_, side_effects, &induction).Run();
}
ArenaPool pool_;
ArenaAllocator allocator_;
HGraph* graph_;
};
// if (i < 0) { array[i] = 1; // Can't eliminate. }
// else if (i >= array.length) { array[i] = 1; // Can't eliminate. }
// else { array[i] = 1; // Can eliminate. }
TEST_F(BoundsCheckEliminationTest, NarrowingRangeArrayBoundsElimination) {
HBasicBlock* entry = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(entry);
graph_->SetEntryBlock(entry);
HInstruction* parameter1 = new (&allocator_)
HParameterValue(graph_->GetDexFile(), 0, 0, Primitive::kPrimNot); // array
HInstruction* parameter2 = new (&allocator_)
HParameterValue(graph_->GetDexFile(), 0, 0, Primitive::kPrimInt); // i
entry->AddInstruction(parameter1);
entry->AddInstruction(parameter2);
HInstruction* constant_1 = graph_->GetIntConstant(1);
HInstruction* constant_0 = graph_->GetIntConstant(0);
HBasicBlock* block1 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block1);
HInstruction* cmp = new (&allocator_) HGreaterThanOrEqual(parameter2, constant_0);
HIf* if_inst = new (&allocator_) HIf(cmp);
block1->AddInstruction(cmp);
block1->AddInstruction(if_inst);
entry->AddSuccessor(block1);
HBasicBlock* block2 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block2);
HNullCheck* null_check = new (&allocator_) HNullCheck(parameter1, 0);
HArrayLength* array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check2 = new (&allocator_)
HBoundsCheck(parameter2, array_length, 0);
HArraySet* array_set = new (&allocator_) HArraySet(
null_check, bounds_check2, constant_1, Primitive::kPrimInt, 0);
block2->AddInstruction(null_check);
block2->AddInstruction(array_length);
block2->AddInstruction(bounds_check2);
block2->AddInstruction(array_set);
HBasicBlock* block3 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block3);
null_check = new (&allocator_) HNullCheck(parameter1, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
cmp = new (&allocator_) HLessThan(parameter2, array_length);
if_inst = new (&allocator_) HIf(cmp);
block3->AddInstruction(null_check);
block3->AddInstruction(array_length);
block3->AddInstruction(cmp);
block3->AddInstruction(if_inst);
HBasicBlock* block4 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block4);
null_check = new (&allocator_) HNullCheck(parameter1, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check4 = new (&allocator_)
HBoundsCheck(parameter2, array_length, 0);
array_set = new (&allocator_) HArraySet(
null_check, bounds_check4, constant_1, Primitive::kPrimInt, 0);
block4->AddInstruction(null_check);
block4->AddInstruction(array_length);
block4->AddInstruction(bounds_check4);
block4->AddInstruction(array_set);
HBasicBlock* block5 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block5);
null_check = new (&allocator_) HNullCheck(parameter1, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check5 = new (&allocator_)
HBoundsCheck(parameter2, array_length, 0);
array_set = new (&allocator_) HArraySet(
null_check, bounds_check5, constant_1, Primitive::kPrimInt, 0);
block5->AddInstruction(null_check);
block5->AddInstruction(array_length);
block5->AddInstruction(bounds_check5);
block5->AddInstruction(array_set);
HBasicBlock* exit = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(exit);
block2->AddSuccessor(exit);
block4->AddSuccessor(exit);
block5->AddSuccessor(exit);
exit->AddInstruction(new (&allocator_) HExit());
block1->AddSuccessor(block3); // True successor
block1->AddSuccessor(block2); // False successor
block3->AddSuccessor(block5); // True successor
block3->AddSuccessor(block4); // False successor
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check2));
ASSERT_FALSE(IsRemoved(bounds_check4));
ASSERT_TRUE(IsRemoved(bounds_check5));
}
// if (i > 0) {
// // Positive number plus MAX_INT will overflow and be negative.
// int j = i + Integer.MAX_VALUE;
// if (j < array.length) array[j] = 1; // Can't eliminate.
// }
TEST_F(BoundsCheckEliminationTest, OverflowArrayBoundsElimination) {
HBasicBlock* entry = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(entry);
graph_->SetEntryBlock(entry);
HInstruction* parameter1 = new (&allocator_)
HParameterValue(graph_->GetDexFile(), 0, 0, Primitive::kPrimNot); // array
HInstruction* parameter2 = new (&allocator_)
HParameterValue(graph_->GetDexFile(), 0, 0, Primitive::kPrimInt); // i
entry->AddInstruction(parameter1);
entry->AddInstruction(parameter2);
HInstruction* constant_1 = graph_->GetIntConstant(1);
HInstruction* constant_0 = graph_->GetIntConstant(0);
HInstruction* constant_max_int = graph_->GetIntConstant(INT_MAX);
HBasicBlock* block1 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block1);
HInstruction* cmp = new (&allocator_) HLessThanOrEqual(parameter2, constant_0);
HIf* if_inst = new (&allocator_) HIf(cmp);
block1->AddInstruction(cmp);
block1->AddInstruction(if_inst);
entry->AddSuccessor(block1);
HBasicBlock* block2 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block2);
HInstruction* add = new (&allocator_) HAdd(Primitive::kPrimInt, parameter2, constant_max_int);
HNullCheck* null_check = new (&allocator_) HNullCheck(parameter1, 0);
HArrayLength* array_length = new (&allocator_) HArrayLength(null_check, 0);
HInstruction* cmp2 = new (&allocator_) HGreaterThanOrEqual(add, array_length);
if_inst = new (&allocator_) HIf(cmp2);
block2->AddInstruction(add);
block2->AddInstruction(null_check);
block2->AddInstruction(array_length);
block2->AddInstruction(cmp2);
block2->AddInstruction(if_inst);
HBasicBlock* block3 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block3);
HBoundsCheck* bounds_check = new (&allocator_)
HBoundsCheck(add, array_length, 0);
HArraySet* array_set = new (&allocator_) HArraySet(
null_check, bounds_check, constant_1, Primitive::kPrimInt, 0);
block3->AddInstruction(bounds_check);
block3->AddInstruction(array_set);
HBasicBlock* exit = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(exit);
exit->AddInstruction(new (&allocator_) HExit());
block1->AddSuccessor(exit); // true successor
block1->AddSuccessor(block2); // false successor
block2->AddSuccessor(exit); // true successor
block2->AddSuccessor(block3); // false successor
block3->AddSuccessor(exit);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
// if (i < array.length) {
// int j = i - Integer.MAX_VALUE;
// j = j - Integer.MAX_VALUE; // j is (i+2) after subtracting MAX_INT twice
// if (j > 0) array[j] = 1; // Can't eliminate.
// }
TEST_F(BoundsCheckEliminationTest, UnderflowArrayBoundsElimination) {
HBasicBlock* entry = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(entry);
graph_->SetEntryBlock(entry);
HInstruction* parameter1 = new (&allocator_)
HParameterValue(graph_->GetDexFile(), 0, 0, Primitive::kPrimNot); // array
HInstruction* parameter2 = new (&allocator_)
HParameterValue(graph_->GetDexFile(), 0, 0, Primitive::kPrimInt); // i
entry->AddInstruction(parameter1);
entry->AddInstruction(parameter2);
HInstruction* constant_1 = graph_->GetIntConstant(1);
HInstruction* constant_0 = graph_->GetIntConstant(0);
HInstruction* constant_max_int = graph_->GetIntConstant(INT_MAX);
HBasicBlock* block1 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block1);
HNullCheck* null_check = new (&allocator_) HNullCheck(parameter1, 0);
HArrayLength* array_length = new (&allocator_) HArrayLength(null_check, 0);
HInstruction* cmp = new (&allocator_) HGreaterThanOrEqual(parameter2, array_length);
HIf* if_inst = new (&allocator_) HIf(cmp);
block1->AddInstruction(null_check);
block1->AddInstruction(array_length);
block1->AddInstruction(cmp);
block1->AddInstruction(if_inst);
entry->AddSuccessor(block1);
HBasicBlock* block2 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block2);
HInstruction* sub1 = new (&allocator_) HSub(Primitive::kPrimInt, parameter2, constant_max_int);
HInstruction* sub2 = new (&allocator_) HSub(Primitive::kPrimInt, sub1, constant_max_int);
HInstruction* cmp2 = new (&allocator_) HLessThanOrEqual(sub2, constant_0);
if_inst = new (&allocator_) HIf(cmp2);
block2->AddInstruction(sub1);
block2->AddInstruction(sub2);
block2->AddInstruction(cmp2);
block2->AddInstruction(if_inst);
HBasicBlock* block3 = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block3);
HBoundsCheck* bounds_check = new (&allocator_)
HBoundsCheck(sub2, array_length, 0);
HArraySet* array_set = new (&allocator_) HArraySet(
null_check, bounds_check, constant_1, Primitive::kPrimInt, 0);
block3->AddInstruction(bounds_check);
block3->AddInstruction(array_set);
HBasicBlock* exit = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(exit);
exit->AddInstruction(new (&allocator_) HExit());
block1->AddSuccessor(exit); // true successor
block1->AddSuccessor(block2); // false successor
block2->AddSuccessor(exit); // true successor
block2->AddSuccessor(block3); // false successor
block3->AddSuccessor(exit);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
// array[6] = 1; // Can't eliminate.
// array[5] = 1; // Can eliminate.
// array[4] = 1; // Can eliminate.
TEST_F(BoundsCheckEliminationTest, ConstantArrayBoundsElimination) {
HBasicBlock* entry = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(entry);
graph_->SetEntryBlock(entry);
HInstruction* parameter = new (&allocator_) HParameterValue(
graph_->GetDexFile(), 0, 0, Primitive::kPrimNot);
entry->AddInstruction(parameter);
HInstruction* constant_5 = graph_->GetIntConstant(5);
HInstruction* constant_4 = graph_->GetIntConstant(4);
HInstruction* constant_6 = graph_->GetIntConstant(6);
HInstruction* constant_1 = graph_->GetIntConstant(1);
HBasicBlock* block = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block);
entry->AddSuccessor(block);
HNullCheck* null_check = new (&allocator_) HNullCheck(parameter, 0);
HArrayLength* array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check6 = new (&allocator_)
HBoundsCheck(constant_6, array_length, 0);
HInstruction* array_set = new (&allocator_) HArraySet(
null_check, bounds_check6, constant_1, Primitive::kPrimInt, 0);
block->AddInstruction(null_check);
block->AddInstruction(array_length);
block->AddInstruction(bounds_check6);
block->AddInstruction(array_set);
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check5 = new (&allocator_)
HBoundsCheck(constant_5, array_length, 0);
array_set = new (&allocator_) HArraySet(
null_check, bounds_check5, constant_1, Primitive::kPrimInt, 0);
block->AddInstruction(null_check);
block->AddInstruction(array_length);
block->AddInstruction(bounds_check5);
block->AddInstruction(array_set);
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check4 = new (&allocator_)
HBoundsCheck(constant_4, array_length, 0);
array_set = new (&allocator_) HArraySet(
null_check, bounds_check4, constant_1, Primitive::kPrimInt, 0);
block->AddInstruction(null_check);
block->AddInstruction(array_length);
block->AddInstruction(bounds_check4);
block->AddInstruction(array_set);
block->AddInstruction(new (&allocator_) HGoto());
HBasicBlock* exit = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(exit);
block->AddSuccessor(exit);
exit->AddInstruction(new (&allocator_) HExit());
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check6));
ASSERT_TRUE(IsRemoved(bounds_check5));
ASSERT_TRUE(IsRemoved(bounds_check4));
}
// for (int i=initial; i<array.length; i+=increment) { array[i] = 10; }
static HInstruction* BuildSSAGraph1(HGraph* graph,
ArenaAllocator* allocator,
int initial,
int increment,
IfCondition cond = kCondGE) {
HBasicBlock* entry = new (allocator) HBasicBlock(graph);
graph->AddBlock(entry);
graph->SetEntryBlock(entry);
HInstruction* parameter = new (allocator) HParameterValue(
graph->GetDexFile(), 0, 0, Primitive::kPrimNot);
entry->AddInstruction(parameter);
HInstruction* constant_initial = graph->GetIntConstant(initial);
HInstruction* constant_increment = graph->GetIntConstant(increment);
HInstruction* constant_10 = graph->GetIntConstant(10);
HBasicBlock* block = new (allocator) HBasicBlock(graph);
graph->AddBlock(block);
entry->AddSuccessor(block);
block->AddInstruction(new (allocator) HGoto());
HBasicBlock* loop_header = new (allocator) HBasicBlock(graph);
HBasicBlock* loop_body = new (allocator) HBasicBlock(graph);
HBasicBlock* exit = new (allocator) HBasicBlock(graph);
graph->AddBlock(loop_header);
graph->AddBlock(loop_body);
graph->AddBlock(exit);
block->AddSuccessor(loop_header);
loop_header->AddSuccessor(exit); // true successor
loop_header->AddSuccessor(loop_body); // false successor
loop_body->AddSuccessor(loop_header);
HPhi* phi = new (allocator) HPhi(allocator, 0, 0, Primitive::kPrimInt);
HInstruction* null_check = new (allocator) HNullCheck(parameter, 0);
HInstruction* array_length = new (allocator) HArrayLength(null_check, 0);
HInstruction* cmp = nullptr;
if (cond == kCondGE) {
cmp = new (allocator) HGreaterThanOrEqual(phi, array_length);
} else {
DCHECK(cond == kCondGT);
cmp = new (allocator) HGreaterThan(phi, array_length);
}
HInstruction* if_inst = new (allocator) HIf(cmp);
loop_header->AddPhi(phi);
loop_header->AddInstruction(null_check);
loop_header->AddInstruction(array_length);
loop_header->AddInstruction(cmp);
loop_header->AddInstruction(if_inst);
phi->AddInput(constant_initial);
null_check = new (allocator) HNullCheck(parameter, 0);
array_length = new (allocator) HArrayLength(null_check, 0);
HInstruction* bounds_check = new (allocator) HBoundsCheck(phi, array_length, 0);
HInstruction* array_set = new (allocator) HArraySet(
null_check, bounds_check, constant_10, Primitive::kPrimInt, 0);
HInstruction* add = new (allocator) HAdd(Primitive::kPrimInt, phi, constant_increment);
loop_body->AddInstruction(null_check);
loop_body->AddInstruction(array_length);
loop_body->AddInstruction(bounds_check);
loop_body->AddInstruction(array_set);
loop_body->AddInstruction(add);
loop_body->AddInstruction(new (allocator) HGoto());
phi->AddInput(add);
exit->AddInstruction(new (allocator) HExit());
return bounds_check;
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination1a) {
// for (int i=0; i<array.length; i++) { array[i] = 10; // Can eliminate with gvn. }
HInstruction* bounds_check = BuildSSAGraph1(graph_, &allocator_, 0, 1);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination1b) {
// for (int i=1; i<array.length; i++) { array[i] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph1(graph_, &allocator_, 1, 1);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination1c) {
// for (int i=-1; i<array.length; i++) { array[i] = 10; // Can't eliminate. }
HInstruction* bounds_check = BuildSSAGraph1(graph_, &allocator_, -1, 1);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination1d) {
// for (int i=0; i<=array.length; i++) { array[i] = 10; // Can't eliminate. }
HInstruction* bounds_check = BuildSSAGraph1(graph_, &allocator_, 0, 1, kCondGT);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination1e) {
// for (int i=0; i<array.length; i += 2) {
// array[i] = 10; // Can't eliminate due to overflow concern. }
HInstruction* bounds_check = BuildSSAGraph1(graph_, &allocator_, 0, 2);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination1f) {
// for (int i=1; i<array.length; i += 2) { array[i] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph1(graph_, &allocator_, 1, 2);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
// for (int i=array.length; i>0; i+=increment) { array[i-1] = 10; }
static HInstruction* BuildSSAGraph2(HGraph *graph,
ArenaAllocator* allocator,
int initial,
int increment = -1,
IfCondition cond = kCondLE) {
HBasicBlock* entry = new (allocator) HBasicBlock(graph);
graph->AddBlock(entry);
graph->SetEntryBlock(entry);
HInstruction* parameter = new (allocator) HParameterValue(
graph->GetDexFile(), 0, 0, Primitive::kPrimNot);
entry->AddInstruction(parameter);
HInstruction* constant_initial = graph->GetIntConstant(initial);
HInstruction* constant_increment = graph->GetIntConstant(increment);
HInstruction* constant_minus_1 = graph->GetIntConstant(-1);
HInstruction* constant_10 = graph->GetIntConstant(10);
HBasicBlock* block = new (allocator) HBasicBlock(graph);
graph->AddBlock(block);
entry->AddSuccessor(block);
HInstruction* null_check = new (allocator) HNullCheck(parameter, 0);
HInstruction* array_length = new (allocator) HArrayLength(null_check, 0);
block->AddInstruction(null_check);
block->AddInstruction(array_length);
block->AddInstruction(new (allocator) HGoto());
HBasicBlock* loop_header = new (allocator) HBasicBlock(graph);
HBasicBlock* loop_body = new (allocator) HBasicBlock(graph);
HBasicBlock* exit = new (allocator) HBasicBlock(graph);
graph->AddBlock(loop_header);
graph->AddBlock(loop_body);
graph->AddBlock(exit);
block->AddSuccessor(loop_header);
loop_header->AddSuccessor(exit); // true successor
loop_header->AddSuccessor(loop_body); // false successor
loop_body->AddSuccessor(loop_header);
HPhi* phi = new (allocator) HPhi(allocator, 0, 0, Primitive::kPrimInt);
HInstruction* cmp = nullptr;
if (cond == kCondLE) {
cmp = new (allocator) HLessThanOrEqual(phi, constant_initial);
} else {
DCHECK(cond == kCondLT);
cmp = new (allocator) HLessThan(phi, constant_initial);
}
HInstruction* if_inst = new (allocator) HIf(cmp);
loop_header->AddPhi(phi);
loop_header->AddInstruction(cmp);
loop_header->AddInstruction(if_inst);
phi->AddInput(array_length);
HInstruction* add = new (allocator) HAdd(Primitive::kPrimInt, phi, constant_minus_1);
null_check = new (allocator) HNullCheck(parameter, 0);
array_length = new (allocator) HArrayLength(null_check, 0);
HInstruction* bounds_check = new (allocator) HBoundsCheck(add, array_length, 0);
HInstruction* array_set = new (allocator) HArraySet(
null_check, bounds_check, constant_10, Primitive::kPrimInt, 0);
HInstruction* add_phi = new (allocator) HAdd(Primitive::kPrimInt, phi, constant_increment);
loop_body->AddInstruction(add);
loop_body->AddInstruction(null_check);
loop_body->AddInstruction(array_length);
loop_body->AddInstruction(bounds_check);
loop_body->AddInstruction(array_set);
loop_body->AddInstruction(add_phi);
loop_body->AddInstruction(new (allocator) HGoto());
phi->AddInput(add);
exit->AddInstruction(new (allocator) HExit());
return bounds_check;
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination2a) {
// for (int i=array.length; i>0; i--) { array[i-1] = 10; // Can eliminate with gvn. }
HInstruction* bounds_check = BuildSSAGraph2(graph_, &allocator_, 0);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination2b) {
// for (int i=array.length; i>1; i--) { array[i-1] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph2(graph_, &allocator_, 1);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination2c) {
// for (int i=array.length; i>-1; i--) { array[i-1] = 10; // Can't eliminate. }
HInstruction* bounds_check = BuildSSAGraph2(graph_, &allocator_, -1);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination2d) {
// for (int i=array.length; i>=0; i--) { array[i-1] = 10; // Can't eliminate. }
HInstruction* bounds_check = BuildSSAGraph2(graph_, &allocator_, 0, -1, kCondLT);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination2e) {
// for (int i=array.length; i>0; i-=2) { array[i-1] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph2(graph_, &allocator_, 0, -2);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
// int[] array = new int[10];
// for (int i=0; i<10; i+=increment) { array[i] = 10; }
static HInstruction* BuildSSAGraph3(HGraph* graph,
ArenaAllocator* allocator,
int initial,
int increment,
IfCondition cond) {
HBasicBlock* entry = new (allocator) HBasicBlock(graph);
graph->AddBlock(entry);
graph->SetEntryBlock(entry);
HInstruction* constant_10 = graph->GetIntConstant(10);
HInstruction* constant_initial = graph->GetIntConstant(initial);
HInstruction* constant_increment = graph->GetIntConstant(increment);
HBasicBlock* block = new (allocator) HBasicBlock(graph);
graph->AddBlock(block);
entry->AddSuccessor(block);
HInstruction* new_array = new (allocator) HNewArray(
constant_10,
graph->GetCurrentMethod(),
0,
Primitive::kPrimInt,
graph->GetDexFile(),
kQuickAllocArray);
block->AddInstruction(new_array);
block->AddInstruction(new (allocator) HGoto());
HBasicBlock* loop_header = new (allocator) HBasicBlock(graph);
HBasicBlock* loop_body = new (allocator) HBasicBlock(graph);
HBasicBlock* exit = new (allocator) HBasicBlock(graph);
graph->AddBlock(loop_header);
graph->AddBlock(loop_body);
graph->AddBlock(exit);
block->AddSuccessor(loop_header);
loop_header->AddSuccessor(exit); // true successor
loop_header->AddSuccessor(loop_body); // false successor
loop_body->AddSuccessor(loop_header);
HPhi* phi = new (allocator) HPhi(allocator, 0, 0, Primitive::kPrimInt);
HInstruction* cmp = nullptr;
if (cond == kCondGE) {
cmp = new (allocator) HGreaterThanOrEqual(phi, constant_10);
} else {
DCHECK(cond == kCondGT);
cmp = new (allocator) HGreaterThan(phi, constant_10);
}
HInstruction* if_inst = new (allocator) HIf(cmp);
loop_header->AddPhi(phi);
loop_header->AddInstruction(cmp);
loop_header->AddInstruction(if_inst);
phi->AddInput(constant_initial);
HNullCheck* null_check = new (allocator) HNullCheck(new_array, 0);
HArrayLength* array_length = new (allocator) HArrayLength(null_check, 0);
HInstruction* bounds_check = new (allocator) HBoundsCheck(phi, array_length, 0);
HInstruction* array_set = new (allocator) HArraySet(
null_check, bounds_check, constant_10, Primitive::kPrimInt, 0);
HInstruction* add = new (allocator) HAdd(Primitive::kPrimInt, phi, constant_increment);
loop_body->AddInstruction(null_check);
loop_body->AddInstruction(array_length);
loop_body->AddInstruction(bounds_check);
loop_body->AddInstruction(array_set);
loop_body->AddInstruction(add);
loop_body->AddInstruction(new (allocator) HGoto());
phi->AddInput(add);
exit->AddInstruction(new (allocator) HExit());
return bounds_check;
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination3a) {
// int[] array = new int[10];
// for (int i=0; i<10; i++) { array[i] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph3(graph_, &allocator_, 0, 1, kCondGE);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination3b) {
// int[] array = new int[10];
// for (int i=1; i<10; i++) { array[i] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph3(graph_, &allocator_, 1, 1, kCondGE);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination3c) {
// int[] array = new int[10];
// for (int i=0; i<=10; i++) { array[i] = 10; // Can't eliminate. }
HInstruction* bounds_check = BuildSSAGraph3(graph_, &allocator_, 0, 1, kCondGT);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination3d) {
// int[] array = new int[10];
// for (int i=1; i<10; i+=8) { array[i] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph3(graph_, &allocator_, 1, 8, kCondGE);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
// for (int i=initial; i<array.length; i++) { array[array.length-i-1] = 10; }
static HInstruction* BuildSSAGraph4(HGraph* graph,
ArenaAllocator* allocator,
int initial,
IfCondition cond = kCondGE) {
HBasicBlock* entry = new (allocator) HBasicBlock(graph);
graph->AddBlock(entry);
graph->SetEntryBlock(entry);
HInstruction* parameter = new (allocator) HParameterValue(
graph->GetDexFile(), 0, 0, Primitive::kPrimNot);
entry->AddInstruction(parameter);
HInstruction* constant_initial = graph->GetIntConstant(initial);
HInstruction* constant_1 = graph->GetIntConstant(1);
HInstruction* constant_10 = graph->GetIntConstant(10);
HInstruction* constant_minus_1 = graph->GetIntConstant(-1);
HBasicBlock* block = new (allocator) HBasicBlock(graph);
graph->AddBlock(block);
entry->AddSuccessor(block);
block->AddInstruction(new (allocator) HGoto());
HBasicBlock* loop_header = new (allocator) HBasicBlock(graph);
HBasicBlock* loop_body = new (allocator) HBasicBlock(graph);
HBasicBlock* exit = new (allocator) HBasicBlock(graph);
graph->AddBlock(loop_header);
graph->AddBlock(loop_body);
graph->AddBlock(exit);
block->AddSuccessor(loop_header);
loop_header->AddSuccessor(exit); // true successor
loop_header->AddSuccessor(loop_body); // false successor
loop_body->AddSuccessor(loop_header);
HPhi* phi = new (allocator) HPhi(allocator, 0, 0, Primitive::kPrimInt);
HInstruction* null_check = new (allocator) HNullCheck(parameter, 0);
HInstruction* array_length = new (allocator) HArrayLength(null_check, 0);
HInstruction* cmp = nullptr;
if (cond == kCondGE) {
cmp = new (allocator) HGreaterThanOrEqual(phi, array_length);
} else if (cond == kCondGT) {
cmp = new (allocator) HGreaterThan(phi, array_length);
}
HInstruction* if_inst = new (allocator) HIf(cmp);
loop_header->AddPhi(phi);
loop_header->AddInstruction(null_check);
loop_header->AddInstruction(array_length);
loop_header->AddInstruction(cmp);
loop_header->AddInstruction(if_inst);
phi->AddInput(constant_initial);
null_check = new (allocator) HNullCheck(parameter, 0);
array_length = new (allocator) HArrayLength(null_check, 0);
HInstruction* sub = new (allocator) HSub(Primitive::kPrimInt, array_length, phi);
HInstruction* add_minus_1 = new (allocator)
HAdd(Primitive::kPrimInt, sub, constant_minus_1);
HInstruction* bounds_check = new (allocator) HBoundsCheck(add_minus_1, array_length, 0);
HInstruction* array_set = new (allocator) HArraySet(
null_check, bounds_check, constant_10, Primitive::kPrimInt, 0);
HInstruction* add = new (allocator) HAdd(Primitive::kPrimInt, phi, constant_1);
loop_body->AddInstruction(null_check);
loop_body->AddInstruction(array_length);
loop_body->AddInstruction(sub);
loop_body->AddInstruction(add_minus_1);
loop_body->AddInstruction(bounds_check);
loop_body->AddInstruction(array_set);
loop_body->AddInstruction(add);
loop_body->AddInstruction(new (allocator) HGoto());
phi->AddInput(add);
exit->AddInstruction(new (allocator) HExit());
return bounds_check;
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination4a) {
// for (int i=0; i<array.length; i++) { array[array.length-i-1] = 10; // Can eliminate with gvn. }
HInstruction* bounds_check = BuildSSAGraph4(graph_, &allocator_, 0);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination4b) {
// for (int i=1; i<array.length; i++) { array[array.length-i-1] = 10; // Can eliminate. }
HInstruction* bounds_check = BuildSSAGraph4(graph_, &allocator_, 1);
RunBCE();
ASSERT_TRUE(IsRemoved(bounds_check));
}
TEST_F(BoundsCheckEliminationTest, LoopArrayBoundsElimination4c) {
// for (int i=0; i<=array.length; i++) { array[array.length-i] = 10; // Can't eliminate. }
HInstruction* bounds_check = BuildSSAGraph4(graph_, &allocator_, 0, kCondGT);
RunBCE();
ASSERT_FALSE(IsRemoved(bounds_check));
}
// Bubble sort:
// (Every array access bounds-check can be eliminated.)
// for (int i=0; i<array.length-1; i++) {
// for (int j=0; j<array.length-i-1; j++) {
// if (array[j] > array[j+1]) {
// int temp = array[j+1];
// array[j+1] = array[j];
// array[j] = temp;
// }
// }
// }
TEST_F(BoundsCheckEliminationTest, BubbleSortArrayBoundsElimination) {
HBasicBlock* entry = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(entry);
graph_->SetEntryBlock(entry);
HInstruction* parameter = new (&allocator_) HParameterValue(
graph_->GetDexFile(), 0, 0, Primitive::kPrimNot);
entry->AddInstruction(parameter);
HInstruction* constant_0 = graph_->GetIntConstant(0);
HInstruction* constant_minus_1 = graph_->GetIntConstant(-1);
HInstruction* constant_1 = graph_->GetIntConstant(1);
HBasicBlock* block = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(block);
entry->AddSuccessor(block);
block->AddInstruction(new (&allocator_) HGoto());
HBasicBlock* exit = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(exit);
exit->AddInstruction(new (&allocator_) HExit());
HBasicBlock* outer_header = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(outer_header);
HPhi* phi_i = new (&allocator_) HPhi(&allocator_, 0, 0, Primitive::kPrimInt);
HNullCheck* null_check = new (&allocator_) HNullCheck(parameter, 0);
HArrayLength* array_length = new (&allocator_) HArrayLength(null_check, 0);
HAdd* add = new (&allocator_) HAdd(Primitive::kPrimInt, array_length, constant_minus_1);
HInstruction* cmp = new (&allocator_) HGreaterThanOrEqual(phi_i, add);
HIf* if_inst = new (&allocator_) HIf(cmp);
outer_header->AddPhi(phi_i);
outer_header->AddInstruction(null_check);
outer_header->AddInstruction(array_length);
outer_header->AddInstruction(add);
outer_header->AddInstruction(cmp);
outer_header->AddInstruction(if_inst);
phi_i->AddInput(constant_0);
HBasicBlock* inner_header = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(inner_header);
HPhi* phi_j = new (&allocator_) HPhi(&allocator_, 0, 0, Primitive::kPrimInt);
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HSub* sub = new (&allocator_) HSub(Primitive::kPrimInt, array_length, phi_i);
add = new (&allocator_) HAdd(Primitive::kPrimInt, sub, constant_minus_1);
cmp = new (&allocator_) HGreaterThanOrEqual(phi_j, add);
if_inst = new (&allocator_) HIf(cmp);
inner_header->AddPhi(phi_j);
inner_header->AddInstruction(null_check);
inner_header->AddInstruction(array_length);
inner_header->AddInstruction(sub);
inner_header->AddInstruction(add);
inner_header->AddInstruction(cmp);
inner_header->AddInstruction(if_inst);
phi_j->AddInput(constant_0);
HBasicBlock* inner_body_compare = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(inner_body_compare);
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check1 = new (&allocator_) HBoundsCheck(phi_j, array_length, 0);
HArrayGet* array_get_j = new (&allocator_)
HArrayGet(null_check, bounds_check1, Primitive::kPrimInt, 0);
inner_body_compare->AddInstruction(null_check);
inner_body_compare->AddInstruction(array_length);
inner_body_compare->AddInstruction(bounds_check1);
inner_body_compare->AddInstruction(array_get_j);
HInstruction* j_plus_1 = new (&allocator_) HAdd(Primitive::kPrimInt, phi_j, constant_1);
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HBoundsCheck* bounds_check2 = new (&allocator_) HBoundsCheck(j_plus_1, array_length, 0);
HArrayGet* array_get_j_plus_1 = new (&allocator_)
HArrayGet(null_check, bounds_check2, Primitive::kPrimInt, 0);
cmp = new (&allocator_) HGreaterThanOrEqual(array_get_j, array_get_j_plus_1);
if_inst = new (&allocator_) HIf(cmp);
inner_body_compare->AddInstruction(j_plus_1);
inner_body_compare->AddInstruction(null_check);
inner_body_compare->AddInstruction(array_length);
inner_body_compare->AddInstruction(bounds_check2);
inner_body_compare->AddInstruction(array_get_j_plus_1);
inner_body_compare->AddInstruction(cmp);
inner_body_compare->AddInstruction(if_inst);
HBasicBlock* inner_body_swap = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(inner_body_swap);
j_plus_1 = new (&allocator_) HAdd(Primitive::kPrimInt, phi_j, constant_1);
// temp = array[j+1]
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HInstruction* bounds_check3 = new (&allocator_) HBoundsCheck(j_plus_1, array_length, 0);
array_get_j_plus_1 = new (&allocator_)
HArrayGet(null_check, bounds_check3, Primitive::kPrimInt, 0);
inner_body_swap->AddInstruction(j_plus_1);
inner_body_swap->AddInstruction(null_check);
inner_body_swap->AddInstruction(array_length);
inner_body_swap->AddInstruction(bounds_check3);
inner_body_swap->AddInstruction(array_get_j_plus_1);
// array[j+1] = array[j]
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HInstruction* bounds_check4 = new (&allocator_) HBoundsCheck(phi_j, array_length, 0);
array_get_j = new (&allocator_)
HArrayGet(null_check, bounds_check4, Primitive::kPrimInt, 0);
inner_body_swap->AddInstruction(null_check);
inner_body_swap->AddInstruction(array_length);
inner_body_swap->AddInstruction(bounds_check4);
inner_body_swap->AddInstruction(array_get_j);
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HInstruction* bounds_check5 = new (&allocator_) HBoundsCheck(j_plus_1, array_length, 0);
HArraySet* array_set_j_plus_1 = new (&allocator_)
HArraySet(null_check, bounds_check5, array_get_j, Primitive::kPrimInt, 0);
inner_body_swap->AddInstruction(null_check);
inner_body_swap->AddInstruction(array_length);
inner_body_swap->AddInstruction(bounds_check5);
inner_body_swap->AddInstruction(array_set_j_plus_1);
// array[j] = temp
null_check = new (&allocator_) HNullCheck(parameter, 0);
array_length = new (&allocator_) HArrayLength(null_check, 0);
HInstruction* bounds_check6 = new (&allocator_) HBoundsCheck(phi_j, array_length, 0);
HArraySet* array_set_j = new (&allocator_)
HArraySet(null_check, bounds_check6, array_get_j_plus_1, Primitive::kPrimInt, 0);
inner_body_swap->AddInstruction(null_check);
inner_body_swap->AddInstruction(array_length);
inner_body_swap->AddInstruction(bounds_check6);
inner_body_swap->AddInstruction(array_set_j);
inner_body_swap->AddInstruction(new (&allocator_) HGoto());
HBasicBlock* inner_body_add = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(inner_body_add);
add = new (&allocator_) HAdd(Primitive::kPrimInt, phi_j, constant_1);
inner_body_add->AddInstruction(add);
inner_body_add->AddInstruction(new (&allocator_) HGoto());
phi_j->AddInput(add);
HBasicBlock* outer_body_add = new (&allocator_) HBasicBlock(graph_);
graph_->AddBlock(outer_body_add);
add = new (&allocator_) HAdd(Primitive::kPrimInt, phi_i, constant_1);
outer_body_add->AddInstruction(add);
outer_body_add->AddInstruction(new (&allocator_) HGoto());
phi_i->AddInput(add);
block->AddSuccessor(outer_header);
outer_header->AddSuccessor(exit);
outer_header->AddSuccessor(inner_header);
inner_header->AddSuccessor(outer_body_add);
inner_header->AddSuccessor(inner_body_compare);
inner_body_compare->AddSuccessor(inner_body_add);
inner_body_compare->AddSuccessor(inner_body_swap);
inner_body_swap->AddSuccessor(inner_body_add);
inner_body_add->AddSuccessor(inner_header);
outer_body_add->AddSuccessor(outer_header);
RunBCE(); // gvn removes same bounds check already
ASSERT_TRUE(IsRemoved(bounds_check1));
ASSERT_TRUE(IsRemoved(bounds_check2));
ASSERT_TRUE(IsRemoved(bounds_check3));
ASSERT_TRUE(IsRemoved(bounds_check4));
ASSERT_TRUE(IsRemoved(bounds_check5));
ASSERT_TRUE(IsRemoved(bounds_check6));
}
} // namespace art
| android-art-intel/Nougat | art-extension/compiler/optimizing/bounds_check_elimination_test.cc | C++ | apache-2.0 | 39,261 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "reflection.h"
#include <float.h>
#include <limits.h>
#include "ScopedLocalRef.h"
#include "art_method-inl.h"
#include "common_compiler_test.h"
#include "scoped_thread_state_change.h"
namespace art {
// TODO: Convert to CommonRuntimeTest. Currently MakeExecutable is used.
class ReflectionTest : public CommonCompilerTest {
protected:
virtual void SetUp() {
CommonCompilerTest::SetUp();
vm_ = Runtime::Current()->GetJavaVM();
// Turn on -verbose:jni for the JNI tests.
// gLogVerbosity.jni = true;
vm_->AttachCurrentThread(&env_, nullptr);
ScopedLocalRef<jclass> aioobe(env_,
env_->FindClass("java/lang/ArrayIndexOutOfBoundsException"));
CHECK(aioobe.get() != nullptr);
aioobe_ = reinterpret_cast<jclass>(env_->NewGlobalRef(aioobe.get()));
ScopedLocalRef<jclass> ase(env_, env_->FindClass("java/lang/ArrayStoreException"));
CHECK(ase.get() != nullptr);
ase_ = reinterpret_cast<jclass>(env_->NewGlobalRef(ase.get()));
ScopedLocalRef<jclass> sioobe(env_,
env_->FindClass("java/lang/StringIndexOutOfBoundsException"));
CHECK(sioobe.get() != nullptr);
sioobe_ = reinterpret_cast<jclass>(env_->NewGlobalRef(sioobe.get()));
}
void CleanUpJniEnv() {
if (aioobe_ != nullptr) {
env_->DeleteGlobalRef(aioobe_);
aioobe_ = nullptr;
}
if (ase_ != nullptr) {
env_->DeleteGlobalRef(ase_);
ase_ = nullptr;
}
if (sioobe_ != nullptr) {
env_->DeleteGlobalRef(sioobe_);
sioobe_ = nullptr;
}
}
virtual void TearDown() {
CleanUpJniEnv();
CommonCompilerTest::TearDown();
}
jclass GetPrimitiveClass(char descriptor) {
ScopedObjectAccess soa(env_);
mirror::Class* c = class_linker_->FindPrimitiveClass(descriptor);
CHECK(c != nullptr);
return soa.AddLocalReference<jclass>(c);
}
void ReflectionTestMakeExecutable(ArtMethod** method,
mirror::Object** receiver,
bool is_static, const char* method_name,
const char* method_signature)
SHARED_REQUIRES(Locks::mutator_lock_) {
const char* class_name = is_static ? "StaticLeafMethods" : "NonStaticLeafMethods";
jobject jclass_loader(LoadDex(class_name));
Thread* self = Thread::Current();
StackHandleScope<2> hs(self);
Handle<mirror::ClassLoader> class_loader(
hs.NewHandle(
ScopedObjectAccessUnchecked(self).Decode<mirror::ClassLoader*>(jclass_loader)));
if (is_static) {
MakeExecutable(ScopedObjectAccessUnchecked(self).Decode<mirror::ClassLoader*>(jclass_loader),
class_name);
} else {
MakeExecutable(nullptr, "java.lang.Class");
MakeExecutable(nullptr, "java.lang.Object");
MakeExecutable(ScopedObjectAccessUnchecked(self).Decode<mirror::ClassLoader*>(jclass_loader),
class_name);
}
mirror::Class* c = class_linker_->FindClass(self, DotToDescriptor(class_name).c_str(),
class_loader);
CHECK(c != nullptr);
*method = is_static ? c->FindDirectMethod(method_name, method_signature, sizeof(void*))
: c->FindVirtualMethod(method_name, method_signature, sizeof(void*));
CHECK(method != nullptr);
if (is_static) {
*receiver = nullptr;
} else {
// Ensure class is initialized before allocating object
StackHandleScope<1> hs2(self);
Handle<mirror::Class> h_class(hs2.NewHandle(c));
bool initialized = class_linker_->EnsureInitialized(self, h_class, true, true);
CHECK(initialized);
*receiver = c->AllocObject(self);
}
// Start runtime.
bool started = runtime_->Start();
CHECK(started);
self->TransitionFromSuspendedToRunnable();
}
void InvokeNopMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "nop", "()V");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), nullptr);
}
void InvokeIdentityByteMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "identity", "(B)B");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[1];
args[0].b = 0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(0, result.GetB());
args[0].b = -1;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-1, result.GetB());
args[0].b = SCHAR_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(SCHAR_MAX, result.GetB());
static_assert(SCHAR_MIN == -128, "SCHAR_MIN unexpected");
args[0].b = SCHAR_MIN;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(SCHAR_MIN, result.GetB());
}
void InvokeIdentityIntMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "identity", "(I)I");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[1];
args[0].i = 0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(0, result.GetI());
args[0].i = -1;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-1, result.GetI());
args[0].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(INT_MAX, result.GetI());
args[0].i = INT_MIN;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(INT_MIN, result.GetI());
}
void InvokeIdentityDoubleMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "identity", "(D)D");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[1];
args[0].d = 0.0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(0.0, result.GetD());
args[0].d = -1.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(-1.0, result.GetD());
args[0].d = DBL_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(DBL_MAX, result.GetD());
args[0].d = DBL_MIN;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(DBL_MIN, result.GetD());
}
void InvokeSumIntIntMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(II)I");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[2];
args[0].i = 1;
args[1].i = 2;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(3, result.GetI());
args[0].i = -2;
args[1].i = 5;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(3, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MIN;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-1, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-2, result.GetI());
}
void InvokeSumIntIntIntMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(III)I");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[3];
args[0].i = 0;
args[1].i = 0;
args[2].i = 0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(0, result.GetI());
args[0].i = 1;
args[1].i = 2;
args[2].i = 3;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(6, result.GetI());
args[0].i = -1;
args[1].i = 2;
args[2].i = -3;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-2, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MIN;
args[2].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(2147483646, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MAX;
args[2].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(2147483645, result.GetI());
}
void InvokeSumIntIntIntIntMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(IIII)I");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[4];
args[0].i = 0;
args[1].i = 0;
args[2].i = 0;
args[3].i = 0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(0, result.GetI());
args[0].i = 1;
args[1].i = 2;
args[2].i = 3;
args[3].i = 4;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(10, result.GetI());
args[0].i = -1;
args[1].i = 2;
args[2].i = -3;
args[3].i = 4;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(2, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MIN;
args[2].i = INT_MAX;
args[3].i = INT_MIN;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-2, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MAX;
args[2].i = INT_MAX;
args[3].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-4, result.GetI());
}
void InvokeSumIntIntIntIntIntMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(IIIII)I");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[5];
args[0].i = 0;
args[1].i = 0;
args[2].i = 0;
args[3].i = 0;
args[4].i = 0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(0, result.GetI());
args[0].i = 1;
args[1].i = 2;
args[2].i = 3;
args[3].i = 4;
args[4].i = 5;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(15, result.GetI());
args[0].i = -1;
args[1].i = 2;
args[2].i = -3;
args[3].i = 4;
args[4].i = -5;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(-3, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MIN;
args[2].i = INT_MAX;
args[3].i = INT_MIN;
args[4].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(2147483645, result.GetI());
args[0].i = INT_MAX;
args[1].i = INT_MAX;
args[2].i = INT_MAX;
args[3].i = INT_MAX;
args[4].i = INT_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_EQ(2147483643, result.GetI());
}
void InvokeSumDoubleDoubleMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DD)D");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[2];
args[0].d = 0.0;
args[1].d = 0.0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(0.0, result.GetD());
args[0].d = 1.0;
args[1].d = 2.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(3.0, result.GetD());
args[0].d = 1.0;
args[1].d = -2.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(-1.0, result.GetD());
args[0].d = DBL_MAX;
args[1].d = DBL_MIN;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(1.7976931348623157e308, result.GetD());
args[0].d = DBL_MAX;
args[1].d = DBL_MAX;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(INFINITY, result.GetD());
}
void InvokeSumDoubleDoubleDoubleMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DDD)D");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[3];
args[0].d = 0.0;
args[1].d = 0.0;
args[2].d = 0.0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(0.0, result.GetD());
args[0].d = 1.0;
args[1].d = 2.0;
args[2].d = 3.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(6.0, result.GetD());
args[0].d = 1.0;
args[1].d = -2.0;
args[2].d = 3.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(2.0, result.GetD());
}
void InvokeSumDoubleDoubleDoubleDoubleMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DDDD)D");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[4];
args[0].d = 0.0;
args[1].d = 0.0;
args[2].d = 0.0;
args[3].d = 0.0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(0.0, result.GetD());
args[0].d = 1.0;
args[1].d = 2.0;
args[2].d = 3.0;
args[3].d = 4.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(10.0, result.GetD());
args[0].d = 1.0;
args[1].d = -2.0;
args[2].d = 3.0;
args[3].d = -4.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(-2.0, result.GetD());
}
void InvokeSumDoubleDoubleDoubleDoubleDoubleMethod(bool is_static) {
ScopedObjectAccess soa(env_);
ArtMethod* method;
mirror::Object* receiver;
ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DDDDD)D");
ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver));
jvalue args[5];
args[0].d = 0.0;
args[1].d = 0.0;
args[2].d = 0.0;
args[3].d = 0.0;
args[4].d = 0.0;
JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(0.0, result.GetD());
args[0].d = 1.0;
args[1].d = 2.0;
args[2].d = 3.0;
args[3].d = 4.0;
args[4].d = 5.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(15.0, result.GetD());
args[0].d = 1.0;
args[1].d = -2.0;
args[2].d = 3.0;
args[3].d = -4.0;
args[4].d = 5.0;
result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args);
EXPECT_DOUBLE_EQ(3.0, result.GetD());
}
JavaVMExt* vm_;
JNIEnv* env_;
jclass aioobe_;
jclass ase_;
jclass sioobe_;
};
TEST_F(ReflectionTest, StaticMainMethod) {
TEST_DISABLED_FOR_READ_BARRIER_WITH_OPTIMIZING_FOR_UNSUPPORTED_INSTRUCTION_SETS();
ScopedObjectAccess soa(Thread::Current());
jobject jclass_loader = LoadDex("Main");
StackHandleScope<1> hs(soa.Self());
Handle<mirror::ClassLoader> class_loader(
hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader)));
CompileDirectMethod(class_loader, "Main", "main", "([Ljava/lang/String;)V");
mirror::Class* klass = class_linker_->FindClass(soa.Self(), "LMain;", class_loader);
ASSERT_TRUE(klass != nullptr);
ArtMethod* method = klass->FindDirectMethod("main", "([Ljava/lang/String;)V", sizeof(void*));
ASSERT_TRUE(method != nullptr);
// Start runtime.
bool started = runtime_->Start();
CHECK(started);
soa.Self()->TransitionFromSuspendedToRunnable();
jvalue args[1];
args[0].l = nullptr;
InvokeWithJValues(soa, nullptr, soa.EncodeMethod(method), args);
}
TEST_F(ReflectionTest, StaticNopMethod) {
InvokeNopMethod(true);
}
TEST_F(ReflectionTest, NonStaticNopMethod) {
InvokeNopMethod(false);
}
TEST_F(ReflectionTest, StaticIdentityByteMethod) {
InvokeIdentityByteMethod(true);
}
TEST_F(ReflectionTest, NonStaticIdentityByteMethod) {
InvokeIdentityByteMethod(false);
}
TEST_F(ReflectionTest, StaticIdentityIntMethod) {
InvokeIdentityIntMethod(true);
}
TEST_F(ReflectionTest, NonStaticIdentityIntMethod) {
InvokeIdentityIntMethod(false);
}
TEST_F(ReflectionTest, StaticIdentityDoubleMethod) {
InvokeIdentityDoubleMethod(true);
}
TEST_F(ReflectionTest, NonStaticIdentityDoubleMethod) {
InvokeIdentityDoubleMethod(false);
}
TEST_F(ReflectionTest, StaticSumIntIntMethod) {
InvokeSumIntIntMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumIntIntMethod) {
InvokeSumIntIntMethod(false);
}
TEST_F(ReflectionTest, StaticSumIntIntIntMethod) {
InvokeSumIntIntIntMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumIntIntIntMethod) {
InvokeSumIntIntIntMethod(false);
}
TEST_F(ReflectionTest, StaticSumIntIntIntIntMethod) {
InvokeSumIntIntIntIntMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumIntIntIntIntMethod) {
InvokeSumIntIntIntIntMethod(false);
}
TEST_F(ReflectionTest, StaticSumIntIntIntIntIntMethod) {
InvokeSumIntIntIntIntIntMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumIntIntIntIntIntMethod) {
InvokeSumIntIntIntIntIntMethod(false);
}
TEST_F(ReflectionTest, StaticSumDoubleDoubleMethod) {
InvokeSumDoubleDoubleMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumDoubleDoubleMethod) {
InvokeSumDoubleDoubleMethod(false);
}
TEST_F(ReflectionTest, StaticSumDoubleDoubleDoubleMethod) {
InvokeSumDoubleDoubleDoubleMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumDoubleDoubleDoubleMethod) {
InvokeSumDoubleDoubleDoubleMethod(false);
}
TEST_F(ReflectionTest, StaticSumDoubleDoubleDoubleDoubleMethod) {
InvokeSumDoubleDoubleDoubleDoubleMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumDoubleDoubleDoubleDoubleMethod) {
InvokeSumDoubleDoubleDoubleDoubleMethod(false);
}
TEST_F(ReflectionTest, StaticSumDoubleDoubleDoubleDoubleDoubleMethod) {
InvokeSumDoubleDoubleDoubleDoubleDoubleMethod(true);
}
TEST_F(ReflectionTest, NonStaticSumDoubleDoubleDoubleDoubleDoubleMethod) {
InvokeSumDoubleDoubleDoubleDoubleDoubleMethod(false);
}
} // namespace art
| android-art-intel/Nougat | art-extension/runtime/reflection_test.cc | C++ | apache-2.0 | 20,767 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.android.ddmlib;
import com.android.ddmlib.Log.LogLevel;
/**
* Preferences for the ddm library.
* <p/>This class does not handle storing the preferences. It is merely a central point for
* applications using the ddmlib to override the default values.
* <p/>Various components of the ddmlib query this class to get their values.
* <p/>Calls to some <code>set##()</code> methods will update the components using the values
* right away, while other methods will have no effect once {@link AndroidDebugBridge#init(boolean)}
* has been called.
* <p/>Check the documentation of each method.
*/
public final class DdmPreferences {
/** Default value for thread update flag upon client connection. */
public final static boolean DEFAULT_INITIAL_THREAD_UPDATE = false;
/** Default value for heap update flag upon client connection. */
public final static boolean DEFAULT_INITIAL_HEAP_UPDATE = false;
/** Default value for the selected client debug port */
public final static int DEFAULT_SELECTED_DEBUG_PORT = 8700;
/** Default value for the debug port base */
public final static int DEFAULT_DEBUG_PORT_BASE = 8600;
/** Default value for the logcat {@link LogLevel} */
public final static LogLevel DEFAULT_LOG_LEVEL = LogLevel.WARN;
/** Default timeout values for adb connection (milliseconds) */
public static final int DEFAULT_TIMEOUT = 5000; // standard delay, in ms
/** Default profiler buffer size (megabytes) */
public static final int DEFAULT_PROFILER_BUFFER_SIZE_MB = 8;
/** Default values for the use of the ADBHOST environment variable. */
public final static boolean DEFAULT_USE_ADBHOST = false;
public final static String DEFAULT_ADBHOST_VALUE = "127.0.0.1";
private static boolean sThreadUpdate = DEFAULT_INITIAL_THREAD_UPDATE;
private static boolean sInitialHeapUpdate = DEFAULT_INITIAL_HEAP_UPDATE;
private static int sSelectedDebugPort = DEFAULT_SELECTED_DEBUG_PORT;
private static int sDebugPortBase = DEFAULT_DEBUG_PORT_BASE;
private static LogLevel sLogLevel = DEFAULT_LOG_LEVEL;
private static int sTimeOut = DEFAULT_TIMEOUT;
private static int sProfilerBufferSizeMb = DEFAULT_PROFILER_BUFFER_SIZE_MB;
private static boolean sUseAdbHost = DEFAULT_USE_ADBHOST;
private static String sAdbHostValue = DEFAULT_ADBHOST_VALUE;
/**
* Returns the initial {@link Client} flag for thread updates.
* @see #setInitialThreadUpdate(boolean)
*/
public static boolean getInitialThreadUpdate() {
return sThreadUpdate;
}
/**
* Sets the initial {@link Client} flag for thread updates.
* <p/>This change takes effect right away, for newly created {@link Client} objects.
*/
public static void setInitialThreadUpdate(boolean state) {
sThreadUpdate = state;
}
/**
* Returns the initial {@link Client} flag for heap updates.
* @see #setInitialHeapUpdate(boolean)
*/
public static boolean getInitialHeapUpdate() {
return sInitialHeapUpdate;
}
/**
* Sets the initial {@link Client} flag for heap updates.
* <p/>If <code>true</code>, the {@link ClientData} will automatically be updated with
* the VM heap information whenever a GC happens.
* <p/>This change takes effect right away, for newly created {@link Client} objects.
*/
public static void setInitialHeapUpdate(boolean state) {
sInitialHeapUpdate = state;
}
/**
* Returns the debug port used by the selected {@link Client}.
*/
public static int getSelectedDebugPort() {
return sSelectedDebugPort;
}
/**
* Sets the debug port used by the selected {@link Client}.
* <p/>This change takes effect right away.
* @param port the new port to use.
*/
public static void setSelectedDebugPort(int port) {
sSelectedDebugPort = port;
MonitorThread monitorThread = MonitorThread.getInstance();
if (monitorThread != null) {
monitorThread.setDebugSelectedPort(port);
}
}
/**
* Returns the debug port used by the first {@link Client}. Following clients, will use the
* next port.
*/
public static int getDebugPortBase() {
return sDebugPortBase;
}
/**
* Sets the debug port used by the first {@link Client}.
* <p/>Once a port is used, the next Client will use port + 1. Quitting applications will
* release their debug port, and new clients will be able to reuse them.
* <p/>This must be called before {@link AndroidDebugBridge#init(boolean)}.
*/
public static void setDebugPortBase(int port) {
sDebugPortBase = port;
}
/**
* Returns the minimum {@link LogLevel} being displayed.
*/
public static LogLevel getLogLevel() {
return sLogLevel;
}
/**
* Sets the minimum {@link LogLevel} to display.
* <p/>This change takes effect right away.
*/
public static void setLogLevel(String value) {
sLogLevel = LogLevel.getByString(value);
Log.setLevel(sLogLevel);
}
/**
* Returns the timeout to be used in adb connections (milliseconds).
*/
public static int getTimeOut() {
return sTimeOut;
}
/**
* Sets the timeout value for adb connection.
* <p/>This change takes effect for newly created connections only.
* @param timeOut the timeout value (milliseconds).
*/
public static void setTimeOut(int timeOut) {
sTimeOut = timeOut;
}
/**
* Returns the profiler buffer size (megabytes).
*/
public static int getProfilerBufferSizeMb() {
return sProfilerBufferSizeMb;
}
/**
* Sets the profiler buffer size value.
* @param bufferSizeMb the buffer size (megabytes).
*/
public static void setProfilerBufferSizeMb(int bufferSizeMb) {
sProfilerBufferSizeMb = bufferSizeMb;
}
/**
* Returns a boolean indicating that the user uses or not the variable ADBHOST.
*/
public static boolean getUseAdbHost() {
return sUseAdbHost;
}
/**
* Sets the value of the boolean indicating that the user uses or not the variable ADBHOST.
* @param useAdbHost true if the user uses ADBHOST
*/
public static void setUseAdbHost(boolean useAdbHost) {
sUseAdbHost = useAdbHost;
}
/**
* Returns the value of the ADBHOST variable set by the user.
*/
public static String getAdbHostValue() {
return sAdbHostValue;
}
/**
* Sets the value of the ADBHOST variable.
* @param adbHostValue
*/
public static void setAdbHostValue(String adbHostValue) {
sAdbHostValue = adbHostValue;
}
/**
* Non accessible constructor.
*/
private DdmPreferences() {
// pass, only static methods in the class.
}
}
| 0359xiaodong/ControlAndroidDeviceFromPC | src/com/android/ddmlib/DdmPreferences.java | Java | apache-2.0 | 7,539 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Dns.Models;
using Microsoft.Azure.Management.Dns.Models;
using System;
using System.Collections.Generic;
using System.Management.Automation;
using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources;
namespace Microsoft.Azure.Commands.Dns
{
/// <summary>
/// Adds a record to a record set object.
/// </summary>
[Cmdlet(VerbsCommon.Add, "AzureRmDnsRecordConfig"), OutputType(typeof(DnsRecordSet))]
public class AddAzureDnsRecordConfig : DnsBaseCmdlet
{
[Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The record set in which to add the record.")]
[ValidateNotNullOrEmpty]
public DnsRecordSet RecordSet { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The IPv4 address for the A record to add.", ParameterSetName = "A")]
[ValidateNotNullOrEmpty]
public string Ipv4Address { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The IPv6 address for the AAAA record to add.", ParameterSetName = "AAAA")]
[ValidateNotNullOrEmpty]
public string Ipv6Address { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name server host for the NS record to add. Must not be relative to the name of the zone. Must not have a terminating dot", ParameterSetName = "NS")]
[ValidateNotNullOrEmpty]
public string Nsdname { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The mail exchange host for the MX record to add. Must not be relative to the name of the zone. Must not have a terminating dot", ParameterSetName = "MX")]
[ValidateNotNullOrEmpty]
public string Exchange { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The preference value for the MX record to add.", ParameterSetName = "MX")]
[ValidateNotNullOrEmpty]
public ushort Preference { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The target host for the PTR record to add. Must not be relative to the name of the zone. Must not have a terminating dot", ParameterSetName = "PTR")]
[ValidateNotNullOrEmpty]
public string Ptrdname { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The text value for the TXT record to add.", ParameterSetName = "TXT")]
[ValidateNotNullOrEmpty]
public string Value { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The priority value SRV record to add.", ParameterSetName = "SRV")]
[ValidateNotNullOrEmpty]
public ushort Priority { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The target host for the SRV record to add. Must not be relative to the name of the zone. Must not have a terminating dot", ParameterSetName = "SRV")]
[ValidateNotNullOrEmpty]
public string Target { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The port number for the SRV record to add.", ParameterSetName = "SRV")]
[ValidateNotNullOrEmpty]
public ushort Port { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The weight value for the SRV record to add.", ParameterSetName = "SRV")]
[ValidateNotNullOrEmpty]
public ushort Weight { get; set; }
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The canonical name for the CNAME record to add. Must not be relative to the name of the zone. Must not have a terminating dot", ParameterSetName = "CNAME")]
[ValidateNotNullOrEmpty]
public string Cname { get; set; }
public override void ExecuteCmdlet()
{
var result = this.RecordSet;
if (!string.Equals(this.ParameterSetName, this.RecordSet.RecordType.ToString(), StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(string.Format(ProjectResources.Error_AddRecordTypeMismatch, this.ParameterSetName, this.RecordSet.RecordType));
}
if (result.Records == null)
{
result.Records = new List<DnsRecordBase>();
}
switch (result.RecordType)
{
case RecordType.A:
{
result.Records.Add(new ARecord { Ipv4Address = this.Ipv4Address });
break;
}
case RecordType.AAAA:
{
result.Records.Add(new AaaaRecord { Ipv6Address = this.Ipv6Address });
break;
}
case RecordType.MX:
{
result.Records.Add(new MxRecord { Preference = this.Preference, Exchange = this.Exchange });
break;
}
case RecordType.NS:
{
result.Records.Add(new NsRecord { Nsdname = this.Nsdname });
break;
}
case RecordType.SRV:
{
result.Records.Add(new SrvRecord { Priority = this.Priority, Port = this.Port, Target = this.Target, Weight = this.Weight });
break;
}
case RecordType.TXT:
{
result.Records.Add(new TxtRecord { Value = this.Value });
break;
}
case RecordType.CNAME:
{
if (result.Records.Count == 0)
{
result.Records.Add(new CnameRecord { Cname = this.Cname });
}
else
{
throw new ArgumentException(ProjectResources.Error_AddRecordMultipleCnames);
}
break;
}
default:
{
break;
}
}
WriteVerbose(ProjectResources.Success_RecordAdded);
WriteObject(result);
}
}
}
| akurmi/azure-powershell | src/ResourceManager/Dns/Commands.Dns/Records/AddAzureDnsRecordConfig.cs | C# | apache-2.0 | 7,419 |
/**
* 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 com.huawei.streaming.cql.semanticanalyzer.analyzecontext;
import java.util.List;
import com.google.common.collect.Lists;
import com.huawei.streaming.api.streams.Schema;
import com.huawei.streaming.cql.exception.SemanticAnalyzerException;
/**
* insert语句语义分析内容
*
*/
public abstract class InsertOnlyAnalyzeContext extends AnalyzeContext
{
private String outputStreamName;
private Schema outputSchema;
private boolean isPipeStreamNotCreated = false;
/**
* {@inheritDoc}
*/
@Override
public void validateParseContext()
throws SemanticAnalyzerException
{
// TODO Auto-generated method stub
}
/**
* {@inheritDoc}
*/
@Override
public List<Schema> getCreatedSchemas()
{
List<Schema> schemas = Lists.newArrayList();
if (isPipeStreamNotCreated)
{
schemas.add(outputSchema);
}
return schemas;
}
public String getOutputStreamName()
{
return outputStreamName;
}
public void setOutputStreamName(String outputStreamName)
{
this.outputStreamName = outputStreamName;
}
public Schema getOutputSchema()
{
return outputSchema;
}
public void setOutputSchema(Schema outputSchema)
{
this.outputSchema = outputSchema;
}
public boolean isPipeStreamNotCreated()
{
return isPipeStreamNotCreated;
}
public void setPipeStreamNotCreated(boolean ispipeStreamNotCreated)
{
this.isPipeStreamNotCreated = ispipeStreamNotCreated;
}
}
| jack6215/StreamCQL | cql/src/main/java/com/huawei/streaming/cql/semanticanalyzer/analyzecontext/InsertOnlyAnalyzeContext.java | Java | apache-2.0 | 2,457 |
//
// ETSCalendar.h
// ETSMobile
//
// Created by Jean-Philippe Martin on 2014-03-31.
// Copyright (c) 2014 ApplETS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface ETSCalendar : NSManagedObject
@property (nonatomic, retain) NSString * course;
@property (nonatomic, retain) NSDate * end;
@property (nonatomic, retain) NSString * id;
@property (nonatomic, retain) NSString * room;
@property (nonatomic, retain) NSDate * start;
@property (nonatomic, retain) NSString * summary;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * session;
- (NSDate *)day;
- (nonnull NSDictionary<NSString*, id> *)dictionary;
@end
| krazdax5/ETSMobile-iOS | ETSMobile/ETSCalendar.h | C | apache-2.0 | 710 |
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.graphics.g3d.utils;
import java.util.Comparator;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
public class DefaultRenderableSorter implements RenderableSorter, Comparator<Renderable> {
private Camera camera;
private final Vector3 tmpV1 = new Vector3();
private final Vector3 tmpV2 = new Vector3();
@Override
public void sort (final Camera camera, final Array<Renderable> renderables) {
this.camera = camera;
renderables.sort(this);
}
@Override
public int compare (final Renderable o1, final Renderable o2) {
final boolean b1 = o1.material.has(BlendingAttribute.Type) ?
((BlendingAttribute)o1.material.get(BlendingAttribute.Type)).blended : false;
final boolean b2 = o2.material.has(BlendingAttribute.Type) ?
((BlendingAttribute)o2.material.get(BlendingAttribute.Type)).blended : false;
if (b1 != b2)
return b1 ? 1 : -1;
// FIXME implement better sorting algorithm
// final boolean same = o1.shader == o2.shader && o1.mesh == o2.mesh && (o1.lights == null) == (o2.lights == null) &&
// o1.material.equals(o2.material);
o1.worldTransform.getTranslation(tmpV1);
o2.worldTransform.getTranslation(tmpV2);
final float dst = camera.position.dst2(tmpV1) - camera.position.dst2(tmpV2);
final int result = dst < 0f ? -1 : (dst > 0f ? 1 : 0);
return b1 ? -result : result;
}
} | ryoenji/libgdx | gdx/src/com/badlogic/gdx/graphics/g3d/utils/DefaultRenderableSorter.java | Java | apache-2.0 | 2,304 |
/**
* TypeScript global declarations go here
*/
declare global {
// Defined in es2017 but most major browsers support it
interface String {
padStart(width: number, pad: string): string
}
}
export { } | DanielJoyce/microtome | src/lib/globals.d.ts | TypeScript | apache-2.0 | 213 |
package com.jivesoftware.os.miru.stream.plugins.catwalk;
import com.google.common.base.Optional;
import com.jivesoftware.os.miru.api.MiruHost;
import com.jivesoftware.os.miru.api.MiruQueryServiceException;
import com.jivesoftware.os.miru.api.activity.MiruPartitionId;
import com.jivesoftware.os.miru.catwalk.shared.CatwalkQuery;
import com.jivesoftware.os.miru.plugin.solution.MiruPartitionResponse;
import com.jivesoftware.os.miru.plugin.solution.MiruRemotePartition;
import com.jivesoftware.os.miru.plugin.solution.MiruRemotePartitionReader;
import com.jivesoftware.os.miru.plugin.solution.MiruRequest;
import com.jivesoftware.os.mlogger.core.EndPointMetrics;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
/**
*
*/
public class CatwalkRemotePartition implements MiruRemotePartition<CatwalkQuery, CatwalkAnswer, CatwalkReport> {
private static final MetricLogger LOG = MetricLoggerFactory.getLogger();
private static final EndPointMetrics endPointMetrics = new EndPointMetrics("process", LOG);
private final MiruRemotePartitionReader remotePartitionReader;
public CatwalkRemotePartition(MiruRemotePartitionReader remotePartitionReader) {
this.remotePartitionReader = remotePartitionReader;
}
private String getEndpoint(MiruPartitionId partitionId) {
return CatwalkConstants.CATWALK_PREFIX + CatwalkConstants.CUSTOM_QUERY_ENDPOINT + "/" + partitionId.getId();
}
@Override
public MiruPartitionResponse<CatwalkAnswer> askRemote(MiruHost host,
MiruPartitionId partitionId,
MiruRequest<CatwalkQuery> request,
Optional<CatwalkReport> report) throws MiruQueryServiceException {
return remotePartitionReader.read("catwalk",
host,
getEndpoint(partitionId),
request,
CatwalkAnswer.class,
report,
endPointMetrics,
CatwalkAnswer.EMPTY_RESULTS);
}
}
| jivesoftware/miru | miru-stream-plugins/src/main/java/com/jivesoftware/os/miru/stream/plugins/catwalk/CatwalkRemotePartition.java | Java | apache-2.0 | 1,988 |
/**
* Copyright (c) Istituto Nazionale di Fisica Nucleare, 2006-2014.
*
* 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.italiangrid.voms.error;
import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* A VOMS validation error message class (freely inspired by the CANL validation
* error message class).
*
* @author Andrea Ceccanti
*
*/
public class VOMSValidationErrorMessage {
static final String ERROR_BUNDLE = VOMSValidationErrorMessage.class
.getPackage().getName() + "." + "validationErrors";
private VOMSValidationErrorCode errorCode;
private String message;
private Object[] parameters;
public static VOMSValidationErrorMessage newErrorMessage(
VOMSValidationErrorCode errorCode) {
return new VOMSValidationErrorMessage(errorCode);
}
public static VOMSValidationErrorMessage newErrorMessage(
VOMSValidationErrorCode errorCode, Object... params) {
return new VOMSValidationErrorMessage(errorCode, params);
}
private VOMSValidationErrorMessage(VOMSValidationErrorCode errorCode) {
this(errorCode, (Object[]) null);
}
private VOMSValidationErrorMessage(VOMSValidationErrorCode errorCode,
Object... params) {
this.errorCode = errorCode;
this.parameters = params;
ResourceBundle bundle = ResourceBundle.getBundle(ERROR_BUNDLE);
String template = null;
try {
template = bundle.getString(errorCode.name());
} catch (MissingResourceException e) {
template = "Other error";
}
message = MessageFormat.format(template, parameters);
}
public VOMSValidationErrorCode getErrorCode() {
return errorCode;
}
public String getMessage() {
return message;
}
public Object[] getParameters() {
return parameters;
}
@Override
public String toString() {
return String.format("[%s]:%s", errorCode.name(), message);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((errorCode == null) ? 0 : errorCode.hashCode());
result = prime * result + ((message == null) ? 0 : message.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
VOMSValidationErrorMessage other = (VOMSValidationErrorMessage) obj;
if (errorCode != other.errorCode)
return false;
if (message == null) {
if (other.message != null)
return false;
} else if (!message.equals(other.message))
return false;
return true;
}
}
| ellert/voms-api-java | src/main/java/org/italiangrid/voms/error/VOMSValidationErrorMessage.java | Java | apache-2.0 | 3,203 |
{js:kindeditor}
{js:my97date}
{set:$swfloadObject = new Swfupload('/seller/goods_img_upload');$swfloadObject->show($this->seller['seller_name'],$this->seller['seller_pwd']);}
{set:$seller_id = $this->seller['seller_id']}
<article class="module width_full">
<header>
<h3 class="tabs_involved">商品编辑</h3>
<ul class="tabs" name="menu1">
<li id="li_1" class="active"><a href="javascript:select_tab('1');">商品信息</a></li>
<li id="li_2"><a href="javascript:select_tab('2');">描述</a></li>
<li id="li_3"><a href="javascript:select_tab('3');">SEO优化</a></li>
</ul>
</header>
<form action="{url:/seller/goods_update}" name="goodsForm" method="post">
<input type="hidden" name="id" value="" />
<input type='hidden' name="img" value="" />
<input type='hidden' name="_imgList" value="" />
<input type='hidden' name="callback" value="{echo:IUrl::getRefRoute()}" />
<!--商品信息 开始-->
<div class="module_content" id="table_box_1">
<fieldset>
<label>商品名称</label>
<input name="name" type="text" value="" initmsg="商品名称填写正确" pattern="required" alt="商品名称不能为空" onblur="wordsPart()" />
</fieldset>
<fieldset>
<label>关键词</label>
<input type='text' name='search_words' value='' />
<label class="tip">每个关键词最长为15个字符,超过后系统不予存储,每个词以逗号分隔</label>
</fieldset>
<fieldset>
<label>所属分类</label>
{if:isset($this->category) && $this->category}
<ul class="select">
{foreach:items=$this->category}
<li><input type="checkbox" value="{$item['id']}" name="_goods_category[]" />{$item['name']}</li>
{/foreach}
</ul>
{else:}
<label class="tip">系统暂无商品分类</label>
{/if}
</fieldset>
<fieldset>
<label>商品排序</label>
<input name="sort" type="text" pattern="int" value="99" />
</fieldset>
<fieldset>
<label>计量单位显示</label>
<input name="unit" type="text" value="千克"/>
</fieldset>
<fieldset>
<label>基本数据</label>
<table class="tablesorter clear">
<thead id="goodsBaseHead"></thead>
<tbody id="goodsBaseBody"></tbody>
<!--商品标题模板-->
<script id="goodsHeadTemplate" type='text/html'>
<tr>
<th>商品货号</th>
<%var isProduct = false;%>
<%for(var item in templateData){%>
<%isProduct = true;%>
<th><%=templateData[item]['name']%></th>
<%}%>
<th>库存</th>
<th>市场价格</th>
<th>销售价格</th>
<th>成本价格</th>
<th>重量(克)</th>
<%if(isProduct == true){%>
<th>操作</th>
<%}%>
</tr>
</script>
<!--商品内容模板-->
<script id="goodsRowTemplate" type="text/html">
<%var i=0;%>
<%for(var item in templateData){%>
<%item = templateData[item]%>
<tr>
<td><input class="small" name="_goods_no[<%=i%>]" pattern="required" type="text" value="<%=item['goods_no'] ? item['goods_no'] : item['products_no']%>" /></td>
<%var isProduct = false;%>
<%var specArrayList = parseJSON(item['spec_array'])%>
<%for(var result in specArrayList){%>
<%result = specArrayList[result]%>
<input type='hidden' name="_spec_array[<%=i%>][]" value='{"id":"<%=result.id%>","type":"<%=result.type%>","value":"<%=result.value%>","name":"<%=result.name%>"}' />
<%isProduct = true;%>
<td>
<%if(result['type'] == 1){%>
<%=result['value']%>
<%}else{%>
<img class="img_border" width="30px" height="30px" src="{webroot:<%=result['value']%>}">
<%}%>
</td>
<%}%>
<td><input class="tiny" name="_store_nums[<%=i%>]" type="text" pattern="int" value="<%=item['store_nums']?item['store_nums']:100%>" /></td>
<td><input class="tiny" name="_market_price[<%=i%>]" type="text" pattern="float" value="<%=item['market_price']%>" /></td>
<td><input class="tiny" name="_sell_price[<%=i%>]" type="text" pattern="float" value="<%=item['sell_price']%>" /></td>
<td><input class="tiny" name="_cost_price[<%=i%>]" type="text" pattern="float" empty value="<%=item['cost_price']%>" /></td>
<td><input class="tiny" name="_weight[<%=i%>]" type="text" pattern="float" empty value="<%=item['weight']%>" /></td>
<%if(isProduct == true){%>
<td><a href="javascript:void(0)" onclick="delProduct(this);"><img src="{skin:images/main/icn_trash.png}" alt="删除" /></a></td>
<%}%>
</tr>
<%i++;%>
<%}%>
</script>
</table>
</fieldset>
<fieldset>
<label>规格</label>
<div class="box">
<input type="button" onclick="selSpec()" value="添加规格" />
</div>
</fieldset>
<fieldset>
<label>商品模型</label>
<select name="model_id" onchange="create_attr(this.value)">
<option value="0">通用类型 </option>
{query:name=model}
<option value="{$item['id']}">{$item['name']}</option>
{/query}
</select>
</fieldset>
<fieldset id="properties" style="display:none">
<label>扩展属性</label>
<table class="tablesorter clear" id="propert_table">
</table>
<!--商品属性模板 开始-->
<script type='text/html' id='propertiesTemplate'>
<%for(var item in templateData){%>
<%item = templateData[item]%>
<%var valueItems = item['value'].split(',');%>
<tr>
<td>
<%=item["name"]%>:
<%if(item['type'] == 1){%>
<%for(var tempVal in valueItems){%>
<%tempVal = valueItems[tempVal]%>
<input type="radio" name="attr_id_<%=item['id']%>" value="<%=tempVal%>" /><%=tempVal%>
<%}%>
<%}else if(item['type'] == 2){%>
<%for(var tempVal in valueItems){%>
<%tempVal = valueItems[tempVal]%>
<input type="checkbox" name="attr_id_<%=item['id']%>[]" value="<%=tempVal%>"/><%=tempVal%>
<%}%>
<%}else if(item['type'] == 3){%>
<select name="attr_id_<%=item['id']%>">
<%for(var tempVal in valueItems){%>
<%tempVal = valueItems[tempVal]%>
<option value="<%=tempVal%>"><%=tempVal%></option>
<%}%>
</select>
<%}else if(item['type'] == 4){%>
<input type="text" name="attr_id_<%=item['id']%>" value="<%=item['value']%>" class="small" />
<%}%>
</td>
</tr>
<%}%>
</script>
<!--商品属性模板 结束-->
</fieldset>
<fieldset>
<label>商品品牌</label>
<select name="brand_id">
<option value="0">请选择</option>
{query:name=brand}
<option value="{$item['id']}">{$item['name']}</option>
{/query}
</select>
</fieldset>
<fieldset>
<label>商品状态</label>
<div class="box">
<input type='radio' name='is_del' value='3' checked="checked" />申请上架
<input type='radio' name='is_del' value='2' />下架
</div>
</fieldset>
<fieldset>
<label>产品相册</label>
<div class="box upload_btn">
<span id='uploadButton'></span>
</div>
<label class="tip">可以上传多张图片,分辨率3000px以下,大小不得超过{echo:IUpload::getMaxSize()}</label>
<div class="box" id="divFileProgressContainer" style="margin-bottom:10px;"></div>
<div class="box" id="thumbnails"></div>
<!--图片模板-->
<script type='text/html' id='picTemplate'>
<span class='pic'>
<img onclick="defaultImage(this);" style="margin:5px; opacity:1;width:100px;height:100px" src="{webroot:<%=picRoot%>}" alt="<%=picRoot%>" /><br />
<a href='javascript:void(0)' onclick="$(this).parent().remove();">删除</a>
</span>
</script>
</fieldset>
</div>
<!--商品信息 结束-->
<!--商品描述 开始-->
<div class="module_content" id="table_box_2" style="display:none;">
<fieldset>
<label>详情采集:</label>
<div class="box">
<input type='text' id='collectUrl' class='large' />
<select id="collectType" class="auto">
<option value="">请选择采集器</option>
<option value="jd">京东</option>
<option value="taobao">淘宝</option>
</select>
<input type="button" value="开始采集" onclick='collectAct();' />
<label class="tip">部分详细资料属于异步加载,必须在前台页面可以正常显示</label>
</div>
</fieldset>
<fieldset>
<label>产品描述</label>
<div class="clear" style="width:98%;margin:10px 10px;">
<textarea id="content" name="content" style="width:100%;height:400px;"></textarea>
</div>
</fieldset>
</div>
<!--商品描述 结束-->
<!--SEO 开始-->
<div class="module_content" id="table_box_3" style="display:none;">
<fieldset>
<label>SEO关键词</label>
<input name="keywords" type="text" value="" />
</fieldset>
<fieldset>
<label>SEO描述</label>
<textarea name="description" style="height:200px;"></textarea>
</fieldset>
</div>
<!--SEO 结束-->
<footer>
<div class="submit_link">
<input type="submit" class="alt_btn" value="确 定" onclick="return checkForm()" />
<input type="reset" value="重 置" />
</div>
</footer>
</form>
</article>
<script language="javascript">
//创建表单实例
var formObj = new Form('goodsForm');
//默认货号
var defaultProductNo = '{echo:goods_class::createGoodsNo()}';
$(function()
{
initProductTable();
//存在商品信息
{if:isset($form)}
var goods = {echo:JSON::encode($form)};
var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':[goods]});
$('#goodsBaseBody').html(goodsRowHtml);
formObj.init(goods);
//模型选择
$('[name="model_id"]').change();
{else:}
$('[name="_goods_no[0]"]').val(defaultProductNo);
{/if}
//存在货品信息,进行数据填充
{if:isset($product)}
var spec_array = {echo:$product[0]['spec_array']};
var product = {echo:JSON::encode($product)};
var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':spec_array});
$('#goodsBaseHead').html(goodsHeadHtml);
var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':product});
$('#goodsBaseBody').html(goodsRowHtml);
{/if}
//商品分类回填
{if:isset($goods_category)}
formObj.setValue('_goods_category[]',"{echo:join(';',$goods_category)}");
{/if}
//商品图片的回填
{if:isset($goods_photo)}
var goodsPhoto = {echo:JSON::encode($goods_photo)};
for(var item in goodsPhoto)
{
var picHtml = template.render('picTemplate',{'picRoot':goodsPhoto[item].img});
$('#thumbnails').append(picHtml);
}
{/if}
//商品默认图片
{if:isset($form['img']) && $form['img']}
$('#thumbnails img[alt="{echo:$form['img']}"]').addClass('current');
{/if}
//编辑器载入
KindEditorObj = KindEditor.create('#content',{"filterMode":false});
});
//初始化货品表格
function initProductTable()
{
//默认产生一条商品标题空挡
var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':[]});
$('#goodsBaseHead').html(goodsHeadHtml);
//默认产生一条商品空挡
var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':[[]]});
$('#goodsBaseBody').html(goodsRowHtml);
}
//删除货品
function delProduct(_self)
{
$(_self).parent().parent().remove();
if($('#goodsBaseBody tr').length == 0)
{
initProductTable();
}
}
//提交表单前的检查
function checkForm()
{
//整理商品图片
var goodsPhoto = [];
$('#thumbnails img').each(function(){
goodsPhoto.push(this.alt);
});
if(goodsPhoto.length > 0)
{
$('input[name="_imgList"]').val(goodsPhoto.join(','));
$('input[name="img"]').val($('#thumbnails img[class="current"]').attr('alt'));
}
return true;
}
//tab标签切换
function select_tab(curr_tab)
{
$("form[name='goodsForm'] > div").hide();
$("#table_box_"+curr_tab).show();
$("ul[name=menu1] > li").removeClass('active');
$('#li_'+curr_tab).addClass('active');
}
//添加规格
function selSpec()
{
//货品是否已经存在
if($('input:hidden[name^="_spec_array"]').length > 0)
{
alert('当前货品已经存在,无法进行规格设置。<p>如果需要重新设置规格请您手动删除当前货品</p>');
return;
}
var tempUrl = '{url:/goods/search_spec/model_id/@model_id@/goods_id/@goods_id@/seller_id/$seller_id}';
var model_id = $('[name="model_id"]').val();
var goods_id = $('[name="id"]').val();
tempUrl = tempUrl.replace('@model_id@',model_id);
tempUrl = tempUrl.replace('@goods_id@',goods_id);
art.dialog.open(tempUrl,{
title:'设置商品的规格',
okVal:'保存',
ok:function(iframeWin, topWin)
{
//添加的规格
var addSpecObject = $(iframeWin.document).find('[id^="vertical_"]');
if(addSpecObject.length == 0)
{
initProductTable();
return;
}
//开始遍历规格
var specValueData = {};
var specData = {};
addSpecObject.each(function()
{
$(this).find('input:hidden[name="specJson"]').each(function()
{
var json = $.parseJSON(this.value);
if(!specValueData[json.id])
{
specData[json.id] = {'id':json.id,'name':json.name,'type':json.type};
specValueData[json.id] = [];
}
specValueData[json.id].push(json['value']);
});
});
//生成货品的笛卡尔积
var specMaxData = descartes(specValueData,specData);
//从表单中获取默认商品数据
var productJson = {};
$('#goodsBaseBody tr:first').find('input[type="text"]').each(function(){
productJson[this.name.replace(/^_(\w+)\[\d+\]/g,"$1")] = this.value;
});
//生成最终的货品数据
var productList = [];
for(var i = 0;i < specMaxData.length;i++)
{
var productItem = {};
for(var index in productJson)
{
//自动组建货品号
if(index == 'goods_no')
{
//值为空时设置默认货号
if(productJson[index] == '')
{
productJson[index] = defaultProductNo;
}
if(productJson[index].match(/(?:\-\d*)$/) == null)
{
//正常货号生成
productItem['goods_no'] = productJson[index]+'-'+(i+1);
}
else
{
//货号已经存在则替换
productItem['goods_no'] = productJson[index].replace(/(?:\-\d*)$/,'-'+(i+1));
}
}
else
{
productItem[index] = productJson[index];
}
}
productItem['spec_array'] = specMaxData[i];
productList.push(productItem);
}
//创建规格标题
var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':specData});
$('#goodsBaseHead').html(goodsHeadHtml);
//创建货品数据表格
var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':productList});
$('#goodsBaseBody').html(goodsRowHtml);
}
});
}
//笛卡儿积组合
function descartes(list,specData)
{
//parent上一级索引;count指针计数
var point = {};
var result = [];
var pIndex = null;
var tempCount = 0;
var temp = [];
//根据参数列生成指针对象
for(var index in list)
{
if(typeof list[index] == 'object')
{
point[index] = {'parent':pIndex,'count':0}
pIndex = index;
}
}
//单维度数据结构直接返回
if(pIndex == null)
{
return list;
}
//动态生成笛卡尔积
while(true)
{
for(var index in list)
{
tempCount = point[index]['count'];
temp.push({"id":specData[index].id,"type":specData[index].type,"name":specData[index].name,"value":list[index][tempCount]});
}
//压入结果数组
result.push(temp);
temp = [];
//检查指针最大值问题
while(true)
{
if(point[index]['count']+1 >= list[index].length)
{
point[index]['count'] = 0;
pIndex = point[index]['parent'];
if(pIndex == null)
{
return result;
}
//赋值parent进行再次检查
index = pIndex;
}
else
{
point[index]['count']++;
break;
}
}
}
}
//根据模型动态生成扩展属性
function create_attr(model_id)
{
$.getJSON("{url:/block/attribute_init}",{'model_id':model_id}, function(json)
{
if(json && json.length > 0)
{
var templateHtml = template.render('propertiesTemplate',{'templateData':json});
$('#propert_table').html(templateHtml);
$('#properties').show();
//表单回填设置项
{if:isset($goods_attr)}
{set:$attrArray = array();}
{foreach:items = $goods_attr}
{set:$valArray = explode(',',$item);}
{set:$attrArray[] = '"attr_id_'.$key.'[]":"'.join(";",$valArray).'"'}
{set:$attrArray[] = '"attr_id_'.$key.'":"'.join(";",$valArray).'"'}
{/foreach}
formObj.init({{echo:join(',',$attrArray)}});
{/if}
}
else
{
$('#properties').hide();
}
});
}
/**
* 图片上传回调,handers.js回调
* @param picJson => {'flag','img','list','show'}
*/
function uploadPicCallback(picJson)
{
var picHtml = template.render('picTemplate',{'picRoot':picJson.img});
$('#thumbnails').append(picHtml);
//默认设置第一个为默认图片
if($('#thumbnails img[class="current"]').length == 0)
{
$('#thumbnails img:first').addClass('current');
}
}
/**
* 设置商品默认图片
*/
function defaultImage(_self)
{
$('#thumbnails img').removeClass('current');
$(_self).addClass('current');
}
/**
*分解名称关键词
*/
function wordsPart(){
var goodsName = $('input[name="name"]').val();
if(goodsName)
{
$.getJSON("{url:/goods/goods_tags_words}",{"content":goodsName},function(json)
{
if(json.result == 'success')
{
$('input[name="search_words"]').val(json.data);
}
});
}
}
//开始采集商品详情
function collectAct()
{
var collectType = $('#collectType').val();
var collectUrl = $('#collectUrl').val();
if(!collectType || !collectUrl)
{
alert("请选择采集器并且填写完整的商品详情页URL网址");
return;
}
$.getJSON("{url:/goods/collect_goods_detail}",{"collectType":collectType,"collectUrl":collectUrl},function(json)
{
if(json.result == 'success')
{
KindEditorObj.html(json.data);
KindEditorObj.sync();
}
else
{
alert(json.msg);
}
});
}
</script>
| yangxt/shop | views/sysseller/seller/goods_edit.html | HTML | apache-2.0 | 17,976 |
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/**
* Check that setting a breakpoint in a line without code in the second child
* script will skip forward.
*/
var gDebuggee;
var gClient;
var gThreadClient;
function run_test()
{
initTestDebuggerServer();
gDebuggee = addTestGlobal("test-stack");
gClient = new DebuggerClient(DebuggerServer.connectPipe());
gClient.connect(function () {
attachTestGlobalClientAndResume(gClient,
"test-stack",
function (aResponse, aThreadClient) {
gThreadClient = aThreadClient;
test_second_child_skip_breakpoint();
});
});
do_test_pending();
}
function test_second_child_skip_breakpoint()
{
gThreadClient.addOneTimeListener("paused", function (aEvent, aPacket) {
let path = getFilePath('test_breakpoint-07.js');
let location = { url: path, line: gDebuggee.line0 + 6};
gThreadClient.setBreakpoint(location, function (aResponse, bpClient) {
// Check that the breakpoint has properly skipped forward one line.
do_check_eq(aResponse.actualLocation.url, location.url);
do_check_eq(aResponse.actualLocation.line, location.line + 1);
gThreadClient.addOneTimeListener("paused", function (aEvent, aPacket) {
// Check the return value.
do_check_eq(aPacket.type, "paused");
do_check_eq(aPacket.frame.where.url, path);
do_check_eq(aPacket.frame.where.line, location.line + 1);
do_check_eq(aPacket.why.type, "breakpoint");
do_check_eq(aPacket.why.actors[0], bpClient.actor);
// Check that the breakpoint worked.
do_check_eq(gDebuggee.a, 1);
do_check_eq(gDebuggee.b, undefined);
// Remove the breakpoint.
bpClient.remove(function (aResponse) {
gThreadClient.resume(function () {
finishClient(gClient);
});
});
});
// Continue until the breakpoint is hit.
gThreadClient.resume();
});
});
gDebuggee.eval("var line0 = Error().lineNumber;\n" +
"function foo() {\n" + // line0 + 1
" bar();\n" + // line0 + 2
"}\n" + // line0 + 3
"function bar() {\n" + // line0 + 4
" this.a = 1;\n" + // line0 + 5
" // A comment.\n" + // line0 + 6
" this.b = 2;\n" + // line0 + 7
"}\n" + // line0 + 8
"debugger;\n" + // line0 + 9
"foo();\n"); // line0 + 10
}
| wilebeast/FireFox-OS | B2G/gecko/toolkit/devtools/debugger/tests/unit/test_breakpoint-07.js | JavaScript | apache-2.0 | 2,659 |
<!--
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.
-->
<!DOCTYPE html>
<html>
<head>
<style>
body { margin: 0; width:100%%; height:100%%; }
html { width:100%%; height:100%%; }
.embed-container {
position: relative;
padding-bottom: 56.25%%; /* 16/9 ratio */
height: 0;
overflow: hidden;
}
.embed-container iframe,
.embed-container object,
.embed-container embed {
position: absolute;
top: 0;
left: 0;
width: 100%% !important;
height: 100%% !important;
}
</style>
</head>
<body>
<div class="embed-container">
<div id="player"></div>
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
var error = false;
YT.ready(function() {
player = new YT.Player('player', %@);
player.setSize(window.innerWidth, window.innerHeight);
window.location.href = 'ytplayer://onYouTubeIframeAPIReady';
});
function onReady(event) {
player.paused = false;
player.interrupted = false;
player.oldPlayVideo = player.playVideo;
player.playVideo = function() {
this.paused = false;
this.interrupted = false;
this.oldPlayVideo();
}
player.oldPauseVideo = player.pauseVideo;
player.pauseVideo = function() {
this.paused = true;
this.interrupted = false;
this.oldPauseVideo();
}
player.oldStopVideo = player.stopVideo;
player.stopVideo = function() {
// This has to be done on some other place, because if replay is on, it won't work
this.paused = false;
this.interrupted = false;
this.oldStopVideo();
}
player.oldClearVideo = player.clearVideo;
player.clearVideo = function() {
this.paused = false;
this.interrupted = false;
this.oldClearVideo();
}
function forcePlay() {
if (player.interrupted) {
player.oldPlayVideo();
window.location.href = 'ytplayer://onStateChange?data=' + YT.PlayerState.PLAYING;
}
}
window.setInterval(forcePlay, 5000);
window.location.href = 'ytplayer://onReady?data=' + event.data;
}
function onStateChange(event) {
if (!error) {
// Send notification for all states but Paused and for Paused if the user did pause.
if (event.data != YT.PlayerState.PAUSED) {
// The player state has changed and obviously it is not interrupted.
// Notify the delegate that the state changed.
player.interrupted = false;
window.location.href = 'ytplayer://onStateChange?data=' + event.data;
} else {
if (player.paused == true){
// User has paused. Notify the delegate that the state changed.
window.location.href = 'ytplayer://onStateChange?data=' + event.data;
}
else {
// Youtube player API tried to pause internaly, do not pause.
player.interrupted = true;
}
}
}
else {
error = false;
}
}
function onPlaybackQualityChange(event) {
window.location.href = 'ytplayer://onPlaybackQualityChange?data=' + event.data;
}
function onPlayerError(event) {
if (event.data == 100) {
error = true;
}
window.location.href = 'ytplayer://onError?data=' + event.data;
}
window.onresize = function() {
player.setSize(window.innerWidth, window.innerHeight);
}
</script>
</body>
</html>
| TomGrill/robovm-ios-bindings | youtube-player-helper/resources/YTPlayerView-iframe-player.html | HTML | apache-2.0 | 4,379 |
<?php
/*
* Copyright 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.
*/
namespace Google\Service\Dialogflow;
class GoogleCloudDialogflowCxV3beta1Page extends \Google\Collection
{
protected $collection_key = 'transitionRoutes';
/**
* @var string
*/
public $displayName;
protected $entryFulfillmentType = GoogleCloudDialogflowCxV3beta1Fulfillment::class;
protected $entryFulfillmentDataType = '';
protected $eventHandlersType = GoogleCloudDialogflowCxV3beta1EventHandler::class;
protected $eventHandlersDataType = 'array';
protected $formType = GoogleCloudDialogflowCxV3beta1Form::class;
protected $formDataType = '';
/**
* @var string
*/
public $name;
/**
* @var string[]
*/
public $transitionRouteGroups;
protected $transitionRoutesType = GoogleCloudDialogflowCxV3beta1TransitionRoute::class;
protected $transitionRoutesDataType = 'array';
/**
* @param string
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* @return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* @param GoogleCloudDialogflowCxV3beta1Fulfillment
*/
public function setEntryFulfillment(GoogleCloudDialogflowCxV3beta1Fulfillment $entryFulfillment)
{
$this->entryFulfillment = $entryFulfillment;
}
/**
* @return GoogleCloudDialogflowCxV3beta1Fulfillment
*/
public function getEntryFulfillment()
{
return $this->entryFulfillment;
}
/**
* @param GoogleCloudDialogflowCxV3beta1EventHandler[]
*/
public function setEventHandlers($eventHandlers)
{
$this->eventHandlers = $eventHandlers;
}
/**
* @return GoogleCloudDialogflowCxV3beta1EventHandler[]
*/
public function getEventHandlers()
{
return $this->eventHandlers;
}
/**
* @param GoogleCloudDialogflowCxV3beta1Form
*/
public function setForm(GoogleCloudDialogflowCxV3beta1Form $form)
{
$this->form = $form;
}
/**
* @return GoogleCloudDialogflowCxV3beta1Form
*/
public function getForm()
{
return $this->form;
}
/**
* @param string
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string[]
*/
public function setTransitionRouteGroups($transitionRouteGroups)
{
$this->transitionRouteGroups = $transitionRouteGroups;
}
/**
* @return string[]
*/
public function getTransitionRouteGroups()
{
return $this->transitionRouteGroups;
}
/**
* @param GoogleCloudDialogflowCxV3beta1TransitionRoute[]
*/
public function setTransitionRoutes($transitionRoutes)
{
$this->transitionRoutes = $transitionRoutes;
}
/**
* @return GoogleCloudDialogflowCxV3beta1TransitionRoute[]
*/
public function getTransitionRoutes()
{
return $this->transitionRoutes;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDialogflowCxV3beta1Page::class, 'Google_Service_Dialogflow_GoogleCloudDialogflowCxV3beta1Page');
| googleapis/google-api-php-client-services | src/Dialogflow/GoogleCloudDialogflowCxV3beta1Page.php | PHP | apache-2.0 | 3,651 |
/*
* 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.camel.component.avro.springboot;
import javax.annotation.Generated;
import org.apache.avro.Protocol;
import org.apache.camel.component.avro.AvroTransport;
import org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Working with Apache Avro for data serialization.
*
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@ConfigurationProperties(prefix = "camel.component.avro")
public class AvroComponentConfiguration
extends
ComponentConfigurationPropertiesCommon {
/**
* Whether to enable auto configuration of the avro component. This is
* enabled by default.
*/
private Boolean enabled;
/**
* To use a shared AvroConfiguration to configure options once
*/
private AvroConfigurationNestedConfiguration configuration;
/**
* Whether the component should resolve property placeholders on itself when
* starting. Only properties which are of String type can use property
* placeholders.
*/
private Boolean resolvePropertyPlaceholders = true;
/**
* Whether the component should use basic property binding (Camel 2.x) or
* the newer property binding with additional capabilities
*/
private Boolean basicPropertyBinding = false;
public AvroConfigurationNestedConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(
AvroConfigurationNestedConfiguration configuration) {
this.configuration = configuration;
}
public Boolean getResolvePropertyPlaceholders() {
return resolvePropertyPlaceholders;
}
public void setResolvePropertyPlaceholders(
Boolean resolvePropertyPlaceholders) {
this.resolvePropertyPlaceholders = resolvePropertyPlaceholders;
}
public Boolean getBasicPropertyBinding() {
return basicPropertyBinding;
}
public void setBasicPropertyBinding(Boolean basicPropertyBinding) {
this.basicPropertyBinding = basicPropertyBinding;
}
public static class AvroConfigurationNestedConfiguration {
public static final Class CAMEL_NESTED_CLASS = org.apache.camel.component.avro.AvroConfiguration.class;
/**
* Hostname to use
*/
private String host;
/**
* Port number to use
*/
private Integer port;
/**
* Avro protocol to use
*/
private Protocol protocol;
/**
* Transport to use, can be either http or netty
*/
private AvroTransport transport;
/**
* Avro protocol location
*/
private String protocolLocation;
/**
* Avro protocol to use defined by the FQN class name
*/
private String protocolClassName;
/**
* The name of the message to send.
*/
private String messageName;
/**
* Authority to use (username and password)
*/
private String uriAuthority;
/**
* If protocol object provided is reflection protocol. Should be used
* only with protocol parameter because for protocolClassName protocol
* type will be auto detected
*/
private Boolean reflectionProtocol = false;
/**
* If true, consumer parameter won't be wrapped into array. Will fail if
* protocol specifies more then 1 parameter for the message
*/
private Boolean singleParameter = false;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Protocol getProtocol() {
return protocol;
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public AvroTransport getTransport() {
return transport;
}
public void setTransport(AvroTransport transport) {
this.transport = transport;
}
public String getProtocolLocation() {
return protocolLocation;
}
public void setProtocolLocation(String protocolLocation) {
this.protocolLocation = protocolLocation;
}
public String getProtocolClassName() {
return protocolClassName;
}
public void setProtocolClassName(String protocolClassName) {
this.protocolClassName = protocolClassName;
}
public String getMessageName() {
return messageName;
}
public void setMessageName(String messageName) {
this.messageName = messageName;
}
public String getUriAuthority() {
return uriAuthority;
}
public void setUriAuthority(String uriAuthority) {
this.uriAuthority = uriAuthority;
}
public Boolean getReflectionProtocol() {
return reflectionProtocol;
}
public void setReflectionProtocol(Boolean reflectionProtocol) {
this.reflectionProtocol = reflectionProtocol;
}
public Boolean getSingleParameter() {
return singleParameter;
}
public void setSingleParameter(Boolean singleParameter) {
this.singleParameter = singleParameter;
}
}
} | Fabryprog/camel | platforms/spring-boot/components-starter/camel-avro-starter/src/main/java/org/apache/camel/component/avro/springboot/AvroComponentConfiguration.java | Java | apache-2.0 | 6,533 |
/**
* 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.geronimo.kernel.config;
import java.io.Serializable;
import java.io.File;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.kernel.management.State;
import org.apache.geronimo.kernel.repository.Artifact;
/**
*
*
* @version $Rev$ $Date$
*/
public class ConfigurationInfo implements Serializable {
private static final long serialVersionUID = -16555213664245560L;
private final AbstractName storeName;
private final Artifact configID;
private final ConfigurationModuleType type;
private final long created;
private final File inPlaceLocation;
private final Set ownedConfigurations = new LinkedHashSet();
private final Set childConfigurations = new LinkedHashSet();
private final State state;
private final Artifact parentID;
public ConfigurationInfo(AbstractName storeName, Artifact configID, ConfigurationModuleType type, long created, Set ownedConfigurations, Set childConfigurations, File inPlaceLocation) {
this(storeName, configID, type, created, ownedConfigurations, childConfigurations, inPlaceLocation, null, null);
}
public ConfigurationInfo(AbstractName storeName, Artifact configID, ConfigurationModuleType type, long created, Set ownedConfigurations, Set childConfigurations, File inPlaceLocation, State state) {
this(storeName, configID, type, created, ownedConfigurations, childConfigurations, inPlaceLocation, state, null);
}
public ConfigurationInfo(AbstractName storeName, Artifact configID, ConfigurationModuleType type, long created, Set ownedConfigurations, Set childConfigurations, File inPlaceLocation, State state, Artifact parentID) {
this.storeName = storeName;
this.configID = configID;
this.type = type;
this.created = created;
this.inPlaceLocation = inPlaceLocation;
if (ownedConfigurations != null) {
this.ownedConfigurations.addAll(ownedConfigurations);
}
if (childConfigurations != null) {
this.childConfigurations.addAll(childConfigurations);
}
this.state = state;
this.parentID = parentID;
}
public AbstractName getStoreName() {
return storeName;
}
public Artifact getConfigID() {
return configID;
}
public ConfigurationModuleType getType() {
return type;
}
public long getCreated() {
return created;
}
public File getInPlaceLocation() {
return inPlaceLocation;
}
public Set getOwnedConfigurations() {
return ownedConfigurations;
}
public Set getChildConfigurations() {
return childConfigurations;
}
public State getState() {
return state;
}
public Artifact getParentID() {
return parentID;
}
}
| apache/geronimo | framework/modules/geronimo-kernel/src/main/java/org/apache/geronimo/kernel/config/ConfigurationInfo.java | Java | apache-2.0 | 3,694 |
using System;
namespace Tesseract
{
public enum EngineMode : int
{
/// <summary>
/// Only the legacy tesseract OCR engine is used.
/// </summary>
TesseractOnly = 0,
/// <summary>
/// Only the new LSTM-based OCR engine is used.
/// </summary>
LstmOnly,
/// <summary>
/// Both the legacy and new LSTM based OCR engine is used.
/// </summary>
TesseractAndLstm,
/// <summary>
/// The default OCR engine is used (currently LSTM-ased OCR engine).
/// </summary>
Default
}
}
| nguyenq/tesseract | src/Tesseract/EngineMode.cs | C# | apache-2.0 | 609 |
<!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.6.0_30) on Mon Apr 07 15:14:49 MDT 2014 -->
<title>Uses of Class com.google.android.gms.R.color</title>
<meta name="date" content="2014-04-07">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.google.android.gms.R.color";
}
//-->
</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><a href="../../../../../com/google/android/gms/R.color.html" title="class in com.google.android.gms">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/android/gms//class-useR.color.html" target="_top">FRAMES</a></li>
<li><a href="R.color.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>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.google.android.gms.R.color" class="title">Uses of Class<br>com.google.android.gms.R.color</h2>
</div>
<div class="classUseContainer">No usage of com.google.android.gms.R.color</div>
<!-- ======= 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><a href="../../../../../com/google/android/gms/R.color.html" title="class in com.google.android.gms">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>PREV</li>
<li>NEXT</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/google/android/gms//class-useR.color.html" target="_top">FRAMES</a></li>
<li><a href="R.color.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>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| CMPUT301W14T11/Team11Prototype | LocationApp/doc/com/google/android/gms/class-use/R.color.html | HTML | apache-2.0 | 4,075 |
/*
* Copyright 2013 The Error Prone 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 com.google.errorprone.bugpatterns.inject;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.matchers.InjectMatchers.ASSISTED_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.GUICE_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.JAVAX_INJECT_ANNOTATION;
import static com.google.errorprone.matchers.InjectMatchers.hasInjectAnnotation;
import static com.google.errorprone.matchers.Matchers.anyOf;
import static com.google.errorprone.matchers.Matchers.hasAnnotation;
import static com.google.errorprone.matchers.Matchers.isType;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
/**
* @author sgoldfeder@google.com (Steven Goldfeder)
*/
@BugPattern(
summary = "@AssistedInject and @Inject cannot be used on the same constructor.",
severity = WARNING)
public class AssistedInjectAndInjectOnSameConstructor extends BugChecker
implements AnnotationTreeMatcher {
/** Matches a method/constructor that is annotated with an @AssistedInject annotation. */
private static final Matcher<MethodTree> HAS_ASSISTED_INJECT_MATCHER =
hasAnnotation(ASSISTED_INJECT_ANNOTATION);
/** Matches the @Inject and @Assisted inject annotations. */
private static final Matcher<AnnotationTree> injectOrAssistedInjectMatcher =
anyOf(
isType(JAVAX_INJECT_ANNOTATION),
isType(GUICE_INJECT_ANNOTATION),
isType(ASSISTED_INJECT_ANNOTATION));
@Override
public Description matchAnnotation(AnnotationTree annotationTree, VisitorState state) {
if (injectOrAssistedInjectMatcher.matches(annotationTree, state)) {
Tree treeWithAnnotation = state.getPath().getParentPath().getParentPath().getLeaf();
if (ASTHelpers.getSymbol(treeWithAnnotation).isConstructor()
&& hasInjectAnnotation().matches(treeWithAnnotation, state)
&& HAS_ASSISTED_INJECT_MATCHER.matches((MethodTree) treeWithAnnotation, state)) {
return describeMatch(annotationTree, SuggestedFix.delete(annotationTree));
}
}
return Description.NO_MATCH;
}
}
| google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnSameConstructor.java | Java | apache-2.0 | 3,212 |
// @flow
import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../app';
import { ReducerRegistry } from '../redux';
import { USER_INTERACTION_RECEIVED } from './actionTypes';
ReducerRegistry.register('features/base/user-interaction', (state = {}, action) => {
switch (action.type) {
case APP_WILL_MOUNT:
case APP_WILL_UNMOUNT:
return {
...state,
interacted: false
};
case USER_INTERACTION_RECEIVED:
return {
...state,
interacted: true
};
}
return state;
});
| jitsi/jitsi-meet | react/features/base/user-interaction/reducer.js | JavaScript | apache-2.0 | 563 |
/*
* 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.axis2.addressing;
import junit.framework.TestCase;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.addressing.metadata.WSDLLocation;
import javax.xml.namespace.QName;
import static com.google.common.truth.Truth.assertAbout;
import static org.apache.axiom.truth.xml.XMLTruth.xml;
import java.util.ArrayList;
import java.util.Map;
public class EndpointReferenceHelperTest extends TestCase {
private void compareAttributes(OMAttribute expected, OMAttribute actual) {
assertEquals(expected.getNamespace(), actual.getNamespace());
assertEquals(expected.getLocalName(), actual.getLocalName());
assertEquals(expected.getAttributeValue(), actual.getAttributeValue());
}
public void testToAndFromOMForFinalSpecEPR() throws Exception {
String address = "http://ws.apache.org/axis2";
EndpointReference epr = new EndpointReference(address);
OMFactory omf = OMAbstractFactory.getOMFactory();
OMNamespace ns1 = omf.createOMNamespace("http://uri1", "prefix1");
OMAttribute attr1 = omf.createOMAttribute("attr1", ns1, "attr1value");
OMNamespace ns2 = omf.createOMNamespace("http://uri2", "prefix2");
OMAttribute attr2 = omf.createOMAttribute("attr2", ns2, "attr2value");
epr.addAttribute(attr1);
epr.addAttribute(attr2);
OMElement md1 = omf.createOMElement("md1", "http://mduri1", "md1prefix");
OMElement md2 = omf.createOMElement("md2", "http://mduri2", "md2prefix");
epr.addMetaData(md1);
epr.addMetaData(md2);
OMElement ext1 = omf.createOMElement("ext1", "http://exturi1", "ext1prefix");
OMElement ext2 = omf.createOMElement("ext2", "http://exturi2", "ext2prefix");
epr.addExtensibleElement(ext1);
epr.addExtensibleElement(ext2);
QName rp1Qname = new QName("http://rp1uri", "refParm1", "rp1prefix");
QName rp2Qname = new QName("http://rp2uri", "refParm2", "rp2prefix");
epr.addReferenceParameter(rp1Qname, "rp1");
epr.addReferenceParameter(rp2Qname, "rp2");
ArrayList addressAttributes = new ArrayList();
addressAttributes.add(attr1);
addressAttributes.add(attr2);
epr.setAddressAttributes(addressAttributes);
ArrayList metadataAttributes = new ArrayList();
metadataAttributes.add(attr1);
metadataAttributes.add(attr2);
epr.setMetadataAttributes(metadataAttributes);
OMElement om = EndpointReferenceHelper.toOM(omf, epr, new QName("http://nsurl", "localName",
"prefix"),
AddressingConstants.Final.WSA_NAMESPACE);
//Test deserialize using fromOM(OMElement)
EndpointReference deser = EndpointReferenceHelper.fromOM(om);
assertEquals(epr.getAddress(), deser.getAddress());
ArrayList<OMAttribute> addrAttrs = deser.getAddressAttributes();
compareAttributes(attr1, (OMAttribute)addrAttrs.get(0));
compareAttributes(attr2, (OMAttribute)addrAttrs.get(1));
ArrayList attrs = deser.getAttributes();
compareAttributes(attr1, (OMAttribute)attrs.get(0));
compareAttributes(attr2, (OMAttribute)attrs.get(1));
ArrayList metadata = deser.getMetaData();
assertAbout(xml()).that(metadata.get(0)).hasSameContentAs(md1);
assertAbout(xml()).that(metadata.get(1)).hasSameContentAs(md2);
ArrayList mdAttrs = deser.getMetadataAttributes();
compareAttributes(attr1, (OMAttribute)mdAttrs.get(0));
compareAttributes(attr2, (OMAttribute)mdAttrs.get(1));
ArrayList extelts = deser.getExtensibleElements();
assertAbout(xml()).that(extelts.get(0)).hasSameContentAs(ext1);
assertAbout(xml()).that(extelts.get(1)).hasSameContentAs(ext2);
Map m = deser.getAllReferenceParameters();
assertEquals("rp1", ((OMElement) m.get(rp1Qname)).getText());
assertEquals("rp2", ((OMElement) m.get(rp2Qname)).getText());
//Test deserialize using fromOM(EndpointReference, OMElement, String)
deser = new EndpointReference("");
EndpointReferenceHelper.fromOM(deser, om, AddressingConstants.Final.WSA_NAMESPACE);
assertEquals(epr.getAddress(), deser.getAddress());
addrAttrs = deser.getAddressAttributes();
compareAttributes(attr1, addrAttrs.get(0));
compareAttributes(attr2, addrAttrs.get(1));
attrs = deser.getAttributes();
compareAttributes(attr1, (OMAttribute)attrs.get(0));
compareAttributes(attr2, (OMAttribute)attrs.get(1));
metadata = deser.getMetaData();
assertAbout(xml()).that(metadata.get(0)).hasSameContentAs(md1);
assertAbout(xml()).that(metadata.get(1)).hasSameContentAs(md2);
mdAttrs = deser.getMetadataAttributes();
compareAttributes(attr1, (OMAttribute)mdAttrs.get(0));
compareAttributes(attr2, (OMAttribute)mdAttrs.get(1));
extelts = deser.getExtensibleElements();
assertAbout(xml()).that(extelts.get(0)).hasSameContentAs(ext1);
assertAbout(xml()).that(extelts.get(1)).hasSameContentAs(ext2);
m = deser.getAllReferenceParameters();
assertEquals("rp1", ((OMElement) m.get(rp1Qname)).getText());
assertEquals("rp2", ((OMElement) m.get(rp2Qname)).getText());
//Failure test
try {
deser = new EndpointReference("");
EndpointReferenceHelper.fromOM(deser, om, AddressingConstants.Submission.WSA_NAMESPACE);
fail("An exception should have been thrown due to failure to locate a wsa:Address field.");
}
catch (Exception e) {
//pass
}
}
public void testToAndFromOMForSubmissionSpecEPR() throws Exception {
String address = "http://ws.apache.org/axis2";
EndpointReference epr = new EndpointReference(address);
OMFactory omf = OMAbstractFactory.getOMFactory();
OMNamespace ns1 = omf.createOMNamespace("http://uri1", "prefix1");
OMAttribute attr1 = omf.createOMAttribute("attr1", ns1, "attr1value");
OMNamespace ns2 = omf.createOMNamespace("http://uri2", "prefix2");
OMAttribute attr2 = omf.createOMAttribute("attr2", ns2, "attr2value");
epr.addAttribute(attr1);
epr.addAttribute(attr2);
OMElement md1 = omf.createOMElement("md1", "http://mduri1", "md1prefix");
OMElement md2 = omf.createOMElement("md2", "http://mduri2", "md2prefix");
epr.addMetaData(md1);
epr.addMetaData(md2);
OMElement ext1 = omf.createOMElement("ext1", "http://exturi1", "ext1prefix");
OMElement ext2 = omf.createOMElement("ext2", "http://exturi2", "ext2prefix");
epr.addExtensibleElement(ext1);
epr.addExtensibleElement(ext2);
QName rp1Qname = new QName("http://rp1uri", "refParm1", "rp1prefix");
QName rp2Qname = new QName("http://rp2uri", "refParm2", "rp2prefix");
epr.addReferenceParameter(rp1Qname, "rp1");
epr.addReferenceParameter(rp2Qname, "rp2");
ArrayList addressAttributes = new ArrayList();
addressAttributes.add(attr1);
addressAttributes.add(attr2);
epr.setAddressAttributes(addressAttributes);
OMElement om = EndpointReferenceHelper.toOM(omf, epr, new QName("http://nsurl", "localName",
"prefix"),
AddressingConstants.Submission.WSA_NAMESPACE);
//Add some reference properties.
QName p1Qname = new QName("http://p1uri", "refProp1", "p1prefix");
QName p2Qname = new QName("http://p2uri", "refProp2", "p2prefix");
QName qname = new QName(AddressingConstants.Submission.WSA_NAMESPACE, "ReferenceProperties",
AddressingConstants.WSA_DEFAULT_PREFIX);
OMElement referenceProperties = omf.createOMElement(qname, om);
OMElement prop1 = omf.createOMElement(p1Qname, referenceProperties);
OMElement prop2 = omf.createOMElement(p2Qname, referenceProperties);
prop1.setText("p1");
prop2.setText("p2");
//Test deserialize using fromOM(OMElement)
EndpointReference deser = EndpointReferenceHelper.fromOM(om);
assertEquals(epr.getAddress(), deser.getAddress());
ArrayList addrAttrs = deser.getAddressAttributes();
compareAttributes(attr1, (OMAttribute)addrAttrs.get(0));
compareAttributes(attr2, (OMAttribute)addrAttrs.get(1));
ArrayList attrs = deser.getAttributes();
compareAttributes(attr1, (OMAttribute)attrs.get(0));
compareAttributes(attr2, (OMAttribute)attrs.get(1));
//Metadata will be lost unless it is saved as an extensibility element.
ArrayList metadata = deser.getMetaData();
assertNull(metadata);
ArrayList extelts = deser.getExtensibleElements();
assertAbout(xml()).that(extelts.get(0)).hasSameContentAs(ext1);
assertAbout(xml()).that(extelts.get(1)).hasSameContentAs(ext2);
//All reference properties are returned as reference parameters.
Map m = deser.getAllReferenceParameters();
assertEquals(4, m.size());
assertEquals("rp1", ((OMElement) m.get(rp1Qname)).getText());
assertEquals("rp2", ((OMElement) m.get(rp2Qname)).getText());
assertEquals("p1", ((OMElement) m.get(p1Qname)).getText());
assertEquals("p2", ((OMElement) m.get(p2Qname)).getText());
//Test deserialize using fromOM(EndpointReference, OMElement, String)
deser = new EndpointReference("");
EndpointReferenceHelper.fromOM(deser, om, AddressingConstants.Submission.WSA_NAMESPACE);
assertEquals(epr.getAddress(), deser.getAddress());
addrAttrs = deser.getAddressAttributes();
compareAttributes(attr1, (OMAttribute)addrAttrs.get(0));
compareAttributes(attr2, (OMAttribute)addrAttrs.get(1));
attrs = deser.getAttributes();
compareAttributes(attr1, (OMAttribute)attrs.get(0));
compareAttributes(attr2, (OMAttribute)attrs.get(1));
//Metadata will be lost unless it is saved as an extensibility element.
metadata = deser.getMetaData();
assertNull(metadata);
extelts = deser.getExtensibleElements();
assertAbout(xml()).that(extelts.get(0)).hasSameContentAs(ext1);
assertAbout(xml()).that(extelts.get(1)).hasSameContentAs(ext2);
//All reference properties are returned as reference parameters.
m = deser.getAllReferenceParameters();
assertEquals(4, m.size());
assertEquals("rp1", ((OMElement) m.get(rp1Qname)).getText());
assertEquals("rp2", ((OMElement) m.get(rp2Qname)).getText());
assertEquals("p1", ((OMElement) m.get(p1Qname)).getText());
assertEquals("p2", ((OMElement) m.get(p2Qname)).getText());
//Failure test
try {
deser = new EndpointReference("");
EndpointReferenceHelper.fromOM(deser, om, AddressingConstants.Final.WSA_NAMESPACE);
fail("An exception should have been thrown due to failure to locate a wsa:Address field.");
}
catch (Exception e) {
//pass
}
}
public void testSetAndGetWSDLLocationMetadataForFinalSpecEPR() throws Exception {
String address = "http://ws.apache.org/axis2";
String targetNamespace = "targetNamespace";
String location = "wsdlLocation";
EndpointReference epr = new EndpointReference(address);
OMFactory omf = OMAbstractFactory.getOMFactory();
// Uses final WSDLI namespace on wsdlLocation attribute
EndpointReferenceHelper.setWSDLLocationMetadata(omf, epr, AddressingConstants.Final.WSA_NAMESPACE, new WSDLLocation(targetNamespace, location));
WSDLLocation wsdlLocation = EndpointReferenceHelper.getWSDLLocationMetadata(epr, AddressingConstants.Final.WSA_NAMESPACE);
assertEquals(wsdlLocation.getTargetNamespace(), targetNamespace);
assertEquals(wsdlLocation.getLocation(), location);
}
public void testSetAndGetWSDLLocationMetadataForSubmissionSpecEPR() throws Exception {
String address = "http://ws.apache.org/axis2";
String targetNamespace = "targetNamespace";
String location = "wsdlLocation";
EndpointReference epr = new EndpointReference(address);
OMFactory omf = OMAbstractFactory.getOMFactory();
// Uses final WSDLI namespace on wsdlLocation attribute
EndpointReferenceHelper.setWSDLLocationMetadata(omf, epr, AddressingConstants.Submission.WSA_NAMESPACE, new WSDLLocation(targetNamespace, location));
WSDLLocation wsdlLocation = EndpointReferenceHelper.getWSDLLocationMetadata(epr, AddressingConstants.Submission.WSA_NAMESPACE);
assertEquals(wsdlLocation.getTargetNamespace(), targetNamespace);
assertEquals(wsdlLocation.getLocation(), location);
}
public void testGetWSDLLocationMetadataForFinalSpecEPRWithOldWsdliNamespace() throws Exception {
String address = "http://ws.apache.org/axis2";
String targetNamespace = "targetNamespace";
String location = "wsdlLocation";
EndpointReference epr = new EndpointReference(address);
// Uses old candidate spec WSDLI namespace on wsdlLocation attribute
OMFactory omf = OMAbstractFactory.getOMFactory();
String value = new StringBuffer(targetNamespace).append(" ").append(location).toString();
QName OLD_WSDLI = new QName("http://www.w3.org/2006/01/wsdl-instance", "wsdlLocation", "wsdli");
OMNamespace wsdliNs = omf.createOMNamespace(OLD_WSDLI.getNamespaceURI(), OLD_WSDLI.getPrefix());
OMAttribute attribute = omf.createOMAttribute(OLD_WSDLI.getLocalPart(), wsdliNs, value);
ArrayList list = new ArrayList();
list.add(attribute);
epr.setMetadataAttributes(list);
WSDLLocation wsdlLocation = EndpointReferenceHelper.getWSDLLocationMetadata(epr, AddressingConstants.Final.WSA_NAMESPACE);
assertEquals(wsdlLocation.getTargetNamespace(), targetNamespace);
assertEquals(wsdlLocation.getLocation(), location);
}
public void testGetWSDLLocationMetadataForSubmissionSpecEPRWithOldWsdliNamespace() throws Exception {
String address = "http://ws.apache.org/axis2";
String targetNamespace = "targetNamespace";
String location = "wsdlLocation";
EndpointReference epr = new EndpointReference(address);
// Uses old candidate spec WSDLI namespace on wsdlLocation attribute
OMFactory omf = OMAbstractFactory.getOMFactory();
String value = new StringBuffer(targetNamespace).append(" ").append(location).toString();
QName OLD_WSDLI = new QName("http://www.w3.org/2006/01/wsdl-instance", "wsdlLocation", "wsdli");
OMNamespace wsdliNs = omf.createOMNamespace(OLD_WSDLI.getNamespaceURI(), OLD_WSDLI.getPrefix());
OMAttribute attribute = omf.createOMAttribute(OLD_WSDLI.getLocalPart(), wsdliNs, value);
epr.addAttribute(attribute);
WSDLLocation wsdlLocation = EndpointReferenceHelper.getWSDLLocationMetadata(epr, AddressingConstants.Submission.WSA_NAMESPACE);
assertEquals(wsdlLocation.getTargetNamespace(), targetNamespace);
assertEquals(wsdlLocation.getLocation(), location);
}
}
| apache/axis2-java | modules/kernel/test/org/apache/axis2/addressing/EndpointReferenceHelperTest.java | Java | apache-2.0 | 16,632 |
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.MBean;
import org.jgroups.annotations.ManagedAttribute;
import org.jgroups.annotations.ManagedOperation;
import org.jgroups.annotations.Property;
import org.jgroups.blocks.locking.AwaitInfo;
import org.jgroups.blocks.locking.LockInfo;
import org.jgroups.blocks.locking.LockNotification;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Bits;
import org.jgroups.util.Owner;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
import java.io.DataInput;
import java.io.DataOutput;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
/**
* Base locking protocol, handling most of the protocol communication with other instances. To use distributed locking,
* {@link org.jgroups.blocks.locking.LockService} is placed on a channel. LockService talks to a subclass of Locking
* via events.
* @author Bela Ban
* @since 2.12
* @see org.jgroups.protocols.CENTRAL_LOCK
*/
@MBean(description="Based class for locking functionality")
abstract public class Locking extends Protocol {
@Property(description="bypasses message bundling if set")
protected boolean bypass_bundling=true;
@Property(description="Number of locks to be used for lock striping (for synchronized access to the server_lock entries)")
protected int lock_striping_size=10;
protected Address local_addr;
protected View view;
// server side locks
protected final ConcurrentMap<String,ServerLock> server_locks=Util.createConcurrentMap(20);
// protected access to the same locks in server_locks
protected Lock[] lock_stripes;
// client side locks
protected final ClientLockTable client_lock_table=new ClientLockTable();
protected final Set<LockNotification> lock_listeners=new CopyOnWriteArraySet<>();
protected final static AtomicInteger current_lock_id=new AtomicInteger(1);
protected enum Type {
GRANT_LOCK, // request to acquire a lock
LOCK_GRANTED, // response to sender of GRANT_LOCK on succcessful lock acquisition
LOCK_DENIED, // response to sender of GRANT_LOCK on unsuccessful lock acquisition (e.g. on tryLock())
RELEASE_LOCK, // request to release a lock
CREATE_LOCK, // request to create a server lock (sent by coordinator to backups). Used by CentralLockService
DELETE_LOCK, // request to delete a server lock (sent by coordinator to backups). Used by CentralLockService
LOCK_AWAIT, // request to await until condition is signaled
COND_SIG, // request to signal awaiting thread
COND_SIG_ALL, // request to signal all awaiting threads
SIG_RET, // response to alert of signal
DELETE_LOCK_AWAIT, // request to delete a waiter
CREATE_AWAITER, // request to create a server lock await (sent by coordinator to backups). Used by CentralLockService
DELETE_AWAITER // request to delete a server lock await (sent by coordinator to backups). Used by CentralLockService
}
public Locking() {
}
public boolean getBypassBundling() {
return bypass_bundling;
}
public void setBypassBundling(boolean bypass_bundling) {
this.bypass_bundling=bypass_bundling;
}
public void addLockListener(LockNotification listener) {
if(listener != null)
lock_listeners.add(listener);
}
public void removeLockListener(LockNotification listener) {
if(listener != null)
lock_listeners.remove(listener);
}
@ManagedAttribute
public String getAddress() {
return local_addr != null? local_addr.toString() : null;
}
@ManagedAttribute
public String getView() {
return view != null? view.toString() : null;
}
public void init() throws Exception {
super.init();
lock_stripes=new Lock[lock_striping_size];
for(int i=0; i < lock_stripes.length; i++)
lock_stripes[i]=new ReentrantLock();
}
public Object down(Event evt) {
switch(evt.getType()) {
case Event.LOCK:
LockInfo info=evt.getArg();
ClientLock lock=getLock(info.getName());
if(!info.isTrylock()) {
if(info.isLockInterruptibly()) {
try {
lock.lockInterruptibly();
}
catch(InterruptedException e) {
Thread.currentThread().interrupt(); // has to be checked by caller who has to rethrow ...
}
}
else
lock.lock();
}
else {
if(info.isUseTimeout()) {
try {
return lock.tryLock(info.getTimeout(), info.getTimeUnit());
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else
return lock.tryLock();
}
return null;
case Event.UNLOCK:
info=evt.getArg();
lock=getLock(info.getName(), false);
if(lock != null)
lock.unlock();
return null;
case Event.UNLOCK_ALL:
unlockAll();
return null;
case Event.LOCK_AWAIT:
info=evt.getArg();
lock=getLock(info.getName(), false);
if (lock == null || !lock.acquired) {
throw new IllegalMonitorStateException();
}
Condition condition = lock.newCondition();
if (info.isUseTimeout()) {
try {
return condition.awaitNanos(info.getTimeUnit().toNanos(info.getTimeout()));
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else if (info.isLockInterruptibly()) {
try {
condition.await();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
else {
condition.awaitUninterruptibly();
}
return null;
case Event.LOCK_SIGNAL:
AwaitInfo awaitInfo =evt.getArg();
lock=getLock(awaitInfo.getName(), false);
if (lock == null || !lock.acquired) {
throw new IllegalMonitorStateException();
}
sendSignalConditionRequest(awaitInfo.getName(), awaitInfo.isAll());
return null;
case Event.SET_LOCAL_ADDRESS:
local_addr=evt.getArg();
break;
case Event.VIEW_CHANGE:
handleView(evt.getArg());
break;
}
return down_prot.down(evt);
}
public Object up(Event evt) {
switch(evt.getType()) {
case Event.VIEW_CHANGE:
handleView(evt.getArg());
break;
}
return up_prot.up(evt);
}
public Object up(Message msg) {
LockingHeader hdr=msg.getHeader(id);
if(hdr == null)
return up_prot.up(msg);
if (null != view && !view.containsMember(msg.getSrc())) {
log.error("Received locking event from '%s' but member is not present in the current view - ignoring request", msg.src());
return null;
}
Request req=null;
try {
req=Util.streamableFromBuffer(Request.class, msg.getRawBuffer(), msg.getOffset(), msg.getLength());
}
catch(Exception ex) {
log.error("failed deserializng request", ex);
return null;
}
log.trace("[%s] <-- [%s] %s", local_addr, msg.getSrc(), req);
switch(req.type) {
case GRANT_LOCK:
case RELEASE_LOCK:
handleLockRequest(req);
break;
case LOCK_GRANTED:
handleLockGrantedResponse(req.lock_name, req.lock_id, req.owner);
break;
case LOCK_DENIED:
handleLockDeniedResponse(req.lock_name, req.lock_id, req.owner);
break;
case CREATE_LOCK:
handleCreateLockRequest(req.lock_name, req.owner);
break;
case DELETE_LOCK:
handleDeleteLockRequest(req.lock_name);
break;
case COND_SIG:
case COND_SIG_ALL:
handleSignalRequest(req);
break;
case LOCK_AWAIT:
handleAwaitRequest(req.lock_name, req.owner);
handleLockRequest(req);
break;
case DELETE_LOCK_AWAIT:
handleDeleteAwaitRequest(req.lock_name, req.owner);
break;
case SIG_RET:
handleSignalResponse(req.lock_name, req.owner);
break;
case CREATE_AWAITER:
handleCreateAwaitingRequest(req.lock_name, req.owner);
break;
case DELETE_AWAITER:
handleDeleteAwaitingRequest(req.lock_name, req.owner);
break;
default:
log.error("Request of type %s not known", req.type);
break;
}
return null;
}
protected ClientLock getLock(String name) {
return client_lock_table.getLock(name,getOwner(),true);
}
protected ClientLock getLock(String name, boolean create_if_absent) {
return client_lock_table.getLock(name,getOwner(),create_if_absent);
}
@ManagedOperation(description="Unlocks all currently held locks")
public void unlockAll() {
client_lock_table.unlockAll();
}
@ManagedOperation(description="Dumps all locks")
public String printLocks() {
StringBuilder sb=new StringBuilder();
sb.append("server locks:\n");
for(Map.Entry<String,ServerLock> entry: server_locks.entrySet())
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
sb.append("\nmy locks: ").append(client_lock_table.toString());
return sb.toString();
}
protected void handleView(View view) {
this.view=view;
log.debug("view=%s", view);
List<Address> members=view.getMembers();
List<Response> responses=new ArrayList<>();
for(Map.Entry<String,ServerLock> entry: server_locks.entrySet()) {
String lock_name=entry.getKey();
ServerLock server_lock=entry.getValue();
Lock lock=_getLock(lock_name);
lock.lock();
try {
Response rsp=server_lock.handleView(members);
if(rsp != null)
responses.add(rsp);
if(server_lock.isEmpty() && server_lock.current_owner == null && server_lock.condition.queue.isEmpty())
server_locks.remove(lock_name);
}
finally {
lock.unlock();
}
}
// do the sending outside the lock scope (might block on credits or TCP send)
for(Response rsp: responses)
sendLockResponse(rsp.type, rsp.owner, rsp.lock_name, rsp.lock_id);
}
protected ClientLock createLock(String lock_name, Owner owner) {
return new ClientLock(lock_name, owner);
}
/** Gets a lock from locks based on the hash of the lock name */
protected Lock _getLock(String lock_name) {
int index=lock_name != null? Math.abs(lock_name.hashCode() % lock_stripes.length) : 0;
return lock_stripes[index];
}
protected Owner getOwner() {
return new Owner(local_addr, Thread.currentThread().getId());
}
abstract protected void sendGrantLockRequest(String lock_name, int lock_id, Owner owner, long timeout, boolean is_trylock);
abstract protected void sendReleaseLockRequest(String lock_name, Owner owner);
abstract protected void sendAwaitConditionRequest(String lock_name, Owner owner);
abstract protected void sendSignalConditionRequest(String lock_name, boolean all);
abstract protected void sendDeleteAwaitConditionRequest(String lock_name, Owner owner);
protected void sendRequest(Address dest, Type type, String lock_name, Owner owner, long timeout, boolean is_trylock) {
send(dest, new Request(type, lock_name, owner, timeout, is_trylock));
}
protected void sendRequest(Address dest, Type type, String lock_name, int lock_id, Owner owner, long timeout, boolean is_trylock) {
send(dest, new Request(type, lock_name, owner, timeout, is_trylock).lockId(lock_id));
}
protected void sendLockResponse(Type type, Owner dest, String lock_name, int lock_id) {
send(dest.getAddress(), new Request(type, lock_name, dest, 0).lockId(lock_id));
}
protected void sendSignalResponse(Owner dest, String lock_name) {
send(dest.getAddress(), new Request(Type.SIG_RET, lock_name, dest, 0));
}
protected void send(Address dest, Request req) {
Message msg=new Message(dest, Util.streamableToBuffer(req)).putHeader(id, new LockingHeader());
if(bypass_bundling)
msg.setFlag(Message.Flag.DONT_BUNDLE);
log.trace("[%s] --> %s] %s", local_addr, dest == null? "ALL" : dest, req);
try {
down_prot.down(msg);
}
catch(Exception ex) {
log.error("failed sending %s request: %s", req.type, ex);
}
}
protected void handleLockRequest(Request req) {
Response rsp=null;
Lock lock=_getLock(req.lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(req.lock_name);
if(server_lock == null) {
server_lock=new ServerLock(req.lock_name);
ServerLock tmp=server_locks.putIfAbsent(req.lock_name, server_lock);
if(tmp != null)
server_lock=tmp;
else
notifyLockCreated(req.lock_name);
}
rsp=server_lock.handleRequest(req);
if(server_lock.isEmpty() && server_lock.current_owner == null && server_lock.condition.queue.isEmpty())
server_locks.remove(req.lock_name);
}
finally {
lock.unlock();
}
// moved outside the lock scope
if(rsp != null)
sendLockResponse(rsp.type, rsp.owner, rsp.lock_name, rsp.lock_id);
}
protected void handleLockGrantedResponse(String lock_name, int lock_id, Owner owner) {
ClientLock lock=client_lock_table.getLock(lock_name,owner,false);
if(lock != null)
lock.handleLockGrantedResponse(lock_id);
}
protected void handleLockDeniedResponse(String lock_name, int lock_id, Owner owner) {
ClientLock lock=client_lock_table.getLock(lock_name,owner,false);
if(lock != null)
lock.lockDenied(lock_id);
}
protected void handleAwaitRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(lock_name);
if (server_lock != null)
server_lock.condition.addWaiter(owner);
else
log.error(Util.getMessage("ConditionAwaitWasReceivedButLockWasNotCreatedWaiterMayBlockForever"));
}
finally {
lock.unlock();
}
}
protected void handleDeleteAwaitRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(lock_name);
if (server_lock != null)
server_lock.condition.removeWaiter(owner);
else
log.error(Util.getMessage("ConditionAwaitDeleteWasReceivedButLockWasGone"));
}
finally {
lock.unlock();
}
}
protected void handleSignalResponse(String lock_name, Owner owner) {
ClientLock lock=client_lock_table.getLock(lock_name,owner,false);
if(lock != null) {
lock.condition.signaled();
}
else {
log.error(Util.getMessage("ConditionResponseWasClientLockWasNotPresentIgnoredSignal"));
}
}
protected void handleSignalRequest(Request req) {
Response rsp=null;
Lock lock=_getLock(req.lock_name);
lock.lock();
try {
ServerLock server_lock=server_locks.get(req.lock_name);
if (server_lock != null)
rsp=server_lock.handleRequest(req);
else
log.error(Util.getMessage("ConditionSignalWasReceivedButLockWasNotCreatedCouldnTNotifyAnyone"));
}
finally {
lock.unlock();
}
// moved outside the lock scope
if(rsp != null)
sendLockResponse(rsp.type, rsp.owner, rsp.lock_name, rsp.lock_id);
}
protected void handleCreateLockRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
server_locks.put(lock_name, new ServerLock(lock_name, owner));
}
finally {
lock.unlock();
}
}
protected void handleDeleteLockRequest(String lock_name) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock = server_locks.get(lock_name);
if(server_lock == null)
return;
if (server_lock.condition.queue.isEmpty())
server_locks.remove(lock_name);
else
server_lock.current_owner = null;
}
finally {
lock.unlock();
}
}
protected void handleCreateAwaitingRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock = server_locks.get(lock_name);
if (server_lock == null) {
server_lock = new ServerLock(lock_name);
ServerLock tmp=server_locks.putIfAbsent(lock_name,server_lock);
if(tmp != null)
server_lock=tmp;
}
server_lock.condition.queue.add(owner);
}
finally {
lock.unlock();
}
}
protected void handleDeleteAwaitingRequest(String lock_name, Owner owner) {
Lock lock=_getLock(lock_name);
lock.lock();
try {
ServerLock server_lock = server_locks.get(lock_name);
if (server_lock != null) {
server_lock.condition.queue.remove(owner);
if (server_lock.condition.queue.isEmpty() && server_lock.current_owner == null) {
server_locks.remove(lock_name);
}
}
}
finally {
lock.unlock();
}
}
protected void notifyLockCreated(String lock_name) {
for(LockNotification listener: lock_listeners) {
try {
listener.lockCreated(lock_name);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyLockDeleted(String lock_name) {
for(LockNotification listener: lock_listeners) {
try {
listener.lockDeleted(lock_name);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyLocked(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.locked(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyUnlocked(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.unlocked(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyAwaiting(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.awaiting(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
protected void notifyAwaited(String lock_name, Owner owner) {
for(LockNotification listener: lock_listeners) {
try {
listener.awaited(lock_name,owner);
}
catch(Throwable t) {
log.error("failed notifying %s: %s", listener, t.toString());
}
}
}
/**
* Server side queue for handling of lock requests (lock, release).
* @author Bela Ban
*/
protected class ServerLock {
protected final String lock_name;
protected Owner current_owner;
protected final List<Request> queue=new ArrayList<>();
protected final ServerCondition condition;
public ServerLock(String lock_name) {
this.lock_name=lock_name;
this.condition=new ServerCondition(this);
}
protected ServerLock(String lock_name, Owner owner) {
this.lock_name=lock_name;
this.current_owner=owner;
this.condition=new ServerCondition(this);
}
protected Response handleRequest(Request req) {
switch(req.type) {
case GRANT_LOCK:
if(current_owner == null) {
setOwner(req.owner);
return new Response(Type.LOCK_GRANTED, req.owner, req.lock_name, req.lock_id);
}
if(current_owner.equals(req.owner))
return new Response(Type.LOCK_GRANTED, req.owner, req.lock_name, req.lock_id);
if(req.is_trylock && req.timeout <= 0)
return new Response(Type.LOCK_DENIED, req.owner, req.lock_name, req.lock_id);
addToQueue(req);
break;
case RELEASE_LOCK:
case LOCK_AWAIT:
if(current_owner == null)
break;
if(current_owner.equals(req.owner))
setOwner(null);
else
addToQueue(req);
break;
case COND_SIG:
condition.signal(false);
break;
case COND_SIG_ALL:
condition.signal(true);
break;
default:
throw new IllegalArgumentException("type " + req.type + " is invalid here");
}
return processQueue();
}
protected Response handleView(List<Address> members) {
if(current_owner != null && !members.contains(current_owner.getAddress())) {
Owner tmp=current_owner;
setOwner(null);
log.debug("unlocked \"%s\" because owner %s left", lock_name, tmp);
}
synchronized(queue) {
for(Iterator<Request> it=queue.iterator(); it.hasNext(); ) {
Request req=it.next();
if(!members.contains(req.owner.getAddress()))
it.remove();
}
}
for(Iterator<Owner> it=condition.queue.iterator(); it.hasNext();) {
Owner own=it.next();
if(!members.contains(own.getAddress()))
it.remove();
}
return processQueue();
}
protected void addToQueue(Request req) {
synchronized(queue) {
if(queue.isEmpty()) {
if(req.type == Type.GRANT_LOCK)
queue.add(req);
return; // RELEASE_LOCK is discarded on an empty queue
}
}
// at this point the queue is not empty
switch(req.type) {
// If there is already a lock request from the same owner, discard the new lock request
case GRANT_LOCK:
synchronized(queue) {
if(!isRequestPresent(Type.GRANT_LOCK, req.owner))
queue.add(req);
}
break;
case RELEASE_LOCK:
// Release the lock request from the same owner already in the queue
// If there is no lock request, discard the unlock request
removeRequest(Type.GRANT_LOCK, req.owner);
break;
}
}
/** Checks if a certain request from a given owner is already in the queue */
protected boolean isRequestPresent(Type type, Owner owner) { // holds lock on queue
for(Request req: queue)
if(req.type == type && req.owner.equals(owner))
return true;
return false;
}
protected void removeRequest(Type type, Owner owner) {
synchronized(queue) {
for(Iterator<Request> it=queue.iterator(); it.hasNext(); ) {
Request req=it.next();
if(req.type == type && req.owner.equals(owner))
it.remove();
}
}
}
protected Request getNextRequest() {
synchronized(queue) {
return !queue.isEmpty()? queue.remove(0) : null;
}
}
protected Response processQueue() {
if(current_owner != null)
return null;
Request req;
while((req=getNextRequest()) != null) {
if(req.type == Type.GRANT_LOCK) {
setOwner(req.owner);
return new Response(Type.LOCK_GRANTED, req.owner, req.lock_name, req.lock_id);
}
}
return null;
}
protected void setOwner(Owner owner) {
if(owner == null) {
if(current_owner != null) {
Owner tmp=current_owner;
current_owner=null;
notifyUnlocked(lock_name, tmp);
}
}
else {
current_owner=owner;
notifyLocked(lock_name, owner);
}
}
public boolean isEmpty() {
synchronized(queue) {
return queue.isEmpty();
}
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(current_owner);
synchronized(queue) {
if(!queue.isEmpty()) {
sb.append(", queue: ");
for(Request req : queue) {
sb.append(req.toStringShort()).append(" ");
}
}
}
return sb.toString();
}
}
protected class ServerCondition {
protected final ServerLock lock;
protected final Queue<Owner> queue=new ArrayDeque<>();
public ServerCondition(ServerLock lock) {
this.lock = lock;
}
public void addWaiter(Owner waiter) {
notifyAwaiting(lock.lock_name, waiter);
log.trace("Waiter [%s] was added for %s", waiter, lock.lock_name);
queue.add(waiter);
}
public void removeWaiter(Owner waiter) {
notifyAwaited(lock.lock_name, waiter);
log.trace("Waiter [%s] was removed for %s", waiter, lock.lock_name);
queue.remove(waiter);
}
public void signal(boolean all) {
if (queue.isEmpty())
log.trace("Signal for [%s] ignored since, no one is waiting in queue", lock.lock_name);
Owner entry;
if (all) {
while ((entry = queue.poll()) != null) {
notifyAwaited(lock.lock_name, entry);
log.trace("Signalled %s for %s", entry, lock.lock_name);
sendSignalResponse(entry, lock.lock_name);
}
}
else {
entry = queue.poll();
if (entry != null) {
notifyAwaited(lock.lock_name, entry);
log.trace("Signalled %s for %s", entry, lock.lock_name);
sendSignalResponse(entry, lock.lock_name);
}
}
}
}
/**
* Implementation of {@link Lock}. This is a client stub communicates with a server equivalent. The semantics are
* more or less those of {@link Lock}, but may differ slightly.
* For details see {@link org.jgroups.blocks.locking.LockService}.
*/
protected class ClientLock implements Lock {
protected final String name;
protected Owner owner;
protected volatile boolean acquired;
protected volatile boolean denied;
protected volatile boolean is_trylock;
protected long timeout;
protected final ClientCondition condition;
// unique for locks for the same name:owner, can wrap around (that's ok)
protected final int lock_id=current_lock_id.getAndIncrement();
public ClientLock(String name) {
this.name=name;
this.condition = new ClientCondition(this);
}
public ClientLock(String name, Owner owner) {
this(name);
this.owner=owner;
}
public void lock() {
try {
acquire(false);
}
catch(InterruptedException e) { // should never happen
Thread.currentThread().interrupt(); // just a second line of defense
}
}
public void lockInterruptibly() throws InterruptedException {
acquire(true);
}
public boolean tryLock() {
try {
return acquireTryLock(0, false);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return acquireTryLock(TimeUnit.MILLISECONDS.convert(time, unit), true);
}
public synchronized void unlock() {
_unlock(false);
}
public Condition newCondition() {
// Currently only 1 condition per Lock is supported
return condition;
}
public String toString() {
return name + " (id=" + lock_id + ", locked=" + acquired + ")";
}
protected synchronized void lockGranted(int lock_id) {
if(this.lock_id != lock_id) {
log.error(Util.getMessage("DiscardedLOCKGRANTEDResponseWithLockId") + lock_id + ", my lock-id=" + this.lock_id);
return;
}
acquired=true;
this.notifyAll();
}
protected synchronized void lockDenied(int lock_id) {
if(this.lock_id != lock_id) {
log.error(Util.getMessage("DiscardedLOCKDENIEDResponseWithLockId") + lock_id + ", my lock_id=" + this.lock_id);
return;
}
denied=true;
this.notifyAll();
}
protected void handleLockGrantedResponse(int lock_id) {
lockGranted(lock_id);
}
protected synchronized void acquire(boolean throwInterrupt) throws InterruptedException {
if(acquired)
return;
if(throwInterrupt && Thread.interrupted())
throw new InterruptedException();
owner=getOwner();
sendGrantLockRequest(name, lock_id, owner, 0, false);
boolean interrupted=false;
while(!acquired) {
try {
this.wait();
}
catch(InterruptedException e) {
if(throwInterrupt && !acquired) {
_unlock(true);
throw e;
}
// If we don't throw exceptions then we just set the interrupt flag and let it loop around
interrupted=true;
}
}
if(interrupted)
Thread.currentThread().interrupt();
}
protected synchronized void _unlock(boolean force) {
if(!acquired && !denied && !force)
return;
this.timeout=0;
this.is_trylock=false;
if(!denied)
sendReleaseLockRequest(name, owner);
acquired=denied=false;
notifyAll();
client_lock_table.removeClientLock(name,owner);
notifyLockDeleted(name);
owner=null;
}
protected synchronized boolean acquireTryLock(long timeout, boolean use_timeout) throws InterruptedException {
if(denied)
return false;
if(!acquired) {
if(use_timeout && Thread.interrupted())
throw new InterruptedException();
is_trylock=true;
this.timeout=timeout;
if(owner == null)
owner=getOwner();
sendGrantLockRequest(name, lock_id, owner, timeout, true);
boolean interrupted = false;
while(!acquired && !denied) {
if(use_timeout) {
long timeout_ns=TimeUnit.NANOSECONDS.convert(timeout, TimeUnit.MILLISECONDS),
wait_time=timeout_ns,
start=System.nanoTime();
while(wait_time > 0 && !acquired && !denied) {
try {
long wait_ms=TimeUnit.MILLISECONDS.convert(wait_time, TimeUnit.NANOSECONDS);
if(wait_ms <= 0)
break;
this.wait(wait_ms);
}
catch(InterruptedException e) {
interrupted=true;
}
finally {
wait_time=timeout_ns - (System.nanoTime() - start);
this.timeout=TimeUnit.MILLISECONDS.convert(wait_time, TimeUnit.NANOSECONDS);
}
}
break;
}
else {
try {
this.wait();
}
catch(InterruptedException e) {
interrupted = true;
}
}
}
if(interrupted)
Thread.currentThread().interrupt();
}
boolean retval=acquired && !denied;
if(!acquired || denied)
_unlock(true);
return retval;
}
}
/** Manages access to client locks */
protected class ClientLockTable {
protected final ConcurrentMap<String,Map<Owner,ClientLock>> table=Util.createConcurrentMap(20);
protected synchronized ClientLock getLock(String name, Owner owner, boolean create_if_absent) {
Map<Owner,ClientLock> owners=table.get(name);
if(owners == null) {
if(!create_if_absent)
return null;
owners=new HashMap<>();
Map<Owner,ClientLock> existing=table.putIfAbsent(name,owners);
if(existing != null)
owners=existing;
}
ClientLock lock=owners.get(owner);
if(lock == null) {
if(!create_if_absent)
return null;
lock=createLock(name, owner);
owners.put(owner, lock);
}
return lock;
}
protected synchronized void removeClientLock(String lock_name, Owner owner) {
Map<Owner,ClientLock> owners=table.get(lock_name);
if(owners != null) {
ClientLock lock=owners.remove(owner);
if(lock != null && owners.isEmpty())
table.remove(lock_name);
}
}
protected void unlockAll() {
List<ClientLock> lock_list=new ArrayList<>();
synchronized(this) {
table.values().forEach(map -> lock_list.addAll(map.values()));
}
lock_list.forEach(ClientLock::unlock);
}
protected void resendPendingLockRequests() {
if(!table.isEmpty())
table.values().forEach(map -> map.values().stream().filter(lock -> !lock.acquired && !lock.denied)
.forEach(lock -> sendGrantLockRequest(lock.name, lock.lock_id, lock.owner, lock.timeout, lock.is_trylock)));
}
protected synchronized Collection<Map<Owner,ClientLock>> values() {
return table.values();
}
public String toString() {
StringBuilder sb=new StringBuilder();
boolean first_element=true;
for(Map.Entry<String,Map<Owner,ClientLock>> entry: table.entrySet()) {
if(first_element)
first_element=false;
else
sb.append(", ");
sb.append(entry.getKey()).append(" (");
Map<Owner,ClientLock> owners=entry.getValue();
boolean first=true;
for(Map.Entry<Owner,ClientLock> entry2: owners.entrySet()) {
if(first)
first=false;
else
sb.append(", ");
sb.append(entry2.getKey());
ClientLock cl=entry2.getValue();
if(!cl.acquired || cl.denied)
sb.append(", unlocked");
}
sb.append(")");
}
return sb.toString();
}
}
protected class ClientCondition implements Condition {
protected final ClientLock lock;
protected final AtomicBoolean signaled = new AtomicBoolean(false);
/**
* This is okay only having 1 since a client condition is 1 per
* lock_name, thread id combination.
*/
protected volatile AtomicReference<Thread> parker=new AtomicReference<>();
public ClientCondition(ClientLock lock) {
this.lock = lock;
}
@Override
public void await() throws InterruptedException {
InterruptedException ex = null;
try {
await(true);
}
catch (InterruptedException e) {
ex = e;
throw ex;
}
finally {
lock.lock();
// If we are throwing an InterruptedException
// then clear the interrupt state as well.
if (ex != null) {
Thread.interrupted();
}
}
}
@Override
public void awaitUninterruptibly() {
try {
await(false);
}
catch(InterruptedException e) {
// This should never happen
}
finally {
lock.lock();
}
}
@Override
public long awaitNanos(long nanosTimeout) throws InterruptedException {
InterruptedException ex = null;
try {
return await(nanosTimeout);
}
catch (InterruptedException e) {
ex = e;
throw ex;
}
finally {
lock.lock(); // contract mandates we need to re-acquire the lock (see overridden method)
// If we are throwing an InterruptedException then clear the interrupt state as well
if (ex != null)
Thread.interrupted();
}
}
/**
* Note this wait will only work correctly if the converted value is less
* than 292 years. This is due to the limitation in System.nano and long
* values that can only store up to 292 years (22<sup>63</sup> nanoseconds).
*
* For more information please see {@link System#nanoTime()}
*/
@Override
public boolean await(long time, TimeUnit unit) throws InterruptedException {
return awaitNanos(unit.toNanos(time)) > 0;
}
@Override
public boolean awaitUntil(Date deadline) throws InterruptedException {
long waitUntilTime=deadline.getTime();
long currentTime=System.currentTimeMillis();
long waitTime=waitUntilTime - currentTime;
return waitTime > 0 && await(waitTime, TimeUnit.MILLISECONDS);
}
protected void await(boolean throwInterrupt) throws InterruptedException {
if(!signaled.get()) {
lock.acquired = false;
sendAwaitConditionRequest(lock.name, lock.owner);
boolean interrupted=false;
while(!signaled.get()) {
parker.set(Thread.currentThread());
LockSupport.park(this);
if (Thread.interrupted()) {
// If we were interrupted and haven't received a response yet then we try to
// clean up the lock request and throw the exception
if (!signaled.get()) {
sendDeleteAwaitConditionRequest(lock.name, lock.owner);
throw new InterruptedException();
}
// In the case that we were signaled and interrupted
// we want to return the signal but still interrupt
// our thread
interrupted = true;
}
}
if(interrupted)
Thread.currentThread().interrupt();
}
// We set as if this signal was no released. This way if the
// condition is reused again, but the client condition isn't lost
// we won't think we were signaled immediately
signaled.set(false);
}
// Return the estimated time to wait (in ns), can be negative
protected long await(long nanoSeconds) throws InterruptedException {
long start=System.nanoTime();
if(!signaled.get()) {
// We release the lock at the same time as waiting on the
// condition
lock.acquired = false;
sendAwaitConditionRequest(lock.name, lock.owner);
boolean interrupted = false;
while(!signaled.get()) {
long wait_nano=nanoSeconds - (System.nanoTime() - start);
// If we waited max time break out
if(wait_nano > 0) {
parker.set(Thread.currentThread());
LockSupport.parkNanos(this, wait_nano);
if (Thread.interrupted()) {
// If we were interrupted and haven't received a response yet then we try to
// clean up the lock request and throw the exception
if (!signaled.get()) {
sendDeleteAwaitConditionRequest(lock.name, lock.owner);
throw new InterruptedException();
}
// In the case that we were signaled and interrupted
// we want to return the signal but still interrupt
// our thread
interrupted = true;
}
}
else {
break;
}
}
if(interrupted)
Thread.currentThread().interrupt();
}
// We set as if this signal was no released. This way if the
// condition is reused again, but the client condition isn't lost
// we won't think we were signaled immediately
// If we weren't signaled then delete our request
if (!signaled.getAndSet(false)) {
sendDeleteAwaitConditionRequest(lock.name, lock.owner);
}
return nanoSeconds - (System.nanoTime() - start);
}
@Override
public void signal() {
sendSignalConditionRequest(lock.name, false);
}
@Override
public void signalAll() {
sendSignalConditionRequest(lock.name, true);
}
protected void signaled() {
signaled.set(true);
Thread thread = parker.getAndSet(null);
if (thread != null)
LockSupport.unpark(thread);
}
}
protected static class Request implements Streamable {
protected Type type;
protected String lock_name;
protected int lock_id;
protected Owner owner;
protected long timeout;
protected boolean is_trylock;
public Request() {
}
public Request(Type type, String lock_name, Owner owner, long timeout) {
this.type=type;
this.lock_name=lock_name;
this.owner=owner;
this.timeout=timeout;
}
public Request(Type type, String lock_name, Owner owner, long timeout, boolean is_trylock) {
this(type, lock_name, owner, timeout);
this.is_trylock=is_trylock;
}
public Request lockId(int lock_id) {this.lock_id=lock_id; return this;}
public int lockId() {return lock_id;}
public void writeTo(DataOutput out) throws Exception {
out.writeByte(type.ordinal());
Bits.writeString(lock_name,out);
out.writeInt(lock_id);
Util.writeStreamable(owner, out);
out.writeLong(timeout);
out.writeBoolean(is_trylock);
}
public void readFrom(DataInput in) throws Exception {
type=Type.values()[in.readByte()];
lock_name=Bits.readString(in);
lock_id=in.readInt();
owner=Util.readStreamable(Owner.class, in);
timeout=in.readLong();
is_trylock=in.readBoolean();
}
public String toString() {
return type.name() + " [" + lock_name + ", lock_id=" + lock_id + ", owner=" + owner + (is_trylock? ", trylock " : " ") +
(timeout > 0? "(timeout=" + timeout + ")" : "" + "]");
}
public String toStringShort() {
StringBuilder sb=new StringBuilder();
switch(type) {
case RELEASE_LOCK:
sb.append("U");
break;
case GRANT_LOCK:
sb.append(is_trylock? "TL" : "L");
break;
default:
sb.append("N/A");
break;
}
sb.append("(").append(lock_name).append(",").append(owner);
if(timeout > 0)
sb.append(",").append(timeout);
sb.append(")");
return sb.toString();
}
}
/** A response to a request, to be sent back to the requester as a message */
protected static class Response {
protected final Type type;
protected final Owner owner;
protected final String lock_name;
protected final int lock_id;
public Response(Type type, Owner owner, String lock_name, int lock_id) {
this.type=type;
this.owner=owner;
this.lock_name=lock_name;
this.lock_id=lock_id;
}
}
public static class LockingHeader extends Header {
public LockingHeader() {
}
public short getMagicId() {return 72;}
public Supplier<? extends Header> create() {
return LockingHeader::new;
}
public int serializedSize() {
return 0;
}
public void writeTo(DataOutput out) throws Exception {
}
public void readFrom(DataInput in) throws Exception {
}
}
}
| danberindei/JGroups | src/org/jgroups/protocols/Locking.java | Java | apache-2.0 | 50,639 |
<table class="table table-bordered">
<tbody>
<tr>
<td>
<b>User:</b> {{datawake.user.user_name}}
</td>
<td>
<b>Org:</b> {{datawake.user.org}}
</td>
<td>
<b>Version:</b> {{versionNumber}}
</td>
</tr>
</tbody>
</table>
<table class="table table-bordered">
<tbody>
<tr>
<td>
<b>Domain:</b>
</td>
<td>
{{datawake.domain.name}}
</td>
</tr>
<tr>
<td>
<b>Trail:</b>
</td>
<td>
{{datawake.trail.name}}
</td>
</tr>
<tr>
<td><b>URL: </b></td>
<td>{{current_url}}</td>
</tr>
<tr ng-show="rankingEnabled">
<td>
<b>URL Ranking:</b>
</td>
<td>
<div id="star_rating"></div>
<span id="url_rank_text">{{ranking}} / 10</span>
</td>
</tr>
<tr>
<td>
<b>Page Visits:</b>
</td>
<td>
{{pageVisits}}
</td>
</tr>
</tbody>
</table> | Sotera/Datawake-Legacy | browser-plugins/FirefoxAddon/data/html/partials/header-partial.html | HTML | apache-2.0 | 1,104 |
/*
File: TestConfigurations.java ; This file is part of Twister.
Version: 2.003
Copyright (C) 2012-2013 , Luxoft
Authors: Andrei Costachi <acostachi@luxoft.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.
*/
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TestConfigurations extends JPanel{
public ConfigTree tree;
public ConfigEditor cfgedit;
public JButton save, saveas, close;
public TestConfigurations(){
setBorder(BorderFactory.createTitledBorder("Test Configurations"));
setLayout(new BorderLayout());
cfgedit = new ConfigEditor();
tree = new ConfigTree();
final JSplitPane sp = new JSplitPane();
sp.setLeftComponent(tree);
sp.setRightComponent(cfgedit.sutpanel);
sp.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
sp.setResizeWeight(0.5);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
sp.setResizeWeight(0.5);
}
});
tree.setConfigEditor(cfgedit);
cfgedit.setConfigTree(tree);
final JSplitPane sp2 = new JSplitPane();
sp2.setLeftComponent(sp);
sp2.setRightComponent(cfgedit);
sp2.setOrientation(JSplitPane.VERTICAL_SPLIT);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
sp2.setResizeWeight(0.5);
}
});
add(sp2,BorderLayout.CENTER);
}
} | ctgriffiths/twister | plugins/TestCaseExecution/TestConfigurations.java | Java | apache-2.0 | 2,201 |
/**
* Author: CZ cz.theng@gmail.com
*/
package bucket
import (
"encoding/xml"
"github.com/cz-it/aliyun-oss-golang-sdk/ossapi"
"path"
"strconv"
)
// LocationInfo is locaiton struct
type LocationInfo struct {
XMLName xml.Name `xml:"LocationConstraint"`
Location string `xml:",chardata"`
}
// QueryLocation Query bucket's location
// @param name: name of bucket
// @return location : location name of bucket
// @return ossapiError : nil on success
func QueryLocation(name string) (location string, ossapiError *ossapi.Error) {
host := name + ".oss.aliyuncs.com"
resource := path.Join("/", name) + "/"
req := &ossapi.Request{
Host: host,
Path: "/?location",
Method: "GET",
Resource: resource,
SubRes: []string{"location"}}
rsp, err := req.Send()
if err != nil {
if _, ok := err.(*ossapi.Error); !ok {
ossapi.Logger.Error("GetService's Send Error:%s", err.Error())
ossapiError = ossapi.OSSAPIError
return
}
}
if rsp.Result != ossapi.ErrSUCC {
ossapiError = err.(*ossapi.Error)
return
}
bodyLen, err := strconv.Atoi(rsp.HTTPRsp.Header["Content-Length"][0])
if err != nil {
ossapi.Logger.Error("GetService's Send Error:%s", err.Error())
ossapiError = ossapi.OSSAPIError
return
}
body := make([]byte, bodyLen)
rsp.HTTPRsp.Body.Read(body)
locationInfo := new(LocationInfo)
err = xml.Unmarshal(body, locationInfo)
if err != nil {
ossapi.Logger.Error("GetService's Send Error:%s", err.Error())
ossapiError = ossapi.OSSAPIError
return
}
location = locationInfo.Location
return
}
| gotajuly/aliyun-oss-golang-sdk-linthub | ossapi/bucket/get_bucket_location.go | GO | apache-2.0 | 1,552 |
/*
* Copyright 2016 the original author or 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 org.gradle.initialization;
import org.gradle.internal.classloader.ClassLoaderFactory;
import org.gradle.internal.classloader.ClasspathUtil;
import org.gradle.internal.classpath.DefaultClassPath;
import org.gradle.internal.jvm.Jvm;
import java.io.File;
import java.net.URLClassLoader;
public class DefaultJdkToolsInitializer implements JdkToolsInitializer {
private final ClassLoaderFactory classLoaderFactory;
public DefaultJdkToolsInitializer(ClassLoaderFactory classLoaderFactory) {
this.classLoaderFactory = classLoaderFactory;
}
public void initializeJdkTools() {
// Add in tools.jar to the systemClassloader parent
File toolsJar = Jvm.current().getToolsJar();
if (toolsJar != null) {
final ClassLoader systemClassLoaderParent = classLoaderFactory.getIsolatedSystemClassLoader();
ClasspathUtil.addUrl((URLClassLoader) systemClassLoaderParent, new DefaultClassPath(toolsJar).getAsURLs());
}
}
} | gstevey/gradle | subprojects/core/src/main/java/org/gradle/initialization/DefaultJdkToolsInitializer.java | Java | apache-2.0 | 1,612 |
// Copyright 2013 Selenium committers
// Copyright 2013 Software Freedom Conservancy
//
// 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.
/**
* @fileoverview Utilities for working with the browser window extension bar.
*/
goog.provide('safaridriver.extension.bar');
/**
* Sets the message to display to the user in the extension bar.
* @param {string} message The message text.
* @param {string=} opt_color The message color; defaults to black.
*/
safaridriver.extension.bar.setUserMessage = function(message, opt_color) {
var color = opt_color || 'black';
if (message.length > 75) {
message = message.substring(0, 75) + '...';
}
var bars = safari.extension.bars;
for (var i = 0, n = bars.length; i < n; ++i) {
var bar = bars[i];
var msgEl = bar.contentWindow.document.getElementById('message');
if (msgEl) {
msgEl.innerText = message;
msgEl.style.color = color;
}
}
}; | lummyare/lummyare-lummy | javascript/safari-driver/extension/extensionbar.js | JavaScript | apache-2.0 | 1,430 |
/* 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 java.nio.charset;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Arrays;
public abstract class CharsetEncoder {
private static final int RESET = 0;
private static final int ONGOING = 1;
private static final int END_OF_INPUT = 2;
private static final int FLUSHED = 3;
private final Charset charset;
private final float averageBytesPerChar;
private final float maxBytesPerChar;
private byte[] replacementBytes;
private int state = RESET;
static private CoderResult dummyCR = CoderResult.OVERFLOW;
static private CodingErrorAction malformedInputAction = CodingErrorAction.REPORT;
static private CodingErrorAction unmappableCharacterAction = CodingErrorAction.REPORT;
// decoder instance for this encoder's charset, used for replacement value checking
private CharsetDecoder decoder;
/**
* Constructs a new {@code CharsetEncoder} using the given parameters and
* the replacement byte array {@code { (byte) '?' }}.
*/
protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar) {
this(cs, averageBytesPerChar, maxBytesPerChar, new byte[] { (byte) '?' });
}
/**
* Constructs a new <code>CharsetEncoder</code> using the given
* <code>Charset</code>, replacement byte array, average number and
* maximum number of bytes created by this encoder for one input character.
*
* @param cs
* the <code>Charset</code> to be used by this encoder.
* @param averageBytesPerChar
* average number of bytes created by this encoder for one single
* input character, must be positive.
* @param maxBytesPerChar
* maximum number of bytes which can be created by this encoder
* for one single input character, must be positive.
* @param replacement
* the replacement byte array, cannot be null or empty, its
* length cannot be larger than <code>maxBytesPerChar</code>,
* and must be a legal replacement, which can be justified by
* {@link #isLegalReplacement(byte[]) isLegalReplacement}.
* @throws IllegalArgumentException
* if any parameters are invalid.
*/
protected CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement) {
this(cs, averageBytesPerChar, maxBytesPerChar, replacement, false);
}
CharsetEncoder(Charset cs, float averageBytesPerChar, float maxBytesPerChar, byte[] replacement, boolean trusted) {
if (averageBytesPerChar <= 0 || maxBytesPerChar <= 0) {
throw new IllegalArgumentException("averageBytesPerChar and maxBytesPerChar must both be positive");
}
if (averageBytesPerChar > maxBytesPerChar) {
throw new IllegalArgumentException("averageBytesPerChar is greater than maxBytesPerChar");
}
this.charset = cs;
this.averageBytesPerChar = averageBytesPerChar;
this.maxBytesPerChar = maxBytesPerChar;
if (trusted) {
// The RI enforces unnecessary restrictions on the replacement bytes. We trust ICU to
// know what it's doing. Doing so lets us support ICU's EUC-JP, SCSU, and Shift_JIS.
this.replacementBytes = replacement;
} else {
replaceWith(replacement);
}
}
/**
* Returns the average number of bytes created by this encoder for a single
* input character.
*/
public final float averageBytesPerChar() {
return averageBytesPerChar;
}
/**
* Tests whether the given character can be encoded by this encoder.
*
* <p>Note that this method may change the internal state of this encoder, so
* it should not be called when another encoding process is ongoing,
* otherwise it will throw an <code>IllegalStateException</code>.
*
* @throws IllegalStateException if another encode process is ongoing.
*/
public boolean canEncode(char c) {
return canEncode(CharBuffer.wrap(new char[] { c }));
}
/**
* Tests whether the given <code>CharSequence</code> can be encoded by this
* encoder.
*
* <p>Note that this method may change the internal state of this encoder, so
* it should not be called when another encode process is ongoing, otherwise
* it will throw an <code>IllegalStateException</code>.
*
* @throws IllegalStateException if another encode process is ongoing.
*/
public boolean canEncode(CharSequence sequence) {
CharBuffer cb;
if (sequence instanceof CharBuffer) {
cb = ((CharBuffer) sequence).duplicate();
} else {
cb = CharBuffer.wrap(sequence);
}
if (state == FLUSHED) {
reset();
}
if (state != RESET) {
throw illegalStateException();
}
CodingErrorAction originalMalformedInputAction = malformedInputAction;
CodingErrorAction originalUnmappableCharacterAction = unmappableCharacterAction;
onMalformedInput(CodingErrorAction.REPORT);
onUnmappableCharacter(CodingErrorAction.REPORT);
try {
encode(cb);
return true;
} catch (CharacterCodingException e) {
return false;
} finally {
onMalformedInput(originalMalformedInputAction);
onUnmappableCharacter(originalUnmappableCharacterAction);
reset();
}
}
/**
* Returns the {@link Charset} which this encoder uses.
*/
public final Charset charset() {
return charset;
}
/**
* This is a facade method for the encoding operation.
* <p>
* This method encodes the remaining character sequence of the given
* character buffer into a new byte buffer. This method performs a complete
* encoding operation, resets at first, then encodes, and flushes at last.
* <p>
* This method should not be invoked if another encode operation is ongoing.
*
* @param in
* the input buffer.
* @return a new <code>ByteBuffer</code> containing the bytes produced by
* this encoding operation. The buffer's limit will be the position
* of the last byte in the buffer, and the position will be zero.
* @throws IllegalStateException
* if another encoding operation is ongoing.
* @throws MalformedInputException
* if an illegal input character sequence for this charset is
* encountered, and the action for malformed error is
* {@link CodingErrorAction#REPORT CodingErrorAction.REPORT}
* @throws UnmappableCharacterException
* if a legal but unmappable input character sequence for this
* charset is encountered, and the action for unmappable
* character error is
* {@link CodingErrorAction#REPORT CodingErrorAction.REPORT}.
* Unmappable means the Unicode character sequence at the input
* buffer's current position cannot be mapped to a equivalent
* byte sequence.
* @throws CharacterCodingException
* if other exception happened during the encode operation.
*/
public final ByteBuffer encode(CharBuffer in) throws CharacterCodingException {
int length = (int) (in.remaining() * averageBytesPerChar);
ByteBuffer out = ByteBuffer.allocate(length);
reset();
while (state != FLUSHED) {
CoderResult result = encode(in, out, true);
if (result == CoderResult.OVERFLOW) {
out = allocateMore(out);
continue; // No point trying to flush to an already-full buffer.
} else {
checkCoderResult(result);
}
result = flush(out);
if (result == CoderResult.OVERFLOW) {
out = allocateMore(out);
} else {
checkCoderResult(result);
}
}
out.flip();
return out;
}
private void checkCoderResult(CoderResult result) throws CharacterCodingException {
if (malformedInputAction == CodingErrorAction.REPORT && result.isMalformed()) {
throw new MalformedInputException(result.length());
} else if (unmappableCharacterAction == CodingErrorAction.REPORT && result.isUnmappable()) {
throw new UnmappableCharacterException(result.length());
}
}
private ByteBuffer allocateMore(ByteBuffer output) {
if (output.capacity() == 0) {
return ByteBuffer.allocate(1);
}
ByteBuffer result = ByteBuffer.allocate(output.capacity() * 2);
output.flip();
result.put(output);
return result;
}
/**
* Encodes characters starting at the current position of the given input
* buffer, and writes the equivalent byte sequence into the given output
* buffer from its current position.
* <p>
* The buffers' position will be changed with the reading and writing
* operation, but their limits and marks will be kept intact.
* <p>
* A <code>CoderResult</code> instance will be returned according to
* following rules:
* <ul>
* <li>A {@link CoderResult#malformedForLength(int) malformed input} result
* indicates that some malformed input error was encountered, and the
* erroneous characters start at the input buffer's position and their
* number can be got by result's {@link CoderResult#length() length}. This
* kind of result can be returned only if the malformed action is
* {@link CodingErrorAction#REPORT CodingErrorAction.REPORT}.</li>
* <li>{@link CoderResult#UNDERFLOW CoderResult.UNDERFLOW} indicates that
* as many characters as possible in the input buffer have been encoded. If
* there is no further input and no characters left in the input buffer then
* this task is complete. If this is not the case then the client should
* call this method again supplying some more input characters.</li>
* <li>{@link CoderResult#OVERFLOW CoderResult.OVERFLOW} indicates that the
* output buffer has been filled, while there are still some characters
* remaining in the input buffer. This method should be invoked again with a
* non-full output buffer.</li>
* <li>A {@link CoderResult#unmappableForLength(int) unmappable character}
* result indicates that some unmappable character error was encountered,
* and the erroneous characters start at the input buffer's position and
* their number can be got by result's {@link CoderResult#length() length}.
* This kind of result can be returned only on
* {@link CodingErrorAction#REPORT CodingErrorAction.REPORT}.</li>
* </ul>
* <p>
* The <code>endOfInput</code> parameter indicates if the invoker can
* provider further input. This parameter is true if and only if the
* characters in the current input buffer are all inputs for this encoding
* operation. Note that it is common and won't cause an error if the invoker
* sets false and then has no more input available, while it may cause an
* error if the invoker always sets true in several consecutive invocations.
* This would make the remaining input to be treated as malformed input.
* input.
* <p>
* This method invokes the
* {@link #encodeLoop(CharBuffer, ByteBuffer) encodeLoop} method to
* implement the basic encode logic for a specific charset.
*
* @param in
* the input buffer.
* @param out
* the output buffer.
* @param endOfInput
* true if all the input characters have been provided.
* @return a <code>CoderResult</code> instance indicating the result.
* @throws IllegalStateException
* if the encoding operation has already started or no more
* input is needed in this encoding process.
* @throws CoderMalfunctionError
* If the {@link #encodeLoop(CharBuffer, ByteBuffer) encodeLoop}
* method threw an <code>BufferUnderflowException</code> or
* <code>BufferUnderflowException</code>.
*/
public final CoderResult encode(CharBuffer in, ByteBuffer out, boolean endOfInput) {
if (state != RESET && state != ONGOING && !(endOfInput && state == END_OF_INPUT)) {
throw illegalStateException();
}
state = endOfInput ? END_OF_INPUT : ONGOING;
while (true) {
CoderResult result;
try {
result = encodeLoop(in, out);
} catch (BufferOverflowException ex) {
throw new CoderMalfunctionError(ex);
} catch (BufferUnderflowException ex) {
throw new CoderMalfunctionError(ex);
}
if (result == CoderResult.UNDERFLOW) {
if (endOfInput && in.hasRemaining()) {
result = CoderResult.malformedForLength(in.remaining());
} else {
return result;
}
} else if (result == CoderResult.OVERFLOW) {
return result;
}
// We have a real error, so do what the appropriate action tells us what to do...
CodingErrorAction action =
result.isUnmappable() ? unmappableCharacterAction : malformedInputAction;
if (action == CodingErrorAction.REPORT) {
return result;
} else if (action == CodingErrorAction.REPLACE) {
if (out.remaining() < replacementBytes.length) {
return CoderResult.OVERFLOW;
}
out.put(replacementBytes);
}
in.position(in.position() + result.length());
}
}
/**
* Encodes characters into bytes. This method is called by
* {@link #encode(CharBuffer, ByteBuffer, boolean) encode}.
* <p>
* This method will implement the essential encoding operation, and it won't
* stop encoding until either all the input characters are read, the output
* buffer is filled, or some exception is encountered. Then it will
* return a <code>CoderResult</code> object indicating the result of the
* current encoding operation. The rule to construct the
* <code>CoderResult</code> is the same as for
* {@link #encode(CharBuffer, ByteBuffer, boolean) encode}. When an
* exception is encountered in the encoding operation, most implementations
* of this method will return a relevant result object to the
* {@link #encode(CharBuffer, ByteBuffer, boolean) encode} method, and
* subclasses may handle the exception and
* implement the error action themselves.
* <p>
* The buffers are scanned from their current positions, and their positions
* will be modified accordingly, while their marks and limits will be
* intact. At most {@link CharBuffer#remaining() in.remaining()} characters
* will be read, and {@link ByteBuffer#remaining() out.remaining()} bytes
* will be written.
* <p>
* Note that some implementations may pre-scan the input buffer and return
* <code>CoderResult.UNDERFLOW</code> until it receives sufficient input.
* <p>
* @param in
* the input buffer.
* @param out
* the output buffer.
* @return a <code>CoderResult</code> instance indicating the result.
*/
protected abstract CoderResult encodeLoop(CharBuffer in, ByteBuffer out);
/**
* Flushes this encoder.
* <p>
* This method will call {@link #implFlush(ByteBuffer) implFlush}. Some
* encoders may need to write some bytes to the output buffer when they have
* read all input characters, subclasses can overridden
* {@link #implFlush(ByteBuffer) implFlush} to perform writing action.
* <p>
* The maximum number of written bytes won't larger than
* {@link ByteBuffer#remaining() out.remaining()}. If some encoder wants to
* write more bytes than the output buffer's available remaining space, then
* <code>CoderResult.OVERFLOW</code> will be returned, and this method
* must be called again with a byte buffer that has free space. Otherwise
* this method will return <code>CoderResult.UNDERFLOW</code>, which
* means one encoding process has been completed successfully.
* <p>
* During the flush, the output buffer's position will be changed
* accordingly, while its mark and limit will be intact.
*
* @param out
* the given output buffer.
* @return <code>CoderResult.UNDERFLOW</code> or
* <code>CoderResult.OVERFLOW</code>.
* @throws IllegalStateException
* if this encoder isn't already flushed or at end of input.
*/
public final CoderResult flush(ByteBuffer out) {
if (state != FLUSHED && state != END_OF_INPUT) {
throw illegalStateException();
}
CoderResult result = implFlush(out);
if (result == CoderResult.UNDERFLOW) {
state = FLUSHED;
}
return result;
}
/**
* Flushes this encoder. The default implementation does nothing and always
* returns <code>CoderResult.UNDERFLOW</code>; this method can be
* overridden if needed.
*
* @param out
* the output buffer.
* @return <code>CoderResult.UNDERFLOW</code> or
* <code>CoderResult.OVERFLOW</code>.
*/
protected CoderResult implFlush(ByteBuffer out) {
return CoderResult.UNDERFLOW;
}
/**
* Notifies that this encoder's <code>CodingErrorAction</code> specified
* for malformed input error has been changed. The default implementation
* does nothing; this method can be overridden if needed.
*
* @param newAction
* the new action.
*/
protected void implOnMalformedInput(CodingErrorAction newAction) {
// default implementation is empty
}
/**
* Notifies that this encoder's <code>CodingErrorAction</code> specified
* for unmappable character error has been changed. The default
* implementation does nothing; this method can be overridden if needed.
*
* @param newAction
* the new action.
*/
protected void implOnUnmappableCharacter(CodingErrorAction newAction) {
// default implementation is empty
}
/**
* Notifies that this encoder's replacement has been changed. The default
* implementation does nothing; this method can be overridden if needed.
*
* @param newReplacement
* the new replacement string.
*/
protected void implReplaceWith(byte[] newReplacement) {
// default implementation is empty
}
/**
* Resets this encoder's charset related state. The default implementation
* does nothing; this method can be overridden if needed.
*/
protected void implReset() {
// default implementation is empty
}
/**
* Tests whether the given argument is legal as this encoder's replacement byte
* array. The given byte array is legal if and only if it can be decoded into
* characters.
*/
public boolean isLegalReplacement(byte[] replacement) {
if (decoder == null) {
decoder = charset.newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
}
ByteBuffer in = ByteBuffer.wrap(replacement);
CharBuffer out = CharBuffer.allocate((int) (replacement.length * decoder.maxCharsPerByte()));
CoderResult result = decoder.decode(in, out, true);
return !result.isError();
}
/**
* Returns this encoder's <code>CodingErrorAction</code> when a malformed
* input error occurred during the encoding process.
*/
public CodingErrorAction malformedInputAction() {
return malformedInputAction;
}
/**
* Returns the maximum number of bytes which can be created by this encoder for
* one input character, must be positive.
*/
public final float maxBytesPerChar() {
return maxBytesPerChar;
}
/**
* Sets this encoder's action on malformed input error.
*
* This method will call the
* {@link #implOnMalformedInput(CodingErrorAction) implOnMalformedInput}
* method with the given new action as argument.
*
* @param newAction
* the new action on malformed input error.
* @return this encoder.
* @throws IllegalArgumentException
* if the given newAction is null.
*/
public final CharsetEncoder onMalformedInput(CodingErrorAction newAction) {
if (newAction == null) {
throw new IllegalArgumentException("newAction == null");
}
malformedInputAction = newAction;
implOnMalformedInput(newAction);
return this;
}
/**
* Sets this encoder's action on unmappable character error.
*
* This method will call the
* {@link #implOnUnmappableCharacter(CodingErrorAction) implOnUnmappableCharacter}
* method with the given new action as argument.
*
* @param newAction
* the new action on unmappable character error.
* @return this encoder.
* @throws IllegalArgumentException
* if the given newAction is null.
*/
public final CharsetEncoder onUnmappableCharacter(CodingErrorAction newAction) {
if (newAction == null) {
throw new IllegalArgumentException("newAction == null");
}
unmappableCharacterAction = newAction;
implOnUnmappableCharacter(newAction);
return this;
}
/**
* Returns the replacement byte array, which is never null or empty.
*/
public final byte[] replacement() {
return replacementBytes;
}
/**
* Sets the new replacement value.
*
* This method first checks the given replacement's validity, then changes
* the replacement value and finally calls the
* {@link #implReplaceWith(byte[]) implReplaceWith} method with the given
* new replacement as argument.
*
* @param replacement
* the replacement byte array, cannot be null or empty, its
* length cannot be larger than <code>maxBytesPerChar</code>,
* and it must be legal replacement, which can be justified by
* calling <code>isLegalReplacement(byte[] replacement)</code>.
* @return this encoder.
* @throws IllegalArgumentException
* if the given replacement cannot satisfy the requirement
* mentioned above.
*/
public final CharsetEncoder replaceWith(byte[] replacement) {
if (replacement == null) {
throw new IllegalArgumentException("replacement == null");
}
if (replacement.length == 0) {
throw new IllegalArgumentException("replacement.length == 0");
}
if (replacement.length > maxBytesPerChar()) {
throw new IllegalArgumentException("replacement.length > maxBytesPerChar: " +
replacement.length + " > " + maxBytesPerChar());
}
if (!isLegalReplacement(replacement)) {
throw new IllegalArgumentException("Bad replacement: " + Arrays.toString(replacement));
}
// It seems like a bug, but the RI doesn't clone, and we have tests that check we don't.
this.replacementBytes = replacement;
implReplaceWith(replacementBytes);
return this;
}
/**
* Resets this encoder. This method will reset the internal state and then
* calls {@link #implReset} to reset any state related to the
* specific charset.
*/
public final CharsetEncoder reset() {
state = RESET;
implReset();
return this;
}
/**
* Returns this encoder's <code>CodingErrorAction</code> when unmappable
* character occurred during encoding process.
*/
public CodingErrorAction unmappableCharacterAction() {
return unmappableCharacterAction;
}
private IllegalStateException illegalStateException() {
throw new IllegalStateException("State: " + state);
}
} | intrigus/jtransc | jtransc-rt/src/java/nio/charset/CharsetEncoder.java | Java | apache-2.0 | 23,146 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Saltr iOS SDK: SLTBoardLayer Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Saltr iOS SDK
 <span id="projectnumber">1.3.2</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.9.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Instance Methods</a> |
<a href="#properties">Properties</a> |
<a href="class_s_l_t_board_layer-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">SLTBoardLayer Class Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>The <a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a> class represents the game board's layer.
<a href="interface_s_l_t_board_layer.html#details">More...</a></p>
<p><code>#import <<a class="el" href="_s_l_t_board_layer_8h_source.html">SLTBoardLayer.h</a>></code></p>
<div class="dynheader">
Inheritance diagram for SLTBoardLayer:</div>
<div class="dyncontent">
<div class="center">
<img src="interface_s_l_t_board_layer.png" usemap="#SLTBoardLayer_map" alt=""/>
<map id="SLTBoardLayer_map" name="SLTBoardLayer_map">
<area href="interface_s_l_t2_d_board_layer.html" title="The SLT2DBoardLayer class represents the game 2D board's layer. " alt="SLT2DBoardLayer" shape="rect" coords="0,112,153,136"/>
<area href="interface_s_l_t_matching_board_layer.html" title="The SLTMatchingBoardLayer class represents the matching board. " alt="SLTMatchingBoardLayer" shape="rect" coords="163,112,316,136"/>
</map>
</div></div>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Instance Methods</h2></td></tr>
<tr class="memitem:a98070e01e36b88dd3423ec8539b65bac"><td class="memItemLeft" align="right" valign="top">(id) </td><td class="memItemRight" valign="bottom">- <a class="el" href="interface_s_l_t_board_layer.html#a98070e01e36b88dd3423ec8539b65bac">initWithToken:andLayerIndex:</a></td></tr>
<tr class="separator:a98070e01e36b88dd3423ec8539b65bac"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a>
Properties</h2></td></tr>
<tr class="memitem:ab8816d81fe83a9e0330b0e50544e4f1c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab8816d81fe83a9e0330b0e50544e4f1c"></a>
NSString * </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_s_l_t_board_layer.html#ab8816d81fe83a9e0330b0e50544e4f1c">token</a></td></tr>
<tr class="memdesc:ab8816d81fe83a9e0330b0e50544e4f1c"><td class="mdescLeft"> </td><td class="mdescRight">The unique identifier of the layer. <br /></td></tr>
<tr class="separator:ab8816d81fe83a9e0330b0e50544e4f1c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a21cd27f9d72048ac17628bff558feffb"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a21cd27f9d72048ac17628bff558feffb"></a>
NSInteger </td><td class="memItemRight" valign="bottom"><a class="el" href="interface_s_l_t_board_layer.html#a21cd27f9d72048ac17628bff558feffb">index</a></td></tr>
<tr class="memdesc:a21cd27f9d72048ac17628bff558feffb"><td class="mdescLeft"> </td><td class="mdescRight">The layer's ordering index. <br /></td></tr>
<tr class="separator:a21cd27f9d72048ac17628bff558feffb"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>The <a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a> class represents the game board's layer. </p>
</div><h2 class="groupheader">Method Documentation</h2>
<a class="anchor" id="a98070e01e36b88dd3423ec8539b65bac"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">- (id) initWithToken: </td>
<td></td>
<td class="paramtype">(NSString *) </td>
<td class="paramname"><em>theToken</em></td>
</tr>
<tr>
<td class="paramkey">andLayerIndex:</td>
<td></td>
<td class="paramtype">(NSInteger) </td>
<td class="paramname"><em>theLayerIndex</em> </td>
</tr>
<tr>
<td></td>
<td></td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Inits an instance of <b><a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a></b> class with the given token and layer index. </p><dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">theToken</td><td>The unique identifier of the layer. </td></tr>
<tr><td class="paramname">theLayerIndex</td><td>The layer's ordering index. </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>The instance of <b><a class="el" href="interface_s_l_t_board_layer.html" title="The SLTBoardLayer class represents the game board's layer. ">SLTBoardLayer</a></b> class. </dd></dl>
<p>Implemented in <a class="el" href="interface_s_l_t_matching_board_layer.html#a285f9b3227504cd9ea9d536215c598de">SLTMatchingBoardLayer</a>, and <a class="el" href="interface_s_l_t2_d_board_layer.html#a1b2f67d46a6967050957a6db7a46e5fd">SLT2DBoardLayer</a>.</p>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>Saltr/game/<a class="el" href="_s_l_t_board_layer_8h_source.html">SLTBoardLayer.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Feb 4 2015 16:13:48 for Saltr iOS SDK by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.9.1
</small></address>
</body>
</html>
| SALTR/saltr-ios-sdk | build/bin/Saltr.v.1.3.2/doc/interface_s_l_t_board_layer.html | HTML | apache-2.0 | 9,310 |
/*
* 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.guacamole.auth.jdbc.tunnel;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.net.InetGuacamoleSocket;
/**
* Implementation of GuacamoleSocket which connects via TCP to a given hostname
* and port. If the socket is closed for any reason, a given task is run.
*
* @author Michael Jumper
*/
public class ManagedInetGuacamoleSocket extends InetGuacamoleSocket {
/**
* The task to run when the socket is closed.
*/
private final Runnable socketClosedTask;
/**
* Creates a new socket which connects via TCP to a given hostname and
* port. If the socket is closed for any reason, the given task is run.
*
* @param hostname
* The hostname of the Guacamole proxy server to connect to.
*
* @param port
* The port of the Guacamole proxy server to connect to.
*
* @param socketClosedTask
* The task to run when the socket is closed. This task will NOT be
* run if an exception occurs during connection, and this
* ManagedInetGuacamoleSocket instance is ultimately not created.
*
* @throws GuacamoleException
* If an error occurs while connecting to the Guacamole proxy server.
*/
public ManagedInetGuacamoleSocket(String hostname, int port,
Runnable socketClosedTask) throws GuacamoleException {
super(hostname, port);
this.socketClosedTask = socketClosedTask;
}
@Override
public void close() throws GuacamoleException {
super.close();
socketClosedTask.run();
}
}
| DaanWillemsen/guacamole-client | extensions/guacamole-auth-jdbc/modules/guacamole-auth-jdbc-base/src/main/java/org/apache/guacamole/auth/jdbc/tunnel/ManagedInetGuacamoleSocket.java | Java | apache-2.0 | 2,418 |
# Notifications in Zulip
This is a design document aiming to provide context for developers
working on Zulip's email notifications and mobile push notifications
code paths. We recommend first becoming familiar with [sending
messages](../subsystems/sending-messages.md); this document expands on
the details of the email/mobile push notifications code path.
## Important corner cases
Here we name a few corner cases worth understanding in designing this
sort of notifications system:
- The **idle desktop problem**: We don't want the presence of a
desktop computer at the office to eat all notifications because the
user has an "online" client that they may not have used in 3 days.
- The **hard disconnect problem**: A client can lose its connection to
the Internet (or be suspended, or whatever) at any time, and this
happens routinely. We want to ensure that races where a user closes
their laptop shortly after a notifiable message is sent does not
result in the user never receiving a notification about a message
(due to the system thinking that client received it).
## The mobile/email notifications flow
As a reminder, the relevant part of the flow for sending messages is
as follows:
- `do_send_messages` is the synchronous message-sending code path,
and passing the following data in its `send_event` call:
- Data about the message's content (E.g. mentions, wildcard
mentions, and alert words) and encodes it into the `UserMessage`
table's `flags` structure, which is in turn passed into
`send_event` for each user receiving the message.
- Data about user configuration relevant to the message, such as
`online_push_user_ids` and `stream_notify_user_ids`, are included
in the main event dictionary.
- The `presence_idle_user_ids` set, containing the subset of
recipient users who can potentially receive notifications, but have not
interacted with a Zulip client in the last few minutes. (Users who
have generally will not receive a notification unless the
`enable_online_push_notifications` flag is enabled). This data
structure ignores users for whom the message is not notifiable,
which is important to avoid this being thousands of `user_ids` for
messages to large streams with few currently active users.
- The Tornado [event queue system](../subsystems/events-system.md)
processes that data, as well as data about each user's active event
queues, to (1) push an event to each queue needing that message and
(2) for notifiable messages, pushing an event onto the
`missedmessage_mobile_notifications` and/or `missedmessage_emails`
queues. This important message-processing logic has notable extra
logic not present when processing normal events, both for details
like splicing `flags` to customize event payloads per-user, as well.
- The Tornado system determines whether the user is "offline/idle".
Zulip's email notifications are designed to not fire when the user
is actively using Zulip to avoid spam, and this is where those
checks are implemented.
- Users in `presence_idle_user_ids` are always considered idle:
the variable name means "users who are idle because of
presence". This is how we solve the idle desktop problem; users
with an idle desktop are treated the same as users who aren't
logged in for this check.
- However, that check does not handle the hard disconnect problem:
if a user was present 1 minute before a message was sent, and then
closed their laptop, the user will not be in
`presence_idle_user_ids` (because it takes a
[few minutes](../subsystems/presence.md) of being idle for Zulip
clients to declare to the server that the user is actually idle),
and so without an additional mechanism, messages sent shortly after
a user leaves would never trigger a notification (!).
- We solve that problem by also notifying if
`receiver_is_off_zulip` returns `True`, which checks whether the user has any
current events system clients registered to receive `message`
events. This check is done immediately (handling soft disconnects,
where E.g. the user closes their last Zulip tab and we get the
`DELETE /events/{queue_id}` request).
- The `receiver_is_off_zulip` check is effectively repeated when
event queues are garbage-collected (in `missedmessage_hook`) by
looking for whether the queue being garbage-collected was the only
one; this second check solves the hard disconnect problem, resulting in
notifications for these hard-disconnect cases usually coming 10
minutes late.
- We try to contain the "when to notify" business logic in the
`zerver/lib/notification_data.py` class methods. The module has
unit tests for all possible situations in
`test_notification_data.py`.
- The message-edit code path has parallel logic in
`maybe_enqueue_notifications_for_message_update` for triggering
notifications in cases like a mention added during message
editing.
- The notification sending logic for message edits
inside Tornado has extensive automated test suites; e.g.
`test_message_edit_notifications.py` covers all the cases around
editing a message to add/remove a mention.
- We may in the future want to add some sort of system for letting
users see past notifications, to help with explaining and
debugging this system, since it has so much complexity.
- Desktop notifications are the simplest; they are implemented
client-side by the web/desktop app's logic
(`static/js/notifications.js`) inspecting the `flags` fields that
were spliced into `message` events by the Tornado system, as well as
the user's notification settings.
- The queue processors for those queues make the final determination
for whether to send a notification, and do the work to generate an
email (`zerver/lib/email_notifications.py`) or mobile
(`zerver/lib/push_notifications.py`) notification. We'll detail
this process in more detail for each system below, but it's
important to know that it's normal for a message to sit in these
queues for minutes (and in the future, possibly hours).
- Both queue processor code paths do additional filtering before
sending a notification:
- Messages that have already been marked as read by the user before
the queue processor runs never trigger a notification.
- Messages that were already deleted never trigger a notification.
- The user-level settings for whether email/mobile notifications are
disabled are rechecked, as the user may have disabled one of these
settings during the queuing period.
- The **Email notifications queue processor**, `MissedMessageWorker`,
takes care to wait for 2 minutes (hopefully in the future this will be a
configuration setting) and starts a thread to batch together multiple
messages into a single email. These features are unnecessary
for mobile push notifications, because we can live-update those
details with a future notification, whereas emails cannot be readily
updated once sent. Zulip's email notifications are styled similarly
to GitHub's email notifications, with a clean, simple design that
makes replying from an email client possible (using the [incoming
email integration](../production/email-gateway.md)).
- The **Push notifications queue processor**,
`PushNotificationsWorker`, is a simple wrapper around the
`push_notifications.py` code that actually sends the
notification. This logic is somewhat complicated by having to track
the number of unread push notifications to display on the mobile
apps' badges, as well as using the [mobile push notifications
service](../production/mobile-push-notifications.md) for self-hosted
systems.
The following important constraints are worth understanding about the
structure of the system, when thinking about changes to it:
- **Bulk database queries** are much more efficient for checking
details from the database like "which users receiving this message
are online".
- **Thousands of users**. Zulip supports thousands of users, and we
want to avoid `send_event()` pushing large amounts of per-user data
to Tornado via RabbitMQ for scalability reasons.
- **Tornado doesn't do database queries**. Because the Tornado system
is an asynchronous event-driven framework, and our Django database
library is synchronous, database queries are very expensive. So
these queries need to be done in either `do_send_messages` or the
queue processor logic. (For example, this means `presence` data
should be checked in either `do_send_messages` or the queue
processors, not in Tornado).
- **Future configuration**. Notification settings are an area that we
expect to only expand with time, with upcoming features like
following a topic (to get notifications for messages only within
that topic in a stream). There are a lot of different workflows
possible with Zulip's threading, and it's important to make it easy
for users to set up Zulip's notification to fit as many of those
workflows as possible.
- **Message editing**. Zulip supports editing messages, and that
interacts with notifications in ways that require careful handling:
Notifications should have
the latest edited content (users often fix typos 30 seconds after
sending a message), adding a mention when editing a message should
send a notification to the newly mentioned user(s), and deleting a
message should cancel any unsent notifications for it.
| eeshangarg/zulip | docs/subsystems/notifications.md | Markdown | apache-2.0 | 9,556 |
/*
* Copyright 2003,2004 The Apache Software 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.apache.axis.management;
import org.apache.axis.components.logger.LogFactory;
import org.apache.axis.i18n.Messages;
import org.apache.commons.logging.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* class to act as a dynamic loading registrar to commons-modeler, so
* as to autoregister stuff
*
* @link http://www.webweavertech.com/costin/archives/000168.html#000168
*/
public class Registrar {
/**
* our log
*/
protected static Log log = LogFactory.getLog(Registrar.class.getName());
/**
* register using reflection. The perf hit is moot as jmx is
* all reflection anyway
*
* @param objectToRegister
* @param name
* @param context
*/
public static boolean register(Object objectToRegister,
String name, String context) {
if (isBound()) {
if (log.isDebugEnabled()) {
log.debug("Registering " + objectToRegister + " as "
+ name);
}
return modelerBinding.register(objectToRegister, name, context);
} else {
return false;
}
}
/**
* Check for being bound to a modeler -this will force
* a binding if none existed.
*
* @return
*/
public static boolean isBound() {
createModelerBinding();
return modelerBinding.canBind();
}
/**
* create the modeler binding if it is needed
* At the end of this call, modelerBinding != null
*/
private static void createModelerBinding() {
if (modelerBinding == null) {
modelerBinding = new ModelerBinding();
}
}
/**
* the inner class that does the binding
*/
private static ModelerBinding modelerBinding = null;
/**
* This class provides a dynamic binding to the
* commons-modeler registry at run time
*/
static class ModelerBinding {
/**
* the constructor binds
*/
public ModelerBinding() {
bindToModeler();
}
/**
* can the binding bind?
*
* @return true iff the classes are bound
*/
public boolean canBind() {
return registry != null;
}
/**
* log
*/
protected static Log log = LogFactory.getLog(ModelerBinding.class.getName());
/**
* registry object
*/
Object registry;
/**
* method to call
*/
Method registerComponent;
/**
* register using reflection. The perf hit is moot as jmx is
* all reflection anyway
*
* @param objectToRegister
* @param name
* @param context
*/
public boolean register(Object objectToRegister, String name, String context) {
if (registry != null) {
Object args[] = new Object[]{objectToRegister, name, context};
try {
registerComponent.invoke(registry, args);
if (log.isDebugEnabled()) {
log.debug("Registered " + name + " in " + context);
}
} catch (IllegalAccessException e) {
log.error(e);
return false;
} catch (IllegalArgumentException e) {
log.error(e);
return false;
} catch (InvocationTargetException e) {
log.error(e);
return false;
}
return true;
} else {
return false;
}
}
/**
* bind to the modeler; return success/failure flag
*
* @return true if the binding worked
*/
private boolean bindToModeler() {
Exception ex = null;
Class clazz;
try {
clazz = Class.forName("org.apache.commons.modeler.Registry");
} catch (ClassNotFoundException e) {
// just ignore it silently if we don't have commons-modeler.jar around
registry = null;
return false;
}
try {
Class[] getRegistryArgs = new Class[]{Object.class, Object.class,};
Method getRegistry = clazz.getMethod("getRegistry", getRegistryArgs);
Object[] getRegistryOptions = new Object[]{null, null};
registry = getRegistry.invoke(null, getRegistryOptions);
Class[] registerArgs = new Class[]{Object.class,
String.class,
String.class};
registerComponent = clazz.getMethod("registerComponent", registerArgs);
} catch (IllegalAccessException e) {
ex = e;
} catch (IllegalArgumentException e) {
ex = e;
} catch (InvocationTargetException e) {
ex = e;
} catch (NoSuchMethodException e) {
ex = e;
}
// handle any of these exceptions
if (ex != null) {
//log the error
log.warn(Messages.getMessage("Registrar.cantregister"), ex);
//mark the registration as a failure
registry = null;
//and fail
return false;
} else {
//success
return true;
}
}
}
}
| hugosato/apache-axis | src/org/apache/axis/management/Registrar.java | Java | apache-2.0 | 6,272 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.ResourceManager.V3.Snippets
{
// [START cloudresourcemanager_v3_generated_TagValues_ListTagValues_async_flattened_resourceNames]
using Google.Api.Gax;
using Google.Cloud.ResourceManager.V3;
using System;
using System.Linq;
using System.Threading.Tasks;
public sealed partial class GeneratedTagValuesClientSnippets
{
/// <summary>Snippet for ListTagValuesAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task ListTagValuesResourceNamesAsync()
{
// Create client
TagValuesClient tagValuesClient = await TagValuesClient.CreateAsync();
// Initialize request argument(s)
IResourceName parent = new UnparsedResourceName("a/wildcard/resource");
// Make the request
PagedAsyncEnumerable<ListTagValuesResponse, TagValue> response = tagValuesClient.ListTagValuesAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((TagValue item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTagValuesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (TagValue item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<TagValue> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (TagValue item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END cloudresourcemanager_v3_generated_TagValues_ListTagValues_async_flattened_resourceNames]
}
| googleapis/google-cloud-dotnet | apis/Google.Cloud.ResourceManager.V3/Google.Cloud.ResourceManager.V3.GeneratedSnippets/TagValuesClient.ListTagValuesResourceNamesAsyncSnippet.g.cs | C# | apache-2.0 | 3,287 |
/**
* ÎļþÃû£ºMusic3.java
* ÏîÄ¿-°ü£ºJAVA±à³Ì˼Ïë - µÚ°ËÕÂ
* ×÷ÕߣºÕÅÎĵÏ
* ´´½¨ÈÕÆÚ£º2014-9-10
*/
package µÚ°ËÕÂ;
import java.util.Random;
/**
* @author ÕÅÎĵÏ
* ÀàÃû£ºMusic3
* Àà˵Ã÷£ºÁ·Ï° 6,7,8.
*/
enum Note
{
ºÃµÄ°É,¶î,¹þ¹þ;
}
class Instrument
{
void play(Note n)
{
System.out.println("Instrument.play()"+n);
}
public String toString()
{
return "Instrument";
}
void adjust()
{
System.out.println("Adjusting Instrument");
}
}
class Wind extends Instrument
{
void play(Note n)
{
System.out.println("Wind.play()"+n);
}
public String toString()
{
return "Wind";
}
void adjust()
{
System.out.println("Adjusting Wind");
}
}
class Percussin extends Instrument
{
void play(Note n)
{
System.out.println("Percussin.play()"+n);
}
public String toString()
{
return "Percussin";
}
void adjust()
{
System.out.println("Adjusting Percussin");
}
}
class Stringed extends Instrument
{
void play(Note n)
{
System.out.println("Stringed.play()"+n);
}
public String toString()
{
return "Stringed";
}
void adjust()
{
System.out.println("Adjusting Stringed");
}
}
class Brass extends Wind
{
void play(Note n)
{
System.out.println("Brass.play()"+n);
}
void adjust()
{
System.out.println("Adjusting Brass");
}
}
class Woodwind extends Wind
{
void play(Note n)
{
System.out.println("Woodwind.play()"+n);
}
void adjust()
{
System.out.println("Adjusting Woodwind");
}
}
public class Music3
{
public static void tune(Instrument i)
{
i.play(Note.ºÃµÄ°É);
}
/*
* public static void tuneAll(Instrument[] e)
{
for(Instrument i:e)
tune(i);
}
*/
public static void main(String args[])
{
/* Instrument[] allInstruments =
{
new Wind(),
new Percussin(),
new Stringed(),
new Brass(),
new Woodwind(),
new Instrument()
};
tuneAll(allInstruments);
for(Instrument i :allInstruments)
System.out.println(i);
*/
Random random = new Random(47);
switch (random.nextInt(6))
{
case 0:
Instrument inst1 = new Wind();
tune(inst1);
System.out.println(inst1);
case 1: Instrument inst2 = new Percussin();
tune(inst2);
System.out.println(inst2);
case 2: Instrument inst3 = new Stringed();
tune(inst3);
System.out.println(inst3);
case 3: Instrument inst4 = new Brass();
tune(inst4);
System.out.println(inst4);
case 4: Instrument inst5 = new Woodwind();
tune(inst5);
System.out.println(inst5);
case 5: Instrument inst6 = new Instrument();
tune(inst6);
System.out.println(inst6);
}
}
}
| 00wendi00/MyProject | W_eclipse2_1/JAVA编程思想/src/第八章/Music3.java | Java | apache-2.0 | 2,982 |
/*
* 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.ignite.internal.util.ipc.loopback;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.internal.util.ipc.IpcEndpoint;
import org.apache.ignite.internal.util.ipc.IpcEndpointBindException;
import org.apache.ignite.internal.util.ipc.IpcServerEndpoint;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.resources.LoggerResource;
/**
* Server loopback IPC endpoint.
*/
public class IpcServerTcpEndpoint implements IpcServerEndpoint {
/** Default endpoint port number. */
public static final int DFLT_IPC_PORT = 10500;
/** Server socket. */
private ServerSocket srvSock;
/** Port to bind socket to. */
private int port = DFLT_IPC_PORT;
/** Host to bind socket to. */
private String host;
/** Management endpoint flag. */
private boolean mgmt;
/** Logger. */
@LoggerResource
private IgniteLogger log;
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
if (port <= 0 || port >= 0xffff)
throw new IpcEndpointBindException("Port value is illegal: " + port);
try {
srvSock = new ServerSocket();
assert host != null;
srvSock.bind(new InetSocketAddress(U.resolveLocalHost(host), port));
if (log.isInfoEnabled())
log.info("IPC server loopback endpoint started [port=" + port + ']');
}
catch (IOException e) {
if (srvSock != null)
U.closeQuiet(srvSock);
throw new IpcEndpointBindException("Failed to bind loopback IPC endpoint (is port already in " +
"use?): " + port, e);
}
}
/** {@inheritDoc} */
@Override public IpcEndpoint accept() throws IgniteCheckedException {
try {
Socket sock = srvSock.accept();
return new IpcClientTcpEndpoint(sock);
}
catch (IOException e) {
throw new IgniteCheckedException(e);
}
}
/** {@inheritDoc} */
@Override public void close() {
U.closeQuiet(srvSock);
}
/** {@inheritDoc} */
@Override public int getPort() {
return port;
}
/**
* Sets port endpoint will be bound to.
*
* @param port Port number.
*/
public void setPort(int port) {
this.port = port;
}
/** {@inheritDoc} */
@Override public String getHost() {
return host;
}
/**
* Sets host endpoint will be bound to.
*
* @param host Host.
*/
public void setHost(String host) {
this.host = host;
}
/** {@inheritDoc} */
@Override public boolean isManagement() {
return mgmt;
}
/**
* Sets management property.
*
* @param mgmt flag.
*/
public void setManagement(boolean mgmt) {
this.mgmt = mgmt;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(IpcServerTcpEndpoint.class, this);
}
/**
* Sets configuration properties from the map.
*
* @param endpointCfg Map of properties.
* @throws IgniteCheckedException If invalid property name or value.
*/
public void setupConfiguration(Map<String, String> endpointCfg) throws IgniteCheckedException {
for (Map.Entry<String, String> e : endpointCfg.entrySet()) {
try {
switch (e.getKey()) {
case "type":
//Ignore this property
break;
case "port":
setPort(Integer.parseInt(e.getValue()));
break;
case "host":
setHost(e.getValue());
break;
case "management":
setManagement(Boolean.valueOf(e.getValue()));
break;
default:
throw new IgniteCheckedException("Invalid property '" + e.getKey() + "' of " + getClass().getSimpleName());
}
}
catch (Throwable t) {
if (t instanceof IgniteCheckedException || t instanceof Error)
throw t;
throw new IgniteCheckedException("Invalid value '" + e.getValue() + "' of the property '" + e.getKey() + "' in " +
getClass().getSimpleName(), t);
}
}
}
}
| ascherbakoff/ignite | modules/core/src/main/java/org/apache/ignite/internal/util/ipc/loopback/IpcServerTcpEndpoint.java | Java | apache-2.0 | 5,549 |
<!DOCTYPE html>
<!--
@license
Copyright (C) 2016 The Android Open Source Project
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.
-->
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-change-reply-js-api</title>
<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>
<!--
This must refer to the element this interface is wrapping around. Otherwise
breaking changes to gr-reply-dialog won’t be noticed.
-->
<link rel="import" href="../../change/gr-reply-dialog/gr-reply-dialog.html">
<script>void(0);</script>
<test-fixture id="basic">
<template>
<gr-reply-dialog></gr-reply-dialog>
</template>
</test-fixture>
<script>
suite('gr-change-reply-js-api tests', () => {
let element;
let sandbox;
let changeReply;
let plugin;
setup(() => {
sandbox = sinon.sandbox.create();
stub('gr-rest-api-interface', {
getConfig() { return Promise.resolve({}); },
getAccount() { return Promise.resolve(null); },
});
});
teardown(() => {
sandbox.restore();
});
suite('early init', () => {
setup(() => {
Gerrit.install(p => { plugin = p; }, '0.1',
'http://test.com/plugins/testplugin/static/test.js');
changeReply = plugin.changeReply();
element = fixture('basic');
});
teardown(() => {
changeReply = null;
});
test('works', () => {
sandbox.stub(element, 'getLabelValue').returns('+123');
assert.equal(changeReply.getLabelValue('My-Label'), '+123');
sandbox.stub(element, 'setLabelValue');
changeReply.setLabelValue('My-Label', '+1337');
assert.isTrue(
element.setLabelValue.calledWithExactly('My-Label', '+1337'));
sandbox.stub(element, 'send');
changeReply.send(false);
assert.isTrue(element.send.calledWithExactly(false));
sandbox.stub(element, 'setPluginMessage');
changeReply.showMessage('foobar');
assert.isTrue(element.setPluginMessage.calledWithExactly('foobar'));
});
});
suite('normal init', () => {
setup(() => {
element = fixture('basic');
Gerrit.install(p => { plugin = p; }, '0.1',
'http://test.com/plugins/testplugin/static/test.js');
changeReply = plugin.changeReply();
});
teardown(() => {
changeReply = null;
});
test('works', () => {
sandbox.stub(element, 'getLabelValue').returns('+123');
assert.equal(changeReply.getLabelValue('My-Label'), '+123');
sandbox.stub(element, 'setLabelValue');
changeReply.setLabelValue('My-Label', '+1337');
assert.isTrue(
element.setLabelValue.calledWithExactly('My-Label', '+1337'));
sandbox.stub(element, 'send');
changeReply.send(false);
assert.isTrue(element.send.calledWithExactly(false));
sandbox.stub(element, 'setPluginMessage');
changeReply.showMessage('foobar');
assert.isTrue(element.setPluginMessage.calledWithExactly('foobar'));
});
});
});
</script>
| qtproject/qtqa-gerrit | polygerrit-ui/app/elements/shared/gr-js-api-interface/gr-change-reply-js-api_test.html | HTML | apache-2.0 | 3,800 |
/*
* Copyright 2015 - 2017 Atlarge Research Team,
* operating at Technische Universiteit Delft
* and Vrije Universiteit Amsterdam, the Netherlands.
*
* 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 science.atlarge.graphalytics.util.io;
import java.io.IOException;
import java.util.Arrays;
/**
* Decorator for a EdgeListStream that filters and rearranges edge properties.
*
* @author Tim Hegeman
* @author Wing Lung Ngai
*/
public class EdgeListPropertyFilter implements EdgeListStream {
private final EdgeListStream inputStream;
private final int[] propertyIndicesToKeep;
private final EdgeData cache = new EdgeData();
/**
* Construct a EdgeListPropertyFilter that reads edges from a EdgeListStream, and filter and rearranges
* edge properties before outputting the edges. Properties are identified by their index (0 represents the first
* property in the underlying EdgeListStream). Property indices may occur multiple times to duplicate a property.
*
* @param inputStream the underlying EdgeListStream to filter
* @param propertyIndicesToKeep a list of property indices to copy to the output
*/
public EdgeListPropertyFilter(EdgeListStream inputStream, int[] propertyIndicesToKeep) {
this.inputStream = inputStream;
this.propertyIndicesToKeep = Arrays.copyOf(propertyIndicesToKeep, propertyIndicesToKeep.length);
this.cache.setValues(new String[propertyIndicesToKeep.length]);
}
@Override
public boolean hasNextEdge() throws IOException {
return inputStream.hasNextEdge();
}
@Override
public EdgeData getNextEdge() throws IOException {
EdgeData inputData = inputStream.getNextEdge();
cache.setSourceId(inputData.getSourceId());
cache.setDestinationId(inputData.getDestinationId());
String[] inputValues = inputData.getValues();
String[] outputValues = cache.getValues();
for (int i = 0; i < propertyIndicesToKeep.length; i++) {
outputValues[i] = inputValues[propertyIndicesToKeep[i]];
}
return cache;
}
@Override
public void close() throws IOException {
inputStream.close();
}
}
| tudelft-atlarge/graphalytics | graphalytics-core/src/main/java/science/atlarge/graphalytics/util/io/EdgeListPropertyFilter.java | Java | apache-2.0 | 2,590 |
/**
* @license
* Copyright 2015 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
*/
CLASS({
package: 'foam.ui',
name: 'CSSTransition',
requires: [
'foam.ui.CSSFunction',
'foam.ui.CSSTime',
],
properties: [
{
type: 'String',
name: 'property',
defaultValue: 'all',
required: true,
},
{
name: 'duration',
defaultValue: null,
},
{
name: 'timingFunction',
defaultValue: null,
},
{
name: 'delay',
defaultValue: null,
},
{
name: 'regExStr',
lazyFactory: function() {
var t = this.CSSTime.create().REG_EX_STR;
var f = this.CSSFunction.create().regExStr;
return '([a-zA-Z_-]+)\\s*(' + t + ')\\s*(' + f + ')?' + '(' + t + ')?';
},
},
],
methods: [
function fromString(s) {
var match = this.fromString_(s);
if ( ! match ) return null;
this.property = match[1];
this.duration = this.CSSTime.create().fromString(match[2]);
this.timingFunction = this.CSSFunction.create().fromString(match[7]);
return this;
},
function fromString_(s) {
var re = new RegExp('^' + this.regExStr + '$', 'gi');
return re.exec(s);
},
function toString() {
var seq = [this.property.toString(), this.duration.toString()];
if ( this.timingFunction ) seq.push(this.timingFunction.toString());
if ( this.delay ) seq.push(this.delay.toString());
return seq.join(' ');
},
],
});
| jlhughes/foam | js/foam/ui/CSSTransition.js | JavaScript | apache-2.0 | 1,723 |
在Android平台上可以操作数据库,这是第一次接触Android时的惊艳之一。在Android平台上,绑定了SQLite数据库,这个数据库系统也是极具性格的,它的最大的应用场景是嵌入式系统。
如果有JDBC的经验,那么在这里会容易的多。Android中操作数据库首先要通过一个类:android.database.sqlite.SQLiteOpenHelper。它封装了如何打开一个数据库,其中当然也包含如果数据库不存在 就创建这样的逻辑。
看一个例子:
```
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "com.roiding.simple.note";
private static final int DATABASE_VERSION = 1;
private static final String NOTES_TABLE_NAME = "notes";
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + NOTES_TABLE_NAME
+ " (id integer primary key autoincrement, name text);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
```
这里面,如下的语句需要解释:
```
super(context, DATABASE_NAME, null, DATABASE_VERSION)
```
数据库连接的初始化,中间的那个null,是一个CursorFactory参数,没有仔细研究这个参数,暂时置空吧。
public void onCreate(SQLiteDatabase db)
这里面的onCreate是指数据库onCreate时,而不是DatabaseHelper的onCreate。也就是说,如果已经指定 database已经存在,那么在重新运行程序的时候,就不会执行这个方法了。要不然,岂不是每次重新启动程序都要重新创建一次数据库了!在这个方法中, 完成了数据库的创建工作。也就是那个execSQL()方法。
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
在程序的开发维护过程中,数据库的结构可能会有变化,那么这个方法就有用处了。在DatabaseHelper这个对象一创建时,就已经把参数 DATABASE_VERSION传入,这样,如果Android发现此版本与现有版本不一致,就会调用这个onUpgrate方法。于是,可以在这里面 实现一些数据的upgrade工作,比如说创建一个临时表,将数据由临时表中转到新的表结构中。需要注意的是,这里面的onUpgrade是在版本不一致 时调用,也就是说不管当前需要的版本高于现有版本还是低于现有版本,都会出发这个方法,类似的这种情况,就需要对oldVersion和 newVersion进行判断之后再决定使用什么策略来更新数据。
在Android中,数据库存放在 /data/data/PACKAGE_NAME/databases 目录下。
接下来就可以使用这个Helper来操作数据库了,操作数据库也就无非是增、删、改、查。先看一个增的例子:
```
public static void insert(Context context, String s) {
DatabaseHelper mOpenHelper = new DatabaseHelper(context);
String table = "notes";
String nullColumnHack = "id";
ContentValues values = new ContentValues();
values.put("name", "www.roiding.com");
long id = mOpenHelper.getReadableDatabase().insert(table,
nullColumnHack, values);
mOpenHelper.getReadableDatabase().close();
}
DatabaseHelper mOpenHelper = new DatabaseHelper(context);
```
如果和JDBC例子的话,这一步貌似就像是获得了一个Statement,用它就可以操作数据库了。
ContentValues values = new ContentValues();
Android在向数据库中插入数据的时候,要求数据存放到ContentValues中,这里面的ContentValues其实就是一个 Map,Key值是字段名称,Value值是字段的值。这样,也许你会发现一个问题,那数据类型怎么办?其实在SQLite数据库中就是没有数据类型的, 一切都是字符串。
mOpenHelper.getReadableDatabase().insert(table,nullColumnHack, values);
将数据入库,注意这里面有一个nullColumnHack,看文档是和所有字段都是空的记录有关系,我没有去实验他具体的效果,只是随便给他一个字段名称。
再看一个查的例子:
```
public static void select(Context context) {
DatabaseHelper mOpenHelper = new DatabaseHelper(context);
String table = "notes";
String[] columns = new String[] { "id", "name" };
String selection = "id>? and name<>?";
String[] selectionArgs = new String[] { "0", "roiding.com" };
String groupBy = null;
String having = null;
String orderBy = "id desc";
String limit = "1";
Cursor c = mOpenHelper.getReadableDatabase().query(table, columns,
selection, selectionArgs, groupBy, having, orderBy, limit);
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
String s = c.getString(1);
c.moveToNext();
}
c.close();
mOpenHelper.getReadableDatabase().close();
}
DatabaseHelper mOpenHelper = new DatabaseHelper(context);
```
于前文中的相同
mOpenHelper.getReadableDatabase().query();
通过mOpenHelper.getReadableDatabase(),会得到一个SQLiteDatabase类型的只读的数据库连接,在这里直接调用了他的query方法。这个query方法相对复杂,因为他将一个完整的SQL语句拆成了若干个部分:
```
table:表名。相当于SQL的from后面的部分。那如果是多表联合查询怎么办?那就用逗号将两个表名分开,拼成一个字符串作为table的值。
columns:要查询出来的列名。相当于SQL的select后面的部分。
selection:查询条件,相当于SQL的where后面的部分,在这个语句中允许使用“?”,也就是说这个用法和JDBC中的PreparedStatement的用法相似。
selectionArgs:对应于selection的值,selection有几个问号,这里就得用几个值。两者必须一致,否则就会有异常。
groupBy:相当于SQL的group by后面的部分
having:相当于SQL的having后面的部分
orderBy:相当于SQL的order by后面的部分,如果是倒序,或者是联合排序,可以写成类似这样:String orderBy = “id desc, name”;
limit:指定结果集的大小,它和Mysql的limit用法不太一样,mysql可以指定从多少行开始之后取多少条,例如“limit 100,10”,但是这里只支持一个数值。
```
c.moveToFirst();
这一句也比较重要,如果读取数据之前,没有这一句,会有异常。
c.getString(1);
与JDBC一致了,Android不支持按字段名来取值,只能用序号。
再看一个删除和修改的例子:
```
public static void delete(Context context) {
DatabaseHelper mOpenHelper = new DatabaseHelper(context);
String table = "notes";
String selection = "id>? and name<>?";
String[] selectionArgs = new String[] { "0", "roiding.com" };
String whereClause = selection;
String[] whereArgs = selectionArgs;
mOpenHelper.getWritableDatabase().delete(table, whereClause, whereArgs);
mOpenHelper.getWritableDatabase().close();
}
```
有了上面的基础这里就容易理解了,这里的whereClause相当于前面的selection,whereArgs相当于前面的selectionArgs。
```
public static void update(Context context) {
DatabaseHelper mOpenHelper = new DatabaseHelper(context);
String table = "notes";
String selection = "id>? and name<>?";
String[] selectionArgs = new String[] { "0", "roiding.com" };
String whereClause = selection;
String[] whereArgs = selectionArgs;
ContentValues values = new ContentValues();
values.put("name", "www.roiding.com");
mOpenHelper.getWritableDatabase().update(table, values, whereClause,
whereArgs);
mOpenHelper.getWritableDatabase().close();
}
```
这个update的用法,综合select和delete就可以理解。
#### 注意:
Cursor和Databases要及时关闭,不然也会有异常。
getWritableDatabase()和getReadableDatabase()在当前的Android版本中貌似可以通用,像上面的insert,用的就是getReadableDatabase。
在真实的应用中,会对上面这些基本操作做更高一级的抽象和封装,使之更容易使用。在select时,除了用上述的方法,将分段的SQL语句传进去之外,Android还支持一种方法:使用SQLiteQueryBuilder。如果使用的是上述的分段SQL语句的方法,在Android的内部实现中,也是先将分段的SQL使用SQLiteQueryBuilder的静态方法来生成一个真正的SQL的,而且,我没有看出来使用 SQLiteQueryBuilder的优势。 | EManual/EManual.github.io | android-tmp/test/android_datastorage/数据库/0000-Android 数据存取之Databases.md | Markdown | apache-2.0 | 8,382 |
/*
* 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.
*/
// Generated by jextract
package org.apache.tomcat.util.openssl;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.VarHandle;
import java.nio.ByteOrder;
import jdk.incubator.foreign.*;
import static jdk.incubator.foreign.CLinker.*;
class constants$5 {
static final FunctionDescriptor EVP_PKEY_base_id$FUNC = FunctionDescriptor.of(C_INT,
C_POINTER
);
static final MethodHandle EVP_PKEY_base_id$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "EVP_PKEY_base_id",
"(Ljdk/incubator/foreign/MemoryAddress;)I",
constants$5.EVP_PKEY_base_id$FUNC, false
);
static final FunctionDescriptor EVP_PKEY_bits$FUNC = FunctionDescriptor.of(C_INT,
C_POINTER
);
static final MethodHandle EVP_PKEY_bits$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "EVP_PKEY_bits",
"(Ljdk/incubator/foreign/MemoryAddress;)I",
constants$5.EVP_PKEY_bits$FUNC, false
);
static final FunctionDescriptor EC_GROUP_free$FUNC = FunctionDescriptor.ofVoid(
C_POINTER
);
static final MethodHandle EC_GROUP_free$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "EC_GROUP_free",
"(Ljdk/incubator/foreign/MemoryAddress;)V",
constants$5.EC_GROUP_free$FUNC, false
);
static final FunctionDescriptor EC_GROUP_get_curve_name$FUNC = FunctionDescriptor.of(C_INT,
C_POINTER
);
static final MethodHandle EC_GROUP_get_curve_name$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "EC_GROUP_get_curve_name",
"(Ljdk/incubator/foreign/MemoryAddress;)I",
constants$5.EC_GROUP_get_curve_name$FUNC, false
);
static final FunctionDescriptor EC_KEY_new_by_curve_name$FUNC = FunctionDescriptor.of(C_POINTER,
C_INT
);
static final MethodHandle EC_KEY_new_by_curve_name$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "EC_KEY_new_by_curve_name",
"(I)Ljdk/incubator/foreign/MemoryAddress;",
constants$5.EC_KEY_new_by_curve_name$FUNC, false
);
static final FunctionDescriptor EC_KEY_free$FUNC = FunctionDescriptor.ofVoid(
C_POINTER
);
static final MethodHandle EC_KEY_free$MH = RuntimeHelper.downcallHandle(
openssl_h.LIBRARIES, "EC_KEY_free",
"(Ljdk/incubator/foreign/MemoryAddress;)V",
constants$5.EC_KEY_free$FUNC, false
);
}
| apache/tomcat | modules/openssl-java17/src/main/java/org/apache/tomcat/util/openssl/constants$5.java | Java | apache-2.0 | 3,205 |
using UnityEngine;
using System.Collections;
public class UIManager : Singleton<UIManager> {
protected UIManager () {}
public GameObject BottomLeftAnchor, TopLeftAnchor;
public void Awake() {
BottomLeftAnchor = transform.Find ("BottomLeftAnchor").gameObject;
TopLeftAnchor = transform.Find ("TopLeftAnchor").gameObject;
}
}
| DarrenTsung/turbo-octopus | turbo-octopus-unity/Assets/Scripts/Managers/UIManager.cs | C# | apache-2.0 | 339 |
#!/bin/bash -xe
PREV_DIR=`pwd`
cd "$(dirname $0)"
echo "Cleaning environment"
python3 setup.py clean
echo "Building chrome-loader.exe"
rm -f bzt/resources/chrome-loader.exe
x86_64-w64-mingw32-gcc -std=c99 -o bzt/resources/chrome-loader.exe bzt/resources/chrome-loader.c
echo "Creating distribution packages"
rm -rf ./dist
python3 ./setup.py sdist bdist_wheel
cd "${PREV_DIR}"
| Blazemeter/taurus | build-artifacts.sh | Shell | apache-2.0 | 381 |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import shutil
import tempfile
from pants.base.build_invalidator import CacheKey, CacheKeyGenerator
from pants.base.cache_manager import InvalidationCacheManager, InvalidationCheck, VersionedTarget
from pants_test.base_test import BaseTest
class AppendingCacheKeyGenerator(CacheKeyGenerator):
"""Generates cache keys for versions of target sets."""
@staticmethod
def combine_cache_keys(cache_keys):
if len(cache_keys) == 1:
return cache_keys[0]
else:
sorted_cache_keys = sorted(cache_keys) # For commutativity.
combined_id = ','.join([cache_key.id for cache_key in sorted_cache_keys])
combined_hash = ','.join([cache_key.hash for cache_key in sorted_cache_keys])
combined_num_sources = reduce(lambda x, y: x + y,
[cache_key.num_sources for cache_key in sorted_cache_keys], 0)
return CacheKey(combined_id, combined_hash, combined_num_sources)
def key_for_target(self, target, sources=None, transitive=False, fingerprint_strategy=None):
return CacheKey(target.id, target.id, target.num_chunking_units)
def key_for(self, tid, sources):
return CacheKey(tid, tid, len(sources))
def print_vt(vt):
print('%d (%s) %s: [ %s ]' % (len(vt.targets), vt.cache_key, vt.valid, ', '.join(['%s(%s)' % (v.id, v.cache_key) for v in vt.versioned_targets])))
class InvalidationCacheManagerTest(BaseTest):
class TestInvalidationCacheManager(InvalidationCacheManager):
def __init__(self, tmpdir):
InvalidationCacheManager.__init__(self, AppendingCacheKeyGenerator(), tmpdir, True, None)
def setUp(self):
super(InvalidationCacheManagerTest, self).setUp()
self._dir = tempfile.mkdtemp()
self.cache_manager = InvalidationCacheManagerTest.TestInvalidationCacheManager(self._dir)
def tearDown(self):
shutil.rmtree(self._dir, ignore_errors=True)
super(InvalidationCacheManagerTest, self).tearDown()
def make_vts(self, target):
return VersionedTarget(self.cache_manager, target, target.id)
def test_partition(self):
# The default EmptyPayload chunking unit happens to be 1, so each of these Targets
# has a chunking unit contribution of 1
a = self.make_target(':a', dependencies=[])
b = self.make_target(':b', dependencies=[a])
c = self.make_target(':c', dependencies=[b])
d = self.make_target(':d', dependencies=[c, a])
e = self.make_target(':e', dependencies=[d])
targets = [a, b, c, d, e]
def print_partitions(partitions):
strs = []
for partition in partitions:
strs.append('(%s)' % ', '.join([t.id for t in partition.targets]))
print('[%s]' % ' '.join(strs))
# Verify basic data structure soundness.
all_vts = self.cache_manager._wrap_targets(targets)
invalid_vts = filter(lambda vt: not vt.valid, all_vts)
self.assertEquals(5, len(invalid_vts))
self.assertEquals(5, len(all_vts))
vts_targets = [vt.targets[0] for vt in all_vts]
self.assertEquals(set(targets), set(vts_targets))
# Test a simple partition.
ic = InvalidationCheck(all_vts, [], 3)
partitioned = ic.all_vts_partitioned
print_partitions(partitioned)
# Several correct partitionings are possible, but in all cases 4 1-source targets will be
# added to the first partition before it exceeds the limit of 3, and the final target will
# be in a partition by itself.
self.assertEquals(2, len(partitioned))
self.assertEquals(4, len(partitioned[0].targets))
self.assertEquals(1, len(partitioned[1].targets))
# Test partition with colors.
red = 'red'
blue = 'blue'
colors = {
a: blue,
b: red,
c: red,
d: red,
e: blue
}
# As a reference, we partition without colors.
ic = InvalidationCheck(all_vts, [], 2)
partitioned = ic.all_vts_partitioned
print_partitions(partitioned)
self.assertEquals(2, len(partitioned))
self.assertEquals(3, len(partitioned[0].targets))
self.assertEquals(2, len(partitioned[1].targets))
# Now apply color restrictions.
ic = InvalidationCheck(all_vts, [], 2, target_colors=colors)
partitioned = ic.all_vts_partitioned
print_partitions(partitioned)
self.assertEquals(3, len(partitioned))
self.assertEquals(1, len(partitioned[0].targets))
self.assertEquals(3, len(partitioned[1].targets))
self.assertEquals(1, len(partitioned[2].targets))
| pgroudas/pants | tests/python/pants_test/tasks/test_cache_manager.py | Python | apache-2.0 | 4,697 |
/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
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 __itktubeEnhanceContrastUsingPriorImageFilter_h
#define __itktubeEnhanceContrastUsingPriorImageFilter_h
#include <itkArray.h>
#include <itkImageToImageFilter.h>
#include <itktubeContrastCostFunction.h>
#include <itkNormalVariateGenerator.h>
#include <itkOnePlusOneEvolutionaryOptimizer.h>
#include <itkFRPROptimizer.h>
#include <itkImageRegionIterator.h>
namespace itk
{
namespace tube
{
/** \class EnhanceContrastUsingPriorImageFilter
*/
template< class TPixel, unsigned int VDimension >
class EnhanceContrastUsingPriorImageFilter
: public ImageToImageFilter< Image< TPixel, VDimension >,
Image< TPixel, VDimension > >
{
public:
/** Standard class typedefs. */
typedef Image< TPixel, VDimension > ImageType;
typedef EnhanceContrastUsingPriorImageFilter Self;
typedef ImageToImageFilter< ImageType, ImageType > Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information ( and related methods ). */
itkTypeMacro( EnhanceContrastUsingPriorImageFilter, ImageToImageFilter );
/** Some convenient typedefs. */
typedef itk::tube::ContrastCostFunction< TPixel, VDimension >
ContrastCostFunctionType;
typedef itk::OnePlusOneEvolutionaryOptimizer InitialOptimizerType;
typedef itk::FRPROptimizer OptimizerType;
typedef itk::ImageRegionIterator< ImageType > ImageIteratorType;
/** Set/Get input Mask Image */
itkSetObjectMacro( InputMaskImage, ImageType );
itkGetModifiableObjectMacro( InputMaskImage, ImageType );
/** Set/Get Object Scale */
itkSetMacro( ObjectScale, float );
itkGetMacro( ObjectScale, float );
/** Set/Get Background Scale */
itkSetMacro( BackgroundScale, float );
itkGetMacro( BackgroundScale, float );
/** Set/Get Mask Object Value */
itkSetMacro( MaskObjectValue, int );
itkGetMacro( MaskObjectValue, int );
/** Set/Get Mask Background Value */
itkSetMacro( MaskBackgroundValue, int );
itkGetMacro( MaskBackgroundValue, int );
/** Set/Get Optimization Iterations */
itkSetMacro( OptimizationIterations, int );
itkGetMacro( OptimizationIterations, int );
/** Set/Get Optimization Seed */
itkSetMacro( OptimizationSeed, int );
itkGetMacro( OptimizationSeed, int );
protected:
EnhanceContrastUsingPriorImageFilter( void );
virtual ~EnhanceContrastUsingPriorImageFilter( void ) {}
void PrintSelf( std::ostream& os, Indent indent ) const override;
virtual void GenerateData( void ) override;
private:
//purposely not implemented
EnhanceContrastUsingPriorImageFilter( const Self& );
//purposely not implemented
void operator=( const Self& );
typename ImageType::Pointer m_InputMaskImage;
float m_ObjectScale;
float m_BackgroundScale;
int m_MaskObjectValue;
int m_MaskBackgroundValue;
int m_OptimizationIterations;
int m_OptimizationSeed;
}; // End class EnhanceContrastUsingPriorImageFilter
} // End namespace tube
} // End namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itktubeEnhanceContrastUsingPriorImageFilter.hxx"
#endif
#endif // End !defined( __itktubeEnhanceContrastUsingPriorImageFilter_h )
| thewtex/TubeTK | src/Filtering/itktubeEnhanceContrastUsingPriorImageFilter.h | C | apache-2.0 | 4,372 |
# Copyright 2017 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.
require "helper"
# require "datetime"
describe Google::Cloud::Pubsub::Convert, :timestamp, :mock_pubsub do
# This tests is a sanity check on the implementation of the conversion method.
# We are testing the private method. This functionality is also covered elsewhere,
# but it was thought that since this conversion is so important we might as well
# also test it apart from the other tests.
it "converts a Time to a Timestamp" do
time = Time.parse "2014-10-02T15:01:23.045123456Z"
timestamp = Google::Cloud::Pubsub::Convert.time_to_timestamp time
timestamp.must_be_kind_of Google::Protobuf::Timestamp
timestamp.seconds.must_equal 1412262083
timestamp.nanos.must_equal 45123456
end
it "converts a DateTime to a Timestamp" do
datetime = DateTime.parse "2014-10-02T15:01:23.045123456Z"
timestamp = Google::Cloud::Pubsub::Convert.time_to_timestamp datetime
timestamp.must_be_kind_of Google::Protobuf::Timestamp
timestamp.seconds.must_equal 1412262083
timestamp.nanos.must_equal 45123456
end
it "converts an empty Time to an empty Timestamp" do
time = nil
timestamp = Google::Cloud::Pubsub::Convert.time_to_timestamp time
timestamp.must_be :nil?
end
it "converts a Timestamp to a Time" do
timestamp = Google::Protobuf::Timestamp.new seconds: 1412262083, nanos: 45123456
time = Google::Cloud::Pubsub::Convert.timestamp_to_time timestamp
time.must_be_kind_of Time
time.must_equal Time.parse("2014-10-02T15:01:23.045123456Z")
end
it "converts an empty Timestamp to an empty Time" do
timestamp = nil
time = Google::Cloud::Pubsub::Convert.timestamp_to_time timestamp
time.must_be :nil?
end
end
| qingling128/google-cloud-ruby | google-cloud-pubsub/test/google/cloud/pubsub/convert/timestamp_test.rb | Ruby | apache-2.0 | 2,297 |
/*
* 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.log;
import java.io.Serializable;
/**
* Class representing and holding constants for priority.
*
* @author Peter Donald
*/
public final class Priority
implements Serializable
{
/**
* Developer orientated messages, usually used during development of product.
*/
public static final Priority DEBUG = new Priority( "DEBUG", 5 );
/**
* Useful information messages such as state changes, client connection, user login etc.
*/
public static final Priority INFO = new Priority( "INFO", 10 );
/**
* A problem or conflict has occurred but it may be recoverable, then
* again it could be the start of the system failing.
*/
public static final Priority WARN = new Priority( "WARN", 15 );
/**
* A problem has occurred but it is not fatal. The system will still function.
*/
public static final Priority ERROR = new Priority( "ERROR", 20 );
/**
* Something caused whole system to fail. This indicates that an administrator
* should restart the system and try to fix the problem that caused the failure.
*/
public static final Priority FATAL_ERROR = new Priority( "FATAL_ERROR", 25 );
/**
* Do not log anything.
*/
public static final Priority NONE = new Priority( "NONE", Integer.MAX_VALUE );
private final String m_name;
private final int m_priority;
/**
* Retrieve a Priority object for the name parameter.
*
* @param priority the priority name
* @return the Priority for name
*/
public static Priority getPriorityForName( final String priority )
{
if( Priority.DEBUG.getName().equals( priority ) )
{
return Priority.DEBUG;
}
else if( Priority.INFO.getName().equals( priority ) )
{
return Priority.INFO;
}
else if( Priority.WARN.getName().equals( priority ) )
{
return Priority.WARN;
}
else if( Priority.ERROR.getName().equals( priority ) )
{
return Priority.ERROR;
}
else if( Priority.FATAL_ERROR.getName().equals( priority ) )
{
return Priority.FATAL_ERROR;
}
else if( Priority.NONE.getName().equals( priority ) )
{
return Priority.NONE;
}
else
{
return Priority.DEBUG;
}
}
/**
* Private Constructor to block instantiation outside class.
*
* @param name the string name of priority
* @param priority the numerical code of priority
*/
private Priority( final String name, final int priority )
{
if( null == name )
{
throw new NullPointerException( "name" );
}
m_name = name;
m_priority = priority;
}
/**
* Overidden string to display Priority in human readable form.
*
* @return the string describing priority
*/
public String toString()
{
return "Priority[" + getName() + "/" + getValue() + "]";
}
/**
* Get numerical value associated with priority.
*
* @return the numerical value
*/
public int getValue()
{
return m_priority;
}
/**
* Get name of priority.
*
* @return the priorities name
*/
public String getName()
{
return m_name;
}
/**
* Test whether this priority is greater than other priority.
*
* @param other the other Priority
* @return TRUE if the priority is greater else FALSE
*/
public boolean isGreater( final Priority other )
{
return m_priority > other.getValue();
}
/**
* Test whether this priority is lower than other priority.
*
* @param other the other Priority
* @return TRUE if the priority is lower else FALSE
*/
public boolean isLower( final Priority other )
{
return m_priority < other.getValue();
}
/**
* Test whether this priority is lower or equal to other priority.
*
* @param other the other Priority
* @return TRUE if the priority is lower or equal else FALSE
*/
public boolean isLowerOrEqual( final Priority other )
{
return m_priority <= other.getValue();
}
/**
* Helper method that replaces deserialized object with correct singleton.
*
* @return the singleton version of object
*/
private Object readResolve()
{
return getPriorityForName( m_name );
}
}
| eva-xuyen/excalibur | containerkit/logkit/src/main/java/org/apache/log/Priority.java | Java | apache-2.0 | 5,377 |
/**
* 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.metron.common.configuration;
import org.apache.metron.common.configuration.enrichment.SensorEnrichmentConfig;
import org.apache.metron.common.utils.JSONUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
public class EnrichmentConfigurations extends Configurations {
public SensorEnrichmentConfig getSensorEnrichmentConfig(String sensorType) {
return (SensorEnrichmentConfig) configurations.get(getKey(sensorType));
}
public void updateSensorEnrichmentConfig(String sensorType, byte[] data) throws IOException {
updateSensorEnrichmentConfig(sensorType, new ByteArrayInputStream(data));
}
public void updateSensorEnrichmentConfig(String sensorType, InputStream io) throws IOException {
SensorEnrichmentConfig sensorEnrichmentConfig = JSONUtils.INSTANCE.load(io, SensorEnrichmentConfig.class);
updateSensorEnrichmentConfig(sensorType, sensorEnrichmentConfig);
}
public void updateSensorEnrichmentConfig(String sensorType, SensorEnrichmentConfig sensorEnrichmentConfig) {
configurations.put(getKey(sensorType), sensorEnrichmentConfig);
}
private String getKey(String sensorType) {
return ConfigurationType.ENRICHMENT.getTypeName() + "." + sensorType;
}
}
| dlyle65535/metron | metron-platform/metron-common/src/main/java/org/apache/metron/common/configuration/EnrichmentConfigurations.java | Java | apache-2.0 | 2,122 |
/*
* Copyright (c) 2008-2020, Hazelcast, 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.hazelcast.internal.networking.nio;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.logging.ILogger;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static com.hazelcast.internal.util.Preconditions.checkNotNull;
import static java.lang.Class.forName;
import static java.lang.System.arraycopy;
/**
* The SelectorOptimizer optimizes the Selector so less litter is being created.
* The Selector uses a HashSet, but this creates an object for every add of a
* selection key. With this SelectorOptimizer a SelectionKeysSet, which contains
* an array, is being used since every key is going to be inserted only once.
*
* This trick comes from Netty.
*/
public final class SelectorOptimizer {
static final String SELECTOR_IMPL = "sun.nio.ch.SelectorImpl";
private SelectorOptimizer() {
}
/**
* Creates a new Selector and will optimize it if possible.
*
* @param logger the logger used for the optimization process.
* @return the created Selector.
* @throws NullPointerException if logger is null.
*/
static Selector newSelector(ILogger logger) {
checkNotNull(logger, "logger");
Selector selector;
try {
selector = Selector.open();
} catch (IOException e) {
throw new HazelcastException("Failed to open a Selector", e);
}
boolean optimize = Boolean.parseBoolean(System.getProperty("hazelcast.io.optimizeselector", "true"));
if (optimize) {
optimize(selector, logger);
}
return selector;
}
/**
* Tries to optimize the provided Selector.
*
* @param selector the selector to optimize
* @return an FastSelectionKeySet if the optimization was a success, null otherwise.
* @throws NullPointerException if selector or logger is null.
*/
static SelectionKeysSet optimize(Selector selector, ILogger logger) {
checkNotNull(selector, "selector");
checkNotNull(logger, "logger");
try {
SelectionKeysSet set = new SelectionKeysSet();
Class<?> selectorImplClass = findOptimizableSelectorClass(selector);
if (selectorImplClass == null) {
return null;
}
Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys");
selectedKeysField.setAccessible(true);
Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys");
publicSelectedKeysField.setAccessible(true);
selectedKeysField.set(selector, set);
publicSelectedKeysField.set(selector, set);
logger.finest("Optimized Selector: " + selector.getClass().getName());
return set;
} catch (Throwable t) {
// we don't want to print at warning level because it could very well be that the target JVM doesn't
// support this optimization. That is why we print on finest
logger.finest("Failed to optimize Selector: " + selector.getClass().getName(), t);
return null;
}
}
static Class<?> findOptimizableSelectorClass(Selector selector) throws ClassNotFoundException {
Class<?> selectorImplClass = forName(SELECTOR_IMPL, false, SelectorOptimizer.class.getClassLoader());
// Ensure the current selector implementation is what we can instrument.
if (!selectorImplClass.isAssignableFrom(selector.getClass())) {
return null;
}
return selectorImplClass;
}
static class SelectionKeysSet extends AbstractSet<SelectionKey> {
// the active SelectionKeys is the one where is being added to.
SelectionKeys activeKeys = new SelectionKeys();
// the passive SelectionKeys is one that is being read using the iterator.
SelectionKeys passiveKeys = new SelectionKeys();
// the iterator is recycled.
private final IteratorImpl iterator = new IteratorImpl();
SelectionKeysSet() {
}
@Override
public boolean add(SelectionKey o) {
return activeKeys.add(o);
}
@Override
public int size() {
return activeKeys.size;
}
@Override
public Iterator<SelectionKey> iterator() {
iterator.init(flip());
return iterator;
}
private SelectionKey[] flip() {
SelectionKeys tmp = activeKeys;
activeKeys = passiveKeys;
passiveKeys = tmp;
activeKeys.size = 0;
return passiveKeys.keys;
}
@Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean contains(Object o) {
return false;
}
}
static final class SelectionKeys {
static final int INITIAL_CAPACITY = 32;
SelectionKey[] keys = new SelectionKey[INITIAL_CAPACITY];
int size;
private boolean add(SelectionKey key) {
if (key == null) {
return false;
}
ensureCapacity();
keys[size] = key;
size++;
return true;
}
private void ensureCapacity() {
if (size < keys.length) {
return;
}
SelectionKey[] newKeys = new SelectionKey[keys.length * 2];
arraycopy(keys, 0, newKeys, 0, size);
keys = newKeys;
}
}
static final class IteratorImpl implements Iterator<SelectionKey> {
SelectionKey[] keys;
int index;
private void init(SelectionKey[] keys) {
this.keys = keys;
this.index = -1;
}
@Override
public boolean hasNext() {
if (index >= keys.length - 1) {
return false;
}
return keys[index + 1] != null;
}
@Override
public SelectionKey next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
index++;
return keys[index];
}
@Override
public void remove() {
if (index == -1 || index >= keys.length || keys[index] == null) {
throw new IllegalStateException();
}
keys[index] = null;
}
}
}
| mdogan/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/networking/nio/SelectorOptimizer.java | Java | apache-2.0 | 7,259 |
<!DOCTYPE html >
<html>
<head>
<link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.dynamic.js" ></script>
<script src="../libraries/RGraph.gauge.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]-->
<title>A skeleton Gauge chart</title>
<meta name="robots" content="noindex,nofollow" />
<meta name="description" content="A Gauge chart without some of the Chrome" />
</head>
<body>
<h1>A skeleton Gauge chart</h1>
<canvas id="cvs" width="300" height="150" style="box-shadow: ">[No canvas support]</canvas>
<script>
$(document).ready(function ()
{
var gauge = new RGraph.Gauge({
id: 'cvs',
min: 0,
max: 50,
value: 46,
options: {
'centery': 120,
'radius': 130,
'angles.start': RGraph.PI,
'angles.end': RGraph.TWOPI,
'needle.size': 85,
'border.width': 0,
shadow: false,
'needle.type': 'line',
'colors.ranges': [[0,10,'red'], [10,20,'yellow'],[20,50,'#0f0']],
'border.inner': 'rgba(0,0,0,0)',
'border.outer': 'rgba(0,0,0,0)',
'border.outline': 'rgba(0,0,0,0)',
'centerpin.color': 'rgba(0,0,0,0)',
'centerpin.radius': 0
}
}).grow()
gauge.canvas.onclick = function (e)
{
var value = gauge.getValue(e);
if (typeof value === 'number') {
gauge.value = value;
gauge.grow();
}
}
})
</script>
<p>
<a href="./">« Back</a>
</p>
<p>
<a href="https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net" target="_blank" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net', null, 'top=50,left=50,width=600,height=368'); return false"><img src="../images/facebook-large.png" width="200" height="43" alt="Share on Facebook" border="0" title="Visit the RGraph Facebook page" /></a>
<a href="https://twitter.com/_rgraph" target="_blank" onclick="window.open('https://twitter.com/_rgraph', null, 'top=50,left=50,width=700,height=400'); return false"><img src="../images/twitter-large.png" width="200" height="43" alt="Share on Twitter" border="0" title="Mention RGraph on Twitter" /></a>
</p>
</body>
</html> | ubiss2015d/alpha | web_parser/RGraph4/demos/gauge-skeleton.html | HTML | apache-2.0 | 2,888 |
// Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_interface.java
// Do not modify
package org.projectfloodlight.openflow.protocol.action;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import java.util.Set;
import io.netty.buffer.ByteBuf;
public interface OFActionSetNwTos extends OFObject, OFAction {
OFActionType getType();
short getNwTos();
OFVersion getVersion();
void writeTo(ByteBuf channelBuffer);
Builder createBuilder();
public interface Builder extends OFAction.Builder {
OFActionSetNwTos build();
OFActionType getType();
short getNwTos();
Builder setNwTos(short nwTos);
OFVersion getVersion();
}
}
| mehdi149/OF_COMPILER_0.1 | gen-src/main/java/org/projectfloodlight/openflow/protocol/action/OFActionSetNwTos.java | Java | apache-2.0 | 1,867 |
// 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.
#include <mesos/agent/agent.hpp>
#include <mesos/master/master.hpp>
#include <mesos/v1/agent/agent.hpp>
#include <mesos/v1/master/master.hpp>
#include <process/pid.hpp>
#include <stout/check.hpp>
#include <stout/json.hpp>
#include <stout/protobuf.hpp>
#include "internal/evolve.hpp"
#include "master/constants.hpp"
using std::string;
using google::protobuf::RepeatedPtrField;
using process::UPID;
namespace mesos {
namespace internal {
// Helper for evolving a type by serializing/parsing when the types
// have not changed across versions.
template <typename T>
static T evolve(const google::protobuf::Message& message)
{
T t;
string data;
// NOTE: We need to use 'SerializePartialToString' instead of
// 'SerializeToString' because some required fields might not be set
// and we don't want an exception to get thrown.
CHECK(message.SerializePartialToString(&data))
<< "Failed to serialize " << message.GetTypeName()
<< " while evolving to " << t.GetTypeName();
// NOTE: We need to use 'ParsePartialFromString' instead of
// 'ParseFromString' because some required fields might not
// be set and we don't want an exception to get thrown.
CHECK(t.ParsePartialFromString(data))
<< "Failed to parse " << t.GetTypeName()
<< " while evolving from " << message.GetTypeName();
return t;
}
v1::AgentID evolve(const SlaveID& slaveId)
{
// NOTE: Not using 'evolve<SlaveID, v1::AgentID>(slaveId)' since
// this will be a common 'evolve' call and we wanted to speed up
// performance.
v1::AgentID id;
id.set_value(slaveId.value());
return id;
}
v1::AgentInfo evolve(const SlaveInfo& slaveInfo)
{
return evolve<v1::AgentInfo>(slaveInfo);
}
v1::DomainInfo evolve(const DomainInfo& domainInfo)
{
return evolve<v1::DomainInfo>(domainInfo);
}
v1::ExecutorID evolve(const ExecutorID& executorId)
{
return evolve<v1::ExecutorID>(executorId);
}
v1::ExecutorInfo evolve(const ExecutorInfo& executorInfo)
{
return evolve<v1::ExecutorInfo>(executorInfo);
}
v1::FileInfo evolve(const FileInfo& fileInfo)
{
return evolve<v1::FileInfo>(fileInfo);
}
v1::FrameworkID evolve(const FrameworkID& frameworkId)
{
return evolve<v1::FrameworkID>(frameworkId);
}
v1::FrameworkInfo evolve(const FrameworkInfo& frameworkInfo)
{
return evolve<v1::FrameworkInfo>(frameworkInfo);
}
v1::InverseOffer evolve(const InverseOffer& inverseOffer)
{
return evolve<v1::InverseOffer>(inverseOffer);
}
v1::KillPolicy evolve(const KillPolicy& killPolicy)
{
return evolve<v1::KillPolicy>(killPolicy);
}
v1::MachineID evolve(const MachineID& machineId)
{
return evolve<v1::MachineID>(machineId);
}
v1::MasterInfo evolve(const MasterInfo& masterInfo)
{
return evolve<v1::MasterInfo>(masterInfo);
}
v1::Offer evolve(const Offer& offer)
{
return evolve<v1::Offer>(offer);
}
v1::OfferID evolve(const OfferID& offerId)
{
return evolve<v1::OfferID>(offerId);
}
v1::OperationStatus evolve(const OperationStatus& status)
{
v1::OperationStatus _status = evolve<v1::OperationStatus>(status);
if (status.has_slave_id()) {
*_status.mutable_agent_id() = evolve<v1::AgentID>(status.slave_id());
}
return _status;
}
v1::Resource evolve(const Resource& resource)
{
return evolve<v1::Resource>(resource);
}
v1::ResourceProviderID evolve(
const ResourceProviderID& resourceProviderId)
{
// NOTE: We do not use the common 'devolve' call for performance.
v1::ResourceProviderID id;
id.set_value(resourceProviderId.value());
return id;
}
v1::Resources evolve(const Resources& resources)
{
return evolve<v1::Resource>(
static_cast<const RepeatedPtrField<Resource>&>(resources));
}
v1::Task evolve(const Task& task)
{
return evolve<v1::Task>(task);
}
v1::TaskID evolve(const TaskID& taskId)
{
return evolve<v1::TaskID>(taskId);
}
v1::TaskInfo evolve(const TaskInfo& taskInfo)
{
return evolve<v1::TaskInfo>(taskInfo);
}
v1::TaskStatus evolve(const TaskStatus& status)
{
return evolve<v1::TaskStatus>(status);
}
v1::UUID evolve(const UUID& uuid)
{
return evolve<v1::UUID>(uuid);
}
v1::agent::Call evolve(const agent::Call& call)
{
return evolve<v1::agent::Call>(call);
}
v1::agent::ProcessIO evolve(const agent::ProcessIO& processIO)
{
return evolve<v1::agent::ProcessIO>(processIO);
}
v1::agent::Response evolve(const agent::Response& response)
{
return evolve<v1::agent::Response>(response);
}
v1::maintenance::ClusterStatus evolve(const maintenance::ClusterStatus& status)
{
return evolve<v1::maintenance::ClusterStatus>(status);
}
v1::maintenance::Schedule evolve(const maintenance::Schedule& schedule)
{
return evolve<v1::maintenance::Schedule>(schedule);
}
v1::master::Response evolve(const mesos::master::Response& response)
{
return evolve<v1::master::Response>(response);
}
v1::resource_provider::Call evolve(const resource_provider::Call& call)
{
return evolve<v1::resource_provider::Call>(call);
}
v1::resource_provider::Event evolve(const resource_provider::Event& event)
{
return evolve<v1::resource_provider::Event>(event);
}
// TODO(xujyan): Do we need this conversion when Mesos never sends out
// `scheduler::Call` thus never needs to evovle internal call to a v1 call?
// Perhaps we should remove the method so there's no need to maintain it.
v1::scheduler::Call evolve(const scheduler::Call& call)
{
v1::scheduler::Call _call = evolve<v1::scheduler::Call>(call);
// Certain conversions require special handling.
if (_call.type() == v1::scheduler::Call::SUBSCRIBE) {
// v1 Subscribe.suppressed_roles cannot be automatically converted
// because its tag is used by another field in the internal Subscribe.
*(_call.mutable_subscribe()->mutable_suppressed_roles()) =
call.subscribe().suppressed_roles();
}
return _call;
}
v1::scheduler::Event evolve(const scheduler::Event& event)
{
return evolve<v1::scheduler::Event>(event);
}
v1::scheduler::Event evolve(const ExitedExecutorMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::FAILURE);
v1::scheduler::Event::Failure* failure = event.mutable_failure();
*failure->mutable_agent_id() = evolve(message.slave_id());
*failure->mutable_executor_id() = evolve(message.executor_id());
failure->set_status(message.status());
return event;
}
v1::scheduler::Event evolve(const ExecutorToFrameworkMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::MESSAGE);
v1::scheduler::Event::Message* message_ = event.mutable_message();
*message_->mutable_agent_id() = evolve(message.slave_id());
*message_->mutable_executor_id() = evolve(message.executor_id());
message_->set_data(message.data());
return event;
}
v1::scheduler::Event evolve(const FrameworkErrorMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::ERROR);
v1::scheduler::Event::Error* error = event.mutable_error();
error->set_message(message.message());
return event;
}
v1::scheduler::Event evolve(const FrameworkRegisteredMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::SUBSCRIBED);
v1::scheduler::Event::Subscribed* subscribed = event.mutable_subscribed();
*subscribed->mutable_framework_id() = evolve(message.framework_id());
// TODO(anand): The master should pass the heartbeat interval as an argument
// to `evolve()`.
subscribed->set_heartbeat_interval_seconds(
master::DEFAULT_HEARTBEAT_INTERVAL.secs());
*subscribed->mutable_master_info() = evolve(message.master_info());
return event;
}
v1::scheduler::Event evolve(const FrameworkReregisteredMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::SUBSCRIBED);
v1::scheduler::Event::Subscribed* subscribed = event.mutable_subscribed();
*subscribed->mutable_framework_id() = evolve(message.framework_id());
// TODO(anand): The master should pass the heartbeat interval as an argument
// to `evolve()`.
subscribed->set_heartbeat_interval_seconds(
master::DEFAULT_HEARTBEAT_INTERVAL.secs());
*subscribed->mutable_master_info() = evolve(message.master_info());
return event;
}
v1::scheduler::Event evolve(const InverseOffersMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::INVERSE_OFFERS);
v1::scheduler::Event::InverseOffers* inverse_offers =
event.mutable_inverse_offers();
*inverse_offers->mutable_inverse_offers() =
evolve<v1::InverseOffer>(message.inverse_offers());
return event;
}
v1::scheduler::Event evolve(const LostSlaveMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::FAILURE);
v1::scheduler::Event::Failure* failure = event.mutable_failure();
*failure->mutable_agent_id() = evolve(message.slave_id());
return event;
}
v1::scheduler::Event evolve(const ResourceOffersMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::OFFERS);
v1::scheduler::Event::Offers* offers = event.mutable_offers();
*offers->mutable_offers() = evolve<v1::Offer>(message.offers());
return event;
}
v1::scheduler::Event evolve(const RescindInverseOfferMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::RESCIND_INVERSE_OFFER);
v1::scheduler::Event::RescindInverseOffer* rescindInverseOffer =
event.mutable_rescind_inverse_offer();
*rescindInverseOffer->mutable_inverse_offer_id() =
evolve(message.inverse_offer_id());
return event;
}
v1::scheduler::Event evolve(const RescindResourceOfferMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::RESCIND);
v1::scheduler::Event::Rescind* rescind = event.mutable_rescind();
*rescind->mutable_offer_id() = evolve(message.offer_id());
return event;
}
v1::scheduler::Event evolve(const StatusUpdateMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::UPDATE);
v1::scheduler::Event::Update* update = event.mutable_update();
*update->mutable_status() = evolve(message.update().status());
if (message.update().has_slave_id()) {
*update->mutable_status()->mutable_agent_id() =
evolve(message.update().slave_id());
}
if (message.update().has_executor_id()) {
*update->mutable_status()->mutable_executor_id() =
evolve(message.update().executor_id());
}
update->mutable_status()->set_timestamp(message.update().timestamp());
// If the update does not have a 'uuid', it does not need
// acknowledging. However, prior to 0.23.0, the update uuid
// was required and always set. In 0.24.0, we can rely on the
// update uuid check here, until then we must still check for
// this being sent from the driver (from == UPID()) or from
// the master (pid == UPID()).
// TODO(vinod): Get rid of this logic in 0.25.0 because master
// and slave correctly set task status in 0.24.0.
if (!message.update().has_uuid() || message.update().uuid() == "") {
update->mutable_status()->clear_uuid();
} else if (UPID(message.pid()) == UPID()) {
update->mutable_status()->clear_uuid();
} else {
update->mutable_status()->set_uuid(message.update().uuid());
}
return event;
}
v1::scheduler::Event evolve(const UpdateOperationStatusMessage& message)
{
v1::scheduler::Event event;
event.set_type(v1::scheduler::Event::UPDATE_OPERATION_STATUS);
*event.mutable_update_operation_status()->mutable_status() =
evolve(message.status());
return event;
}
v1::executor::Call evolve(const executor::Call& call)
{
return evolve<v1::executor::Call>(call);
}
v1::executor::Event evolve(const executor::Event& event)
{
return evolve<v1::executor::Event>(event);
}
v1::scheduler::Response evolve(const scheduler::Response& response)
{
return evolve<v1::scheduler::Response>(response);
}
v1::executor::Event evolve(const ExecutorRegisteredMessage& message)
{
v1::executor::Event event;
event.set_type(v1::executor::Event::SUBSCRIBED);
v1::executor::Event::Subscribed* subscribed = event.mutable_subscribed();
*subscribed->mutable_executor_info() = evolve(message.executor_info());
*subscribed->mutable_framework_info() = evolve(message.framework_info());
*subscribed->mutable_agent_info() = evolve(message.slave_info());
return event;
}
v1::executor::Event evolve(const FrameworkToExecutorMessage& message)
{
v1::executor::Event event;
event.set_type(v1::executor::Event::MESSAGE);
v1::executor::Event::Message* message_ = event.mutable_message();
message_->set_data(message.data());
return event;
}
v1::executor::Event evolve(const KillTaskMessage& message)
{
v1::executor::Event event;
event.set_type(v1::executor::Event::KILL);
v1::executor::Event::Kill* kill = event.mutable_kill();
*kill->mutable_task_id() = evolve(message.task_id());
if (message.has_kill_policy()) {
*kill->mutable_kill_policy() = evolve(message.kill_policy());
}
return event;
}
v1::executor::Event evolve(const RunTaskMessage& message)
{
v1::executor::Event event;
event.set_type(v1::executor::Event::LAUNCH);
v1::executor::Event::Launch* launch = event.mutable_launch();
*launch->mutable_task() = evolve(message.task());
return event;
}
v1::executor::Event evolve(const ShutdownExecutorMessage&)
{
v1::executor::Event event;
event.set_type(v1::executor::Event::SHUTDOWN);
return event;
}
v1::executor::Event evolve(
const StatusUpdateAcknowledgementMessage& message)
{
v1::executor::Event event;
event.set_type(v1::executor::Event::ACKNOWLEDGED);
v1::executor::Event::Acknowledged* acknowledged =
event.mutable_acknowledged();
*acknowledged->mutable_task_id() = evolve(message.task_id());
acknowledged->set_uuid(message.uuid());
return event;
}
v1::master::Event evolve(const mesos::master::Event& event)
{
return evolve<v1::master::Event>(event);
}
template<>
v1::master::Response evolve<v1::master::Response::GET_FLAGS>(
const JSON::Object& object)
{
v1::master::Response response;
response.set_type(v1::master::Response::GET_FLAGS);
v1::master::Response::GetFlags* getFlags = response.mutable_get_flags();
Result<JSON::Object> flags = object.at<JSON::Object>("flags");
CHECK_SOME(flags) << "Failed to find 'flags' key in the JSON object";
foreachpair (const string& key,
const JSON::Value& value,
flags->values) {
v1::Flag* flag = getFlags->add_flags();
flag->set_name(key);
CHECK(value.is<JSON::String>())
<< "Flag '" + key + "' value is not a string";
flag->set_value(value.as<JSON::String>().value);
}
return response;
}
// TODO(vinod): Consolidate master and agent flags evolution.
template<>
v1::agent::Response evolve<v1::agent::Response::GET_FLAGS>(
const JSON::Object& object)
{
v1::agent::Response response;
response.set_type(v1::agent::Response::GET_FLAGS);
v1::agent::Response::GetFlags* getFlags = response.mutable_get_flags();
Result<JSON::Object> flags = object.at<JSON::Object>("flags");
CHECK_SOME(flags) << "Failed to find 'flags' key in the JSON object";
foreachpair (const string& key,
const JSON::Value& value,
flags->values) {
v1::Flag* flag = getFlags->add_flags();
flag->set_name(key);
CHECK(value.is<JSON::String>())
<< "Flag '" + key + "' value is not a string";
flag->set_value(value.as<JSON::String>().value);
}
return response;
}
template<>
v1::master::Response evolve<v1::master::Response::GET_VERSION>(
const JSON::Object& object)
{
v1::master::Response response;
response.set_type(v1::master::Response::GET_VERSION);
*response.mutable_get_version()->mutable_version_info() =
CHECK_NOTERROR(::protobuf::parse<v1::VersionInfo>(object));
return response;
}
// TODO(vinod): Consolidate master and agent version evolution.
template<>
v1::agent::Response evolve<v1::agent::Response::GET_VERSION>(
const JSON::Object& object)
{
v1::agent::Response response;
response.set_type(v1::agent::Response::GET_VERSION);
*response.mutable_get_version()->mutable_version_info() =
CHECK_NOTERROR(::protobuf::parse<v1::VersionInfo>(object));
return response;
}
template<>
v1::agent::Response evolve<v1::agent::Response::GET_CONTAINERS>(
const JSON::Array& array)
{
v1::agent::Response response;
response.set_type(v1::agent::Response::GET_CONTAINERS);
foreach (const JSON::Value& value, array.values) {
v1::agent::Response::GetContainers::Container* container =
response.mutable_get_containers()->add_containers();
JSON::Object object = value.as<JSON::Object>();
Result<JSON::String> container_id =
object.find<JSON::String>("container_id");
CHECK_SOME(container_id);
container->mutable_container_id()->set_value(container_id->value);
Result<JSON::String> framework_id =
object.find<JSON::String>("framework_id");
CHECK(!framework_id.isError());
if (framework_id.isSome()) {
container->mutable_framework_id()->set_value(framework_id->value);
}
Result<JSON::String> executor_id = object.find<JSON::String>("executor_id");
CHECK(!executor_id.isError());
if (executor_id.isSome()) {
container->mutable_executor_id()->set_value(executor_id->value);
}
Result<JSON::String> executor_name =
object.find<JSON::String>("executor_name");
CHECK(!executor_name.isError());
if (executor_name.isSome()) {
container->set_executor_name(executor_name->value);
}
Result<JSON::Object> container_status = object.find<JSON::Object>("status");
if (container_status.isSome()) {
*container->mutable_container_status() = CHECK_NOTERROR(
::protobuf::parse<v1::ContainerStatus>(container_status.get()));
}
Result<JSON::Object> resource_statistics =
object.find<JSON::Object>("statistics");
if (resource_statistics.isSome()) {
*container->mutable_resource_statistics() = CHECK_NOTERROR(
::protobuf::parse<v1::ResourceStatistics>(resource_statistics.get()));
}
}
return response;
}
} // namespace internal {
} // namespace mesos {
| jpeach/mesos | src/internal/evolve.cpp | C++ | apache-2.0 | 19,005 |
package org.apache.lucene.index;
/*
* 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 java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.FilterCodec;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.lucene42.Lucene42Codec;
import org.apache.lucene.codecs.pulsing.Pulsing41PostingsFormat;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.BaseDirectoryWrapper;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
public class TestAddIndexes extends LuceneTestCase {
public void testSimpleCase() throws IOException {
// main directory
Directory dir = newDirectory();
// two auxiliary directories
Directory aux = newDirectory();
Directory aux2 = newDirectory();
IndexWriter writer = null;
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random()))
.setOpenMode(OpenMode.CREATE));
// add 100 documents
addDocs(writer, 100);
assertEquals(100, writer.maxDoc());
writer.close();
_TestUtil.checkIndex(dir);
writer = newWriter(
aux,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setMergePolicy(newLogMergePolicy(false))
);
// add 40 documents in separate files
addDocs(writer, 40);
assertEquals(40, writer.maxDoc());
writer.close();
writer = newWriter(aux2, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.CREATE));
// add 50 documents in compound files
addDocs2(writer, 50);
assertEquals(50, writer.maxDoc());
writer.close();
// test doc count before segments are merged
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
assertEquals(100, writer.maxDoc());
writer.addIndexes(aux, aux2);
assertEquals(190, writer.maxDoc());
writer.close();
_TestUtil.checkIndex(dir);
// make sure the old index is correct
verifyNumDocs(aux, 40);
// make sure the new index is correct
verifyNumDocs(dir, 190);
// now add another set in.
Directory aux3 = newDirectory();
writer = newWriter(aux3, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
// add 40 documents
addDocs(writer, 40);
assertEquals(40, writer.maxDoc());
writer.close();
// test doc count before segments are merged
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
assertEquals(190, writer.maxDoc());
writer.addIndexes(aux3);
assertEquals(230, writer.maxDoc());
writer.close();
// make sure the new index is correct
verifyNumDocs(dir, 230);
verifyTermDocs(dir, new Term("content", "aaa"), 180);
verifyTermDocs(dir, new Term("content", "bbb"), 50);
// now fully merge it.
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
writer.forceMerge(1);
writer.close();
// make sure the new index is correct
verifyNumDocs(dir, 230);
verifyTermDocs(dir, new Term("content", "aaa"), 180);
verifyTermDocs(dir, new Term("content", "bbb"), 50);
// now add a single document
Directory aux4 = newDirectory();
writer = newWriter(aux4, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
addDocs2(writer, 1);
writer.close();
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
assertEquals(230, writer.maxDoc());
writer.addIndexes(aux4);
assertEquals(231, writer.maxDoc());
writer.close();
verifyNumDocs(dir, 231);
verifyTermDocs(dir, new Term("content", "bbb"), 51);
dir.close();
aux.close();
aux2.close();
aux3.close();
aux4.close();
}
public void testWithPendingDeletes() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux);
IndexWriter writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
writer.addIndexes(aux);
// Adds 10 docs, then replaces them with another 10
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++) {
Document doc = new Document();
doc.add(newStringField("id", "" + (i % 10), Field.Store.NO));
doc.add(newTextField("content", "bbb " + i, Field.Store.NO));
writer.updateDocument(new Term("id", "" + (i%10)), doc);
}
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.add(new Term("content", "bbb"));
q.add(new Term("content", "14"));
writer.deleteDocuments(q);
writer.forceMerge(1);
writer.commit();
verifyNumDocs(dir, 1039);
verifyTermDocs(dir, new Term("content", "aaa"), 1030);
verifyTermDocs(dir, new Term("content", "bbb"), 9);
writer.close();
dir.close();
aux.close();
}
public void testWithPendingDeletes2() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux);
IndexWriter writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
// Adds 10 docs, then replaces them with another 10
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++) {
Document doc = new Document();
doc.add(newStringField("id", "" + (i % 10), Field.Store.NO));
doc.add(newTextField("content", "bbb " + i, Field.Store.NO));
writer.updateDocument(new Term("id", "" + (i%10)), doc);
}
writer.addIndexes(aux);
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.add(new Term("content", "bbb"));
q.add(new Term("content", "14"));
writer.deleteDocuments(q);
writer.forceMerge(1);
writer.commit();
verifyNumDocs(dir, 1039);
verifyTermDocs(dir, new Term("content", "aaa"), 1030);
verifyTermDocs(dir, new Term("content", "bbb"), 9);
writer.close();
dir.close();
aux.close();
}
public void testWithPendingDeletes3() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux);
IndexWriter writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
// Adds 10 docs, then replaces them with another 10
// docs, so 10 pending deletes:
for (int i = 0; i < 20; i++) {
Document doc = new Document();
doc.add(newStringField("id", "" + (i % 10), Field.Store.NO));
doc.add(newTextField("content", "bbb " + i, Field.Store.NO));
writer.updateDocument(new Term("id", "" + (i%10)), doc);
}
// Deletes one of the 10 added docs, leaving 9:
PhraseQuery q = new PhraseQuery();
q.add(new Term("content", "bbb"));
q.add(new Term("content", "14"));
writer.deleteDocuments(q);
writer.addIndexes(aux);
writer.forceMerge(1);
writer.commit();
verifyNumDocs(dir, 1039);
verifyTermDocs(dir, new Term("content", "aaa"), 1030);
verifyTermDocs(dir, new Term("content", "bbb"), 9);
writer.close();
dir.close();
aux.close();
}
// case 0: add self or exceed maxMergeDocs, expect exception
public void testAddSelf() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
IndexWriter writer = null;
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
// add 100 documents
addDocs(writer, 100);
assertEquals(100, writer.maxDoc());
writer.close();
writer = newWriter(
aux,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(1000).
setMergePolicy(newLogMergePolicy(false))
);
// add 140 documents in separate files
addDocs(writer, 40);
writer.close();
writer = newWriter(
aux,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(1000).
setMergePolicy(newLogMergePolicy(false))
);
addDocs(writer, 100);
writer.close();
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND));
try {
// cannot add self
writer.addIndexes(aux, dir);
assertTrue(false);
}
catch (IllegalArgumentException e) {
assertEquals(100, writer.maxDoc());
}
writer.close();
// make sure the index is correct
verifyNumDocs(dir, 100);
dir.close();
aux.close();
}
// in all the remaining tests, make the doc count of the oldest segment
// in dir large so that it is never merged in addIndexes()
// case 1: no tail segments
public void testNoTailSegments() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux);
IndexWriter writer = newWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setMaxBufferedDocs(10).
setMergePolicy(newLogMergePolicy(4))
);
addDocs(writer, 10);
writer.addIndexes(aux);
assertEquals(1040, writer.maxDoc());
assertEquals(1000, writer.getDocCount(0));
writer.close();
// make sure the index is correct
verifyNumDocs(dir, 1040);
dir.close();
aux.close();
}
// case 2: tail segments, invariants hold, no copy
public void testNoCopySegments() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux);
IndexWriter writer = newWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setMaxBufferedDocs(9).
setMergePolicy(newLogMergePolicy(4))
);
addDocs(writer, 2);
writer.addIndexes(aux);
assertEquals(1032, writer.maxDoc());
assertEquals(1000, writer.getDocCount(0));
writer.close();
// make sure the index is correct
verifyNumDocs(dir, 1032);
dir.close();
aux.close();
}
// case 3: tail segments, invariants hold, copy, invariants hold
public void testNoMergeAfterCopy() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux);
IndexWriter writer = newWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setMaxBufferedDocs(10).
setMergePolicy(newLogMergePolicy(4))
);
writer.addIndexes(aux, new MockDirectoryWrapper(random(), new RAMDirectory(aux, newIOContext(random()))));
assertEquals(1060, writer.maxDoc());
assertEquals(1000, writer.getDocCount(0));
writer.close();
// make sure the index is correct
verifyNumDocs(dir, 1060);
dir.close();
aux.close();
}
// case 4: tail segments, invariants hold, copy, invariants not hold
public void testMergeAfterCopy() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
setUpDirs(dir, aux, true);
IndexWriterConfig dontMergeConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))
.setMergePolicy(NoMergePolicy.COMPOUND_FILES);
IndexWriter writer = new IndexWriter(aux, dontMergeConfig);
for (int i = 0; i < 20; i++) {
writer.deleteDocuments(new Term("id", "" + i));
}
writer.close();
IndexReader reader = DirectoryReader.open(aux);
assertEquals(10, reader.numDocs());
reader.close();
writer = newWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setMaxBufferedDocs(4).
setMergePolicy(newLogMergePolicy(4))
);
if (VERBOSE) {
System.out.println("\nTEST: now addIndexes");
}
writer.addIndexes(aux, new MockDirectoryWrapper(random(), new RAMDirectory(aux, newIOContext(random()))));
assertEquals(1020, writer.maxDoc());
assertEquals(1000, writer.getDocCount(0));
writer.close();
dir.close();
aux.close();
}
// case 5: tail segments, invariants not hold
public void testMoreMerges() throws IOException {
// main directory
Directory dir = newDirectory();
// auxiliary directory
Directory aux = newDirectory();
Directory aux2 = newDirectory();
setUpDirs(dir, aux, true);
IndexWriter writer = newWriter(
aux2,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(100).
setMergePolicy(newLogMergePolicy(10))
);
writer.addIndexes(aux);
assertEquals(30, writer.maxDoc());
assertEquals(3, writer.getSegmentCount());
writer.close();
IndexWriterConfig dontMergeConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))
.setMergePolicy(NoMergePolicy.COMPOUND_FILES);
writer = new IndexWriter(aux, dontMergeConfig);
for (int i = 0; i < 27; i++) {
writer.deleteDocuments(new Term("id", "" + i));
}
writer.close();
IndexReader reader = DirectoryReader.open(aux);
assertEquals(3, reader.numDocs());
reader.close();
dontMergeConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))
.setMergePolicy(NoMergePolicy.COMPOUND_FILES);
writer = new IndexWriter(aux2, dontMergeConfig);
for (int i = 0; i < 8; i++) {
writer.deleteDocuments(new Term("id", "" + i));
}
writer.close();
reader = DirectoryReader.open(aux2);
assertEquals(22, reader.numDocs());
reader.close();
writer = newWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setMaxBufferedDocs(6).
setMergePolicy(newLogMergePolicy(4))
);
writer.addIndexes(aux, aux2);
assertEquals(1040, writer.maxDoc());
assertEquals(1000, writer.getDocCount(0));
writer.close();
dir.close();
aux.close();
aux2.close();
}
private IndexWriter newWriter(Directory dir, IndexWriterConfig conf)
throws IOException {
conf.setMergePolicy(new LogDocMergePolicy());
final IndexWriter writer = new IndexWriter(dir, conf);
return writer;
}
private void addDocs(IndexWriter writer, int numDocs) throws IOException {
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(newTextField("content", "aaa", Field.Store.NO));
writer.addDocument(doc);
}
}
private void addDocs2(IndexWriter writer, int numDocs) throws IOException {
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(newTextField("content", "bbb", Field.Store.NO));
writer.addDocument(doc);
}
}
private void verifyNumDocs(Directory dir, int numDocs) throws IOException {
IndexReader reader = DirectoryReader.open(dir);
assertEquals(numDocs, reader.maxDoc());
assertEquals(numDocs, reader.numDocs());
reader.close();
}
private void verifyTermDocs(Directory dir, Term term, int numDocs)
throws IOException {
IndexReader reader = DirectoryReader.open(dir);
DocsEnum docsEnum = _TestUtil.docs(random(), reader, term.field, term.bytes, null, null, DocsEnum.FLAG_NONE);
int count = 0;
while (docsEnum.nextDoc() != DocIdSetIterator.NO_MORE_DOCS)
count++;
assertEquals(numDocs, count);
reader.close();
}
private void setUpDirs(Directory dir, Directory aux) throws IOException {
setUpDirs(dir, aux, false);
}
private void setUpDirs(Directory dir, Directory aux, boolean withID) throws IOException {
IndexWriter writer = null;
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.CREATE).setMaxBufferedDocs(1000));
// add 1000 documents in 1 segment
if (withID) {
addDocsWithID(writer, 1000, 0);
} else {
addDocs(writer, 1000);
}
assertEquals(1000, writer.maxDoc());
assertEquals(1, writer.getSegmentCount());
writer.close();
writer = newWriter(
aux,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(1000).
setMergePolicy(newLogMergePolicy(false, 10))
);
// add 30 documents in 3 segments
for (int i = 0; i < 3; i++) {
if (withID) {
addDocsWithID(writer, 10, 10*i);
} else {
addDocs(writer, 10);
}
writer.close();
writer = newWriter(
aux,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setMaxBufferedDocs(1000).
setMergePolicy(newLogMergePolicy(false, 10))
);
}
assertEquals(30, writer.maxDoc());
assertEquals(3, writer.getSegmentCount());
writer.close();
}
// LUCENE-1270
public void testHangOnClose() throws IOException {
Directory dir = newDirectory();
LogByteSizeMergePolicy lmp = new LogByteSizeMergePolicy();
lmp.setUseCompoundFile(false);
lmp.setMergeFactor(100);
IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random()))
.setMaxBufferedDocs(5).setMergePolicy(lmp));
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.setStoreTermVectors(true);
customType.setStoreTermVectorPositions(true);
customType.setStoreTermVectorOffsets(true);
doc.add(newField("content", "aaa bbb ccc ddd eee fff ggg hhh iii", customType));
for(int i=0;i<60;i++)
writer.addDocument(doc);
Document doc2 = new Document();
FieldType customType2 = new FieldType();
customType2.setStored(true);
doc2.add(newField("content", "aaa bbb ccc ddd eee fff ggg hhh iii", customType2));
doc2.add(newField("content", "aaa bbb ccc ddd eee fff ggg hhh iii", customType2));
doc2.add(newField("content", "aaa bbb ccc ddd eee fff ggg hhh iii", customType2));
doc2.add(newField("content", "aaa bbb ccc ddd eee fff ggg hhh iii", customType2));
for(int i=0;i<10;i++)
writer.addDocument(doc2);
writer.close();
Directory dir2 = newDirectory();
lmp = new LogByteSizeMergePolicy();
lmp.setMinMergeMB(0.0001);
lmp.setUseCompoundFile(false);
lmp.setMergeFactor(4);
writer = new IndexWriter(dir2, newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random()))
.setMergeScheduler(new SerialMergeScheduler()).setMergePolicy(lmp));
writer.addIndexes(dir);
writer.close();
dir.close();
dir2.close();
}
// TODO: these are also in TestIndexWriter... add a simple doc-writing method
// like this to LuceneTestCase?
private void addDoc(IndexWriter writer) throws IOException
{
Document doc = new Document();
doc.add(newTextField("content", "aaa", Field.Store.NO));
writer.addDocument(doc);
}
private abstract class RunAddIndexesThreads {
Directory dir, dir2;
final static int NUM_INIT_DOCS = 17;
IndexWriter writer2;
final List<Throwable> failures = new ArrayList<Throwable>();
volatile boolean didClose;
final IndexReader[] readers;
final int NUM_COPY;
final static int NUM_THREADS = 5;
final Thread[] threads = new Thread[NUM_THREADS];
public RunAddIndexesThreads(int numCopy) throws Throwable {
NUM_COPY = numCopy;
dir = new MockDirectoryWrapper(random(), new RAMDirectory());
IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random()))
.setMaxBufferedDocs(2));
for (int i = 0; i < NUM_INIT_DOCS; i++)
addDoc(writer);
writer.close();
dir2 = newDirectory();
writer2 = new IndexWriter(dir2, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
writer2.commit();
readers = new IndexReader[NUM_COPY];
for(int i=0;i<NUM_COPY;i++)
readers[i] = DirectoryReader.open(dir);
}
void launchThreads(final int numIter) {
for(int i=0;i<NUM_THREADS;i++) {
threads[i] = new Thread() {
@Override
public void run() {
try {
final Directory[] dirs = new Directory[NUM_COPY];
for(int k=0;k<NUM_COPY;k++)
dirs[k] = new MockDirectoryWrapper(random(), new RAMDirectory(dir, newIOContext(random())));
int j=0;
while(true) {
// System.out.println(Thread.currentThread().getName() + ": iter j=" + j);
if (numIter > 0 && j == numIter)
break;
doBody(j++, dirs);
}
} catch (Throwable t) {
handle(t);
}
}
};
}
for(int i=0;i<NUM_THREADS;i++)
threads[i].start();
}
void joinThreads() throws Exception {
for(int i=0;i<NUM_THREADS;i++)
threads[i].join();
}
void close(boolean doWait) throws Throwable {
didClose = true;
writer2.close(doWait);
}
void closeDir() throws Throwable {
for(int i=0;i<NUM_COPY;i++)
readers[i].close();
dir2.close();
}
abstract void doBody(int j, Directory[] dirs) throws Throwable;
abstract void handle(Throwable t);
}
private class CommitAndAddIndexes extends RunAddIndexesThreads {
public CommitAndAddIndexes(int numCopy) throws Throwable {
super(numCopy);
}
@Override
void handle(Throwable t) {
t.printStackTrace(System.out);
synchronized(failures) {
failures.add(t);
}
}
@Override
void doBody(int j, Directory[] dirs) throws Throwable {
switch(j%5) {
case 0:
if (VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[]) then full merge");
}
writer2.addIndexes(dirs);
writer2.forceMerge(1);
break;
case 1:
if (VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[])");
}
writer2.addIndexes(dirs);
break;
case 2:
if (VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(IndexReader[])");
}
writer2.addIndexes(readers);
break;
case 3:
if (VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": TEST: addIndexes(Dir[]) then maybeMerge");
}
writer2.addIndexes(dirs);
writer2.maybeMerge();
break;
case 4:
if (VERBOSE) {
System.out.println(Thread.currentThread().getName() + ": TEST: commit");
}
writer2.commit();
}
}
}
// LUCENE-1335: test simultaneous addIndexes & commits
// from multiple threads
public void testAddIndexesWithThreads() throws Throwable {
final int NUM_ITER = TEST_NIGHTLY ? 15 : 5;
final int NUM_COPY = 3;
CommitAndAddIndexes c = new CommitAndAddIndexes(NUM_COPY);
c.launchThreads(NUM_ITER);
for(int i=0;i<100;i++)
addDoc(c.writer2);
c.joinThreads();
int expectedNumDocs = 100+NUM_COPY*(4*NUM_ITER/5)*RunAddIndexesThreads.NUM_THREADS*RunAddIndexesThreads.NUM_INIT_DOCS;
assertEquals("expected num docs don't match - failures: " + c.failures, expectedNumDocs, c.writer2.numDocs());
c.close(true);
assertTrue("found unexpected failures: " + c.failures, c.failures.isEmpty());
IndexReader reader = DirectoryReader.open(c.dir2);
assertEquals(expectedNumDocs, reader.numDocs());
reader.close();
c.closeDir();
}
private class CommitAndAddIndexes2 extends CommitAndAddIndexes {
public CommitAndAddIndexes2(int numCopy) throws Throwable {
super(numCopy);
}
@Override
void handle(Throwable t) {
if (!(t instanceof AlreadyClosedException) && !(t instanceof NullPointerException)) {
t.printStackTrace(System.out);
synchronized(failures) {
failures.add(t);
}
}
}
}
// LUCENE-1335: test simultaneous addIndexes & close
public void testAddIndexesWithClose() throws Throwable {
final int NUM_COPY = 3;
CommitAndAddIndexes2 c = new CommitAndAddIndexes2(NUM_COPY);
//c.writer2.setInfoStream(System.out);
c.launchThreads(-1);
// Close w/o first stopping/joining the threads
c.close(true);
//c.writer2.close();
c.joinThreads();
c.closeDir();
assertTrue(c.failures.size() == 0);
}
private class CommitAndAddIndexes3 extends RunAddIndexesThreads {
public CommitAndAddIndexes3(int numCopy) throws Throwable {
super(numCopy);
}
@Override
void doBody(int j, Directory[] dirs) throws Throwable {
switch(j%5) {
case 0:
if (VERBOSE) {
System.out.println("TEST: " + Thread.currentThread().getName() + ": addIndexes + full merge");
}
writer2.addIndexes(dirs);
writer2.forceMerge(1);
break;
case 1:
if (VERBOSE) {
System.out.println("TEST: " + Thread.currentThread().getName() + ": addIndexes");
}
writer2.addIndexes(dirs);
break;
case 2:
if (VERBOSE) {
System.out.println("TEST: " + Thread.currentThread().getName() + ": addIndexes(IR[])");
}
writer2.addIndexes(readers);
break;
case 3:
if (VERBOSE) {
System.out.println("TEST: " + Thread.currentThread().getName() + ": full merge");
}
writer2.forceMerge(1);
break;
case 4:
if (VERBOSE) {
System.out.println("TEST: " + Thread.currentThread().getName() + ": commit");
}
writer2.commit();
}
}
@Override
void handle(Throwable t) {
boolean report = true;
if (t instanceof AlreadyClosedException || t instanceof MergePolicy.MergeAbortedException || t instanceof NullPointerException) {
report = !didClose;
} else if (t instanceof FileNotFoundException) {
report = !didClose;
} else if (t instanceof IOException) {
Throwable t2 = t.getCause();
if (t2 instanceof MergePolicy.MergeAbortedException) {
report = !didClose;
}
}
if (report) {
t.printStackTrace(System.out);
synchronized(failures) {
failures.add(t);
}
}
}
}
// LUCENE-1335: test simultaneous addIndexes & close
public void testAddIndexesWithCloseNoWait() throws Throwable {
final int NUM_COPY = 50;
CommitAndAddIndexes3 c = new CommitAndAddIndexes3(NUM_COPY);
c.launchThreads(-1);
Thread.sleep(_TestUtil.nextInt(random(), 10, 500));
// Close w/o first stopping/joining the threads
if (VERBOSE) {
System.out.println("TEST: now close(false)");
}
c.close(false);
c.joinThreads();
if (VERBOSE) {
System.out.println("TEST: done join threads");
}
c.closeDir();
assertTrue(c.failures.size() == 0);
}
// LUCENE-1335: test simultaneous addIndexes & close
public void testAddIndexesWithRollback() throws Throwable {
final int NUM_COPY = TEST_NIGHTLY ? 50 : 5;
CommitAndAddIndexes3 c = new CommitAndAddIndexes3(NUM_COPY);
c.launchThreads(-1);
Thread.sleep(_TestUtil.nextInt(random(), 10, 500));
// Close w/o first stopping/joining the threads
if (VERBOSE) {
System.out.println("TEST: now force rollback");
}
c.didClose = true;
c.writer2.rollback();
c.joinThreads();
c.closeDir();
assertTrue(c.failures.size() == 0);
}
// LUCENE-2996: tests that addIndexes(IndexReader) applies existing deletes correctly.
public void testExistingDeletes() throws Exception {
Directory[] dirs = new Directory[2];
for (int i = 0; i < dirs.length; i++) {
dirs[i] = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
IndexWriter writer = new IndexWriter(dirs[i], conf);
Document doc = new Document();
doc.add(new StringField("id", "myid", Field.Store.NO));
writer.addDocument(doc);
writer.close();
}
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
IndexWriter writer = new IndexWriter(dirs[0], conf);
// Now delete the document
writer.deleteDocuments(new Term("id", "myid"));
IndexReader r = DirectoryReader.open(dirs[1]);
try {
writer.addIndexes(r);
} finally {
r.close();
}
writer.commit();
assertEquals("Documents from the incoming index should not have been deleted", 1, writer.numDocs());
writer.close();
for (Directory dir : dirs) {
dir.close();
}
}
// just like addDocs but with ID, starting from docStart
private void addDocsWithID(IndexWriter writer, int numDocs, int docStart) throws IOException {
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
doc.add(newTextField("content", "aaa", Field.Store.NO));
doc.add(newTextField("id", "" + (docStart + i), Field.Store.YES));
writer.addDocument(doc);
}
}
public void testSimpleCaseCustomCodec() throws IOException {
// main directory
Directory dir = newDirectory();
// two auxiliary directories
Directory aux = newDirectory();
Directory aux2 = newDirectory();
Codec codec = new CustomPerFieldCodec();
IndexWriter writer = null;
writer = newWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random())).setOpenMode(OpenMode.CREATE).setCodec(codec));
// add 100 documents
addDocsWithID(writer, 100, 0);
assertEquals(100, writer.maxDoc());
writer.commit();
writer.close();
_TestUtil.checkIndex(dir);
writer = newWriter(
aux,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setCodec(codec).
setMaxBufferedDocs(10).
setMergePolicy(newLogMergePolicy(false))
);
// add 40 documents in separate files
addDocs(writer, 40);
assertEquals(40, writer.maxDoc());
writer.commit();
writer.close();
writer = newWriter(
aux2,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.CREATE).
setCodec(codec)
);
// add 40 documents in compound files
addDocs2(writer, 50);
assertEquals(50, writer.maxDoc());
writer.commit();
writer.close();
// test doc count before segments are merged
writer = newWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
setOpenMode(OpenMode.APPEND).
setCodec(codec)
);
assertEquals(100, writer.maxDoc());
writer.addIndexes(aux, aux2);
assertEquals(190, writer.maxDoc());
writer.close();
dir.close();
aux.close();
aux2.close();
}
private static final class CustomPerFieldCodec extends Lucene42Codec {
private final PostingsFormat simpleTextFormat = PostingsFormat.forName("SimpleText");
private final PostingsFormat defaultFormat = PostingsFormat.forName("Lucene41");
private final PostingsFormat mockSepFormat = PostingsFormat.forName("MockSep");
@Override
public PostingsFormat getPostingsFormatForField(String field) {
if (field.equals("id")) {
return simpleTextFormat;
} else if (field.equals("content")) {
return mockSepFormat;
} else {
return defaultFormat;
}
}
}
// LUCENE-2790: tests that the non CFS files were deleted by addIndexes
public void testNonCFSLeftovers() throws Exception {
Directory[] dirs = new Directory[2];
for (int i = 0; i < dirs.length; i++) {
dirs[i] = new RAMDirectory();
IndexWriter w = new IndexWriter(dirs[i], new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())));
Document d = new Document();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.setStoreTermVectors(true);
d.add(new Field("c", "v", customType));
w.addDocument(d);
w.close();
}
IndexReader[] readers = new IndexReader[] { DirectoryReader.open(dirs[0]), DirectoryReader.open(dirs[1]) };
Directory dir = new MockDirectoryWrapper(random(), new RAMDirectory());
IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergePolicy(newLogMergePolicy(true));
LogMergePolicy lmp = (LogMergePolicy) conf.getMergePolicy();
// Force creation of CFS:
lmp.setNoCFSRatio(1.0);
lmp.setMaxCFSSegmentSizeMB(Double.POSITIVE_INFINITY);
IndexWriter w3 = new IndexWriter(dir, conf);
w3.addIndexes(readers);
w3.close();
// we should now see segments_X,
// segments.gen,_Y.cfs,_Y.cfe, _Z.si
assertEquals("Only one compound segment should exist, but got: " + Arrays.toString(dir.listAll()), 5, dir.listAll().length);
dir.close();
}
private static final class UnRegisteredCodec extends FilterCodec {
public UnRegisteredCodec() {
super("NotRegistered", new Lucene42Codec());
}
}
/*
* simple test that ensures we getting expected exceptions
*/
public void testAddIndexMissingCodec() throws IOException {
BaseDirectoryWrapper toAdd = newDirectory();
// Disable checkIndex, else we get an exception because
// of the unregistered codec:
toAdd.setCheckIndexOnClose(false);
{
IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random()));
conf.setCodec(new UnRegisteredCodec());
IndexWriter w = new IndexWriter(toAdd, conf);
Document doc = new Document();
FieldType customType = new FieldType();
customType.setIndexed(true);
doc.add(newField("foo", "bar", customType));
w.addDocument(doc);
w.close();
}
{
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random()));
conf.setCodec(_TestUtil.alwaysPostingsFormat(new Pulsing41PostingsFormat(1 + random().nextInt(20))));
IndexWriter w = new IndexWriter(dir, conf);
try {
w.addIndexes(toAdd);
fail("no such codec");
} catch (IllegalArgumentException ex) {
// expected
}
w.close();
IndexReader open = DirectoryReader.open(dir);
assertEquals(0, open.numDocs());
open.close();
dir.close();
}
try {
DirectoryReader.open(toAdd);
fail("no such codec");
} catch (IllegalArgumentException ex) {
// expected
}
toAdd.close();
}
// LUCENE-3575
public void testFieldNamesChanged() throws IOException {
Directory d1 = newDirectory();
RandomIndexWriter w = new RandomIndexWriter(random(), d1);
Document doc = new Document();
doc.add(newStringField("f1", "doc1 field1", Field.Store.YES));
doc.add(newStringField("id", "1", Field.Store.YES));
w.addDocument(doc);
IndexReader r1 = w.getReader();
w.close();
Directory d2 = newDirectory();
w = new RandomIndexWriter(random(), d2);
doc = new Document();
doc.add(newStringField("f2", "doc2 field2", Field.Store.YES));
doc.add(newStringField("id", "2", Field.Store.YES));
w.addDocument(doc);
IndexReader r2 = w.getReader();
w.close();
Directory d3 = newDirectory();
w = new RandomIndexWriter(random(), d3);
w.addIndexes(r1, r2);
r1.close();
d1.close();
r2.close();
d2.close();
IndexReader r3 = w.getReader();
w.close();
assertEquals(2, r3.numDocs());
for(int docID=0;docID<2;docID++) {
Document d = r3.document(docID);
if (d.get("id").equals("1")) {
assertEquals("doc1 field1", d.get("f1"));
} else {
assertEquals("doc2 field2", d.get("f2"));
}
}
r3.close();
d3.close();
}
}
| pkarmstr/NYBC | solr-4.2.1/lucene/core/src/test/org/apache/lucene/index/TestAddIndexes.java | Java | apache-2.0 | 38,814 |
// Copyright 2019 The Bazel 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.
package com.google.devtools.build.lib.query2.cquery;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.packages.BuildType.OUTPUT;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.analysis.util.MockRule;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.query2.PostAnalysisQueryEnvironment;
import com.google.devtools.build.lib.query2.engine.QueryEnvironment.Setting;
import com.google.devtools.build.lib.query2.engine.QueryExpression;
import com.google.devtools.build.lib.query2.engine.QueryParser;
import com.google.devtools.build.lib.query2.query.aspectresolvers.AspectResolver.Mode;
import com.google.devtools.build.lib.util.FileTypeSet;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
/** Tests cquery's BUILD output format. */
public class BuildOutputFormatterCallbackTest extends ConfiguredTargetQueryTest {
private CqueryOptions options;
private Reporter reporter;
private final List<Event> events = new ArrayList<>();
private static MockRule.State simpleRule() {
return MockRule.define(
"my_rule",
(builder, env) ->
builder
.add(attr("deps", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE))
.add(attr("out", OUTPUT)));
}
@Before
public final void setUpCqueryOptions() throws Exception {
this.options = new CqueryOptions();
// TODO(bazel-team): reduce the confusion about these two seemingly similar settings.
// options.aspectDeps impacts how proto and similar output formatters output aspect results.
// Setting.INCLUDE_ASPECTS impacts whether or not aspect dependencies are included when
// following target deps. See CommonQueryOptions for further flag details.
options.aspectDeps = Mode.OFF;
helper.setQuerySettings(Setting.INCLUDE_ASPECTS);
this.reporter = new Reporter(new EventBus(), events::add);
helper.useRuleClassProvider(
setRuleClassProviders(BuildOutputFormatterCallbackTest::simpleRule).build());
}
private List<String> getOutput(String queryExpression) throws Exception {
QueryExpression expression = QueryParser.parse(queryExpression, getDefaultFunctions());
Set<String> targetPatternSet = new LinkedHashSet<>();
expression.collectTargetPatterns(targetPatternSet);
helper.setQuerySettings(Setting.NO_IMPLICIT_DEPS);
PostAnalysisQueryEnvironment<KeyedConfiguredTarget> env =
((ConfiguredTargetQueryHelper) helper).getPostAnalysisQueryEnvironment(targetPatternSet);
ByteArrayOutputStream output = new ByteArrayOutputStream();
BuildOutputFormatterCallback callback =
new BuildOutputFormatterCallback(
reporter,
options,
new PrintStream(output),
getHelper().getSkyframeExecutor(),
env.getAccessor());
env.evaluateQuery(expression, callback);
return Arrays.asList(output.toString().split(System.lineSeparator()));
}
@Test
public void selectInAttribute() throws Exception {
writeFile(
"test/BUILD",
"my_rule(",
" name = 'my_rule',",
" deps = select({",
" ':garfield': ['lasagna.java', 'naps.java'],",
" '//conditions:default': ['mondays.java']",
" })",
")",
"config_setting(",
" name = 'garfield',",
" values = {'test_arg': 'cat'}",
")");
getHelper().useConfiguration("--test_arg=cat");
assertThat(getOutput("//test:my_rule"))
.containsExactly(
"# /workspace/test/BUILD:1:8",
"my_rule(",
" name = \"my_rule\",",
" deps = [\"//test:lasagna.java\", \"//test:naps.java\"],",
")",
"# Rule my_rule instantiated at (most recent call last):",
"# /workspace/test/BUILD:1:8 in <toplevel>")
.inOrder();
getHelper().useConfiguration("--test_arg=hound");
assertThat(getOutput("//test:my_rule"))
.containsExactly(
"# /workspace/test/BUILD:1:8",
"my_rule(",
" name = \"my_rule\",",
" deps = [\"//test:mondays.java\"],",
")",
"# Rule my_rule instantiated at (most recent call last):",
"# /workspace/test/BUILD:1:8 in <toplevel>")
.inOrder();
}
@Test
public void alias() throws Exception {
writeFile(
"test/BUILD",
"my_rule(",
" name = 'my_rule',",
" deps = select({",
" ':garfield': ['lasagna.java', 'naps.java'],",
" '//conditions:default': ['mondays.java']",
" })",
")",
"config_setting(",
" name = 'garfield',",
" values = {'test_arg': 'cat'}",
")",
"alias(",
" name = 'my_alias',",
" actual = ':my_rule'",
")",
"# Rule my_alias instantiated at (most recent call last):",
"# /workspace/test/BUILD:12:6 in <toplevel>");
assertThat(getOutput("//test:my_alias"))
.containsExactly(
"# /workspace/test/BUILD:12:6",
"alias(",
" name = \"my_alias\",",
" actual = \"//test:my_rule\",",
")",
"# Rule my_alias instantiated at (most recent call last):",
"# /workspace/test/BUILD:12:6 in <toplevel>")
.inOrder();
}
@Test
public void aliasWithSelect() throws Exception {
writeFile(
"test/BUILD",
"my_rule(",
" name = 'my_first_rule',",
" deps = ['penne.java'],",
")",
"my_rule(",
" name = 'my_second_rule',",
" deps = ['linguini.java'],",
")",
"config_setting(",
" name = 'garfield',",
" values = {'test_arg': 'cat'}",
")",
"alias(",
" name = 'my_alias',",
" actual = select({",
" ':garfield': ':my_first_rule',",
" '//conditions:default': ':my_second_rule'",
" })",
")");
getHelper().useConfiguration("--test_arg=cat");
assertThat(getOutput("//test:my_alias"))
.containsExactly(
"# /workspace/test/BUILD:13:6",
"alias(",
" name = \"my_alias\",",
" actual = \"//test:my_first_rule\",",
")",
"# Rule my_alias instantiated at (most recent call last):",
"# /workspace/test/BUILD:13:6 in <toplevel>")
.inOrder();
getHelper().useConfiguration("--test_arg=hound");
assertThat(getOutput("//test:my_alias"))
.containsExactly(
"# /workspace/test/BUILD:13:6",
"alias(",
" name = \"my_alias\",",
" actual = \"//test:my_second_rule\",",
")",
"# Rule my_alias instantiated at (most recent call last):",
"# /workspace/test/BUILD:13:6 in <toplevel>")
.inOrder();
}
@Test
public void sourceFile() throws Exception {
writeFile(
"test/BUILD",
"my_rule(",
" name = 'my_rule',",
" deps = select({",
" ':garfield': ['lasagna.java', 'naps.java'],",
" '//conditions:default': ['mondays.java']",
" })",
")",
"config_setting(",
" name = 'garfield',",
" values = {'test_arg': 'cat'}",
")");
assertThat(getOutput("//test:lasagna.java")).containsExactly("");
}
@Test
public void outputFile() throws Exception {
writeFile(
"test/BUILD",
"my_rule(",
" name = 'my_rule',",
" deps = select({",
" ':garfield': ['lasagna.java', 'naps.java'],",
" '//conditions:default': ['mondays.java']",
" }),",
" out = 'output.txt'",
")",
"config_setting(",
" name = 'garfield',",
" values = {'test_arg': 'cat'}",
")");
getHelper().useConfiguration("--test_arg=cat");
assertThat(getOutput("//test:output.txt"))
.containsExactly(
"# /workspace/test/BUILD:1:8",
"my_rule(",
" name = \"my_rule\",",
" deps = [\"//test:lasagna.java\", \"//test:naps.java\"],",
" out = \"//test:output.txt\",",
")",
"# Rule my_rule instantiated at (most recent call last):",
"# /workspace/test/BUILD:1:8 in <toplevel>")
.inOrder();
getHelper().useConfiguration("--test_arg=hound");
assertThat(getOutput("//test:output.txt"))
.containsExactly(
"# /workspace/test/BUILD:1:8",
"my_rule(",
" name = \"my_rule\",",
" deps = [\"//test:mondays.java\"],",
" out = \"//test:output.txt\",",
")",
"# Rule my_rule instantiated at (most recent call last):",
"# /workspace/test/BUILD:1:8 in <toplevel>")
.inOrder();
}
}
| cushon/bazel | src/test/java/com/google/devtools/build/lib/query2/cquery/BuildOutputFormatterCallbackTest.java | Java | apache-2.0 | 9,947 |
/*
* Copyright © 2014 TU Berlin (emma@dima.tu-berlin.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 org.emmalanguage
package lib.ml.feature
import api._
import lib.ml.FPoint
class TokenizeFlinkSpec extends TokenizeSpec with FlinkAware {
override protected def gaps(xs: Seq[(String, Int)]) =
withDefaultFlinkEnv(implicit flink => emma.onFlink {
val rs = for {
(text, id) <- DataBag(xs)
} yield FPoint(id, tokenize.gaps()(text).toSeq)
rs.collect()
})
override protected def words(xs: Seq[(String, Int)]) =
withDefaultFlinkEnv(implicit flink => emma.onFlink {
val rs = for {
(text, id) <- DataBag(xs)
} yield FPoint(id, tokenize.words()(text).toSeq)
rs.collect()
})
}
| emmalanguage/emma | emma-lib-flink/src/test/scala/org/emmalanguage/lib/ml/feature/TokenizeFlinkSpec.scala | Scala | apache-2.0 | 1,270 |
<p>
<strong><?php _e('Certain options below such as the venue featured image and venue excerpt will only be displayed if supported by your WordPress theme.', 'event_espresso'); ?></strong>
</p>
<p><strong><?php _e('Venue Featured Image', 'event_espresso'); ?></strong></p>
<p>
<?php _e('Set a featured image for your venue.', 'event_espresso'); ?>
</p>
<p><strong><?php _e('Venue Excerpt', 'event_espresso'); ?></strong></p>
<p>
<?php _e('An excerpt can be thought of as a short description for your venue.', 'event_espresso'); ?>
</p>
<p><strong><?php _e('Venue Custom Fields', 'event_espresso'); ?></strong></p>
<p>
<?php _e('Setup custom fields for your venue.', 'event_espresso'); ?>
</p>
<p><strong><?php _e('Venue Discussion', 'event_espresso'); ?></strong></p>
<p>
<?php _e('Specify if comments, trackbacks, and pingbacks are allowed for your venue.', 'event_espresso'); ?>
</p>
<p><strong><?php _e('Venue Slug', 'event_espresso'); ?></strong></p>
<p>
<?php _e('The slug is the customizable portion of the URL for your venue. For example, if my venue was called "Annual Parade," then the URL could appear as such: http://example.com/venues/annual-parade -- the slug would be then be annual-parade.', 'event_espresso'); ?>
</p>
<p><strong><?php _e('Venue Author', 'event_espresso'); ?></strong></p>
<p>
<?php _e('This is the site member that will be credited for creating this venue.', 'event_espresso'); ?>
</p> | yoanngern/iahm_2016 | wp-content/plugins/event-espresso-core-reg/admin_pages/venues/help_tabs/venues_editor_other.help_tab.php | PHP | apache-2.0 | 1,418 |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __AES_H__
#define __AES_H__
#include "common.h"
#define CTRL_CTR_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
#define CTRL_ENABLE 1
#define CTRL_ENCRYPT 1
#define CTRL_NO_SOFT_RESET 0
/*
* Use this structure to avoid alignment problems with input and output
* pointers.
*/
struct AES_access_helper {
uint32_t udata;
} __packed;
/*
* AES configuration settings
*/
enum AES_cipher_mode {
AES_CIPHER_MODE_ECB = 0,
AES_CIPHER_MODE_CTR = 1,
AES_CIPHER_MODE_CBC = 2,
AES_CIPHER_MODE_GCM = 3
};
enum AES_encrypt_mode { AES_DECRYPT_MODE = 0, AES_ENCRYPT_MODE = 1 };
/*
* AES implementation, based on a hardware AES block.
*/
#define AES256_BLOCK_CIPHER_KEY_SIZE 32
#define AES128_BLOCK_CIPHER_KEY_SIZE 16
int fips_aes_init(const uint8_t *key, uint32_t key_len, const uint8_t *iv,
enum AES_cipher_mode c_mode, enum AES_encrypt_mode e_mode);
int fips_aes_block(const uint8_t *in, uint8_t *out);
#endif // __AES_H__
| google/tock-on-titan | userspace/personality_test/include/fips_aes.h | C | apache-2.0 | 1,553 |
#!/usr/bin/python
#
# Author: Rajesh Sinha, Karan Narain
# The base class for Twitter and GPlus Objects
#
import logging
import sys
from bs4 import BeautifulSoup
import urllib2
import re
## Some Important constants
_parser = "lxml" ## remember to pip install lxml or else use another parser
_loggingLevel = logging.DEBUG ## How much trace
class AltmetricBase:
def __init__(self, name, snLink, altmetricId, startPage, endPage):
self.name = name # Name of social network
self.snLink = snLink # The /twitter or /google link
self.amUrl = 'https://www.altmetric.com/details/' + altmetricId + snLink # full link to page1 of social network
self.startPagination = startPage
self.endPagination = endPage
self.baseLink = self.amUrl.replace(self.snLink,'') # The baselink which is shown when a non-existent page is used
self.logger = logging.getLogger(__name__)
logging.basicConfig(level=_loggingLevel)
self.logger.debug('Created Altmetric Object')
def findPosters(self, soup):
raise NotImplementedError("Subclass must implement abstract method")
def getMoreSoup(self):
""" Tries to check all possible links starting from 2 to 1000 and breaks out when
we get a redirect. There is no graceful way i.e. HTTP code on redirect when we
access a nonexistant link. So we check when almetric returns the base URL of the
research arcticle and stop then. This is a generator function and keeps returning
the beautifulsoup of the link
"""
# when the list runs out altmteric returns the base url of the research paper
for a in range(self.startPagination, self.endPagination):
link = self.amUrl + '/page:' + str(a)
self.logger.debug('Trying URL - %s', link)
try:
page = urllib2.urlopen(link)
if self.isRedirect(page):
self.logger.debug('finishing the generator...')
return
else:
self.logger.debug('Yielding Soup')
yield BeautifulSoup(page, _parser)
except urllib2.HTTPError, e:
self.logger.error('Could not open %s because of HTTP error', link)
self.logger.error("%r", e.code)
except urllib2.URLError, e:
self.logger.error('Could not open %s because of URL error', link)
self.logger.error("%r", e.args)
def isRedirect(self, page):
return page.geturl() == self.baseLink
@staticmethod
def isValidURL(url):
testUrl = 'https://www.altmetric.com/details/' + url
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
result = regex.match(testUrl)
return False if result is None else True
def openAndLoadURL(self, fname):
""" Opens the base URL for a network and returns the beautifulSoup through lxml parses """
self.logger.debug('Opening URL ' + fname)
try:
page = urllib2.urlopen(fname)
except urllib2.HTTPError, e:
self.logger.error('Could not open ' + fname+ ': HTTP Error ')
self.logger.error(e.code)
return False, None
except urllib2.URLError, e:
self.logger.error('Could not open ' + fname+ ': URL Error ')
self.logger.error(e.args)
return False, None
soup = BeautifulSoup(page, _parser)
return True, soup
def executeAltmetricAnalysis(self):
posters = []
status, soup = self.openAndLoadURL(self.amUrl)
if status:
posters = self.findPosters(soup)
self.logger.debug('Found %d posts so far', len(posters))
for soup in self.getMoreSoup():
posters.extend(self.findPosters(soup))
self.logger.debug('Found %d posts so far', len(posters))
self.logger.info('Found %d posts in total for the link', len(posters))
posters = list(set(posters))
self.logger.info('Found %d Unique Posters for the link', len(posters))
for poster in posters:
print (poster).encode('utf-8')
self.logger.info('written all the posters to stdout...')
else:
self.logger.error('found error in URL upfront so bailing out')
sys.stderr.flush()
sys.stdout.flush()
sys.exit(1)
| sinharrajesh/dbtools | google-plus-analysis/SocialNW.py | Python | apache-2.0 | 4,807 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Notebooks.V1.Snippets
{
// [START notebooks_v1_generated_NotebookService_UpgradeInstance_async]
using Google.Cloud.Notebooks.V1;
using Google.LongRunning;
using System.Threading.Tasks;
public sealed partial class GeneratedNotebookServiceClientSnippets
{
/// <summary>Snippet for UpgradeInstanceAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task UpgradeInstanceRequestObjectAsync()
{
// Create client
NotebookServiceClient notebookServiceClient = await NotebookServiceClient.CreateAsync();
// Initialize request argument(s)
UpgradeInstanceRequest request = new UpgradeInstanceRequest { Name = "", };
// Make the request
Operation<Instance, OperationMetadata> response = await notebookServiceClient.UpgradeInstanceAsync(request);
// Poll until the returned long-running operation is complete
Operation<Instance, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Instance result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Instance, OperationMetadata> retrievedResponse = await notebookServiceClient.PollOnceUpgradeInstanceAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Instance retrievedResult = retrievedResponse.Result;
}
}
}
// [END notebooks_v1_generated_NotebookService_UpgradeInstance_async]
}
| googleapis/google-cloud-dotnet | apis/Google.Cloud.Notebooks.V1/Google.Cloud.Notebooks.V1.GeneratedSnippets/NotebookServiceClient.UpgradeInstanceRequestObjectAsyncSnippet.g.cs | C# | apache-2.0 | 2,684 |
package io.fabric8.workflow.build;
import io.fabric8.io.fabric8.workflow.build.signal.BuildSignallerService;
import org.jbpm.test.JBPMHelper;
import org.kie.api.KieBase;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.manager.RuntimeEngine;
import org.kie.api.runtime.manager.RuntimeEnvironmentBuilder;
import org.kie.api.runtime.manager.RuntimeManager;
import org.kie.api.runtime.manager.RuntimeManagerFactory;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class MainWithPersistence {
public static void main(String[] args) {
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieBase kbase = kContainer.getKieBase("kbase");
RuntimeManager manager = createRuntimeManager(kbase);
RuntimeEngine engine = manager.getRuntimeEngine(null);
KieSession ksession = engine.getKieSession();
BuildSignallerService signallerService = new BuildSignallerService(ksession);
signallerService.start();
signallerService.join();
manager.disposeRuntimeEngine(engine);
System.exit(0);
}
private static RuntimeManager createRuntimeManager(KieBase kbase) {
JBPMHelper.startH2Server();
JBPMHelper.setupDataSource();
EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.persistence.jpa");
RuntimeEnvironmentBuilder builder = RuntimeEnvironmentBuilder.Factory.get()
.newDefaultBuilder().entityManagerFactory(emf)
.knowledgeBase(kbase);
return RuntimeManagerFactory.Factory.get()
.newSingletonRuntimeManager(builder.get(), "com.sample:example:1.0");
}
}
| jimmidyson/fabric8 | components/fabric8-build-workflow/src/test/java/io/fabric8/workflow/build/MainWithPersistence.java | Java | apache-2.0 | 1,840 |
// Copyright 2017 PingCAP, 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 ddl_test
import (
"context"
"sync/atomic"
"time"
. "github.com/pingcap/check"
"github.com/pingcap/tidb/ddl"
"github.com/pingcap/tidb/parser/model"
"github.com/pingcap/tidb/session"
"github.com/pingcap/tidb/store/mockstore"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/testkit"
"github.com/tikv/client-go/v2/tikv"
)
type testDDLTableSplitSuite struct{}
var _ = Suite(&testDDLTableSplitSuite{})
func (s *testDDLTableSplitSuite) TestTableSplit(c *C) {
store, err := mockstore.NewMockStore()
c.Assert(err, IsNil)
defer func() {
err := store.Close()
c.Assert(err, IsNil)
}()
session.SetSchemaLease(100 * time.Millisecond)
session.DisableStats4Test()
atomic.StoreUint32(&ddl.EnableSplitTableRegion, 1)
dom, err := session.BootstrapSession(store)
c.Assert(err, IsNil)
tk := testkit.NewTestKit(c, store)
tk.MustExec("use test")
// Synced split table region.
tk.MustExec("set global tidb_scatter_region = 1")
tk.MustExec(`create table t_part (a int key) partition by range(a) (
partition p0 values less than (10),
partition p1 values less than (20)
)`)
defer dom.Close()
atomic.StoreUint32(&ddl.EnableSplitTableRegion, 0)
infoSchema := dom.InfoSchema()
c.Assert(infoSchema, NotNil)
t, err := infoSchema.TableByName(model.NewCIStr("mysql"), model.NewCIStr("tidb"))
c.Assert(err, IsNil)
checkRegionStartWithTableID(c, t.Meta().ID, store.(kvStore))
t, err = infoSchema.TableByName(model.NewCIStr("test"), model.NewCIStr("t_part"))
c.Assert(err, IsNil)
pi := t.Meta().GetPartitionInfo()
c.Assert(pi, NotNil)
for _, def := range pi.Definitions {
checkRegionStartWithTableID(c, def.ID, store.(kvStore))
}
}
type kvStore interface {
GetRegionCache() *tikv.RegionCache
}
func checkRegionStartWithTableID(c *C, id int64, store kvStore) {
regionStartKey := tablecodec.EncodeTablePrefix(id)
var loc *tikv.KeyLocation
var err error
cache := store.GetRegionCache()
loc, err = cache.LocateKey(tikv.NewBackoffer(context.Background(), 5000), regionStartKey)
c.Assert(err, IsNil)
// Region cache may be out of date, so we need to drop this expired region and load it again.
cache.InvalidateCachedRegion(loc.Region)
c.Assert(loc.StartKey, BytesEquals, []byte(regionStartKey))
}
| coocood/tidb | ddl/table_split_test.go | GO | apache-2.0 | 2,839 |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*<author>James Nies</author>
// - Fixed the shifting of the Edit button under Mono
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Gui.Configuration
{
using System;
using System.IO;
using System.Windows.Forms;
using NArrange.Core;
/// <summary>
/// Control that allows the user to select, create or edit a configuration.
/// </summary>
public partial class ConfigurationPicker : UserControl
{
#region Constructors
/// <summary>
/// Creates a new ConfigurationPicker.
/// </summary>
public ConfigurationPicker()
{
InitializeComponent();
}
#endregion Constructors
#region Events
/// <summary>
/// Occurs when the create button is clicked.
/// </summary>
public event EventHandler CreateClick;
/// <summary>
/// Occurs when the edit button is clicked.
/// </summary>
public event EventHandler EditClick;
#endregion Events
#region Properties
/// <summary>
/// Gets or sets the selected configuration file.
/// </summary>
public string SelectedFile
{
get
{
return this._textBoxFile.Text;
}
set
{
this._textBoxFile.Text = value;
this.UpdateButtons();
}
}
#endregion Properties
#region Methods
/// <summary>
/// Refreshes this control.
/// </summary>
public override void Refresh()
{
this.UpdateButtons();
base.Refresh();
}
/// <summary>
/// Event handler for the Browse button click event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void HandleButtonBrowseClick(object sender, EventArgs e)
{
_openFileDialog.FileName = _textBoxFile.Text;
DialogResult result = _openFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
string filename = _openFileDialog.FileName;
_textBoxFile.Text = filename;
this.OnEditClick();
}
}
/// <summary>
/// Event handler for the Create button click event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void HandleButtonCreateClick(object sender, EventArgs e)
{
this.OnCreateClick();
}
/// <summary>
/// Event handler for the Edit button click event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void HandleButtonEditClick(object sender, EventArgs e)
{
this.OnEditClick();
}
/// <summary>
/// Event handler for the file textbox TextChanged event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void HandleTextBoxFileTextChanged(object sender, EventArgs e)
{
UpdateButtons();
}
/// <summary>
/// Called when the Create button is clicked.
/// </summary>
private void OnCreateClick()
{
EventHandler temp = CreateClick;
if (temp != null)
{
temp(this, new EventArgs());
}
}
/// <summary>
/// Called when the Edit button is clicked.
/// </summary>
private void OnEditClick()
{
EventHandler temp = EditClick;
if (temp != null)
{
temp(this, new EventArgs());
}
}
/// <summary>
/// Updates the button state when the selected file changes.
/// </summary>
private void UpdateButtons()
{
string filename = _textBoxFile.Text.Trim();
bool fileEntered = filename.Length > 0;
_buttonEdit.Enabled = fileEntered;
_buttonCreate.Enabled = fileEntered;
bool fileExists = fileEntered && File.Exists(filename);
_buttonCreate.Visible = !fileExists;
_buttonEdit.Visible = fileExists;
if (MonoUtilities.IsMonoRuntime)
{
// Not sure why in Mono, but the edit button shifts when it becomes
// visible. Let's just reallign it to the position of the hidden
// create button.
_buttonEdit.Location = _buttonCreate.Location;
}
}
#endregion Methods
}
} | adgistics/Adgistics.Build | NArrange/src/NArrange.Gui/Configuration/ConfigurationPicker.cs | C# | apache-2.0 | 6,800 |
/*
* Copyright 2022 ThoughtWorks, 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.
*/
import {ErrorsJSON} from "models/mixins/errors";
import {AutoSuggestionJSON} from "models/roles/auto_suggestion";
import {RuleJSON} from "models/rules/rules";
import {PropertyJSON} from "models/shared/configuration";
interface EmbeddedJSON {
secret_configs: SecretConfigJSON[];
}
export interface SecretConfigsJSON {
_embedded: EmbeddedJSON;
}
export interface SecretConfigJSON {
id: string;
description: string;
plugin_id: string;
properties: PropertyJSON[];
rules: RuleJSON[];
errors?: ErrorsJSON;
}
export interface SecretConfigsWithSuggestionsJSON extends SecretConfigsJSON {
auto_completion: AutoSuggestionJSON[];
}
| gocd/gocd | server/src/main/webapp/WEB-INF/rails/webpack/models/secret_configs/secret_configs_json.ts | TypeScript | apache-2.0 | 1,246 |
#!/usr/bin/env python
import logging
import sys
import os
import signal
import conf
import core
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol.TBinaryProtocol import TBinaryProtocolAcceleratedFactory
from thrift.server import TServer
from rpc import RndNodeApi
logger = logging.getLogger(__name__)
class RndProcessHandler(object):
def runTask(self, rtc):
logger.debug("starting core.ProcessMgr.runProcess(rtc): %s", rtc.taskId)
core.ProcessMgr.runProcess(rtc)
logger.debug("finished core.ProcessMgr.runProcess(rtc): %s", rtc.taskId)
def killRunningTask(self, procId, reason):
core.ProcessMgr.killRunningTask(procId, reason)
def getRunningTasks(self):
logger.debug("starting core.ProcessMgr.getRunningTasks()")
tasks = core.ProcessMgr.getRunningTasks()
logger.debug("finished core.ProcessMgr.getRunningTasks()")
return tasks
def reboot(self, now=False):
core.ProcessMgr.reboot(now)
def pingPong(self, withTasks=False):
ping = core.Profiler.getPing()
ping.isReboot = core.ProcessMgr.isReboot
if withTasks:
ping.tasks = self.getRunningTasks()
return ping
def get_server(api, handler, port, **kwargs):
processor = api.Processor(handler)
socket = TSocket.TServerSocket(port=port)
tfactory = kwargs.get('transport') or TTransport.TFramedTransportFactory()
pfactory = kwargs.get('protocol') or TBinaryProtocolAcceleratedFactory()
server = TServer.TThreadPoolServer(processor, socket, tfactory, pfactory)
server.setNumThreads(8)
return server
def exit_handler(*args):
logger.info("Caught SIGTERM. Shutting down Process Manager...")
core.ProcessMgr.shutdown()
logger.info("Process Manager finished shutting down")
os._exit(0)
signal.signal(signal.SIGTERM, exit_handler)
def start():
logger.info("Staring Render Node Daemon on TCP port %d" % conf.NETWORK_PORT)
server = get_server(RndNodeApi, RndProcessHandler(), conf.NETWORK_PORT)
try:
server.serve()
except KeyboardInterrupt:
exit_handler()
sys.exit(0)
| chadmv/plow | lib/python/plow/rndaemon/server.py | Python | apache-2.0 | 2,191 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef imgStatusTracker_h__
#define imgStatusTracker_h__
class imgIContainer;
class imgRequest;
class imgRequestProxy;
class imgStatusNotifyRunnable;
class imgRequestNotifyRunnable;
struct nsIntRect;
namespace mozilla {
namespace image {
class Image;
} // namespace image
} // namespace mozilla
#include "nsCOMPtr.h"
#include "nsIRunnable.h"
#include "nscore.h"
enum {
stateRequestStarted = PR_BIT(0),
stateHasSize = PR_BIT(1),
stateDecodeStarted = PR_BIT(2),
stateDecodeStopped = PR_BIT(3),
stateFrameStopped = PR_BIT(4),
stateRequestStopped = PR_BIT(5),
stateBlockingOnload = PR_BIT(6)
};
/*
* The image status tracker is a class that encapsulates all the loading and
* decoding status about an Image, and makes it possible to send notifications
* to imgRequestProxys, both synchronously (i.e., the status now) and
* asynchronously (the status later).
*
* When a new proxy needs to be notified of the current state of an image, call
* the Notify() method on this class with the relevant proxy as its argument,
* and the notifications will be replayed to the proxy asynchronously.
*/
class imgStatusTracker
{
public:
// aImage is the image that this status tracker will pass to the
// imgRequestProxys in SyncNotify() and EmulateRequestFinished(), and must be
// alive as long as this instance is, because we hold a weak reference to it.
imgStatusTracker(mozilla::image::Image* aImage);
imgStatusTracker(const imgStatusTracker& aOther);
// Image-setter, for imgStatusTrackers created by imgRequest::Init, which
// are created before their Image is created. This method should only
// be called once, and only on an imgStatusTracker that was initialized
// without an image.
void SetImage(mozilla::image::Image* aImage);
// Schedule an asynchronous "replaying" of all the notifications that would
// have to happen to put us in the current state.
// We will also take note of any notifications that happen between the time
// Notify() is called and when we call SyncNotify on |proxy|, and replay them
// as well.
void Notify(imgRequest* request, imgRequestProxy* proxy);
// Schedule an asynchronous "replaying" of all the notifications that would
// have to happen to put us in the state we are in right now.
// Unlike Notify(), does *not* take into account future notifications.
// This is only useful if you do not have an imgRequest, e.g., if you are a
// static request returned from imgIRequest::GetStaticRequest().
void NotifyCurrentState(imgRequestProxy* proxy);
// "Replay" all of the notifications that would have to happen to put us in
// the state we're currently in.
// Only use this if you're already servicing an asynchronous call (e.g.
// OnStartRequest).
void SyncNotify(imgRequestProxy* proxy);
// Send all notifications that would be necessary to make |proxy| believe the
// request is finished downloading and decoding.
// If aOnlySendStopRequest is true, we will only send OnStopRequest, and then
// only if that is necessary.
void EmulateRequestFinished(imgRequestProxy* proxy, nsresult aStatus,
bool aOnlySendStopRequest);
// Returns whether we are in the process of loading; that is, whether we have
// not received OnStopRequest.
bool IsLoading() const;
// Get the current image status (as in imgIRequest).
uint32_t GetImageStatus() const;
// Following are all the notification methods. You must call the Record
// variant on this status tracker, then call the Send variant for each proxy
// you want to notify.
// Call when the request is being cancelled.
void RecordCancel();
// Shorthand for recording all the load notifications: StartRequest,
// StartContainer, StopRequest.
void RecordLoaded();
// Shorthand for recording all the decode notifications: StartDecode,
// StartFrame, DataAvailable, StopFrame, StopContainer, StopDecode.
void RecordDecoded();
/* non-virtual imgIDecoderObserver methods */
void RecordStartDecode();
void SendStartDecode(imgRequestProxy* aProxy);
void RecordStartContainer(imgIContainer* aContainer);
void SendStartContainer(imgRequestProxy* aProxy, imgIContainer* aContainer);
void RecordStartFrame(uint32_t aFrame);
void SendStartFrame(imgRequestProxy* aProxy, uint32_t aFrame);
void RecordDataAvailable(bool aCurrentFrame, const nsIntRect* aRect);
void SendDataAvailable(imgRequestProxy* aProxy, bool aCurrentFrame, const nsIntRect* aRect);
void RecordStopFrame(uint32_t aFrame);
void SendStopFrame(imgRequestProxy* aProxy, uint32_t aFrame);
void RecordStopContainer(imgIContainer* aContainer);
void SendStopContainer(imgRequestProxy* aProxy, imgIContainer* aContainer);
void RecordStopDecode(nsresult status, const PRUnichar* statusArg);
void SendStopDecode(imgRequestProxy* aProxy, nsresult aStatus, const PRUnichar* statusArg);
void RecordDiscard();
void SendDiscard(imgRequestProxy* aProxy);
void RecordImageIsAnimated();
void SendImageIsAnimated(imgRequestProxy *aProxy);
/* non-virtual imgIContainerObserver methods */
void RecordFrameChanged(imgIContainer* aContainer,
const nsIntRect* aDirtyRect);
void SendFrameChanged(imgRequestProxy* aProxy, imgIContainer* aContainer,
const nsIntRect* aDirtyRect);
/* non-virtual sort-of-nsIRequestObserver methods */
void RecordStartRequest();
void SendStartRequest(imgRequestProxy* aProxy);
void RecordStopRequest(bool aLastPart, nsresult aStatus);
void SendStopRequest(imgRequestProxy* aProxy, bool aLastPart, nsresult aStatus);
/* non-virtual imgIOnloadBlocker methods */
// NB: If UnblockOnload is sent, and then we are asked to replay the
// notifications, we will not send a BlockOnload/UnblockOnload pair. This
// is different from all the other notifications.
void RecordBlockOnload();
void SendBlockOnload(imgRequestProxy* aProxy);
void RecordUnblockOnload();
void SendUnblockOnload(imgRequestProxy* aProxy);
private:
friend class imgStatusNotifyRunnable;
friend class imgRequestNotifyRunnable;
nsCOMPtr<nsIRunnable> mRequestRunnable;
// A weak pointer to the Image, because it owns us, and we
// can't create a cycle.
mozilla::image::Image* mImage;
uint32_t mState;
uint32_t mImageStatus;
bool mHadLastPart;
};
#endif
| wilebeast/FireFox-OS | B2G/gecko/image/src/imgStatusTracker.h | C | apache-2.0 | 6,666 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.BinaryAuthorization.V1.Snippets
{
// [START binaryauthorization_v1_generated_BinauthzManagementServiceV1_UpdateAttestor_sync_flattened]
using Google.Cloud.BinaryAuthorization.V1;
public sealed partial class GeneratedBinauthzManagementServiceV1ClientSnippets
{
/// <summary>Snippet for UpdateAttestor</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void UpdateAttestor()
{
// Create client
BinauthzManagementServiceV1Client binauthzManagementServiceV1Client = BinauthzManagementServiceV1Client.Create();
// Initialize request argument(s)
Attestor attestor = new Attestor();
// Make the request
Attestor response = binauthzManagementServiceV1Client.UpdateAttestor(attestor);
}
}
// [END binaryauthorization_v1_generated_BinauthzManagementServiceV1_UpdateAttestor_sync_flattened]
}
| googleapis/google-cloud-dotnet | apis/Google.Cloud.BinaryAuthorization.V1/Google.Cloud.BinaryAuthorization.V1.GeneratedSnippets/BinauthzManagementServiceV1Client.UpdateAttestorSnippet.g.cs | C# | apache-2.0 | 1,727 |
<!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_45) on Fri Sep 05 23:33:05 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.io.VIntWritable (Apache Hadoop Main 2.5.1 API)
</TITLE>
<META NAME="date" CONTENT="2014-09-05">
<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 org.apache.hadoop.io.VIntWritable (Apache Hadoop Main 2.5.1 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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/io/VIntWritable.html" title="class in org.apache.hadoop.io"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/io//class-useVIntWritable.html" target="_top"><B>FRAMES</B></A>
<A HREF="VIntWritable.html" target="_top"><B>NO FRAMES</B></A>
<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>org.apache.hadoop.io.VIntWritable</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="../../../../../org/apache/hadoop/io/VIntWritable.html" title="class in org.apache.hadoop.io">VIntWritable</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.io"><B>org.apache.hadoop.io</B></A></TD>
<TD>Generic i/o code for use when reading and writing data to the network,
to databases, and to files. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.io"><!-- --></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="../../../../../org/apache/hadoop/io/VIntWritable.html" title="class in org.apache.hadoop.io">VIntWritable</A> in <A HREF="../../../../../org/apache/hadoop/io/package-summary.html">org.apache.hadoop.io</A></FONT></TH>
</TR>
</TABLE>
<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="../../../../../org/apache/hadoop/io/package-summary.html">org.apache.hadoop.io</A> with parameters of type <A HREF="../../../../../org/apache/hadoop/io/VIntWritable.html" title="class in org.apache.hadoop.io">VIntWritable</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B>VIntWritable.</B><B><A HREF="../../../../../org/apache/hadoop/io/VIntWritable.html#compareTo(org.apache.hadoop.io.VIntWritable)">compareTo</A></B>(<A HREF="../../../../../org/apache/hadoop/io/VIntWritable.html" title="class in org.apache.hadoop.io">VIntWritable</A> o)</CODE>
<BR>
Compares two VIntWritables.</TD>
</TR>
</TABLE>
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/io/VIntWritable.html" title="class in org.apache.hadoop.io"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/apache/hadoop/io//class-useVIntWritable.html" target="_top"><B>FRAMES</B></A>
<A HREF="VIntWritable.html" target="_top"><B>NO FRAMES</B></A>
<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 © 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| jimmypw/hadoop | share/doc/hadoop/api/org/apache/hadoop/io/class-use/VIntWritable.html | HTML | apache-2.0 | 8,073 |
/*
* Copyright 2014 Red Hat, Inc.
*
* 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 io.vertx.ext.web.templ;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.file.FileSystemOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.ext.web.common.template.TemplateEngine;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import io.vertx.ext.web.templ.pebble.PebbleTemplateEngine;
import org.junit.runner.RunWith;
/**
* @author Dan Kristensen
*/
@RunWith(VertxUnitRunner.class)
public class PebbleTemplateNoCacheTest {
private static Vertx vertx;
@BeforeClass
public static void before() {
vertx = Vertx.vertx(new VertxOptions().setFileSystemOptions(new FileSystemOptions().setFileCachingEnabled(false)));
}
@Test
public void testCachingDisabled(TestContext should) throws IOException {
System.setProperty("vertxweb.environment", "development");
TemplateEngine engine = PebbleTemplateEngine.create(vertx);
File temp = File.createTempFile("template", ".peb", new File("target/classes"));
temp.deleteOnExit();
try (PrintWriter out = new PrintWriter(temp)) {
out.print("before");
out.flush();
}
engine.render(new JsonObject(), temp.getParent() + "/" + temp.getName(), should.asyncAssertSuccess(render -> {
should.assertEquals("before", PebbleTemplateTest.normalizeCRLF(render.toString()));
// cache is enabled so if we change the content that should not affect the result
try (PrintWriter out2 = new PrintWriter(temp)) {
out2.print("after");
out2.flush();
} catch (IOException e) {
should.fail(e);
}
engine.render(new JsonObject(), temp.getParent() + "/" + temp.getName(), should.asyncAssertSuccess(render2 -> {
should.assertEquals("after", PebbleTemplateTest.normalizeCRLF(render2.toString()));
}));
}));
}
}
| vert-x3/vertx-web | vertx-template-engines/vertx-web-templ-pebble/src/test/java/io/vertx/ext/web/templ/PebbleTemplateNoCacheTest.java | Java | apache-2.0 | 2,511 |
/*
* Copyright 2021 ThoughtWorks, 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.
*/
function spinny(element) {
$(element).update(' ');
$(element).addClassName('spinny');
}
function removeSpinny(element) {
$(element).removeClassName('spinny');
}
function showElement(ele,show){
if(show) ele.show();
else ele.hide();
}
function goToUrl(url) {
window.location = window.location.protocol + '//' + window.location.host + url;
}
function redirectToLoginPage(url) {
goToUrl(url);
}
| marques-work/gocd | server/src/main/webapp/WEB-INF/rails/app/assets/javascripts/helpers.js | JavaScript | apache-2.0 | 1,029 |
package org.insightech.er.common.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.insightech.er.ResourceString;
import org.insightech.er.Resources;
import org.insightech.er.common.exception.InputException;
public abstract class ValidatableTabWrapper extends Composite {
protected TabItem tabItem;
protected AbstractTabbedDialog dialog;
public ValidatableTabWrapper(AbstractTabbedDialog dialog, TabFolder parent,
String title) {
super(parent, SWT.NONE);
this.dialog = dialog;
this.tabItem = new TabItem(parent, SWT.NONE);
this.tabItem.setText(ResourceString.getResourceString(title));
this.tabItem.setControl(this);
}
abstract public void validatePage() throws InputException;
protected final void init() {
GridLayout layout = new GridLayout();
this.initLayout(layout);
this.setLayout(layout);
this.initComposite();
this.addListener();
this.setData();
}
protected void initLayout(GridLayout layout) {
layout.marginTop = Resources.MARGIN_TAB;
layout.marginLeft = Resources.MARGIN_TAB;
layout.marginRight = Resources.MARGIN_TAB;
layout.marginBottom = Resources.MARGIN_TAB;
}
public void reset() {
}
public void restruct() {
}
abstract protected void initComposite();
protected void addListener() {
}
protected void setData() {
}
abstract public void perfomeOK();
abstract public void setInitFocus();
}
| kozake/ermaster-k | org.insightech.er/src/org/insightech/er/common/dialog/ValidatableTabWrapper.java | Java | apache-2.0 | 1,603 |
// <copyright file="RemoteTargetLocator.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Text.RegularExpressions;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a mechanism for finding elements on the page with locators.
/// </summary>
internal class RemoteTargetLocator : ITargetLocator
{
private RemoteWebDriver driver;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteTargetLocator"/> class
/// </summary>
/// <param name="driver">The driver that is currently in use</param>
public RemoteTargetLocator(RemoteWebDriver driver)
{
this.driver = driver;
}
/// <summary>
/// Move to a different frame using its index
/// </summary>
/// <param name="frameIndex">The index of the </param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(int frameIndex)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", frameIndex);
this.driver.InternalExecute(DriverCommand.SwitchToFrame, parameters);
return this.driver;
}
/// <summary>
/// Move to different frame using its name
/// </summary>
/// <param name="frameName">name of the frame</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Frame(string frameName)
{
if (frameName == null)
{
throw new ArgumentNullException("frameName", "Frame name cannot be null");
}
// Dictionary<string, object> parameters = new Dictionary<string, object>();
// parameters.Add("id", frameName);
// this.driver.InternalExecute(DriverCommand.SwitchToFrame, parameters);
// return this.driver;
string name = Regex.Replace(frameName, @"(['""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", @"\$1");
ReadOnlyCollection<IWebElement> frameElements = this.driver.FindElements(By.CssSelector("frame[name='" + name + "'],iframe[name='" + name + "']"));
if (frameElements.Count == 0)
{
frameElements = this.driver.FindElements(By.CssSelector("frame#" + name + ",iframe#" + name));
if (frameElements.Count == 0)
{
throw new NoSuchFrameException("No frame element found with name or id " + frameName);
}
}
return this.Frame(frameElements[0]);
}
/// <summary>
/// Move to a frame element.
/// </summary>
/// <param name="frameElement">a previously found FRAME or IFRAME element.</param>
/// <returns>A WebDriver instance that is currently in use.</returns>
public IWebDriver Frame(IWebElement frameElement)
{
if (frameElement == null)
{
throw new ArgumentNullException("frameElement", "Frame element cannot be null");
}
RemoteWebElement convertedElement = frameElement as RemoteWebElement;
if (convertedElement == null)
{
throw new ArgumentException("frameElement cannot be converted to RemoteWebElement", "frameElement");
}
Dictionary<string, object> elementDictionary = new Dictionary<string, object>();
elementDictionary.Add("ELEMENT", convertedElement.InternalElementId);
elementDictionary.Add("element-6066-11e4-a52e-4f735466cecf", convertedElement.InternalElementId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", elementDictionary);
this.driver.InternalExecute(DriverCommand.SwitchToFrame, parameters);
return this.driver;
}
/// <summary>
/// Select the parent frame of the currently selected frame.
/// </summary>
/// <returns>An <see cref="IWebDriver"/> instance focused on the specified frame.</returns>
public IWebDriver ParentFrame()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
this.driver.InternalExecute(DriverCommand.SwitchToParentFrame, parameters);
return this.driver;
}
/// <summary>
/// Change to the Window by passing in the name
/// </summary>
/// <param name="windowHandleOrName">Window handle or name of the window that you wish to move to</param>
/// <returns>A WebDriver instance that is currently in use</returns>
public IWebDriver Window(string windowHandleOrName)
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
if (this.driver.IsSpecificationCompliant)
{
parameters.Add("handle", windowHandleOrName);
try
{
this.driver.InternalExecute(DriverCommand.SwitchToWindow, parameters);
return this.driver;
}
catch (NoSuchWindowException)
{
// simulate search by name
string original = this.driver.CurrentWindowHandle;
foreach (string handle in this.driver.WindowHandles)
{
this.Window(handle);
if (windowHandleOrName == this.driver.ExecuteScript("return window.name").ToString())
{
return this.driver; // found by name
}
}
this.Window(original);
throw;
}
}
else
{
parameters.Add("name", windowHandleOrName);
}
this.driver.InternalExecute(DriverCommand.SwitchToWindow, parameters);
return this.driver;
}
/// <summary>
/// Change the active frame to the default
/// </summary>
/// <returns>Element of the default</returns>
public IWebDriver DefaultContent()
{
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("id", null);
this.driver.InternalExecute(DriverCommand.SwitchToFrame, parameters);
return this.driver;
}
/// <summary>
/// Finds the active element on the page and returns it
/// </summary>
/// <returns>Element that is active</returns>
public IWebElement ActiveElement()
{
Response response = this.driver.InternalExecute(DriverCommand.GetActiveElement, null);
return this.driver.GetElementFromResponse(response);
}
/// <summary>
/// Switches to the currently active modal dialog for this particular driver instance.
/// </summary>
/// <returns>A handle to the dialog.</returns>
public IAlert Alert()
{
// N.B. We only execute the GetAlertText command to be able to throw
// a NoAlertPresentException if there is no alert found.
this.driver.InternalExecute(DriverCommand.GetAlertText, null);
return new RemoteAlert(this.driver);
}
}
}
| actmd/selenium | dotnet/src/webdriver/Remote/RemoteTargetLocator.cs | C# | apache-2.0 | 8,398 |
package ru.aserdyuchenko.start;
/*
Исключения делятся на три типа: контролируемые исключения (checked) и
неконтролируемые исключения (unchecked), к которым относятся ошибки (Errors) и
исключения времени выполнения (RuntimeExceptions, потомок класса Exception).
*/
/**
* Exemple exeption.
* @author Anton Serdyuchenko (anton415@gmail.com)
* @version $Id$
* @since 28.11.2016
*/
public class SecondQuestion {
/**
* Method for example Exception.
* @param first - first number.
* @param second - second number.
*/
public void exceptionExample(int first, int second) {
try {
/**
* @param result - the result of the division.
*/
int result = first / second;
} catch (ArithmeticException example) {
System.out.print("The arithmetic operation error.");
}
}
}
| anton415/Job4j | Intern/Part_2_OOP_Control_questions/src/main/java/ru/aserdyuchenko/start/SecondQuestion.java | Java | apache-2.0 | 935 |
/*
* 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.shardingsphere.shardingproxy.frontend.mysql.command.admin.quit;
import org.apache.shardingsphere.database.protocol.mysql.packet.generic.MySQLOKPacket;
import org.apache.shardingsphere.database.protocol.packet.DatabasePacket;
import org.apache.shardingsphere.shardingproxy.frontend.api.CommandExecutor;
import java.util.Collection;
import java.util.Collections;
/**
* COM_QUIT executor for MySQL.
*/
public final class MySQLComQuitExecutor implements CommandExecutor {
@Override
public Collection<DatabasePacket> execute() {
return Collections.singletonList(new MySQLOKPacket(1));
}
}
| leeyazhou/sharding-jdbc | sharding-proxy/sharding-proxy-frontend/sharding-proxy-frontend-mysql/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/mysql/command/admin/quit/MySQLComQuitExecutor.java | Java | apache-2.0 | 1,436 |
define({
root: ({
}),
es: true,
it: true,
ru: true,
tr: true,
"zh-cn": true
}); | Esri/workflowmanager-viewer-js | js/widget/charting/StackedBarChart/nls/Strings.js | JavaScript | apache-2.0 | 121 |
/**
* 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.hcatalog.templeton;
import javax.xml.bind.annotation.XmlRootElement;
/**
* A description of the partition to create.
*/
@XmlRootElement
public class PartitionDesc extends GroupPermissionsDesc {
public String partition;
public String location;
public boolean ifNotExists = false;
public PartitionDesc() {}
public String toString() {
return String.format("PartitionDesc(partition=%s, location=%s, ifNotExists=%s)",
partition, location, ifNotExists);
}
}
| cloudera/hcatalog | webhcat/svr/src/main/java/org/apache/hcatalog/templeton/PartitionDesc.java | Java | apache-2.0 | 1,349 |
package test.thread.parallelization;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.CLASS_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.METHOD_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.EventInfo.SUITE_NAME;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_SUITE_FINISH;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_SUITE_START;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_FINISH;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_PASS;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_METHOD_START;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.LISTENER_TEST_START;
import static test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent.TEST_METHOD_EXECUTION;
import static test.thread.parallelization.TestNgRunStateTracker.getTestMethodEventLogsForMethod;
import com.google.common.collect.Multimap;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.testng.annotations.Test;
import org.testng.internal.collections.Pair;
import org.testng.log4testng.Logger;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import test.SimpleBaseTest;
import test.thread.parallelization.TestNgRunStateTracker.EventLog;
import test.thread.parallelization.TestNgRunStateTracker.TestNgRunEvent;
public class BaseParallelizationTest extends SimpleBaseTest {
private static final Logger log = Logger.getLogger(BaseParallelizationTest.class);
// Get a list of the names of declared methods with the @Test annotation from the specified class
public static List<String> getDeclaredTestMethods(Class<?> clazz) {
List<String> methodNames = new ArrayList<>();
for (Method method : clazz.getMethods()) {
List<Annotation> declaredAnnotations = Arrays.asList(method.getDeclaredAnnotations());
for (Annotation a : declaredAnnotations) {
if (a.annotationType().isAssignableFrom(org.testng.annotations.Test.class)) {
methodNames.add(method.getName());
}
}
}
return methodNames;
}
// Send the name of the suite and the name of the test as parameters so that the methods can
// associate their
// execution event logs with them. Specified the delay in seconds to apply for the method
// execution. This delay
// helps in determining the parallelism or lack thereof for method executions.
public static void addParams(XmlSuite suite, String suiteName, String testName, String sleepFor) {
Map<String, String> parameters = new HashMap<>();
parameters.put("suiteName", suiteName);
parameters.put("testName", testName);
parameters.put("sleepFor", sleepFor);
for (XmlTest test : suite.getTests()) {
if (test.getName().equals(testName)) {
test.setParameters(parameters);
}
}
}
public static void addParams(
XmlSuite suite,
String suiteName,
String testName,
String sleepFor,
String dataProviderParam) {
Map<String, String> parameters = new HashMap<>();
parameters.put("suiteName", suiteName);
parameters.put("testName", testName);
parameters.put("sleepFor", sleepFor);
parameters.put("dataProviderParam", dataProviderParam);
for (XmlTest test : suite.getTests()) {
if (test.getName().equals(testName)) {
test.setParameters(parameters);
}
}
}
// Verify that the list of event logs have the specified event type. Print the specified failure
// message if the
// assertion on the event type fails.
public static void verifyEventTypeForEventsLogs(
List<EventLog> eventLogs, TestNgRunEvent event, String failMessage) {
for (EventLog eventLog : eventLogs) {
assertTrue(eventLog.getEvent() == event, failMessage);
}
}
// Verify that the list of event logs all have different thread IDS. Print the specified failure
// message if the
// assertion on the thread IDs fails.
public static void verifyDifferentThreadIdsForEvents(
List<EventLog> eventLogs, String failMessage) {
List<Long> threadIds = new ArrayList<>();
for (EventLog eventLog : eventLogs) {
assertFalse(threadIds.contains(eventLog.getThreadId()), failMessage);
threadIds.add(eventLog.getThreadId());
}
}
// Verify that the event logs in the first list all have different thread IDs from the event logs
// in the second
// list. Print the specified failure message if the assertion on the thread IDs fails.
public static void verifyDifferentThreadIdsForEvents(
List<EventLog> eventLogsOne, List<EventLog> eventLogsTwo, String failMessage) {
List<Long> threadIds = new ArrayList<>();
for (EventLog eventLog : eventLogsOne) {
threadIds.add(eventLog.getThreadId());
}
for (EventLog eventLog : eventLogsTwo) {
assertFalse(threadIds.contains(eventLog.getThreadId()), failMessage);
}
}
// Verify that the list of event logs all have the same thread ID. Print the specified failure
// message if the
// assertion on the event type fails.
public static void verifySameThreadIdForAllEvents(List<EventLog> eventLogs, String failMessage) {
long threadId = -1;
for (EventLog eventLog : eventLogs) {
if (threadId == -1) {
threadId = eventLog.getThreadId();
} else {
assertEquals(eventLog.getThreadId(), threadId, failMessage);
}
}
}
// Verify that the threads from the specified list of event logs are all greater than the
// specified thread ID. Print
// the specified failure message if the assertion on the thread IDs fails.
public static void verifyEventThreadsSpawnedAfter(
Long earlierThreadId, List<EventLog> eventsFromLaterThread, String failMessage) {
for (EventLog eventLog : eventsFromLaterThread) {
assertTrue(eventLog.getThreadId() > earlierThreadId, failMessage);
}
}
// //Verify that the timestamps of the list of event logs are all within the specified range of
// each other. Print
// //the specified failure message if the assertion on the timing range fails.
// public static void verifyTimingOfEvents(List<EventLog> eventLogs, long timingRange, String
// failMessage) {
// if(!eventLogs.isEmpty()) {
// Pair<Long,Long> timestamps = getEarliestAndLatestTimestamps(eventLogs);
// verifyTimestampDifference(timestamps.second(), timestamps.first(), timingRange,
// failMessage);
// }
// }
// public static void verifyTimingOfEvents(EventLog eventLogOne, EventLog eventLogTwo, long
// timingRange, String
// failMessage) {
// verifyTimestampDifference(eventLogOne.getTimeOfEvent(), eventLogTwo.getTimeOfEvent(),
// timingRange, failMessage);
// }
//
// //Verify that the timestamps of the first list of events are all within the specified range
// from the timestamps
// //of the second list of events. Print the specified failure message if the assertion on the
// timing range fails.
// public static void verifyTimingOfEvents(List<EventLog> firstEventLogs, List<EventLog>
// secondEventLogs,
// long lowerTimingRange, long upperTimingRange, String failMessage) {
//
// if(!firstEventLogs.isEmpty() && !secondEventLogs.isEmpty()) {
// Pair<Long, Long> timestampsListOne = getEarliestAndLatestTimestamps(firstEventLogs);
// Pair<Long, Long> timestampsListTwo =
// getEarliestAndLatestTimestamps(secondEventLogs);
//
// verifyTimestampDifference(timestampsListTwo.first(), timestampsListOne.first(),
// lowerTimingRange,
// upperTimingRange, failMessage);
// verifyTimestampDifference(timestampsListTwo.first(), timestampsListOne.second(),
// lowerTimingRange,
// upperTimingRange, failMessage);
// verifyTimestampDifference(timestampsListTwo.second(), timestampsListOne.first(),
// lowerTimingRange,
// upperTimingRange, failMessage);
// verifyTimestampDifference(timestampsListTwo.second(), timestampsListOne.second(),
// lowerTimingRange,
// upperTimingRange, failMessage);
// }
// }
// //Verify that the difference between the two specified timestamps is within the specfied
// upper and lower bound. The
// //difference is calculated as an absolute value.
// public static void verifyTimestampDifference(long timestampOne, long timestampTwo, long
// lowerTimingRange,
// long upperTimingRange, String failMessage) {
// assertTrue(Math.abs(timestampOne - timestampTwo) <= upperTimingRange &&
// Math.abs(timestampOne - timestampTwo) >= lowerTimingRange, failMessage + ".
// Difference: " +
// Math.abs(timestampOne - timestampTwo));
// }
//
// public static void verifyTimestampDifference(long timestampOne, long timestampTwo, long
// timingRange, String
// failMessage) {
// assertTrue(Math.abs(timestampOne - timestampTwo) <= timingRange, failMessage + ".
// Difference: " +
// Math.abs(timestampOne - timestampTwo));
// }
// Verify that the specified event logs all have timestamps between the specified earlier and
// later event logs.
// Print the specified failure message if the assertion on the timestamps fails.
public static void verifyEventsOccurBetween(
EventLog earlierEventLog,
List<EventLog> inBetweenEventLogs,
EventLog laterEventLog,
String failMessage) {
for (EventLog eventLog : inBetweenEventLogs) {
assertTrue(
eventLog.getTimeOfEvent() >= earlierEventLog.getTimeOfEvent()
&& eventLog.getTimeOfEvent() <= laterEventLog.getTimeOfEvent(),
failMessage);
}
}
// Verify that the timestamps for the events if the specified list are all increasing. That each
// the timestamps of
// a given event logger is later than the event logger immediately preceding it. Print the
// specified failure message if
// the assertion on the timestamps fails
public static void verifySequentialTimingOfEvents(List<EventLog> eventLogs, String failMessage) {
for (int i = 0; i + 1 < eventLogs.size(); i++) {
assertTrue(
eventLogs.get(i).getTimeOfEvent() < eventLogs.get(i + 1).getTimeOfEvent(), failMessage);
}
}
// Verify that the first list of event logs all have timestamps earlier than all the events in the
// second list of
// event logs. Print the specified failure message if the assertion on the timestamps fails.
public static void verifySequentialTimingOfEvents(
List<EventLog> firstEventLogs, List<EventLog> secondEventLogs, String failMessage) {
if (!firstEventLogs.isEmpty() && !secondEventLogs.isEmpty()) {
Pair<Long, Long> timestampsListOne = getEarliestAndLatestTimestamps(firstEventLogs);
Pair<Long, Long> timestampsListTwo = getEarliestAndLatestTimestamps(secondEventLogs);
assertTrue(timestampsListTwo.first() > timestampsListOne.second(), failMessage);
}
}
// Verify that the test methods declared in the specified list of classes have the specified
// number of class
// instances associated with them for the specified suite and test.
public static void verifyNumberOfInstancesOfTestClassesForMethods(
String suiteName, String testName, List<Class<?>> classes, int numInstances) {
for (Class<?> clazz : classes) {
verifyNumberOfInstancesOfTestClassForMethods(suiteName, testName, clazz, numInstances);
}
}
// Verify that the test methods declared in the specified list of classes have the specified
// number of class
// instances associated with them for the specified suite and test.
public static void verifyNumberOfInstancesOfTestClassesForMethods(
String suiteName, String testName, List<Class<?>> classes, int... numInstances) {
for (int i = 0; i < numInstances.length; i++) {
verifyNumberOfInstancesOfTestClassForMethods(
suiteName, testName, classes.get(i), numInstances[i]);
}
}
// Verify that the test methods declared in the specified class have the specified number of class
// instances
// associated with them for the specified suite and test.
public static void verifyNumberOfInstancesOfTestClassForMethods(
String suiteName, String testName, Class<?> clazz, int numInstances) {
for (String methodName : getDeclaredTestMethods(clazz)) {
verifyNumberOfInstancesOfTestClassForMethod(
suiteName, testName, clazz, methodName, numInstances);
}
}
// Verify that the specified test method has the specified number of class instances associated
// with it for the
// specified suite and test.
public static void verifyNumberOfInstancesOfTestClassForMethod(
String suiteName, String testName, Class<?> clazz, String methodName, int numInstances) {
Multimap<Object, EventLog> eventLogMap =
getTestMethodEventLogsForMethod(suiteName, testName, clazz.getCanonicalName(), methodName);
assertEquals(
eventLogMap.keySet().size(),
numInstances,
"There should be "
+ numInstances
+ " instances "
+ "associated with the class "
+ clazz.getCanonicalName()
+ " for method "
+ methodName
+ " in the "
+ "test "
+ testName
+ " in the suite "
+ suiteName
+ ": "
+ eventLogMap);
}
// Verify that all the test methods declared in the specified list of classes have the same
// instances of the classes
// associated with them for the specified suite and test.
public static void verifySameInstancesOfTestClassesAssociatedWithMethods(
String suiteName, String testName, List<Class<?>> classes) {
for (Class<?> clazz : classes) {
verifySameInstancesOfTestClassAssociatedWithMethods(suiteName, testName, clazz);
}
}
// Verify that all the test methods declared in the specified class have the same instances of the
// class associated /
// with them for the specified suite and test.
public static void verifySameInstancesOfTestClassAssociatedWithMethods(
String suiteName, String testName, Class<?> clazz) {
Set<Object> instanceKeys = null;
for (String methodName : getDeclaredTestMethods(clazz)) {
Multimap<Object, EventLog> eventLogMap =
getTestMethodEventLogsForMethod(
suiteName, testName, clazz.getCanonicalName(), methodName);
if (instanceKeys == null) {
instanceKeys = eventLogMap.keySet();
} else {
assertTrue(
instanceKeys.containsAll(eventLogMap.keySet())
&& eventLogMap.keySet().containsAll(instanceKeys),
"The same instances of "
+ clazz.getCanonicalName()
+ " should be associated with its methods for the test "
+ testName
+ " in the suite "
+ suiteName);
}
}
}
// Verify that methods associated with the specified event logs execute simultaneously in parallel
// fashion, in
// accordance with the thread count. This verification is for blocks of parallel methods, none of
// which use
// data providers. This verification is for blocks of parallel methods that have the same sleep
// delays for their
// execution bodies and which do not have any BeforeMethod AfterMethod, BeforeGroup or AfterGroup
// configuration methods.
public static void verifySimultaneousTestMethods(
List<EventLog> testMethodEventLogs, String testName, int threadCount) {
if (log.isDebugEnabled()) {
log.debug(
"Verifying parallel execution of test methods for test named "
+ testName
+ " with "
+ "thread count "
+ threadCount);
log.debug(
testMethodEventLogs.size()
+ " test method event logs for "
+ testMethodEventLogs.size() / 3
+ " test methods");
}
// Keep track of the methods that have started, but not completed execution.
Map<ClassInstanceMethodKey, EventLog> methodsExecuting = new HashMap<>();
// Keep track of the methods whose start, execute and test method pass events have all been
// found in the list
// of logs
Map<ClassInstanceMethodKey, EventLog> methodsCompleted = new HashMap<>();
// Keep track of the thread IDs for all the methods that are executing and check that all a
// method's events
// run in the same thread.
List<Long> executingMethodThreadIds = new ArrayList<>();
// Make a list of the all the thread IDs of the first batch of start method events and check
// that no other
// thread IDs are found in the rest of the event logs.
List<Long> allThreadIds = new ArrayList<>();
// If number of test methods is more than the thread count, then the first block of methods will
// be equal to
// the thread count. If not, it will be equal to the total number of methods.
int blockSize =
testMethodEventLogs.size() / 3 >= threadCount
? threadCount
: testMethodEventLogs.size() / 3;
// Get the start events for the first batch of methods.
List<EventLog> eventLogTestMethodListenerStartEvents =
testMethodEventLogs.subList(0, blockSize);
if (log.isDebugEnabled()) {
log.debug(
"First "
+ blockSize
+ " test method event logs should all be test method start events: "
+ getStringForEventLogList(eventLogTestMethodListenerStartEvents));
}
// Verify that all the events in the sublist extracted for the start events of the block of
// methods expected
// to execute in parallel all have the test method start event type and that they all executed
// in different
// threads.
verifySimultaneousTestMethodListenerStartEvents(
eventLogTestMethodListenerStartEvents, testName, blockSize);
// Keep track of the current methods that are executing and their thread IDs
for (EventLog eventLog : eventLogTestMethodListenerStartEvents) {
ClassInstanceMethodKey classAndMethodNameAndInstanceHash =
new ClassInstanceMethodKey(eventLog);
assertNull(
methodsExecuting.get(classAndMethodNameAndInstanceHash),
"There should only be one start "
+ "event logged for a method in the first block of test method events");
assertFalse(
executingMethodThreadIds.contains(eventLog.getThreadId()),
"The first block of test method " + "events should all have different thread IDs");
methodsExecuting.put(classAndMethodNameAndInstanceHash, eventLog);
executingMethodThreadIds.add(eventLog.getThreadId());
allThreadIds.add(eventLog.getThreadId());
}
for (int i = blockSize; i < testMethodEventLogs.size(); i++) {
EventLog eventLog = testMethodEventLogs.get(i);
log.debug("Processing test method event log at index " + i + ": " + eventLog);
ClassInstanceMethodKey classAndMethodNameAndInstanceHash =
new ClassInstanceMethodKey(eventLog);
if (eventLog.getEvent() == LISTENER_TEST_METHOD_START) {
assertTrue(
methodsExecuting.get(classAndMethodNameAndInstanceHash) == null
&& methodsCompleted.get(classAndMethodNameAndInstanceHash) == null,
"There should only be one " + "execution of any given method");
assertFalse(
executingMethodThreadIds.contains(eventLog.getThreadId()),
"Event logs for currently "
+ "executing test methods should have different thread IDs");
assertTrue(
allThreadIds.contains(eventLog.getThreadId()),
"All of the test method event logs should "
+ "have the same "
+ threadCount
+ " thread IDs: "
+ allThreadIds.toString());
assertTrue(
methodsExecuting.size() < threadCount,
"The current event log is a test method start "
+ "event. The list of currently executing methods should be less than the thread count. "
+ "Thread count: "
+ threadCount
+ ". Currently executing methods: "
+ getStringForEventLogList(methodsExecuting.values()));
methodsExecuting.put(classAndMethodNameAndInstanceHash, eventLog);
executingMethodThreadIds.add(eventLog.getThreadId());
}
if (eventLog.getEvent() == TEST_METHOD_EXECUTION) {
assertTrue(
methodsExecuting.get(classAndMethodNameAndInstanceHash) != null,
"Found a test method "
+ "execution event log that does not have a corresponding test method start event log");
assertTrue(
methodsExecuting.get(classAndMethodNameAndInstanceHash).getThreadId()
== eventLog.getThreadId(),
"All the event logs for a given method should have the same thread ID");
}
if (eventLog.getEvent() == LISTENER_TEST_METHOD_PASS) {
assertTrue(
methodsExecuting.get(classAndMethodNameAndInstanceHash) != null,
"Found a test method "
+ "pass event log that does not have a corresponding test method start event log");
assertTrue(
methodsExecuting.get(classAndMethodNameAndInstanceHash).getThreadId()
== eventLog.getThreadId(),
"All the event logs for a given method should have the same thread ID");
methodsExecuting.remove(classAndMethodNameAndInstanceHash);
executingMethodThreadIds.remove(eventLog.getThreadId());
methodsCompleted.put(classAndMethodNameAndInstanceHash, eventLog);
}
}
}
// Verify that methods associated with the specified event logs execute simultaneously in parallel
// fashion, in
// accordance with the thread count. This verification is for blocks of parallel methods, some of
// which use
// non-parallel data providers without factories, so all the invocations of the methods run on the
// same class
// instances. This verification is for blocks of parallel methods that have the same sleep delays
// for their
// execution bodies and which do not have any BeforeMethod AfterMethod, BeforeGroup or AfterGroup
// configuration methods.
//
// Some of the test methods use non-parallel data providers without factories. All the invocations
// of those
// test methods will occur serially within the same thread on the same class instances. There are
// three test
// method events expected per test method: a start event, an execution event, and a test method
// pass event.
public static void verifyParallelTestMethodsWithNonParallelDataProvider(
List<EventLog> testMethodEventLogs,
String testName,
Map<String, Integer> expectedInvocationCounts,
int numUniqueMethods,
int threadCount) {
log.debug(
"Verifying parallel execution of test methods using non-parallel data providers for "
+ "test named "
+ testName
+ " with thread count "
+ threadCount);
log.debug(
testMethodEventLogs.size()
+ " test method event logs for "
+ numUniqueMethods
+ " unique methods");
Map<String, EventLog> methodsExecuting = new HashMap<>();
Map<String, EventLog> methodsCompleted = new HashMap<>();
// Because this method verifies combination of parallel-by-methods mode and the use of
// non-parallel data
// providers without factories, it is necessary to track the number of times that test methods
// are invoked in
// order to check that this is consistent with the number of times they are expected to be
// invoked based on
// their use of non-parallel data providers.
Map<String, Integer> methodInvocationsCounts = new HashMap<>();
// In order to verify that all invocations of test methods which use non-parallel data providers
// occur in the
// same thread, it is necessary to keep track of the thread IDs of methods that are executing
// within a
// block of simultaneously executing methods.
Map<String, Long> executingMethodThreadIds = new HashMap<>();
// Make a list of the all the thread IDs of the first batch of start method events and check
// that no other
// thread IDs are found in the rest of the event logs.
List<Long> allThreadIds = new ArrayList<>();
// The logic for determining the block size of simultaneously executing parallel methods is
// initially determined
// by whether the total number of unique methods less than the thread count. If it is less than
// the thread count,
// then the block size is equal to the number of unique methods. Those methods will execute in
// parallel
// until all invocations of all the methods completes. Otherwise, there are more methods queued
// up than the
// thread count, so the block size is equal to the thread count.
int blockSize = numUniqueMethods >= threadCount ? threadCount : numUniqueMethods;
// Get the start events for the first batch of methods.
List<EventLog> eventLogTestMethodListenerStartEvents =
testMethodEventLogs.subList(0, blockSize);
log.debug(
"First "
+ blockSize
+ " test method event logs should all be test method start events: "
+ "\n"
+ getStringForEventLogList(eventLogTestMethodListenerStartEvents));
log.debug(getStringForEventLogList(eventLogTestMethodListenerStartEvents));
// Keep track of the current methods that are executing and their thread IDs
for (EventLog eventLog : eventLogTestMethodListenerStartEvents) {
String classAndMethodName =
(String) eventLog.getData(CLASS_NAME) + "." + (String) eventLog.getData(METHOD_NAME);
assertNull(
methodsExecuting.get(classAndMethodName),
"There should only be one start event logged for a "
+ "method in the first block of test method events");
assertNull(
executingMethodThreadIds.get(classAndMethodName),
"The first block of test method events " + "should all have different thread IDs");
methodsExecuting.put(classAndMethodName, eventLog);
executingMethodThreadIds.put(classAndMethodName, eventLog.getThreadId());
allThreadIds.add(eventLog.getThreadId());
methodInvocationsCounts.put(classAndMethodName, 1);
}
// Verify that all the events in the sublist extracted for the test method execution events of
// the block of
// methods expected to execute in parallel all have the test method execution event type and
// that they all
// executed in different threads.
verifySimultaneousTestMethodListenerStartEvents(
eventLogTestMethodListenerStartEvents, testName, blockSize);
for (int i = blockSize; i < testMethodEventLogs.size(); i++) {
EventLog eventLog = testMethodEventLogs.get(i);
log.debug("Processing test method event log at index " + i + ": " + eventLog);
String classAndMethodName =
(String) eventLog.getData(CLASS_NAME) + "." + (String) eventLog.getData(METHOD_NAME);
if (i != blockSize) {
// All methods that are in the list of currently executing methods should still have
// invocations left.
// Otherwise, they would have been removed from that list and added to the completed methods
// list.
allExecutingMethodsHaveMoreInvocations(
methodsExecuting, methodInvocationsCounts, expectedInvocationCounts);
}
if (eventLog.getEvent() == LISTENER_TEST_METHOD_START) {
assertTrue(
executingMethodThreadIds.get(classAndMethodName) == null
|| executingMethodThreadIds.get(classAndMethodName) == eventLog.getThreadId(),
"Event logs for all invocations of a method on a give class instance should have the same "
+ "thread ID ");
for (String key : executingMethodThreadIds.keySet()) {
if (!key.equals(classAndMethodName)) {
assertFalse(
executingMethodThreadIds.get(key) == eventLog.getThreadId(),
"Events for " + "different methods should have different thread IDs");
}
}
assertTrue(
allThreadIds.contains(eventLog.getThreadId()),
"All of the test method event logs should "
+ "have the same "
+ threadCount
+ " thread IDs: "
+ allThreadIds.toString());
if (methodsExecuting.get(classAndMethodName) == null) {
assertTrue(
methodsExecuting.size() < threadCount,
"The current event log is a test method start "
+ "event for a method that has not yet been invoked. The list of currently executing "
+ "methods should be less than the thread count. Thread count: "
+ threadCount
+ ". Currently executing methods: "
+ getStringForEventLogList(methodsExecuting.values()));
methodsExecuting.put(classAndMethodName, eventLog);
executingMethodThreadIds.put(classAndMethodName, eventLog.getThreadId());
methodInvocationsCounts.put(classAndMethodName, 1);
} else {
methodInvocationsCounts.put(
classAndMethodName, methodInvocationsCounts.get(classAndMethodName) + 1);
assertTrue(
methodInvocationsCounts.get(classAndMethodName)
<= expectedInvocationCounts.get(classAndMethodName),
"Method '"
+ classAndMethodName
+ "' is expected to execute only "
+ expectedInvocationCounts.get(classAndMethodName)
+ " times, but event logs show "
+ "that it was execute at least "
+ methodInvocationsCounts.get(classAndMethodName)
+ " times");
}
}
if (eventLog.getEvent() == TEST_METHOD_EXECUTION) {
assertTrue(
methodsExecuting.get(classAndMethodName) != null,
"Found a test method execution event "
+ "log that does not have a corresponding test method start event log");
assertTrue(
methodsExecuting.get(classAndMethodName).getThreadId() == eventLog.getThreadId(),
"All the event logs for a given method should have the same thread ID");
}
if (eventLog.getEvent() == LISTENER_TEST_METHOD_PASS) {
assertTrue(
methodsExecuting.get(classAndMethodName) != null,
"Found a test method pass event log "
+ "that does not have a corresponding test method start event log");
assertTrue(
methodsExecuting.get(classAndMethodName).getThreadId() == eventLog.getThreadId(),
"All the event logs for a given method should have the same thread ID");
if (methodInvocationsCounts
.get(classAndMethodName)
.equals(expectedInvocationCounts.get(classAndMethodName))) {
methodsExecuting.remove(classAndMethodName);
executingMethodThreadIds.remove(classAndMethodName);
methodsCompleted.put(classAndMethodName, eventLog);
}
log.debug(
classAndMethodName
+ " has executed "
+ methodInvocationsCounts.get(classAndMethodName)
+ " times. Expected to execute "
+ (expectedInvocationCounts.get(classAndMethodName)
- methodInvocationsCounts.get(classAndMethodName))
+ " more times");
}
}
}
// Verify that the specified test method listener onTestStart event logs execute simultaneously in
// parallel fashion
// according to the expected maximum number of simultaneous executions. Verifies that each of them
// has the same
// event type and all have different thread IDs.
public static void verifySimultaneousTestMethodListenerStartEvents(
List<EventLog> listenerStartEventLogs, String testName, int blockSize) {
verifyEventTypeForEventsLogs(
listenerStartEventLogs,
LISTENER_TEST_METHOD_START,
"Expected "
+ blockSize
+ " test method start event logs to be in a block of methods executing in parallel. Found an event log "
+ "of a different type in the block being processed: "
+ listenerStartEventLogs);
verifyDifferentThreadIdsForEvents(
listenerStartEventLogs,
"Expected "
+ blockSize
+ " test method start "
+ "event logs to be in a block of methods executing in parallel. Each one of these event logs should "
+ "be associated with a different thread ID, but found that at two event logs share the same thread "
+ "ID: "
+ listenerStartEventLogs);
}
// Verify that the test method level events for the test methods declared in the specified class
// run in the same
// thread for each instance of the test class for the specified suite and test
public static void verifyEventsForTestMethodsRunInTheSameThread(
Class<?> testClass, String suiteName, String testName) {
for (Method method : testClass.getMethods()) {
boolean isTestMethod = false;
Annotation[] annotations = method.getDeclaredAnnotations();
for (Annotation a : annotations) {
if (Test.class.isAssignableFrom(a.getClass())) {
isTestMethod = true;
}
}
if (method.getDeclaringClass().equals(testClass) && isTestMethod) {
Multimap<Object, EventLog> testMethodEventLogs =
getTestMethodEventLogsForMethod(
suiteName, testName, testClass.getCanonicalName(), method.getName());
for (Object instanceKey : testMethodEventLogs.keySet()) {
long threadId = -1;
for (EventLog eventLog : testMethodEventLogs.get(instanceKey)) {
if (threadId == -1) {
threadId = eventLog.getThreadId();
} else {
assertEquals(
eventLog.getThreadId(),
threadId,
"All of the method level events for the test "
+ "method "
+ method.getName()
+ " in the test class "
+ testClass.getCanonicalName()
+ " for the test "
+ suiteName
+ " should be run in the same thread");
}
}
}
}
}
}
public static void verifySequentialSuites(
List<EventLog> suiteLevelEventLogs, Map<String, List<EventLog>> suiteEventLogsMap) {
verifySameThreadIdForAllEvents(
suiteLevelEventLogs,
"Because the suites execute sequentially, the event logs "
+ "suite level events should have the same thread ID: "
+ suiteLevelEventLogs);
List<EventLog> suiteListenerStartEventLogs = new ArrayList<>();
for (int i = 0; i < suiteLevelEventLogs.size(); i = i + 2) {
assertTrue(
suiteLevelEventLogs.get(i).getEvent() == LISTENER_SUITE_START
&& suiteLevelEventLogs.get(i + 1).getEvent() == LISTENER_SUITE_FINISH,
"Because the suites are "
+ "expected to execute sequentially, the suite level event logs should consist of a series of "
+ "pairs of a suite listener onStart event logger followed by a suite listener onFinish event logger: "
+ suiteLevelEventLogs);
suiteListenerStartEventLogs.add((suiteLevelEventLogs.get(i)));
}
for (int i = 0; i < suiteListenerStartEventLogs.size() - 1; i++) {
String firstSuite = (String) suiteListenerStartEventLogs.get(i).getData(SUITE_NAME);
String secondSuite = (String) suiteListenerStartEventLogs.get(i + 1).getData(SUITE_NAME);
List<EventLog> firstSuiteEventLogs = suiteEventLogsMap.get(firstSuite);
List<EventLog> secondSuiteEventLogs = suiteEventLogsMap.get(secondSuite);
verifySequentialTimingOfEvents(
firstSuiteEventLogs,
secondSuiteEventLogs,
"The first suite listener "
+ "onStart event logger is for "
+ firstSuite
+ " and the second suite listener onStart event logger is "
+ "for "
+ secondSuite
+ ". Because the suites are supposed to execute sequentially, all of the "
+ "event logs for "
+ firstSuite
+ " should have timestamps earlier than all of the event logs for "
+ secondSuite
+ ". First suite event logs: "
+ firstSuiteEventLogs
+ ". Second suite event logs: "
+ secondSuiteEventLogs);
}
}
public static void verifySequentialTests(
List<EventLog> suiteAndTestLevelEventLogs,
List<EventLog> testLevelEventLogs,
EventLog suiteListenerOnStartEventLog,
EventLog suiteListenerOnFinishEventLog) {
verifySameThreadIdForAllEvents(
suiteAndTestLevelEventLogs,
"All suite level and test level event logs "
+ "should have the same thread ID because there is no parallelism specified at the suite or test "
+ "level: "
+ suiteAndTestLevelEventLogs);
verifySequentialTimingOfEvents(
suiteAndTestLevelEventLogs,
"The timestamps of suite and test level events "
+ "logged first should be earlier than those which are logged afterwards because there is no "
+ "parallelism specified at the suite or test level: "
+ suiteAndTestLevelEventLogs);
verifyEventsOccurBetween(
suiteListenerOnStartEventLog,
testLevelEventLogs,
suiteListenerOnFinishEventLog,
"All of the test level event logs should have timestamps between the suite listener's onStart and "
+ "onFinish event logs. Suite listener onStart event logger: "
+ suiteListenerOnStartEventLog
+ ". Suite listener onFinish event logger: "
+ suiteListenerOnFinishEventLog
+ ". Test level "
+ "event logs: "
+ testLevelEventLogs);
for (int i = 0; i < testLevelEventLogs.size(); i = i + 2) {
assertTrue(
testLevelEventLogs.get(i).getEvent() == LISTENER_TEST_START
&& testLevelEventLogs.get(i + 1).getEvent() == LISTENER_TEST_FINISH,
"Because the tests are "
+ "expected to execute sequentially, the test level event logs should consist of a series of "
+ "pairs of a test listener onStart event logger followed by a test listener onFinish event logger: "
+ testLevelEventLogs);
}
}
public static void verifyParallelSuitesWithUnequalExecutionTimes(
List<EventLog> suiteLevelEventLogs, int threadPoolSize) {
Map<String, EventLog> suitesExecuting = new HashMap<>();
Map<String, EventLog> suitesCompleted = new HashMap<>();
List<Long> executingSuiteThreadIds = new ArrayList<>();
if (suiteLevelEventLogs.size() > 2) {
int offset =
suiteLevelEventLogs.size() >= 2 * threadPoolSize
? threadPoolSize
: suiteLevelEventLogs.size() / 2;
List<EventLog> suiteListenerStartEventLogs = suiteLevelEventLogs.subList(0, offset);
verifyFirstBlockOfSimultaneouslyExecutingSuites(suiteListenerStartEventLogs, threadPoolSize);
for (EventLog eventLog : suiteListenerStartEventLogs) {
suitesExecuting.put((String) eventLog.getData(SUITE_NAME), eventLog);
executingSuiteThreadIds.add(eventLog.getThreadId());
}
for (int i = offset; i < suiteLevelEventLogs.size(); i++) {
EventLog eventLog = suiteLevelEventLogs.get(i);
String suiteName = (String) eventLog.getData(SUITE_NAME);
if (eventLog.getEvent() == LISTENER_SUITE_START) {
if (suitesExecuting.keySet().size() == threadPoolSize) {
fail(
"The thread pool size is "
+ threadPoolSize
+ ", so there should be no more than "
+ threadPoolSize
+ " suites executing at the same time: "
+ suiteLevelEventLogs);
}
assertFalse(
suitesExecuting.get(suiteName) != null || suitesCompleted.get(suiteName) != null,
"There should only be one execution of any given suite");
assertFalse(
executingSuiteThreadIds.contains(eventLog.getThreadId()),
"Event logs for currently " + "executing suites should have different thread IDs");
suitesExecuting.put(suiteName, eventLog);
executingSuiteThreadIds.add(eventLog.getThreadId());
if (suitesCompleted.size() > 0) {
EventLog priorEventLog = suiteLevelEventLogs.get(i - 1);
assertEquals(
priorEventLog.getEvent(),
LISTENER_SUITE_FINISH,
"When suites are executing in "
+ "parallel and a new suite begins execution when the active thread count was last "
+ "known to be equal to the maximum thread pool size, the previously logged suite "
+ "level event should be a suite listener onFinish event.");
}
}
if (suitesExecuting.keySet().size() < threadPoolSize
&& suiteLevelEventLogs.size() - i + 1 > threadPoolSize) {
fail(
"The thread pool size is "
+ threadPoolSize
+ ", so there should be at least "
+ threadPoolSize
+ " suites executing at the same time unless there are no suites left to "
+ "queue and the final block of suites is currently in execution: "
+ suiteLevelEventLogs);
}
if (eventLog.getEvent() == LISTENER_SUITE_FINISH) {
assertTrue(
suitesExecuting.get(suiteName) != null,
"Found an event logger for a suite listener "
+ "onFinish event that does not have a corresponding event logger for a suite listener "
+ "onStart event");
assertTrue(
suitesExecuting.get(suiteName).getThreadId() == eventLog.getThreadId(),
"All the "
+ "suite level event logs for a given suite should have the same thread ID");
suitesExecuting.remove(suiteName);
executingSuiteThreadIds.remove(eventLog.getThreadId());
suitesCompleted.put((String) eventLog.getData(SUITE_NAME), eventLog);
}
}
}
}
public static void verifySimultaneousSuiteListenerStartEvents(
List<EventLog> listenerStartEventLogs, int threadPoolSize) {
verifyEventTypeForEventsLogs(
listenerStartEventLogs,
LISTENER_SUITE_START,
"The suite thread pool size is "
+ threadPoolSize
+ ", so no more than "
+ threadPoolSize
+ " suites should start running at the "
+ "same time if there are more than "
+ threadPoolSize
+ " suites remaining to execute.");
verifyDifferentThreadIdsForEvents(
listenerStartEventLogs,
"The suite thread pool size is "
+ threadPoolSize
+ ", so the thread IDs for all the suite listener's onStart method for the "
+ threadPoolSize
+ " currently executing suites should be different");
}
private static void verifyFirstBlockOfSimultaneouslyExecutingSuites(
List<EventLog> suiteListenerStartEventLogs, int threadPoolSize) {
verifySimultaneousSuiteListenerStartEvents(suiteListenerStartEventLogs, threadPoolSize);
verifyDifferentThreadIdsForEvents(
suiteListenerStartEventLogs,
"The thread count is "
+ threadPoolSize
+ " so the thread IDs for the suite listener onStart events for simultaneously executing suites "
+ "should be different. Event logs: "
+ suiteListenerStartEventLogs);
}
// Helper method that retrieves the earliest and latest timestamps for the specified list of event
// logs
private static Pair<Long, Long> getEarliestAndLatestTimestamps(List<EventLog> eventLogs) {
if (eventLogs.isEmpty()) {
return null;
}
long earliestTimestamp = eventLogs.get(0).getTimeOfEvent();
long latestTimestamp = eventLogs.get(0).getTimeOfEvent();
for (int i = 1; i < eventLogs.size(); i++) {
long timestamp = eventLogs.get(i).getTimeOfEvent();
if (timestamp < earliestTimestamp) {
earliestTimestamp = timestamp;
}
if (timestamp > latestTimestamp) {
latestTimestamp = timestamp;
}
}
return new Pair<>(earliestTimestamp, latestTimestamp);
}
private static boolean allExecutingMethodsHaveMoreInvocations(
Map<String, EventLog> methodsExecuting,
Map<String, Integer> methodInvocationsCounts,
Map<String, Integer> expectedInvocationCounts) {
for (String methodAndClassName : methodsExecuting.keySet()) {
if (Objects.equals(
methodInvocationsCounts.get(methodAndClassName),
expectedInvocationCounts.get(methodAndClassName))) {
return false;
}
}
return true;
}
private static String getStringForEventLogList(Collection<EventLog> list) {
StringBuilder sb = new StringBuilder();
ArrayList<EventLog> eventLogs = new ArrayList<>(list);
for (int i = 0; i < eventLogs.size(); i++) {
sb.append(eventLogs.get(i));
if (i != eventLogs.size() - 1) {
sb.append("\n");
}
}
return sb.toString();
}
}
| krmahadevan/testng | testng-core/src/test/java/test/thread/parallelization/BaseParallelizationTest.java | Java | apache-2.0 | 46,945 |
package server
import (
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"golang.org/x/net/websocket"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/api"
"github.com/docker/docker/api/types"
"github.com/docker/docker/autogen/dockerversion"
"github.com/docker/docker/builder"
"github.com/docker/docker/cliconfig"
"github.com/docker/docker/daemon"
"github.com/docker/docker/graph"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/docker/docker/pkg/parsers"
"github.com/docker/docker/pkg/parsers/filters"
"github.com/docker/docker/pkg/parsers/kernel"
"github.com/docker/docker/pkg/signal"
"github.com/docker/docker/pkg/sockets"
"github.com/docker/docker/pkg/stdcopy"
"github.com/docker/docker/pkg/streamformatter"
"github.com/docker/docker/pkg/version"
"github.com/docker/docker/runconfig"
"github.com/docker/docker/utils"
)
type ServerConfig struct {
Logging bool
EnableCors bool
CorsHeaders string
Version string
SocketGroup string
TLSConfig *tls.Config
}
type Server struct {
daemon *daemon.Daemon
cfg *ServerConfig
router *mux.Router
start chan struct{}
servers []serverCloser
}
func New(cfg *ServerConfig) *Server {
srv := &Server{
cfg: cfg,
start: make(chan struct{}),
}
r := createRouter(srv)
srv.router = r
return srv
}
func (s *Server) Close() {
for _, srv := range s.servers {
if err := srv.Close(); err != nil {
logrus.Error(err)
}
}
}
type serverCloser interface {
Serve() error
Close() error
}
// ServeApi loops through all of the protocols sent in to docker and spawns
// off a go routine to setup a serving http.Server for each.
func (s *Server) ServeApi(protoAddrs []string) error {
var chErrors = make(chan error, len(protoAddrs))
for _, protoAddr := range protoAddrs {
protoAddrParts := strings.SplitN(protoAddr, "://", 2)
if len(protoAddrParts) != 2 {
return fmt.Errorf("bad format, expected PROTO://ADDR")
}
srv, err := s.newServer(protoAddrParts[0], protoAddrParts[1])
if err != nil {
return err
}
s.servers = append(s.servers, srv...)
for _, s := range srv {
logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
go func(s serverCloser) {
if err := s.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
err = nil
}
chErrors <- err
}(s)
}
}
for i := 0; i < len(protoAddrs); i++ {
err := <-chErrors
if err != nil {
return err
}
}
return nil
}
type HttpServer struct {
srv *http.Server
l net.Listener
}
func (s *HttpServer) Serve() error {
return s.srv.Serve(s.l)
}
func (s *HttpServer) Close() error {
return s.l.Close()
}
type HttpApiFunc func(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error
func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
return nil, nil, err
}
// Flush the options to make sure the client sets the raw mode
conn.Write([]byte{})
return conn, conn, nil
}
func closeStreams(streams ...interface{}) {
for _, stream := range streams {
if tcpc, ok := stream.(interface {
CloseWrite() error
}); ok {
tcpc.CloseWrite()
} else if closer, ok := stream.(io.Closer); ok {
closer.Close()
}
}
}
// Check to make sure request's Content-Type is application/json
func checkForJson(r *http.Request) error {
ct := r.Header.Get("Content-Type")
// No Content-Type header is ok as long as there's no Body
if ct == "" {
if r.Body == nil || r.ContentLength == 0 {
return nil
}
}
// Otherwise it better be json
if api.MatchesContentType(ct, "application/json") {
return nil
}
return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
}
//If we don't do this, POST method without Content-type (even with empty body) will fail
func parseForm(r *http.Request) error {
if r == nil {
return nil
}
if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
return err
}
return nil
}
func parseMultipartForm(r *http.Request) error {
if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
return err
}
return nil
}
func httpError(w http.ResponseWriter, err error) {
if err == nil || w == nil {
logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling")
return
}
statusCode := http.StatusInternalServerError
// FIXME: this is brittle and should not be necessary.
// If we need to differentiate between different possible error types, we should
// create appropriate error types with clearly defined meaning.
errStr := strings.ToLower(err.Error())
for keyword, status := range map[string]int{
"not found": http.StatusNotFound,
"no such": http.StatusNotFound,
"bad parameter": http.StatusBadRequest,
"conflict": http.StatusConflict,
"impossible": http.StatusNotAcceptable,
"wrong login/password": http.StatusUnauthorized,
"hasn't been activated": http.StatusForbidden,
} {
if strings.Contains(errStr, keyword) {
statusCode = status
break
}
}
logrus.WithFields(logrus.Fields{"statusCode": statusCode, "err": err}).Error("HTTP Error")
http.Error(w, err.Error(), statusCode)
}
// writeJSON writes the value v to the http response stream as json with standard
// json encoding.
func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
return json.NewEncoder(w).Encode(v)
}
func (s *Server) postAuth(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
var config *cliconfig.AuthConfig
err := json.NewDecoder(r.Body).Decode(&config)
r.Body.Close()
if err != nil {
return err
}
status, err := s.daemon.RegistryService.Auth(config)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, &types.AuthResponse{
Status: status,
})
}
func (s *Server) getVersion(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
v := &types.Version{
Version: dockerversion.VERSION,
ApiVersion: api.Version,
GitCommit: dockerversion.GITCOMMIT,
GoVersion: runtime.Version(),
Os: runtime.GOOS,
Arch: runtime.GOARCH,
BuildTime: dockerversion.BUILDTIME,
}
if version.GreaterThanOrEqualTo("1.19") {
v.Experimental = utils.ExperimentalBuild()
}
if kernelVersion, err := kernel.GetKernelVersion(); err == nil {
v.KernelVersion = kernelVersion.String()
}
return writeJSON(w, http.StatusOK, v)
}
func (s *Server) postContainersKill(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
var sig uint64
name := vars["name"]
// If we have a signal, look at it. Otherwise, do nothing
if sigStr := r.Form.Get("signal"); sigStr != "" {
// Check if we passed the signal as a number:
// The largest legal signal is 31, so let's parse on 5 bits
sigN, err := strconv.ParseUint(sigStr, 10, 5)
if err != nil {
// The signal is not a number, treat it as a string (either like
// "KILL" or like "SIGKILL")
syscallSig, ok := signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")]
if !ok {
return fmt.Errorf("Invalid signal: %s", sigStr)
}
sig = uint64(syscallSig)
} else {
sig = sigN
}
if sig == 0 {
return fmt.Errorf("Invalid signal: %s", sigStr)
}
}
if err := s.daemon.ContainerKill(name, sig); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersPause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
if err := s.daemon.ContainerPause(vars["name"]); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersUnpause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
if err := s.daemon.ContainerUnpause(vars["name"]); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) getContainersExport(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
return s.daemon.ContainerExport(vars["name"], w)
}
func (s *Server) getImagesJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
imagesConfig := graph.ImagesConfig{
Filters: r.Form.Get("filters"),
// FIXME this parameter could just be a match filter
Filter: r.Form.Get("filter"),
All: boolValue(r, "all"),
}
images, err := s.daemon.Repositories().Images(&imagesConfig)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, images)
}
func (s *Server) getInfo(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
info, err := s.daemon.SystemInfo()
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, info)
}
func (s *Server) getEvents(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var since int64 = -1
if r.Form.Get("since") != "" {
s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
if err != nil {
return err
}
since = s
}
var until int64 = -1
if r.Form.Get("until") != "" {
u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64)
if err != nil {
return err
}
until = u
}
timer := time.NewTimer(0)
timer.Stop()
if until > 0 {
dur := time.Unix(until, 0).Sub(time.Now())
timer = time.NewTimer(dur)
}
ef, err := filters.FromParam(r.Form.Get("filters"))
if err != nil {
return err
}
isFiltered := func(field string, filter []string) bool {
if len(filter) == 0 {
return false
}
for _, v := range filter {
if v == field {
return false
}
if strings.Contains(field, ":") {
image := strings.Split(field, ":")
if image[0] == v {
return false
}
}
}
return true
}
d := s.daemon
es := d.EventsService
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(ioutils.NewWriteFlusher(w))
getContainerId := func(cn string) string {
c, err := d.Get(cn)
if err != nil {
return ""
}
return c.ID
}
sendEvent := func(ev *jsonmessage.JSONMessage) error {
//incoming container filter can be name,id or partial id, convert and replace as a full container id
for i, cn := range ef["container"] {
ef["container"][i] = getContainerId(cn)
}
if isFiltered(ev.Status, ef["event"]) || isFiltered(ev.From, ef["image"]) ||
isFiltered(ev.ID, ef["container"]) {
return nil
}
return enc.Encode(ev)
}
current, l := es.Subscribe()
if since == -1 {
current = nil
}
defer es.Evict(l)
for _, ev := range current {
if ev.Time < since {
continue
}
if err := sendEvent(ev); err != nil {
return err
}
}
var closeNotify <-chan bool
if closeNotifier, ok := w.(http.CloseNotifier); ok {
closeNotify = closeNotifier.CloseNotify()
}
for {
select {
case ev := <-l:
jev, ok := ev.(*jsonmessage.JSONMessage)
if !ok {
continue
}
if err := sendEvent(jev); err != nil {
return err
}
case <-timer.C:
return nil
case <-closeNotify:
logrus.Debug("Client disconnected, stop sending events")
return nil
}
}
}
func (s *Server) getImagesHistory(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
history, err := s.daemon.Repositories().History(name)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, history)
}
func (s *Server) getContainersChanges(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
changes, err := s.daemon.ContainerChanges(vars["name"])
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, changes)
}
func (s *Server) getContainersTop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args"))
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, procList)
}
func (s *Server) getContainersJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
config := &daemon.ContainersConfig{
All: boolValue(r, "all"),
Size: boolValue(r, "size"),
Since: r.Form.Get("since"),
Before: r.Form.Get("before"),
Filters: r.Form.Get("filters"),
}
if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
limit, err := strconv.Atoi(tmpLimit)
if err != nil {
return err
}
config.Limit = limit
}
containers, err := s.daemon.Containers(config)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, containers)
}
func (s *Server) getContainersStats(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
stream := boolValueOrDefault(r, "stream", true)
var out io.Writer
if !stream {
w.Header().Set("Content-Type", "application/json")
out = w
} else {
out = ioutils.NewWriteFlusher(w)
}
var closeNotifier <-chan bool
if notifier, ok := w.(http.CloseNotifier); ok {
closeNotifier = notifier.CloseNotify()
}
config := &daemon.ContainerStatsConfig{
Stream: stream,
OutStream: out,
Stop: closeNotifier,
}
return s.daemon.ContainerStats(vars["name"], config)
}
func (s *Server) getContainersLogs(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
// Validate args here, because we can't return not StatusOK after job.Run() call
stdout, stderr := boolValue(r, "stdout"), boolValue(r, "stderr")
if !(stdout || stderr) {
return fmt.Errorf("Bad parameters: you must choose at least one stream")
}
var since time.Time
if r.Form.Get("since") != "" {
s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
if err != nil {
return err
}
since = time.Unix(s, 0)
}
var closeNotifier <-chan bool
if notifier, ok := w.(http.CloseNotifier); ok {
closeNotifier = notifier.CloseNotify()
}
logsConfig := &daemon.ContainerLogsConfig{
Follow: boolValue(r, "follow"),
Timestamps: boolValue(r, "timestamps"),
Since: since,
Tail: r.Form.Get("tail"),
UseStdout: stdout,
UseStderr: stderr,
OutStream: ioutils.NewWriteFlusher(w),
Stop: closeNotifier,
}
if err := s.daemon.ContainerLogs(vars["name"], logsConfig); err != nil {
fmt.Fprintf(w, "Error running logs job: %s\n", err)
}
return nil
}
func (s *Server) postImagesTag(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
repo := r.Form.Get("repo")
tag := r.Form.Get("tag")
force := boolValue(r, "force")
name := vars["name"]
if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
return err
}
s.daemon.EventsService.Log("tag", utils.ImageReference(repo, tag), "")
w.WriteHeader(http.StatusCreated)
return nil
}
func (s *Server) postCommit(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if err := checkForJson(r); err != nil {
return err
}
cname := r.Form.Get("container")
pause := boolValue(r, "pause")
if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
pause = true
}
c, _, err := runconfig.DecodeContainerConfig(r.Body)
if err != nil && err != io.EOF { //Do not fail if body is empty.
return err
}
commitCfg := &builder.BuilderCommitConfig{
Pause: pause,
Repo: r.Form.Get("repo"),
Tag: r.Form.Get("tag"),
Author: r.Form.Get("author"),
Comment: r.Form.Get("comment"),
Changes: r.Form["changes"],
Config: c,
}
imgID, err := builder.Commit(cname, s.daemon, commitCfg)
if err != nil {
return err
}
return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
ID: imgID,
})
}
// Creates an image from Pull or from Import
func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
image = r.Form.Get("fromImage")
repo = r.Form.Get("repo")
tag = r.Form.Get("tag")
)
authEncoded := r.Header.Get("X-Registry-Auth")
authConfig := &cliconfig.AuthConfig{}
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
authConfig = &cliconfig.AuthConfig{}
}
}
var (
err error
output = ioutils.NewWriteFlusher(w)
)
w.Header().Set("Content-Type", "application/json")
if image != "" { //pull
if tag == "" {
image, tag = parsers.ParseRepositoryTag(image)
}
metaHeaders := map[string][]string{}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
metaHeaders[k] = v
}
}
imagePullConfig := &graph.ImagePullConfig{
MetaHeaders: metaHeaders,
AuthConfig: authConfig,
OutStream: output,
}
err = s.daemon.Repositories().Pull(image, tag, imagePullConfig)
} else { //import
if tag == "" {
repo, tag = parsers.ParseRepositoryTag(repo)
}
src := r.Form.Get("fromSrc")
imageImportConfig := &graph.ImageImportConfig{
Changes: r.Form["changes"],
InConfig: r.Body,
OutStream: output,
}
// 'err' MUST NOT be defined within this block, we need any error
// generated from the download to be available to the output
// stream processing below
var newConfig *runconfig.Config
newConfig, err = builder.BuildFromConfig(s.daemon, &runconfig.Config{}, imageImportConfig.Changes)
if err != nil {
return err
}
imageImportConfig.ContainerConfig = newConfig
err = s.daemon.Repositories().Import(src, repo, tag, imageImportConfig)
}
if err != nil {
if !output.Flushed() {
return err
}
sf := streamformatter.NewJSONStreamFormatter()
output.Write(sf.FormatError(err))
}
return nil
}
func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
config *cliconfig.AuthConfig
authEncoded = r.Header.Get("X-Registry-Auth")
headers = map[string][]string{}
)
if authEncoded != "" {
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(&config); err != nil {
// for a search it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting to be empty
config = &cliconfig.AuthConfig{}
}
}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
headers[k] = v
}
}
query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
if err != nil {
return err
}
return json.NewEncoder(w).Encode(query.Results)
}
func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
metaHeaders := map[string][]string{}
for k, v := range r.Header {
if strings.HasPrefix(k, "X-Meta-") {
metaHeaders[k] = v
}
}
if err := parseForm(r); err != nil {
return err
}
authConfig := &cliconfig.AuthConfig{}
authEncoded := r.Header.Get("X-Registry-Auth")
if authEncoded != "" {
// the new format is to handle the authConfig as a header
authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
// to increase compatibility to existing api it is defaulting to be empty
authConfig = &cliconfig.AuthConfig{}
}
} else {
// the old format is supported for compatibility if there was no authConfig header
if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
}
}
name := vars["name"]
output := ioutils.NewWriteFlusher(w)
imagePushConfig := &graph.ImagePushConfig{
MetaHeaders: metaHeaders,
AuthConfig: authConfig,
Tag: r.Form.Get("tag"),
OutStream: output,
}
w.Header().Set("Content-Type", "application/json")
if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil {
if !output.Flushed() {
return err
}
sf := streamformatter.NewJSONStreamFormatter()
output.Write(sf.FormatError(err))
}
return nil
}
func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := parseForm(r); err != nil {
return err
}
w.Header().Set("Content-Type", "application/x-tar")
output := ioutils.NewWriteFlusher(w)
imageExportConfig := &graph.ImageExportConfig{Outstream: output}
if name, ok := vars["name"]; ok {
imageExportConfig.Names = []string{name}
} else {
imageExportConfig.Names = r.Form["names"]
}
if err := s.daemon.Repositories().ImageExport(imageExportConfig); err != nil {
if !output.Flushed() {
return err
}
sf := streamformatter.NewJSONStreamFormatter()
output.Write(sf.FormatError(err))
}
return nil
}
func (s *Server) postImagesLoad(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
return s.daemon.Repositories().Load(r.Body, w)
}
func (s *Server) postContainersCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if err := checkForJson(r); err != nil {
return err
}
var (
warnings []string
name = r.Form.Get("name")
)
config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
if err != nil {
return err
}
adjustCpuShares(version, hostConfig)
containerId, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig)
if err != nil {
return err
}
return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
ID: containerId,
Warnings: warnings,
})
}
func (s *Server) postContainersRestart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
timeout, _ := strconv.Atoi(r.Form.Get("t"))
if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainerRename(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
newName := r.Form.Get("name")
if err := s.daemon.ContainerRename(name, newName); err != nil {
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) deleteContainers(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
config := &daemon.ContainerRmConfig{
ForceRemove: boolValue(r, "force"),
RemoveVolume: boolValue(r, "v"),
RemoveLink: boolValue(r, "link"),
}
if err := s.daemon.ContainerRm(name, config); err != nil {
// Force a 404 for the empty string
if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
return fmt.Errorf("no such id: \"\"")
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) deleteImages(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
name := vars["name"]
force := boolValue(r, "force")
noprune := boolValue(r, "noprune")
list, err := s.daemon.ImageDelete(name, force, noprune)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, list)
}
func (s *Server) postContainersStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
// If contentLength is -1, we can assumed chunked encoding
// or more technically that the length is unknown
// https://golang.org/src/pkg/net/http/request.go#L139
// net/http otherwise seems to swallow any headers related to chunked encoding
// including r.TransferEncoding
// allow a nil body for backwards compatibility
var hostConfig *runconfig.HostConfig
if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
if err := checkForJson(r); err != nil {
return err
}
c, err := runconfig.DecodeHostConfig(r.Body)
if err != nil {
return err
}
hostConfig = c
}
if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
if err.Error() == "Container already started" {
w.WriteHeader(http.StatusNotModified)
return nil
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersStop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
seconds, _ := strconv.Atoi(r.Form.Get("t"))
if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
if err.Error() == "Container already stopped" {
w.WriteHeader(http.StatusNotModified)
return nil
}
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainersWait(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second)
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
StatusCode: status,
})
}
func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
height, err := strconv.Atoi(r.Form.Get("h"))
if err != nil {
return err
}
width, err := strconv.Atoi(r.Form.Get("w"))
if err != nil {
return err
}
return s.daemon.ContainerResize(vars["name"], height, width)
}
func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
inStream, outStream, err := hijackServer(w)
if err != nil {
return err
}
defer closeStreams(inStream, outStream)
if _, ok := r.Header["Upgrade"]; ok {
fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
} else {
fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
}
attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
InStream: inStream,
OutStream: outStream,
UseStdin: boolValue(r, "stdin"),
UseStdout: boolValue(r, "stdout"),
UseStderr: boolValue(r, "stderr"),
Logs: boolValue(r, "logs"),
Stream: boolValue(r, "stream"),
}
if err := s.daemon.ContainerAttachWithLogs(vars["name"], attachWithLogsConfig); err != nil {
fmt.Fprintf(outStream, "Error attaching: %s\n", err)
}
return nil
}
func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
h := websocket.Handler(func(ws *websocket.Conn) {
defer ws.Close()
wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
InStream: ws,
OutStream: ws,
ErrStream: ws,
Logs: boolValue(r, "logs"),
Stream: boolValue(r, "stream"),
}
if err := s.daemon.ContainerWsAttachWithLogs(vars["name"], wsAttachWithLogsConfig); err != nil {
logrus.Errorf("Error attaching websocket: %s", err)
}
})
h.ServeHTTP(w, r)
return nil
}
func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if version.LessThan("1.19") {
containerJSONRaw, err := s.daemon.ContainerInspectRaw(vars["name"])
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, containerJSONRaw)
}
containerJSON, err := s.daemon.ContainerInspect(vars["name"])
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, containerJSON)
}
func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter 'id'")
}
eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, eConfig)
}
func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
if err != nil {
return err
}
return writeJSON(w, http.StatusOK, imageInspect)
}
func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
var (
authConfigs = map[string]cliconfig.AuthConfig{}
authConfigsEncoded = r.Header.Get("X-Registry-Config")
buildConfig = builder.NewBuildConfig()
)
if authConfigsEncoded != "" {
authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
// for a pull it is not an error if no auth was given
// to increase compatibility with the existing api it is defaulting
// to be empty.
}
}
w.Header().Set("Content-Type", "application/json")
if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
buildConfig.Remove = true
} else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
buildConfig.Remove = true
} else {
buildConfig.Remove = boolValue(r, "rm")
}
if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
buildConfig.Pull = true
}
output := ioutils.NewWriteFlusher(w)
buildConfig.Stdout = output
buildConfig.Context = r.Body
buildConfig.RemoteURL = r.FormValue("remote")
buildConfig.DockerfileName = r.FormValue("dockerfile")
buildConfig.RepoName = r.FormValue("t")
buildConfig.SuppressOutput = boolValue(r, "q")
buildConfig.NoCache = boolValue(r, "nocache")
buildConfig.ForceRemove = boolValue(r, "forcerm")
buildConfig.AuthConfigs = authConfigs
buildConfig.MemorySwap = int64ValueOrZero(r, "memswap")
buildConfig.Memory = int64ValueOrZero(r, "memory")
buildConfig.CpuShares = int64ValueOrZero(r, "cpushares")
buildConfig.CpuPeriod = int64ValueOrZero(r, "cpuperiod")
buildConfig.CpuQuota = int64ValueOrZero(r, "cpuquota")
buildConfig.CpuSetCpus = r.FormValue("cpusetcpus")
buildConfig.CpuSetMems = r.FormValue("cpusetmems")
buildConfig.CgroupParent = r.FormValue("cgroupparent")
// Job cancellation. Note: not all job types support this.
if closeNotifier, ok := w.(http.CloseNotifier); ok {
finished := make(chan struct{})
defer close(finished)
go func() {
select {
case <-finished:
case <-closeNotifier.CloseNotify():
logrus.Infof("Client disconnected, cancelling job: build")
buildConfig.Cancel()
}
}()
}
if err := builder.Build(s.daemon, buildConfig); err != nil {
// Do not write the error in the http output if it's still empty.
// This prevents from writing a 200(OK) when there is an interal error.
if !output.Flushed() {
return err
}
sf := streamformatter.NewJSONStreamFormatter()
w.Write(sf.FormatError(err))
}
return nil
}
func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if vars == nil {
return fmt.Errorf("Missing parameter")
}
if err := checkForJson(r); err != nil {
return err
}
cfg := types.CopyConfig{}
if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
return err
}
if cfg.Resource == "" {
return fmt.Errorf("Path cannot be empty")
}
data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "no such id") {
w.WriteHeader(http.StatusNotFound)
return nil
}
if os.IsNotExist(err) {
return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
}
return err
}
defer data.Close()
w.Header().Set("Content-Type", "application/x-tar")
if _, err := io.Copy(w, data); err != nil {
return err
}
return nil
}
func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
name := vars["name"]
execConfig := &runconfig.ExecConfig{}
if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil {
return err
}
execConfig.Container = name
if len(execConfig.Cmd) == 0 {
return fmt.Errorf("No exec command specified")
}
// Register an instance of Exec in container.
id, err := s.daemon.ContainerExecCreate(execConfig)
if err != nil {
logrus.Errorf("Error setting up exec command in container %s: %s", name, err)
return err
}
return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
ID: id,
})
}
// TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
var (
execName = vars["name"]
stdin io.ReadCloser
stdout io.Writer
stderr io.Writer
)
execStartCheck := &types.ExecStartCheck{}
if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil {
return err
}
if !execStartCheck.Detach {
// Setting up the streaming http interface.
inStream, outStream, err := hijackServer(w)
if err != nil {
return err
}
defer closeStreams(inStream, outStream)
var errStream io.Writer
if _, ok := r.Header["Upgrade"]; ok {
fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
} else {
fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
}
if !execStartCheck.Tty {
errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
}
stdin = inStream
stdout = outStream
stderr = errStream
}
// Now run the user process in container.
if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
return err
}
w.WriteHeader(http.StatusNoContent)
return nil
}
func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
if err := parseForm(r); err != nil {
return err
}
if vars == nil {
return fmt.Errorf("Missing parameter")
}
height, err := strconv.Atoi(r.Form.Get("h"))
if err != nil {
return err
}
width, err := strconv.Atoi(r.Form.Get("w"))
if err != nil {
return err
}
return s.daemon.ContainerExecResize(vars["name"], height, width)
}
func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
w.WriteHeader(http.StatusOK)
return nil
}
func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
}
func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
_, err := w.Write([]byte{'O', 'K'})
return err
}
func (s *Server) initTcpSocket(addr string) (l net.Listener, err error) {
if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
}
if l, err = sockets.NewTcpSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
return nil, err
}
if err := allocateDaemonPort(addr); err != nil {
return nil, err
}
return
}
func makeHttpHandler(logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// log the request
logrus.Debugf("Calling %s %s", localMethod, localRoute)
if logging {
logrus.Infof("%s %s", r.Method, r.RequestURI)
}
if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
// v1.20 onwards includes the GOOS of the client after the version
// such as Docker/1.7.0 (linux)
if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
userAgent[1] = strings.Split(userAgent[1], " ")[0]
}
if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
}
}
version := version.Version(mux.Vars(r)["version"])
if version == "" {
version = api.Version
}
if corsHeaders != "" {
writeCorsHeaders(w, r, corsHeaders)
}
if version.GreaterThan(api.Version) {
http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", version, api.Version).Error(), http.StatusBadRequest)
return
}
if version.LessThan(api.MinVersion) {
http.Error(w, fmt.Errorf("client is too old, minimum supported API version is %s, please upgrade your client to a newer version", api.MinVersion).Error(), http.StatusBadRequest)
return
}
w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil {
logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
httpError(w, err)
}
}
}
// we keep enableCors just for legacy usage, need to be removed in the future
func createRouter(s *Server) *mux.Router {
r := mux.NewRouter()
if os.Getenv("DEBUG") != "" {
ProfilerSetup(r, "/debug/")
}
m := map[string]map[string]HttpApiFunc{
"GET": {
"/_ping": s.ping,
"/events": s.getEvents,
"/info": s.getInfo,
"/version": s.getVersion,
"/images/json": s.getImagesJSON,
"/images/search": s.getImagesSearch,
"/images/get": s.getImagesGet,
"/images/{name:.*}/get": s.getImagesGet,
"/images/{name:.*}/history": s.getImagesHistory,
"/images/{name:.*}/json": s.getImagesByName,
"/containers/ps": s.getContainersJSON,
"/containers/json": s.getContainersJSON,
"/containers/{name:.*}/export": s.getContainersExport,
"/containers/{name:.*}/changes": s.getContainersChanges,
"/containers/{name:.*}/json": s.getContainersByName,
"/containers/{name:.*}/top": s.getContainersTop,
"/containers/{name:.*}/logs": s.getContainersLogs,
"/containers/{name:.*}/stats": s.getContainersStats,
"/containers/{name:.*}/attach/ws": s.wsContainersAttach,
"/exec/{id:.*}/json": s.getExecByID,
},
"POST": {
"/auth": s.postAuth,
"/commit": s.postCommit,
"/build": s.postBuild,
"/images/create": s.postImagesCreate,
"/images/load": s.postImagesLoad,
"/images/{name:.*}/push": s.postImagesPush,
"/images/{name:.*}/tag": s.postImagesTag,
"/containers/create": s.postContainersCreate,
"/containers/{name:.*}/kill": s.postContainersKill,
"/containers/{name:.*}/pause": s.postContainersPause,
"/containers/{name:.*}/unpause": s.postContainersUnpause,
"/containers/{name:.*}/restart": s.postContainersRestart,
"/containers/{name:.*}/start": s.postContainersStart,
"/containers/{name:.*}/stop": s.postContainersStop,
"/containers/{name:.*}/wait": s.postContainersWait,
"/containers/{name:.*}/resize": s.postContainersResize,
"/containers/{name:.*}/attach": s.postContainersAttach,
"/containers/{name:.*}/copy": s.postContainersCopy,
"/containers/{name:.*}/exec": s.postContainerExecCreate,
"/exec/{name:.*}/start": s.postContainerExecStart,
"/exec/{name:.*}/resize": s.postContainerExecResize,
"/containers/{name:.*}/rename": s.postContainerRename,
},
"DELETE": {
"/containers/{name:.*}": s.deleteContainers,
"/images/{name:.*}": s.deleteImages,
},
"OPTIONS": {
"": s.optionsHandler,
},
}
// If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
// otherwise, all head values will be passed to HTTP handler
corsHeaders := s.cfg.CorsHeaders
if corsHeaders == "" && s.cfg.EnableCors {
corsHeaders = "*"
}
for method, routes := range m {
for route, fct := range routes {
logrus.Debugf("Registering %s, %s", method, route)
// NOTE: scope issue, make sure the variables are local and won't be changed
localRoute := route
localFct := fct
localMethod := method
// build the handler function
f := makeHttpHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
// add the new route
if localRoute == "" {
r.Methods(localMethod).HandlerFunc(f)
} else {
r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
}
}
}
return r
}
| sheavner/docker | api/server/server.go | GO | apache-2.0 | 44,592 |
#!/usr/bin/env python
import lib_v2 as lib
import sys
import os
def main(argv=None):
"""
Usage is:
submit.py [--account <chargecode>] [--url <url>] -- <commandline>
Run from the working dir of the job which must contain (in addition
to the job files) a file named scheduler.conf with scheduler properties for the job.
<chargecode>, if present, gives the project to charge the job to.
Url is the url of the submitting website including the taskid parameter.
Returns 0 with "jobid=<jobid>" on stdout if job submitted ok
Returns 1 with multiline error message on stdout if error.
Returns 2 for the specific error of queue limit exceeded.
"""
#COMMAND LINE PARSING
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--account', metavar="ACCOUNT", type=str, default=lib.account,
help="The account string to use when submitting jobs. Default is read from config files.")
parser.add_argument('--url', metavar="URL", dest="URL", type=str,
help="Notification URL")
try:
cmdline_options, cmdline = parser.parse_known_args(argv)
cmdline = cmdline[1:] if not ('--' in cmdline) else cmdline[cmdline.index('--')+1:]
except Exception as e:
print "There was a problem submitting your job"
print e
sys.exit(1)
account = cmdline_options.account
url = cmdline_options.URL
#cmdline as an array (and already set)
tooltype = lib.getToolType(cmdline)
scheduler_properties = lib.getProperties("scheduler.conf")
# print scheduler_properties
scheduler_info = lib.schedulerInfo(scheduler_properties, tooltype)
# print scheduler_info
# If this is a "direct" run type job we don't need to create a qsub script, we'll just run batch_ommand.cmdline.
if scheduler_info["is_direct"]:
return lib.submitDirectJob(account, url, lib.email, lib.jobname, cmdline)
runtime = int(scheduler_info["runtime"])
useLocalDisk = False
"""
Workaround for problems with file io on oasis and longer mrbayes runs. Instead of running on
oasis, we'll copy the working dir to the compute nodes local storage and copy the results back
when the job completes. Since many mrbayes jobs timeout we need a special trick to copy results
of jobs that timeout: Right before we launch mrbayes we launch a shell script in the background
that sleeps a few min less than the job's runtime and then copies the results. If mrbayes terminates
normally the background sleep is killed automatically.
"""
if (tooltype == "mrbayes" and runtime > 60):
useLocalDisk = True
# I'm backing out the workaround by setting useLocalDisk to false.
useLocalDisk = False
# Write the command line to a file, batch_command.cmdline.
rfile = open(lib.cmdfile, "w")
rfile.write("#!/bin/sh\n")
rfile.writelines((" ".join(cmdline), "\n"))
rfile.close()
os.chmod(lib.cmdfile, 0744);
# Create the qsub script
rfile = open(lib.runfile, "w")
text = """#!/bin/sh
#PBS -q %s
#PBS -N %s
#PBS -l walltime=00:%d:00
#PBS -o scheduler_stdout.txt
#PBS -e scheduler_stderr.txt
#PBS -W umask=0007
##PBS -V
#PBS -v QOS=2
#PBS -M %s
#PBS -m ae
#PBS -A %s
""" % (scheduler_info["queue"], lib.jobname, scheduler_info["runtime"], lib.email, account)
rfile.write(text)
text = "#PBS -l nodes=%d:ppn=%d\n" % (scheduler_info["nodes"], scheduler_info["ppn"])
rfile.write(text)
rfile.write("cd %s\n" % (lib.jobdir, lib.local_jobdir)[useLocalDisk])
if useLocalDisk == True:
# Note that it's critical that newlines in the text string are all within the double
# quotes; otherwise the echo command line would be split across lines and make no sense.
text = """"Due to filesystem problems intermediate results for longer mrbayes runs
will not be available while the job is running. The result files will be
available when mrbayes finishes.
We're working to find a solution." """
rfile.write("echo %s > %s/INTERMEDIATE_RESULTS_README.TXT\n" % (text, lib.jobdir))
rfile.write("cp -r %s/* .\n" % lib.jobdir);
sleepTime = int(scheduler_info["runtime"]) - 10
rfile.write("sleep_cp.sh %s %s &\n" % (sleepTime, lib.jobdir))
text = """
source /etc/profile.d/modules.sh
echo Job starting at `date` > start.txt
curl %s\&status=START
export CIPRES_THREADSPP=%d
export CIPRES_NP=%d
%s 1>stdout.txt 2>stderr.txt
echo Job finished at `date` > done.txt
""" % (url,
int(scheduler_info["threads_per_process"]),
int(scheduler_info["mpi_processes"]),
lib.cmdfile)
rfile.write(text)
if (useLocalDisk):
text = """
echo "Job completed, starting to copy working directory."
echo "mkdir %s.complete"
mkdir %s.complete
echo "cp -r * %s.complete"
cp -r * %s.complete
echo "mv %s %s.sleep"
mv %s %s.sleep
echo "mv %s.complete %s"
mv %s.complete %s
echo "rm -rf %s.sleep"
rm -rf %s.sleep
echo "Finished copying working directory."
""" % (lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir, lib.jobdir)
rfile.write(text)
rfile.write("curl %s\&status=DONE\n" % url)
rfile.close()
return lib.submitJob()
return 0
if __name__ == "__main__":
sys.exit(main())
| SciGaP/DEPRECATED-Cipres-Airavata-POC | saminda/cipres-airavata/sdk/scripts/remote_resource/trestles/submit_v2.py | Python | apache-2.0 | 5,478 |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace BuiltToRoam.Synchronization
{
public enum SyncAction
{
None,
Start,
Progress,
End,
Error,
Cancel
}
public class SynchronizationContext<TSynchronizationStages> :
INotifySynchronizationChanged<TSynchronizationStages>,
ISynchronizationContext<TSynchronizationStages>
where TSynchronizationStages : struct
{
public event EventHandler<SynchronizationEventArgs<TSynchronizationStages>> SynchronizationChanged;
public async Task Synchronize(TSynchronizationStages stagesToSynchronize,
bool cancelExistingSynchronization = false,
bool waitForSynchronizationToComplete = false)
{
var syncTask = InternalSync(stagesToSynchronize,
cancelExistingSynchronization);
if (waitForSynchronizationToComplete)
{
await syncTask;
}
}
public async Task Cancel(bool waitForSynchronizationToComplete = false)
{
var syncTask = Task.Run(() => BackgroundThreadCancel());
if (waitForSynchronizationToComplete)
{
await syncTask;
}
}
public void OnSynchronizationChanged(SyncAction action,
TSynchronizationStages? stage=null,
ISynchronizationEventArgs child=null,
double? percentageComplete = null,
Exception error = null)
{
var args = new SynchronizationEventArgs<TSynchronizationStages>
{
PercentageComplete = percentageComplete??0,
Stage = stage,
Action = action,
Error = error,
ChildStage=child
};
if (SynchronizationChanged == null) return;
SynchronizationChanged(this, args);
}
private readonly AutoResetEvent syncWaiter = new AutoResetEvent(true);
private CancellationTokenSource cancellationSource;
private readonly object cancelLock = new object();
private async Task InternalSync(TSynchronizationStages stagesToSynchronize,
bool cancelExistingSynchronization)
{
try
{
lock (cancelLock)
{
if (cancelExistingSynchronization)
{
var currentCancellation = cancellationSource;
if (currentCancellation != null)
{
currentCancellation.Cancel();
}
}
}
// Force the actual sync to a background thread to avoid blocking any UI
await Task.Run(() => BackgroundThreadSync(stagesToSynchronize));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private void BackgroundThreadCancel()
{
try
{
lock (cancelLock)
{
var currentCancellation = cancellationSource;
if (currentCancellation != null)
{
currentCancellation.Cancel();
}
syncWaiter.WaitOne(); // This will wait for sync to finish
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
syncWaiter.Set(); // This will make sure no one is blocked on the cancel operation
}
}
private async Task BackgroundThreadSync(TSynchronizationStages stagesToSynchronize)
{
var cancel = new CancellationTokenSource();
try
{
syncWaiter.WaitOne();
lock (cancelLock)
{
cancellationSource = cancel;
}
var steps = (from s in synchronizationSteps
where (((int)(object)s.Stage) & ((int)(object)stagesToSynchronize)) > 0
select s).ToArray();
if (steps == null || steps.Length == 0)
{
OnSynchronizationChanged(SyncAction.Start, percentageComplete: 0.0);
OnSynchronizationChanged(SyncAction.End, percentageComplete: 1.0);
return;
}
var percentage = 0.0;
var increment = 1.0 / (double)steps.Length;
OnSynchronizationChanged(SyncAction.Start, percentageComplete: 0.0);
foreach (var step in steps)
{
try
{
if (cancel.Token.IsCancellationRequested) return;
var progEvent = SynchronizationEventArgs<TSynchronizationStages>.Build(
SyncAction.Start,
step.Stage);
OnSynchronizationChanged(SyncAction.Progress, null, progEvent.Progress(SyncAction.Start,0.0), percentage);
OnSynchronizationChanged(SyncAction.Progress, null, progEvent.Progress(SyncAction.Progress), percentage);
Action<ISynchronizationEventArgs> callback = percent =>
{
var inc = increment * percent.PercentageComplete;
OnSynchronizationChanged(SyncAction.Progress,null, percent, percentage + inc);
};
step.CancellationToken = cancel.Token;
step.SynchronizationChanged = callback;
try
{
var ok = await step.StepAction(step); // InvokeStepAction(cancel.Token, callback);
if (cancel.Token.IsCancellationRequested) return;
if (!ok)
{
OnSynchronizationChanged(SyncAction.Error,null, progEvent.Progress(SyncAction.Error));
return;
}
}
catch(Exception ex)
{
OnSynchronizationChanged(SyncAction.Error, null, progEvent.Progress(SyncAction.Error,error: ex));
throw;
}
finally
{
// Make sure we clean up references to the token and callback
step.CancellationToken = default(CancellationToken);
step.SynchronizationChanged = null;
}
percentage += increment;
OnSynchronizationChanged(SyncAction.Progress, null,progEvent.Progress(SyncAction.Progress,1.0), percentage);
OnSynchronizationChanged(SyncAction.Progress, null, progEvent.Progress(SyncAction.End), percentage);
}
catch (Exception ex)
{
OnSynchronizationChanged(SyncAction.Error, step.Stage, error: ex);
throw;
}
}
OnSynchronizationChanged(SyncAction.End, percentageComplete: 1.0);
}
catch (Exception ex)
{
OnSynchronizationChanged(SyncAction.Error, error: ex);
}
finally
{
if (cancel.Token.IsCancellationRequested)
{
OnSynchronizationChanged(SyncAction.Cancel);
}
syncWaiter.Set();
lock (cancelLock)
{
var existing = cancellationSource;
if (existing == cancel)
{
cancellationSource = null;
}
}
}
}
private readonly List<ISynchronizationStage<TSynchronizationStages>> synchronizationSteps = new List<ISynchronizationStage<TSynchronizationStages>>();
public void DefineSynchronizationStep(TSynchronizationStages synchronizationStage,
Func<ISynchronizationStage<TSynchronizationStages>, Task<bool>> stepAction)
{
var wrapper = SyncStepWrapper<TSynchronizationStages>.Build(synchronizationStage,
stepAction);
synchronizationSteps.Add(wrapper);
}
}
public interface INotifySynchronizationChanged<TSynchronizationStages> where TSynchronizationStages:struct
{
event EventHandler<SynchronizationEventArgs<TSynchronizationStages>> SynchronizationChanged;
void OnSynchronizationChanged(SyncAction action,
TSynchronizationStages? stage = null,
ISynchronizationEventArgs child = null,
double? percentageComplete = null,
Exception error = null);
}
public class SyncStepWrapper<TStage> : ISynchronizationStage<TStage>
where TStage : struct
{
public static ISynchronizationStage<TSyncStage> Build<TSyncStage>(TSyncStage stage,
Func<ISynchronizationStage<TSyncStage>,Task<bool>> action
) where TSyncStage:struct
{
return new SyncStepWrapper<TSyncStage>
{
Stage = stage,
StepAction = action
};
}
public TStage Stage { get; private set; }
public CancellationToken CancellationToken { get; set; }
public Action<ISynchronizationEventArgs> SynchronizationChanged { get; set; }
private double CurrentSubStage { get; set; }
private double SubStageCount
{
get { return subStageCount; }
set
{
subStageCount = value;
StageIncrement = 1.0 / SubStageCount;
CurrentSubStage = -1;
}
}
private double StageIncrement { get; set; }
public void RegisterSubStagesCount(int numberOfSubStages)
{
SubStageCount = numberOfSubStages;
}
public void OnSynchronizationChanged(SyncAction action,
ISynchronizationEventArgs child = null,
double? percentageComplete = null,
Exception error = null)
{
var args = new SynchronizationEventArgs<TStage>
{
PercentageComplete = percentageComplete??0,
Stage = Stage,
Action = action,
Error = error,
ChildStage = child
};
if (SynchronizationChanged == null) return;
SynchronizationChanged(args);
}
public void StartSubStage()
{
CurrentSubStage++;
var progSummary = SynchronizationEventArgs<TStage>.Build(SyncAction.Start, percentageComplete: 0.0);
OnSynchronizationChanged(SyncAction.Progress,progSummary, StageIncrement * CurrentSubStage);
}
public void EndSubStage()
{
var progSummary = SynchronizationEventArgs<TStage>.Build(SyncAction.End, percentageComplete: 1.0);
OnSynchronizationChanged(SyncAction.Progress, progSummary, StageIncrement * (CurrentSubStage + 1));
}
public void Progress(double progress)
{
OnSynchronizationChanged(SyncAction.Progress, null, progress);
}
private readonly List<object> synchronizationSteps = new List<object>();
private double subStageCount;
public void RegisterSubStages<TSubStage>(params TSubStage[] stages) where TSubStage : struct
{
synchronizationSteps.AddRange(stages.OfType<object>());
SubStageCount = synchronizationSteps.Count;
}
public async Task RunSubStage<TSubStage>(TSubStage stage,
Func<ISynchronizationStage<TSubStage>, Task<bool>> stageAction) where TSubStage : struct
{
var progSummary = SynchronizationEventArgs<TSubStage>.Build(SyncAction.Start, stage, percentageComplete: 0.0);
try
{
var idx = synchronizationSteps.IndexOf(stage);
var progress = StageIncrement*idx;
OnSynchronizationChanged(SyncAction.Progress, progSummary, progress);
OnSynchronizationChanged(SyncAction.Progress, progSummary.Progress(SyncAction.Progress), progress);
var subAction = SyncStepWrapper<TSubStage>.Build(
stage, stageAction);
subAction.CancellationToken = CancellationToken;
Action<ISynchronizationEventArgs> callback = percent =>
{
var inc = StageIncrement * percent.PercentageComplete;
OnSynchronizationChanged(SyncAction.Progress,percent, progress + inc);
};
subAction.SynchronizationChanged = callback;
try
{
await stageAction(subAction);
}
finally
{
subAction.CancellationToken = default(CancellationToken);
subAction.SynchronizationChanged = null;
}
OnSynchronizationChanged(SyncAction.Progress, progSummary.Progress(SyncAction.Progress,1.0), progress + StageIncrement);
OnSynchronizationChanged(SyncAction.Progress, progSummary.Progress(SyncAction.End,1.0), progress + StageIncrement);
}
catch (Exception ex)
{
// Swallow any step exception, but return false to indicate sync should abort;
OnSynchronizationChanged(SyncAction.Progress, progSummary.Progress(SyncAction.Error));
Debug.WriteLine(ex.Message);
}
}
public Func<ISynchronizationStage<TStage>, Task<bool>> StepAction { get; set; }
}
}
| builttoroam/realestateinspector | BuiltToRoam.Synchronization/SynchronizationContext.cs | C# | apache-2.0 | 14,498 |
# Martian Run!
A 2D running game built with [libGDX](http://libgdx.badlogicgames.com).
<a href="https://play.google.com/store/apps/details?id=com.gamestudio24.cityescape.android">
<img alt="Get it on Google Play"
src="https://developer.android.com/images/brand/en_generic_rgb_wo_60.png" />
</a>
You can find a tutorial on how this project started here:
* [Part 1: Project and World Setup](http://williammora.com/a-running-game-with-libgdx-part-1)
* [Part 2: Main Character and Controls](http://williammora.com/a-running-game-with-libgdx-part-2)
* [Part 3: Enemies](http://williammora.com/a-running-game-with-libgdx-part-3)
* [Part 4: Background Animation](http://williammora.com/a-running-game-with-libgdx-part-4)
* [Part 5: Character Animations](http://williammora.com/a-running-game-with-libgdx-part-5)
**Please, DO NOT publish this same game to Google Play. Use it as a blueprint for your game development**
## Features
* Runs on Android and desktop
* On Android, uses [Google Play Game Services](https://developers.google.com/games/services/) and
[AdMob](https://www.google.com/admob/)
## Setup
You need to add the following string resources to your Android project in order for the module to
compile:
```xml
<!-- Google Analytics: Replace placeholder ID with your tracking ID -->
<string name="ga_trackingId">UA-XXXXXXXX-X</string>
<!--
App ID generated by Google Play Game Services. Replace placeholder ID with yours
-->
<string name="app_id">XXXXXXXXXXX</string>
<!--
Google Play Game Services IDs (achievements, leaderboards). These are the IDs configured
for this particular game and you don't need to set any values for them. For your game you
would have your own achievements, leaderboards, quests and put those strings instead
-->
<string name="achievement_getting_started"></string>
<string name="achievement_like_a_rover"></string>
<string name="achievement_spirit"></string>
<string name="achievement_curiosity"></string>
<string name="achievement_5k_club"></string>
<string name="achievement_10k_club"></string>
<string name="achievement_25k_club"></string>
<string name="achievement_50k_club"></string>
<string name="achievement_10_jump_street"></string>
<string name="achievement_100_jump_street"></string>
<string name="achievement_500_jump_street"></string>
<string name="leaderboard_high_scores"></string>
<!-- Google AdMob Unit ID. Place your ad unit ID here -->
<string name="ad_unit_id"></string>
```
## Credits
Developed by [William Mora](http://williammora.com)
Powered by [libGDX](http://libgdx.badlogicgames.com)
Graphics by [Kenney](http://www.kenney.nl/)
Music by [Kevin MacLeod](http://incompetech.com)
## License
Copyright 2015 William Mora
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.
| sobbin/martianrun | README.md | Markdown | apache-2.0 | 3,380 |
# $NetBSD: Makefile,v 1.2 2004/06/30 03:37:40 jmc Exp $
PKGBASE=base-nis-root
TINY_VERSION=0
.include "../../../mk/bsd.syspkg.mk"
| execunix/vinos | distrib/syspkg/sets/base/base-nis-root/Makefile | Makefile | apache-2.0 | 132 |
/*
* Copyright 2010-2014 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.
*/
/*
* Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.CodePipeline.Model
{
///<summary>
/// CodePipeline exception
/// </summary>
public class InvalidStructureException : AmazonCodePipelineException
{
/// <summary>
/// Constructs a new InvalidStructureException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidStructureException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidStructureException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidStructureException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidStructureException
/// </summary>
/// <param name="innerException"></param>
public InvalidStructureException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidStructureException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidStructureException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidStructureException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidStructureException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
}
} | mwilliamson-firefly/aws-sdk-net | sdk/src/Services/CodePipeline/Generated/Model/InvalidStructureException.cs | C# | apache-2.0 | 3,105 |
package com.xiledsystems.AlternateJavaBridgelib.components.altbridge;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONException;
import com.xiledsystems.AlternateJavaBridgelib.components.altbridge.util.SheetInfo;
import com.xiledsystems.AlternateJavaBridgelib.components.altbridge.util.SheetReader;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class SpriteSheetHelper extends AndroidNonvisibleComponent implements OnDestroyListener {
private final static String TAG = "SpriteSheetHelper";
private Bitmap spriteSheet;
private ArrayList<SheetInfo> sheetInfo;
private int spriteCount;
public SpriteSheetHelper(ComponentContainer container, int sheetResId) {
super(container);
sheetInfo = new ArrayList<SheetInfo>();
BitmapDrawable draw = (BitmapDrawable) container.$context().getResources().getDrawable(sheetResId);
spriteSheet = draw.getBitmap();
}
// TODO Add checks to make sure the sheetinfo list is populated.
/**
* Similar to the other getDrawable method, this one allows
* you to specify the filename of the sprite to use, if you
* don't know the frame number.
*
* @param fileName - the original filename of the image
*
* @return a drawable to use for setting a components image
*/
public Drawable getDrawable(String fileName) {
for (SheetInfo info : sheetInfo) {
if (info.getName().equals(fileName)) {
int x = info.getRect().left;
int y = info.getRect().top;
int width = info.getWidth();
int height = info.getHeight();
BitmapDrawable draw = new BitmapDrawable(container.$context().getResources(),
Bitmap.createBitmap(spriteSheet, x, y, width, height).copy(Bitmap.Config.ARGB_8888, true));
return draw;
}
}
return null;
}
/**
* Get a drawable from the sprite sheet to set in a component.
*
* @param frame the frame number to pull
*
* @return a drawable to use for setting the image of a component
*/
public Drawable getDrawable(int frame) {
if (frame < 0 || frame > (sheetInfo.size()-1)) {
Log.e(TAG, "Frame number is either less than zero, or higher than the size of the info list");
return null;
}
SheetInfo info = sheetInfo.get(frame);
int x = info.getRect().left;
int y = info.getRect().top;
int width = info.getWidth();
int height = info.getHeight();
BitmapDrawable draw = new BitmapDrawable(container.$context().getResources(),
Bitmap.createBitmap(spriteSheet, x, y, width, height).copy(Bitmap.Config.ARGB_8888, true));
return draw;
}
/**
* This will return the order of frames. (First frame, is the first
* item in the list -- index 0). You can then reorder this list,
* and pass it back to reorder the frame list.
*
* @return arraylist of the filenames in the sprite sheet. This is in order of frames.
*/
public ArrayList<String> frameOrder() {
ArrayList<String> list = new ArrayList<String>();
int size = sheetInfo.size();
for ( int i = 0; i < size; i++) {
list.add(sheetInfo.get(i).getName());
}
return list;
}
/**
* Use this method to reorder the frame numbers. Pass an arraylist
* of the filenames in the order you'd like them to be in. This will
* then reorder the frame numbers to the order of the list you pass
* in.
*
* @param names Arraylist of filenames in order
*/
public void setFrameOrder(ArrayList<String> names) {
if (names.size() != sheetInfo.size()) {
Log.e(TAG, "The names list is not the same length as the length of frames!");
return;
}
// Copy the current order into a new temporary list
ArrayList<SheetInfo> tmplist = new ArrayList<SheetInfo>(sheetInfo);
int size = sheetInfo.size();
// Clear the list before we start adding to it.
sheetInfo.clear();
for ( int i = 0; i < size; i++) {
int oldindex=-2;
// We have to iterate through the tmp list to find the index
// of the name given
for (int x = 0; x < size; x++) {
if (tmplist.get(x).getName().equals(names.get(i))) {
oldindex = x;
}
}
if (oldindex == -2) {
Log.e(TAG, "Name was not found. Make sure your list is accurate.");
return;
}
sheetInfo.add(tmplist.get(oldindex));
}
spriteCount = sheetInfo.size();
}
public int getSpriteCount() {
return spriteCount;
}
public SheetInfo getSpriteInfo(int frame) {
return sheetInfo.get(frame);
}
/**
* This method loads the JSON data file located in the
* assets directory. Just pass the name of the file.
*
* @param fileName - Name of the file in assets to load (must be in json format)
*
* @return true is the load was successful, false otherwise
*/
public boolean loadSheetData(String fileName) {
InputStream in;
try {
in = container.$context().getAssets().open(fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
in = null;
return false;
}
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder string = new StringBuilder();
String line;
try {
while ((line = r.readLine()) != null) {
string.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
String jsonString = string.toString();
try {
sheetInfo = SheetReader.getSpriteFrames(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public Drawable getMap() {
return new BitmapDrawable(container.$context().getResources(), spriteSheet);
}
@Override
public void onDestroy() {
if (spriteSheet != null) {
spriteSheet.recycle();
spriteSheet = null;
}
}
}
| roadlabs/alternate-java-bridge-library | src/com/xiledsystems/AlternateJavaBridgelib/components/altbridge/SpriteSheetHelper.java | Java | apache-2.0 | 6,123 |
mongodb CHANGELOG
=================
This file is used to list changes made in each version of the mongodb cookbook.
0.1.0
-----
- [your_name] - Initial release of mongodb
- - -
Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown.
The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.
| niranjan-hanumegowda/chef-repo | cookbooks/mongodb/CHANGELOG.md | Markdown | apache-2.0 | 455 |
//===--- GenericSignature.cpp - Generic Signature AST ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the GenericSignature class.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/Types.h"
#include "swift/Basic/STLExtras.h"
#include <functional>
using namespace swift;
void ConformanceAccessPath::print(raw_ostream &out) const {
interleave(begin(), end(),
[&](const Entry &entry) {
entry.first.print(out);
out << ": " << entry.second->getName();
}, [&] {
out << " -> ";
});
}
void ConformanceAccessPath::dump() const {
print(llvm::errs());
llvm::errs() << "\n";
}
GenericSignature::GenericSignature(TypeArrayView<GenericTypeParamType> params,
ArrayRef<Requirement> requirements,
bool isKnownCanonical)
: NumGenericParams(params.size()), NumRequirements(requirements.size()),
CanonicalSignatureOrASTContext()
{
auto paramsBuffer = getGenericParamsBuffer();
for (unsigned i = 0; i < NumGenericParams; ++i) {
paramsBuffer[i] = params[i];
}
auto reqtsBuffer = getRequirementsBuffer();
for (unsigned i = 0; i < NumRequirements; ++i) {
reqtsBuffer[i] = requirements[i];
}
#ifndef NDEBUG
// Make sure generic parameters are in the right order, and
// none are missing.
unsigned depth = 0;
unsigned count = 0;
for (auto param : params) {
if (param->getDepth() != depth) {
assert(param->getDepth() > depth &&
"Generic parameter depth mismatch");
depth = param->getDepth();
count = 0;
}
assert(param->getIndex() == count &&
"Generic parameter index mismatch");
count++;
}
#endif
if (isKnownCanonical)
CanonicalSignatureOrASTContext = &getASTContext(getGenericParams(),
requirements);
}
TypeArrayView<GenericTypeParamType>
GenericSignature::getInnermostGenericParams() const {
auto params = getGenericParams();
// Find the point at which the depth changes.
unsigned depth = params.back()->getDepth();
for (unsigned n = params.size(); n > 0; --n) {
if (params[n-1]->getDepth() != depth) {
return params.slice(n);
}
}
// All parameters are at the same depth.
return params;
}
SmallVector<GenericTypeParamType *, 2>
GenericSignature::getSubstitutableParams() const {
// Figure out which generic parameters are concrete or same-typed to another
// generic parameter.
auto genericParams = getGenericParams();
auto genericParamsAreNotSubstitutable =
SmallVector<bool, 4>(genericParams.size(), false);
for (auto req : getRequirements()) {
if (req.getKind() != RequirementKind::SameType) continue;
GenericTypeParamType *gp;
if (auto secondGP = req.getSecondType()->getAs<GenericTypeParamType>()) {
// If two generic parameters are same-typed, then the left-hand one
// is canonical.
gp = secondGP;
} else {
// If an associated type is same-typed, it doesn't constrain the generic
// parameter itself.
if (req.getSecondType()->isTypeParameter()) continue;
// Otherwise, the generic parameter is concrete.
gp = req.getFirstType()->getAs<GenericTypeParamType>();
if (!gp) continue;
}
unsigned index = GenericParamKey(gp).findIndexIn(genericParams);
genericParamsAreNotSubstitutable[index] = true;
}
// Collect the generic parameters that are substitutable.
SmallVector<GenericTypeParamType *, 2> result;
for (auto index : indices(genericParams)) {
auto gp = genericParams[index];
if (!genericParamsAreNotSubstitutable[index])
result.push_back(gp);
}
return result;
}
bool GenericSignature::areAllParamsConcrete() const {
unsigned numConcreteGenericParams = 0;
for (const auto &req : getRequirements()) {
if (req.getKind() != RequirementKind::SameType) continue;
if (!req.getFirstType()->is<GenericTypeParamType>()) continue;
if (req.getSecondType()->isTypeParameter()) continue;
++numConcreteGenericParams;
}
return numConcreteGenericParams == getGenericParams().size();
}
ASTContext &GenericSignature::getASTContext(
TypeArrayView<GenericTypeParamType> params,
ArrayRef<swift::Requirement> requirements) {
// The params and requirements cannot both be empty.
if (!params.empty())
return params.front()->getASTContext();
else
return requirements.front().getFirstType()->getASTContext();
}
GenericSignatureBuilder *GenericSignature::getGenericSignatureBuilder() {
// The generic signature builder is associated with the canonical signature.
if (!isCanonical())
return getCanonicalSignature()->getGenericSignatureBuilder();
// generic signature builders are stored on the ASTContext.
return getASTContext().getOrCreateGenericSignatureBuilder(
CanGenericSignature(this));
}
bool GenericSignature::isCanonical() const {
if (CanonicalSignatureOrASTContext.is<ASTContext*>()) return true;
return getCanonicalSignature() == this;
}
#ifndef NDEBUG
/// Determine the canonical ordering of requirements.
static unsigned getRequirementKindOrder(RequirementKind kind) {
switch (kind) {
case RequirementKind::Conformance: return 2;
case RequirementKind::Superclass: return 0;
case RequirementKind::SameType: return 3;
case RequirementKind::Layout: return 1;
}
}
#endif
CanGenericSignature
GenericSignature::getCanonical(TypeArrayView<GenericTypeParamType> params,
ArrayRef<Requirement> requirements,
bool skipValidation) {
// Canonicalize the parameters and requirements.
SmallVector<GenericTypeParamType*, 8> canonicalParams;
canonicalParams.reserve(params.size());
for (auto param : params) {
canonicalParams.push_back(cast<GenericTypeParamType>(param->getCanonicalType()));
}
SmallVector<Requirement, 8> canonicalRequirements;
canonicalRequirements.reserve(requirements.size());
for (auto &reqt : requirements) {
if (reqt.getKind() != RequirementKind::Layout) {
auto secondTy = reqt.getSecondType();
canonicalRequirements.push_back(
Requirement(reqt.getKind(), reqt.getFirstType()->getCanonicalType(),
secondTy ? secondTy->getCanonicalType() : CanType()));
} else
canonicalRequirements.push_back(
Requirement(reqt.getKind(), reqt.getFirstType()->getCanonicalType(),
reqt.getLayoutConstraint()));
}
(void)skipValidation;
auto canSig = get(canonicalParams, canonicalRequirements,
/*isKnownCanonical=*/true);
#ifndef NDEBUG
if (skipValidation)
return CanGenericSignature(canSig);
PrettyStackTraceGenericSignature debugStack("canonicalizing", canSig);
// Check that the signature is canonical.
for (unsigned idx : indices(canonicalRequirements)) {
debugStack.setRequirement(idx);
const auto &reqt = canonicalRequirements[idx];
// Left-hand side must be canonical in its context.
// Check canonicalization of requirement itself.
switch (reqt.getKind()) {
case RequirementKind::Superclass:
assert(canSig->isCanonicalTypeInContext(reqt.getFirstType()) &&
"Left-hand side is not canonical");
assert(canSig->isCanonicalTypeInContext(reqt.getSecondType()) &&
"Superclass type isn't canonical in its own context");
break;
case RequirementKind::Layout:
assert(canSig->isCanonicalTypeInContext(reqt.getFirstType()) &&
"Left-hand side is not canonical");
break;
case RequirementKind::SameType:
assert(reqt.getFirstType()->isTypeParameter() &&
"Left-hand side must be a type parameter");
if (reqt.getSecondType()->isTypeParameter()) {
assert(compareDependentTypes(reqt.getFirstType(), reqt.getSecondType())
< 0 &&
"Out-of-order type parameters in same-type constraint");
} else {
assert(canSig->isCanonicalTypeInContext(reqt.getSecondType()) &&
"Concrete same-type isn't canonical in its own context");
}
break;
case RequirementKind::Conformance:
assert(reqt.getFirstType()->isTypeParameter() &&
"Left-hand side must be a type parameter");
assert(isa<ProtocolType>(reqt.getSecondType().getPointer()) &&
"Right-hand side of conformance isn't a protocol type");
break;
}
// From here on, we're only interested in requirements beyond the first.
if (idx == 0) continue;
// Make sure that the left-hand sides are in nondecreasing order.
const auto &prevReqt = canonicalRequirements[idx-1];
int compareLHS =
compareDependentTypes(prevReqt.getFirstType(), reqt.getFirstType());
assert(compareLHS <= 0 && "Out-of-order left-hand sides");
// If we have two same-type requirements where the left-hand sides differ
// but fall into the same equivalence class, we can check the form.
if (compareLHS < 0 && reqt.getKind() == RequirementKind::SameType &&
prevReqt.getKind() == RequirementKind::SameType &&
canSig->areSameTypeParameterInContext(prevReqt.getFirstType(),
reqt.getFirstType())) {
// If it's a it's a type parameter, make sure the equivalence class is
// wired together sanely.
if (prevReqt.getSecondType()->isTypeParameter()) {
assert(prevReqt.getSecondType()->isEqual(reqt.getFirstType()) &&
"same-type constraints within an equiv. class are out-of-order");
} else {
// Otherwise, the concrete types must match up.
assert(prevReqt.getSecondType()->isEqual(reqt.getSecondType()) &&
"inconsistent concrete same-type constraints in equiv. class");
}
}
// From here on, we only care about cases where the previous and current
// requirements have the same left-hand side.
if (compareLHS != 0) continue;
// Check ordering of requirement kinds.
assert((getRequirementKindOrder(prevReqt.getKind()) <=
getRequirementKindOrder(reqt.getKind())) &&
"Requirements for a given kind are out-of-order");
// From here on, we only care about the same requirement kind.
if (prevReqt.getKind() != reqt.getKind()) continue;
assert(reqt.getKind() == RequirementKind::Conformance &&
"Only conformance requirements can have multiples");
auto prevProto =
prevReqt.getSecondType()->castTo<ProtocolType>()->getDecl();
auto proto = reqt.getSecondType()->castTo<ProtocolType>()->getDecl();
assert(TypeDecl::compare(prevProto, proto) < 0 &&
"Out-of-order conformance requirements");
}
#endif
return CanGenericSignature(canSig);
}
CanGenericSignature
GenericSignature::getCanonicalSignature() const {
// If we haven't computed the canonical signature yet, do so now.
if (CanonicalSignatureOrASTContext.isNull()) {
// Compute the canonical signature.
CanGenericSignature canSig = getCanonical(getGenericParams(),
getRequirements());
// Record either the canonical signature or an indication that
// this is the canonical signature.
if (canSig != this)
CanonicalSignatureOrASTContext = canSig;
else
CanonicalSignatureOrASTContext = &getGenericParams()[0]->getASTContext();
// Return the canonical signature.
return canSig;
}
// A stored ASTContext indicates that this is the canonical
// signature.
if (CanonicalSignatureOrASTContext.is<ASTContext*>())
// TODO: CanGenericSignature should be const-correct.
return CanGenericSignature(const_cast<GenericSignature*>(this));
// Otherwise, return the stored canonical signature.
return CanGenericSignature(
CanonicalSignatureOrASTContext.get<GenericSignature*>());
}
GenericEnvironment *GenericSignature::createGenericEnvironment() {
auto *builder = getGenericSignatureBuilder();
return GenericEnvironment::getIncomplete(this, builder);
}
ASTContext &GenericSignature::getASTContext() const {
// Canonical signatures store the ASTContext directly.
if (auto ctx = CanonicalSignatureOrASTContext.dyn_cast<ASTContext *>())
return *ctx;
// For everything else, just get it from the generic parameter.
return getASTContext(getGenericParams(), getRequirements());
}
Optional<ProtocolConformanceRef>
GenericSignature::lookupConformance(CanType type, ProtocolDecl *proto) const {
// FIXME: Actually implement this properly.
auto *M = proto->getParentModule();
if (type->isTypeParameter())
return ProtocolConformanceRef(proto);
return M->lookupConformance(type, proto);
}
bool GenericSignature::requiresClass(Type type) {
if (!type->isTypeParameter()) return false;
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return false;
// If this type was mapped to a concrete type, then there is no
// requirement.
if (equivClass->concreteType) return false;
// If there is a layout constraint, it might be a class.
if (equivClass->layout && equivClass->layout->isClass()) return true;
// If there is a superclass bound, then obviously it must be a class.
// FIXME: We shouldn't need this?
if (equivClass->superclass) return true;
// If any of the protocols are class-bound, then it must be a class.
// FIXME: We shouldn't need this?
for (const auto &conforms : equivClass->conformsTo) {
if (conforms.first->requiresClass()) return true;
}
return false;
}
/// Determine the superclass bound on the given dependent type.
Type GenericSignature::getSuperclassBound(Type type) {
if (!type->isTypeParameter()) return nullptr;
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return nullptr;
// If this type was mapped to a concrete type, then there is no
// requirement.
if (equivClass->concreteType) return nullptr;
// Retrieve the superclass bound.
return equivClass->superclass;
}
/// Determine the set of protocols to which the given dependent type
/// must conform.
SmallVector<ProtocolDecl *, 2>
GenericSignature::getConformsTo(Type type) {
if (!type->isTypeParameter()) return { };
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return { };
// If this type was mapped to a concrete type, then there are no
// requirements.
if (equivClass->concreteType) return { };
// Retrieve the protocols to which this type conforms.
SmallVector<ProtocolDecl *, 2> result;
for (const auto &conforms : equivClass->conformsTo)
result.push_back(conforms.first);
// Canonicalize the resulting set of protocols.
ProtocolType::canonicalizeProtocols(result);
return result;
}
bool GenericSignature::conformsToProtocol(Type type, ProtocolDecl *proto) {
// FIXME: Deal with concrete conformances here?
if (!type->isTypeParameter()) return false;
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return false;
// FIXME: Deal with concrete conformances here?
if (equivClass->concreteType) return false;
// Check whether the representative conforms to this protocol.
return equivClass->conformsTo.count(proto) > 0;
}
/// Determine whether the given dependent type is equal to a concrete type.
bool GenericSignature::isConcreteType(Type type) {
return bool(getConcreteType(type));
}
/// Return the concrete type that the given dependent type is constrained to,
/// or the null Type if it is not the subject of a concrete same-type
/// constraint.
Type GenericSignature::getConcreteType(Type type) {
if (!type->isTypeParameter()) return Type();
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return Type();
return equivClass->concreteType;
}
LayoutConstraint GenericSignature::getLayoutConstraint(Type type) {
if (!type->isTypeParameter()) return LayoutConstraint();
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return LayoutConstraint();
return equivClass->layout;
}
bool GenericSignature::areSameTypeParameterInContext(Type type1, Type type2) {
assert(type1->isTypeParameter());
assert(type2->isTypeParameter());
if (type1.getPointer() == type2.getPointer())
return true;
auto &builder = *getGenericSignatureBuilder();
auto equivClass1 =
builder.resolveEquivalenceClass(
type1,
ArchetypeResolutionKind::CompleteWellFormed);
assert(equivClass1 && "not a valid dependent type of this signature?");
auto equivClass2 =
builder.resolveEquivalenceClass(
type2,
ArchetypeResolutionKind::CompleteWellFormed);
assert(equivClass2 && "not a valid dependent type of this signature?");
return equivClass1 == equivClass2;
}
bool GenericSignature::isRequirementSatisfied(Requirement requirement) {
auto GSB = getGenericSignatureBuilder();
auto firstType = requirement.getFirstType();
auto canFirstType = getCanonicalTypeInContext(firstType);
switch (requirement.getKind()) {
case RequirementKind::Conformance: {
auto protocolType = requirement.getSecondType()->castTo<ProtocolType>();
auto protocol = protocolType->getDecl();
if (canFirstType->isTypeParameter())
return conformsToProtocol(canFirstType, protocol);
else
return (bool)GSB->lookupConformance(/*dependentType=*/CanType(),
canFirstType, protocol);
}
case RequirementKind::SameType: {
auto canSecondType = getCanonicalTypeInContext(requirement.getSecondType());
return canFirstType->isEqual(canSecondType);
}
case RequirementKind::Superclass: {
auto requiredSuperclass =
getCanonicalTypeInContext(requirement.getSecondType());
// The requirement could be in terms of type parameters like a user-written
// requirement, but it could also be in terms of concrete types if it has
// been substituted/otherwise 'resolved', so we need to handle both.
auto baseType = canFirstType;
if (canFirstType->isTypeParameter()) {
auto directSuperclass = getSuperclassBound(baseType);
if (!directSuperclass)
return false;
baseType = getCanonicalTypeInContext(directSuperclass);
}
return requiredSuperclass->isExactSuperclassOf(baseType);
}
case RequirementKind::Layout: {
auto requiredLayout = requirement.getLayoutConstraint();
if (canFirstType->isTypeParameter()) {
if (auto layout = getLayoutConstraint(canFirstType))
return static_cast<bool>(layout.merge(requiredLayout));
return false;
}
// The requirement is on a concrete type, so it's either globally correct
// or globally incorrect, independent of this generic context. The latter
// case should be diagnosed elsewhere, so let's assume it's correct.
return true;
}
}
}
SmallVector<Requirement, 4> GenericSignature::requirementsNotSatisfiedBy(
GenericSignature *otherSig) {
SmallVector<Requirement, 4> result;
// If the signatures are the same, all requirements are satisfied.
if (otherSig == this) return result;
// If there is no other signature, no requirements are satisfied.
if (!otherSig){
result.insert(result.end(),
getRequirements().begin(), getRequirements().end());
return result;
}
// Find the requirements that aren't satisfied.
for (const auto &req : getRequirements()) {
if (!otherSig->isRequirementSatisfied(req))
result.push_back(req);
}
return result;
}
bool GenericSignature::isCanonicalTypeInContext(Type type) {
// If the type isn't independently canonical, it's certainly not canonical
// in this context.
if (!type->isCanonical())
return false;
// All the contextual canonicality rules apply to type parameters, so if the
// type doesn't involve any type parameters, it's already canonical.
if (!type->hasTypeParameter())
return true;
auto &builder = *getGenericSignatureBuilder();
return isCanonicalTypeInContext(type, builder);
}
bool GenericSignature::isCanonicalTypeInContext(Type type,
GenericSignatureBuilder &builder) {
// If the type isn't independently canonical, it's certainly not canonical
// in this context.
if (!type->isCanonical())
return false;
// All the contextual canonicality rules apply to type parameters, so if the
// type doesn't involve any type parameters, it's already canonical.
if (!type->hasTypeParameter())
return true;
// Look for non-canonical type parameters.
return !type.findIf([&](Type component) -> bool {
if (!component->isTypeParameter()) return false;
auto equivClass =
builder.resolveEquivalenceClass(
Type(component),
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return false;
return (equivClass->concreteType ||
!component->isEqual(equivClass->getAnchor(builder,
getGenericParams())));
});
}
CanType GenericSignature::getCanonicalTypeInContext(Type type,
GenericSignatureBuilder &builder) {
type = type->getCanonicalType();
// All the contextual canonicality rules apply to type parameters, so if the
// type doesn't involve any type parameters, it's already canonical.
if (!type->hasTypeParameter())
return CanType(type);
// Replace non-canonical type parameters.
type = type.transformRec([&](TypeBase *component) -> Optional<Type> {
if (!isa<GenericTypeParamType>(component) &&
!isa<DependentMemberType>(component))
return None;
// Find the equivalence class for this dependent member type.
auto equivClass =
builder.resolveEquivalenceClass(
Type(component),
ArchetypeResolutionKind::CompleteWellFormed);
if (!equivClass) return None;
if (equivClass->concreteType) {
return getCanonicalTypeInContext(equivClass->concreteType, builder);
}
return equivClass->getAnchor(builder, getGenericParams());
});
auto result = type->getCanonicalType();
assert(isCanonicalTypeInContext(result, builder));
return result;
}
CanType GenericSignature::getCanonicalTypeInContext(Type type) {
type = type->getCanonicalType();
// All the contextual canonicality rules apply to type parameters, so if the
// type doesn't involve any type parameters, it's already canonical.
if (!type->hasTypeParameter())
return CanType(type);
auto &builder = *getGenericSignatureBuilder();
return getCanonicalTypeInContext(type, builder);
}
GenericEnvironment *CanGenericSignature::getGenericEnvironment() const {
// generic signature builders are stored on the ASTContext.
auto &ctx = getGenericParams()[0]->getASTContext();
return ctx.getOrCreateCanonicalGenericEnvironment(
ctx.getOrCreateGenericSignatureBuilder(*this),
*this);
}
ArrayRef<CanTypeWrapper<GenericTypeParamType>>
CanGenericSignature::getGenericParams() const{
auto params = Signature->getGenericParams().getOriginalArray();
auto base = static_cast<const CanTypeWrapper<GenericTypeParamType>*>(
params.data());
return {base, params.size()};
}
/// Remove all of the associated type declarations from the given type
/// parameter, producing \c DependentMemberTypes with names alone.
static Type eraseAssociatedTypes(Type type) {
if (auto depMemTy = type->getAs<DependentMemberType>())
return DependentMemberType::get(eraseAssociatedTypes(depMemTy->getBase()),
depMemTy->getName());
return type;
}
namespace {
typedef GenericSignatureBuilder::RequirementSource RequirementSource;
template<typename T>
using GSBConstraint = GenericSignatureBuilder::Constraint<T>;
} // end anonymous namespace
/// Determine whether there is a conformance of the given
/// subject type to the given protocol within the given set of explicit
/// requirements.
static bool hasConformanceInSignature(ArrayRef<Requirement> requirements,
Type subjectType,
ProtocolDecl *proto) {
// Make sure this requirement exists in the requirement signature.
for (const auto &req: requirements) {
if (req.getKind() == RequirementKind::Conformance &&
req.getFirstType()->isEqual(subjectType) &&
req.getSecondType()->castTo<ProtocolType>()->getDecl()
== proto) {
return true;
}
}
return false;
}
/// Check whether the given requirement source has any non-canonical protocol
/// requirements in it.
static bool hasNonCanonicalSelfProtocolRequirement(
const RequirementSource *source,
ProtocolDecl *conformingProto) {
for (; source; source = source->parent) {
// Only look at protocol requirements.
if (!source->isProtocolRequirement())
continue;
// If we don't already have a requirement signature for this protocol,
// build one now.
auto inProto = source->getProtocolDecl();
if (!inProto->isRequirementSignatureComputed()) {
inProto->computeRequirementSignature();
assert(inProto->isRequirementSignatureComputed() &&
"couldn't compute requirement signature?");
}
// Check whether the given requirement is in the requirement signature.
if (!source->usesRequirementSignature &&
!hasConformanceInSignature(inProto->getRequirementSignature(),
source->getStoredType(), conformingProto))
return true;
// Update the conforming protocol for the rest of the search.
conformingProto = inProto;
}
return false;
}
/// Retrieve the best requirement source from the list
static const RequirementSource *
getBestRequirementSource(ArrayRef<GSBConstraint<ProtocolDecl *>> constraints) {
const RequirementSource *bestSource = nullptr;
bool bestIsNonCanonical = false;
auto isBetter = [&](const RequirementSource *source, bool isNonCanonical) {
if (!bestSource) return true;
if (bestIsNonCanonical != isNonCanonical)
return bestIsNonCanonical;
return bestSource->compare(source) > 0;
};
for (const auto &constraint : constraints) {
auto source = constraint.source;
// If there is a non-canonical protocol requirement next to the root,
// skip this requirement source.
bool isNonCanonical =
hasNonCanonicalSelfProtocolRequirement(source, constraint.value);
if (isBetter(source, isNonCanonical)) {
bestSource = source;
bestIsNonCanonical = isNonCanonical;
continue;
}
}
return bestSource;
}
ConformanceAccessPath GenericSignature::getConformanceAccessPath(
Type type,
ProtocolDecl *protocol) {
assert(type->isTypeParameter() && "not a type parameter");
// Resolve this type to a potential archetype.
auto &builder = *getGenericSignatureBuilder();
auto equivClass =
builder.resolveEquivalenceClass(
type,
ArchetypeResolutionKind::CompleteWellFormed);
// Dig out the conformance of this type to the given protocol, because we
// want its requirement source.
auto conforms = equivClass->conformsTo.find(protocol);
assert(conforms != equivClass->conformsTo.end());
// Follow the requirement source to form the conformance access path.
typedef GenericSignatureBuilder::RequirementSource RequirementSource;
ConformanceAccessPath path;
// Local function to construct the conformance access path from the
// requirement.
std::function<void(ArrayRef<Requirement>, const RequirementSource *,
ProtocolDecl *, Type, ProtocolDecl *)> buildPath;
buildPath = [&](ArrayRef<Requirement> reqs, const RequirementSource *source,
ProtocolDecl *conformingProto, Type rootType,
ProtocolDecl *requirementSignatureProto) {
// Each protocol requirement is a step along the path.
if (source->isProtocolRequirement()) {
// If we're expanding for a protocol that had no requirement signature
// and have hit the penultimate step, this is the last step
// that would occur in the requirement signature.
Optional<GenericSignatureBuilder> replacementBuilder;
if (!source->parent->parent && requirementSignatureProto) {
// If we have a requirement signature now, we're done.
if (source->usesRequirementSignature) {
Type subjectType = source->getStoredType()->getCanonicalType();
path.path.push_back({subjectType, conformingProto});
return;
}
// The generic signature builder we're using for this protocol
// wasn't built from its own requirement signature, so we can't
// trust it. Make sure we have a requirement signature, then build
// a new generic signature builder.
// FIXME: It would be better if we could replace the canonical generic
// signature builder with the rebuilt one.
if (!requirementSignatureProto->isRequirementSignatureComputed())
requirementSignatureProto->computeRequirementSignature();
assert(requirementSignatureProto->isRequirementSignatureComputed());
replacementBuilder.emplace(getASTContext());
replacementBuilder->addGenericSignature(
requirementSignatureProto->getGenericSignature());
replacementBuilder->processDelayedRequirements();
}
// Follow the rest of the path to derive the conformance into which
// this particular protocol requirement step would look.
auto inProtocol = source->getProtocolDecl();
buildPath(reqs, source->parent, inProtocol, rootType,
requirementSignatureProto);
assert(path.path.back().second == inProtocol &&
"path produces incorrect conformance");
// If this step was computed via the requirement signature, add it
// directly.
if (source->usesRequirementSignature) {
// Add this step along the path, which involves looking for the
// conformance we want (\c conformingProto) within the protocol
// described by this source.
// Canonicalize the subject type within the protocol's generic
// signature.
Type subjectType = source->getStoredType();
subjectType = inProtocol->getGenericSignature()
->getCanonicalTypeInContext(subjectType);
assert(hasConformanceInSignature(inProtocol->getRequirementSignature(),
subjectType, conformingProto) &&
"missing explicit conformance in requirement signature");
// Record this step.
path.path.push_back({subjectType, conformingProto});
return;
}
// Get the generic signature builder for the protocol.
// Get a generic signature for the protocol's signature.
auto inProtoSig = inProtocol->getGenericSignature();
auto &inProtoSigBuilder =
replacementBuilder ? *replacementBuilder
: *inProtoSig->getGenericSignatureBuilder();
// Retrieve the stored type, but erase all of the specific associated
// type declarations; we don't want any details of the enclosing context
// to sneak in here.
Type storedType = eraseAssociatedTypes(source->getStoredType());
// Dig out the potential archetype for this stored type.
auto equivClass =
inProtoSigBuilder.resolveEquivalenceClass(
storedType,
ArchetypeResolutionKind::CompleteWellFormed);
// Find the conformance of this potential archetype to the protocol in
// question.
auto conforms = equivClass->conformsTo.find(conformingProto);
assert(conforms != equivClass->conformsTo.end());
// Compute the root type, canonicalizing it w.r.t. the protocol context.
auto conformsSource = getBestRequirementSource(conforms->second);
assert(conformsSource != source || !requirementSignatureProto);
Type localRootType = conformsSource->getRootType();
localRootType = inProtoSig->getCanonicalTypeInContext(localRootType);
// Build the path according to the requirement signature.
buildPath(inProtocol->getRequirementSignature(), conformsSource,
conformingProto, localRootType, inProtocol);
// We're done.
return;
}
// If we have a superclass or concrete requirement, the conformance
// we need is stored in it.
if (source->kind == RequirementSource::Superclass ||
source->kind == RequirementSource::Concrete) {
auto conformance = source->getProtocolConformance();
(void)conformance;
assert(conformance.getRequirement() == conformingProto);
path.path.push_back({source->getAffectedType(), conformingProto});
return;
}
// If we still have a parent, keep going.
if (source->parent) {
buildPath(reqs, source->parent, conformingProto, rootType,
requirementSignatureProto);
return;
}
// We are at an explicit or inferred requirement.
assert(source->kind == RequirementSource::Explicit ||
source->kind == RequirementSource::Inferred);
// Skip trivial path elements. These occur when querying a requirement
// signature.
if (!path.path.empty() && conformingProto == path.path.back().second &&
rootType->isEqual(conformingProto->getSelfInterfaceType()))
return;
assert(hasConformanceInSignature(reqs, rootType, conformingProto) &&
"missing explicit conformance in signature");
// Add the root of the path, which starts at this explicit requirement.
path.path.push_back({rootType, conformingProto});
};
// Canonicalize the root type.
auto source = getBestRequirementSource(conforms->second);
Type rootType = source->getRootType()->getCanonicalType(this);
// Build the path.
buildPath(getRequirements(), source, protocol, rootType, nullptr);
// Return the path; we're done!
return path;
}
unsigned GenericParamKey::findIndexIn(
TypeArrayView<GenericTypeParamType> genericParams) const {
// For depth 0, we have random access. We perform the extra checking so that
// we can return
if (Depth == 0 && Index < genericParams.size() &&
genericParams[Index] == *this)
return Index;
// At other depths, perform a binary search.
unsigned result =
std::lower_bound(genericParams.begin(), genericParams.end(), *this,
Ordering())
- genericParams.begin();
if (result < genericParams.size() && genericParams[result] == *this)
return result;
// We didn't find the parameter we were looking for.
return genericParams.size();
}
unsigned GenericSignature::getGenericParamOrdinal(GenericTypeParamType *param) {
return GenericParamKey(param->getDepth(), param->getIndex())
.findIndexIn(getGenericParams());
}
| jopamer/swift | lib/AST/GenericSignature.cpp | C++ | apache-2.0 | 37,369 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ModuleUtils.h"
#include "nsPluginHost.h"
#include "nsPluginsCID.h"
NS_GENERIC_FACTORY_SINGLETON_CONSTRUCTOR(nsPluginHost, nsPluginHost::GetInst)
NS_DEFINE_NAMED_CID(NS_PLUGIN_HOST_CID);
static const mozilla::Module::CIDEntry kPluginCIDs[] = {
{ &kNS_PLUGIN_HOST_CID, false, NULL, nsPluginHostConstructor },
{ NULL }
};
static const mozilla::Module::ContractIDEntry kPluginContracts[] = {
{ MOZ_PLUGIN_HOST_CONTRACTID, &kNS_PLUGIN_HOST_CID },
{ NULL }
};
static const mozilla::Module kPluginModule = {
mozilla::Module::kVersion,
kPluginCIDs,
kPluginContracts
};
NSMODULE_DEFN(nsPluginModule) = &kPluginModule;
| wilebeast/FireFox-OS | B2G/gecko/dom/plugins/base/nsPluginModule.cpp | C++ | apache-2.0 | 932 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_PROFILES_AVATAR_MENU_MODEL_H_
#define CHROME_BROWSER_PROFILES_AVATAR_MENU_MODEL_H_
#include <vector>
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/string16.h"
#include "chrome/browser/profiles/profile_metrics.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "ui/gfx/image/image.h"
class AvatarMenuModelObserver;
class Browser;
class Profile;
class ProfileInfoInterface;
// This class is the model for the menu-like interface that appears when the
// avatar icon is clicked in the browser window frame. This class will notify
// its observer when the backend data changes, and the controller/view for this
// model should forward actions back to it in response to user events.
class AvatarMenuModel : public content::NotificationObserver {
public:
// Represents an item in the menu.
struct Item {
Item(size_t model_index, const gfx::Image& icon);
~Item();
// The icon to be displayed next to the item.
gfx::Image icon;
// Whether or not the current browser is using this profile.
bool active;
// The name of this profile.
string16 name;
// A string representing the sync state of the profile.
string16 sync_state;
// Whether or not the current profile is signed in. If true, |sync_state| is
// expected to be the email of the signed in user.
bool signed_in;
// Whether or not the current profile requires sign-in before use.
bool signin_required;
// The index in the |profile_cache| that this Item represents.
size_t model_index;
};
// Constructor. |observer| can be NULL. |browser| can be NULL and a new one
// will be created if an action requires it.
AvatarMenuModel(ProfileInfoInterface* profile_cache,
AvatarMenuModelObserver* observer,
Browser* browser);
virtual ~AvatarMenuModel();
// Actions performed by the view that the controller forwards back to the
// model:
// Opens a Browser with the specified profile in response to the user
// selecting an item. If |always_create| is true then a new window is created
// even if a window for that profile already exists.
void SwitchToProfile(size_t index, bool always_create);
// Opens the profile settings in response to clicking the edit button next to
// an item.
void EditProfile(size_t index);
// Creates a new profile.
void AddNewProfile(ProfileMetrics::ProfileAdd type);
// Gets the path associated with the profile at |index|.
base::FilePath GetProfilePath(size_t index);
// Gets the number of profiles.
size_t GetNumberOfItems();
// Returns the index of the active profile.
size_t GetActiveProfileIndex();
// Gets the an Item at a specified index.
const Item& GetItemAt(size_t index);
// Returns true if the add profile link should be shown.
bool ShouldShowAddNewProfileLink() const;
// This model is also used for the always-present Mac system menubar. As the
// last active browser changes, the model needs to update accordingly.
void set_browser(Browser* browser) { browser_ = browser; }
// content::NotificationObserver:
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE;
// True if avatar menu should be displayed.
static bool ShouldShowAvatarMenu();
// Start the sign-out process for this profile.
// Parameter |logout_override| alows changing the destination URL for the
// sign-out process and return value (the WebContents executing the sign-out)
// are for testing; pass NULL for normal use.
content::WebContents* BeginSignOut(const char* logout_override);
private:
// Rebuilds the menu from the cache and notifies the |observer_|.
void RebuildMenu();
// Clears the list of items, deleting each.
void ClearMenu();
// The cache that provides the profile information. Weak.
ProfileInfoInterface* profile_info_;
// The observer of this model, which is notified of changes. Weak.
AvatarMenuModelObserver* observer_;
// Browser in which this avatar menu resides. Weak.
Browser* browser_;
// List of built "menu items."
std::vector<Item*> items_;
// Listens for notifications from the ProfileInfoCache.
content::NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(AvatarMenuModel);
};
#endif // CHROME_BROWSER_PROFILES_AVATAR_MENU_MODEL_H_
| plxaye/chromium | src/chrome/browser/profiles/avatar_menu_model.h | C | apache-2.0 | 4,798 |
/*
* 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.camel.component.file;
import org.apache.camel.Consumer;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.spi.PollingConsumerPollStrategy;
import org.junit.Before;
import org.junit.Test;
/**
* Unit test for poll strategy
*/
public class FileConsumerPollStrategyNotBeginTest extends ContextTestSupport {
private static int counter;
private static volatile String event = "";
private String fileUrl = "file://target/data/pollstrategy/?consumer.pollStrategy=#myPoll&noop=true&initialDelay=0&delay=10";
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
jndi.bind("myPoll", new MyPollStrategy());
return jndi;
}
@Override
@Before
public void setUp() throws Exception {
deleteDirectory("target/data/pollstrategy");
super.setUp();
template.sendBodyAndHeader("file:target/data/pollstrategy/", "Hello World", Exchange.FILE_NAME, "hello.txt");
}
@Test
public void testFirstPollNotBegin() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
assertMockEndpointsSatisfied();
oneExchangeDone.matchesMockWaitTime();
// the poll strategy commit is executed after the exchange is done
Thread.sleep(100);
assertTrue(event.startsWith("beginbegincommit"));
}
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() throws Exception {
from(fileUrl).convertBodyTo(String.class).to("mock:result");
}
};
}
private static class MyPollStrategy implements PollingConsumerPollStrategy {
public boolean begin(Consumer consumer, Endpoint endpoint) {
event += "begin";
if (counter++ == 0) {
// deny polling at first call
return false;
}
return true;
}
public void commit(Consumer consumer, Endpoint endpoint, int polledMessages) {
event += "commit";
}
public boolean rollback(Consumer consumer, Endpoint endpoint, int retryCounter, Exception cause) throws Exception {
event += "rollback";
return false;
}
}
} | Fabryprog/camel | core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerPollStrategyNotBeginTest.java | Java | apache-2.0 | 3,408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.