text stringlengths 2 1.04M | meta dict |
|---|---|
layout: page
title: Research Interests
subtitle: "
Software/System architecture,
Cloud computing,
Security,
Component-based software engineering,
Software evolution,
Model-driven engineering,
Software development Process,
Safety lifecycle,
Embedded system,
Robotics,
Domain specific engineering"
---
### Patents
* Title: Sam4C, Authors: Lefray Arnaud, Eddy Caron, Christian Toinard, Huaxi (Yulin) ZHANG, Type: AAP, France
* Multi-robot cooperative localization method based on position mapping algorithm, Lei ZHANG, Huaxi (Yulin) ZHANG, Tengfei LIU, Zheng FANG, Quan XU, Heqiang YU. CN104331078A
### Honors
* Google Cloud Faculty Expert
* Microsoft Azure for Research Award, 2016-2017, 20000$
* Best paper finalist ICIA2015: CRALA: Towards a domain specific language of architecture-centric cloud robotics.
### Professional Service
* Program Chair ICCR2016, ICCR2018 (International Conference on Cloud and Robotics)
* General Chiar ICCR2017 (International Conference on Cloud and Robotics)
* Steering Chair ICCR 2015-2018
* Program Committee Membership, MODELSWARD 2021
### Professional Associations
* Responsable for Database of RobAgri, French National Association for Robotics and Argiculture
<!-- <img src="{{ site.baseurl }}/img/resume.jpg" alt="Research"/> -->
<!-- end .content -->
| {
"content_hash": "6f4bf857bf8417c3d328e5e5e1225104",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 173,
"avg_line_length": 35,
"alnum_prop": 0.7814671814671814,
"repo_name": "yulinz888888/yulinz888888.github.io",
"id": "6ef4329ecf80a8fb4c36c32bf2e6c50c1cefcf41",
"size": "1319",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "research.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18221"
},
{
"name": "Dockerfile",
"bytes": "1101"
},
{
"name": "HTML",
"bytes": "33379"
},
{
"name": "JavaScript",
"bytes": "4356"
},
{
"name": "Ruby",
"bytes": "1109"
}
],
"symlink_target": ""
} |
#include <CUnit/CUnit.h>
#include <guacamole/string.h>
#include <stdlib.h>
#include <string.h>
/**
* Array of test elements containing the strings "Apache" and "Guacamole".
*/
const char* const apache_guacamole[] = { "Apache", "Guacamole" };
/**
* Array of test elements containing the strings "This", "is", "a", and "test".
*/
const char* const this_is_a_test[] = { "This", "is", "a", "test" };
/**
* Array of four test elements containing the strings "A" and "B", each
* preceded by an empty string ("").
*/
const char* const empty_a_empty_b[] = { "", "A", "", "B" };
/**
* Array of test elements containing ten empty strings.
*/
const char* const empty_x10[] = { "", "", "", "", "", "", "", "", "", "" };
/**
* Verify guac_strljoin() behavior when the string fits the buffer without
* truncation. The return value of each call should be the length of the
* resulting string. Each resulting string should contain the full result of
* the join operation, including null terminator.
*/
void test_string__strljoin() {
char buffer[1024];
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, apache_guacamole, 2, " ", sizeof(buffer)), 16);
CU_ASSERT_STRING_EQUAL(buffer, "Apache Guacamole");
CU_ASSERT_EQUAL(buffer[17], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, this_is_a_test, 4, "", sizeof(buffer)), 11);
CU_ASSERT_STRING_EQUAL(buffer, "Thisisatest");
CU_ASSERT_EQUAL(buffer[12], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, this_is_a_test, 4, "-/-", sizeof(buffer)), 20);
CU_ASSERT_STRING_EQUAL(buffer, "This-/-is-/-a-/-test");
CU_ASSERT_EQUAL(buffer[21], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, empty_a_empty_b, 4, "/", sizeof(buffer)), 5);
CU_ASSERT_STRING_EQUAL(buffer, "/A//B");
CU_ASSERT_EQUAL(buffer[6], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, empty_x10, 10, "/", sizeof(buffer)), 9);
CU_ASSERT_STRING_EQUAL(buffer, "/////////");
CU_ASSERT_EQUAL(buffer[10], '\xFF');
}
/**
* Verify guac_strljoin() behavior when the string must be truncated to fit the
* buffer. The return value of each call should be the length that would result
* from joining the strings given an infinite buffer, however only as many
* characters as can fit should be appended to the string within the buffer,
* and the buffer should be null-terminated.
*/
void test_string__strljoin_truncate() {
char buffer[1024];
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, apache_guacamole, 2, " ", 9), 16);
CU_ASSERT_STRING_EQUAL(buffer, "Apache G");
CU_ASSERT_EQUAL(buffer[9], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, this_is_a_test, 4, "", 8), 11);
CU_ASSERT_STRING_EQUAL(buffer, "Thisisa");
CU_ASSERT_EQUAL(buffer[8], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, this_is_a_test, 4, "-/-", 12), 20);
CU_ASSERT_STRING_EQUAL(buffer, "This-/-is-/");
CU_ASSERT_EQUAL(buffer[12], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, empty_a_empty_b, 4, "/", 2), 5);
CU_ASSERT_STRING_EQUAL(buffer, "/");
CU_ASSERT_EQUAL(buffer[2], '\xFF');
memset(buffer, 0xFF, sizeof(buffer));
CU_ASSERT_EQUAL(guac_strljoin(buffer, empty_x10, 10, "/", 7), 9);
CU_ASSERT_STRING_EQUAL(buffer, "//////");
CU_ASSERT_EQUAL(buffer[7], '\xFF');
}
/**
* Verify guac_strljoin() behavior with zero buffer sizes. The return value of
* each call should be the size of the input string, while the buffer remains
* untouched.
*/
void test_string__strljoin_nospace() {
/* 0-byte buffer plus 1 guard byte (to test overrun) */
char buffer[1] = { '\xFF' };
CU_ASSERT_EQUAL(guac_strljoin(buffer, apache_guacamole, 2, " ", 0), 16);
CU_ASSERT_EQUAL(buffer[0], '\xFF');
CU_ASSERT_EQUAL(guac_strljoin(buffer, this_is_a_test, 4, "", 0), 11);
CU_ASSERT_EQUAL(buffer[0], '\xFF');
CU_ASSERT_EQUAL(guac_strljoin(buffer, this_is_a_test, 4, "-/-", 0), 20);
CU_ASSERT_EQUAL(buffer[0], '\xFF');
CU_ASSERT_EQUAL(guac_strljoin(buffer, empty_a_empty_b, 4, "/", 0), 5);
CU_ASSERT_EQUAL(buffer[0], '\xFF');
CU_ASSERT_EQUAL(guac_strljoin(buffer, empty_x10, 10, "/", 0), 9);
CU_ASSERT_EQUAL(buffer[0], '\xFF');
}
| {
"content_hash": "9dbd7a410ec8cff24987a330665881af",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 89,
"avg_line_length": 34.61832061068702,
"alnum_prop": 0.639470782800441,
"repo_name": "mike-jumper/incubator-guacamole-server",
"id": "3993288516c394bc4c7f18e841c3b5577bb39f77",
"size": "5342",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/libguac/tests/string/strljoin.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2035029"
},
{
"name": "C++",
"bytes": "38511"
},
{
"name": "M4",
"bytes": "40779"
},
{
"name": "Makefile",
"bytes": "34508"
},
{
"name": "Objective-C",
"bytes": "5452"
},
{
"name": "Perl",
"bytes": "9080"
},
{
"name": "Roff",
"bytes": "11969"
},
{
"name": "Shell",
"bytes": "11087"
}
],
"symlink_target": ""
} |
.class Landroid/support/v7/util/DiffUtil$PostponedUpdate;
.super Ljava/lang/Object;
.source "DiffUtil.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/support/v7/util/DiffUtil;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0xa
name = "PostponedUpdate"
.end annotation
# instance fields
.field currentPos:I
.field posInOwnerList:I
.field removal:Z
# direct methods
.method public constructor <init>(IIZ)V
.locals 0
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
iput p1, p0, Landroid/support/v7/util/DiffUtil$PostponedUpdate;->posInOwnerList:I
iput p2, p0, Landroid/support/v7/util/DiffUtil$PostponedUpdate;->currentPos:I
iput-boolean p3, p0, Landroid/support/v7/util/DiffUtil$PostponedUpdate;->removal:Z
return-void
.end method
| {
"content_hash": "bdf0e95a4f2e0dbc83adf6ffa2766d77",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 86,
"avg_line_length": 22.55263157894737,
"alnum_prop": 0.7526254375729288,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "036e6473543a04b824c250f9e2a1460befa0d248",
"size": "857",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "SecSettings/smali/android/support/v7/util/DiffUtil$PostponedUpdate.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_41) on Tue Mar 05 22:46:33 EST 2013 -->
<TITLE>
SSHSession.NestedSequential (Apache Ant API)
</TITLE>
<META NAME="date" CONTENT="2013-03-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="SSHSession.NestedSequential (Apache Ant 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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</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">
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.LocalTunnel.html" title="class in org.apache.tools.ant.taskdefs.optional.ssh"><B>PREV CLASS</B></A>
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.RemoteTunnel.html" title="class in org.apache.tools.ant.taskdefs.optional.ssh"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.NestedSequential.html" target="_top"><B>FRAMES</B></A>
<A HREF="SSHSession.NestedSequential.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.apache.tools.ant.taskdefs.optional.ssh</FONT>
<BR>
Class SSHSession.NestedSequential</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../../../resources/inherit.gif" ALT="extended by "><B>org.apache.tools.ant.taskdefs.optional.ssh.SSHSession.NestedSequential</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../../../../org/apache/tools/ant/TaskContainer.html" title="interface in org.apache.tools.ant">TaskContainer</A></DD>
</DL>
<DL>
<DT><B>Enclosing class:</B><DD><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.html" title="class in org.apache.tools.ant.taskdefs.optional.ssh">SSHSession</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public static class <B>SSHSession.NestedSequential</B><DT>extends java.lang.Object<DT>implements <A HREF="../../../../../../../org/apache/tools/ant/TaskContainer.html" title="interface in org.apache.tools.ant">TaskContainer</A></DL>
</PRE>
<P>
The class corresponding to the sequential nested element.
This is a simple task container.
<P>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.NestedSequential.html#SSHSession.NestedSequential()">SSHSession.NestedSequential</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.NestedSequential.html#addTask(org.apache.tools.ant.Task)">addTask</A></B>(<A HREF="../../../../../../../org/apache/tools/ant/Task.html" title="class in org.apache.tools.ant">Task</A> task)</CODE>
<BR>
Add a task or type to the container.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.util.List</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.NestedSequential.html#getNested()">getNested</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="SSHSession.NestedSequential()"><!-- --></A><H3>
SSHSession.NestedSequential</H3>
<PRE>
public <B>SSHSession.NestedSequential</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="addTask(org.apache.tools.ant.Task)"><!-- --></A><H3>
addTask</H3>
<PRE>
public void <B>addTask</B>(<A HREF="../../../../../../../org/apache/tools/ant/Task.html" title="class in org.apache.tools.ant">Task</A> task)</PRE>
<DL>
<DD>Add a task or type to the container.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../../../../org/apache/tools/ant/TaskContainer.html#addTask(org.apache.tools.ant.Task)">addTask</A></CODE> in interface <CODE><A HREF="../../../../../../../org/apache/tools/ant/TaskContainer.html" title="interface in org.apache.tools.ant">TaskContainer</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>task</CODE> - an unknown element.</DL>
</DD>
</DL>
<HR>
<A NAME="getNested()"><!-- --></A><H3>
getNested</H3>
<PRE>
public java.util.List <B>getNested</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>the list of unknown elements</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</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">
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.LocalTunnel.html" title="class in org.apache.tools.ant.taskdefs.optional.ssh"><B>PREV CLASS</B></A>
<A HREF="../../../../../../../org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.RemoteTunnel.html" title="class in org.apache.tools.ant.taskdefs.optional.ssh"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.NestedSequential.html" target="_top"><B>FRAMES</B></A>
<A HREF="SSHSession.NestedSequential.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "66866ad0cd24165a964bf86930d20144",
"timestamp": "",
"source": "github",
"line_count": 289,
"max_line_length": 320,
"avg_line_length": 42.28373702422145,
"alnum_prop": 0.6242225859247136,
"repo_name": "bownie/Brazil",
"id": "87b6efbf4d059181f202c3e3a5cef179cf956a4d",
"size": "12220",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "thirdparty/apache-ant-1.9.0/manual/api/org/apache/tools/ant/taskdefs/optional/ssh/SSHSession.NestedSequential.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "75637"
},
{
"name": "C#",
"bytes": "1793975"
},
{
"name": "FLUX",
"bytes": "8314"
},
{
"name": "Java",
"bytes": "21071"
}
],
"symlink_target": ""
} |
/**
* Tom Select v1.7.3
* Licensed under the Apache License, Version 2.0 (the "License");
*/
import TomSelect from '../../tom-select.js';
/**
* Converts a scalar to its best string representation
* for hash keys and HTML attribute values.
*
* Transformations:
* 'str' -> 'str'
* null -> ''
* undefined -> ''
* true -> '1'
* false -> '0'
* 0 -> '0'
* 1 -> '1'
*
*/
function hash_key(value) {
if (typeof value === 'undefined' || value === null) return null;
return get_hash(value);
}
function get_hash(value) {
if (typeof value === 'boolean') return value ? '1' : '0';
return value + '';
}
/**
* Prevent default
*
*/
function preventDefault(evt, stop = false) {
if (evt) {
evt.preventDefault();
if (stop) {
evt.stopPropagation();
}
}
}
/**
* Return a dom element from either a dom query string, jQuery object, a dom element or html string
* https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518
*
* param query should be {}
*/
function getDom(query) {
if (query.jquery) {
return query[0];
}
if (query instanceof HTMLElement) {
return query;
}
if (query.indexOf('<') > -1) {
let div = document.createElement('div');
div.innerHTML = query.trim(); // Never return a text node of whitespace as the result
return div.firstChild;
}
return document.querySelector(query);
}
/**
* Plugin: "restore_on_backspace" (Tom Select)
* Copyright (c) contributors
*
* 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.
*
*/
TomSelect.define('checkbox_options', function () {
var self = this;
var orig_onOptionSelect = self.onOptionSelect;
self.settings.hideSelected = false; // update the checkbox for an option
var UpdateCheckbox = function UpdateCheckbox(option) {
setTimeout(() => {
var checkbox = option.querySelector('input');
if (option.classList.contains('selected')) {
checkbox.checked = true;
} else {
checkbox.checked = false;
}
}, 1);
}; // add checkbox to option template
self.hook('after', 'setupTemplates', () => {
var orig_render_option = self.settings.render.option;
self.settings.render.option = function (data) {
var rendered = getDom(orig_render_option.apply(self, arguments));
var checkbox = document.createElement('input');
checkbox.addEventListener('click', function (evt) {
preventDefault(evt);
});
checkbox.type = 'checkbox';
const hashed = hash_key(data[self.settings.valueField]);
if (hashed && self.items.indexOf(hashed) > -1) {
checkbox.checked = true;
}
rendered.prepend(checkbox);
return rendered;
};
}); // uncheck when item removed
self.on('item_remove', value => {
var option = self.getOption(value);
if (option) {
// if dropdown hasn't been opened yet, the option won't exist
option.classList.remove('selected'); // selected class won't be removed yet
UpdateCheckbox(option);
}
}); // remove items when selected option is clicked
self.hook('instead', 'onOptionSelect', function (evt, option) {
if (option.classList.contains('selected')) {
option.classList.remove('selected');
self.removeItem(option.dataset.value);
self.refreshOptions();
preventDefault(evt, true);
return;
}
orig_onOptionSelect.apply(self, arguments);
UpdateCheckbox(option);
});
});
//# sourceMappingURL=plugin.js.map
| {
"content_hash": "f3bb80dcbc1649cc7ed5dd5ae04207ce",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 144,
"avg_line_length": 27.693877551020407,
"alnum_prop": 0.6457872758535986,
"repo_name": "cdnjs/cdnjs",
"id": "fac0c043bfdf9a88a7045e382faf6009e03a54df",
"size": "4071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/tom-select/1.7.3/esm/plugins/checkbox_options/plugin.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>projective-geometry: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / extra-dev</a></li>
<li class="active"><a href="">dev / projective-geometry - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
projective-geometry
<small>
8.7.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-10-27 02:59:51 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-10-27 02:59:51 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 3 Virtual package relying on a GMP lib system installation
coq dev Formal proof management system
dune 2.9.1 Fast, portable, and opinionated build system
ocaml 4.12.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.12.0 Official release 4.12.0
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.1 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/projective-geometry"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ProjectiveGeometry"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [
"keyword: geometry"
"keyword: projective"
"keyword: Fano"
"keyword: homogeneous coordinates model"
"keyword: flat"
"keyword: rank"
"keyword: Desargues"
"keyword: Moulton"
"category: Mathematics/Geometry/General"
"date: 2009-10"
]
authors: [ "Nicolas Magaud <Nicolas.Magaud@lsiit-cnrs.unistra.fr>" "Julien Narboux <Julien.Narboux@lsiit-cnrs.unistra.fr>" "Pascal Schreck <Pascal.Schreck@lsiit-cnrs.unistra.fr>" ]
bug-reports: "https://github.com/coq-contribs/projective-geometry/issues"
dev-repo: "git+https://github.com/coq-contribs/projective-geometry.git"
synopsis: "Projective Geometry"
description: """
This contributions contains elements of formalization of projective geometry.
In the plane:
Two axiom systems are shown equivalent. We prove some results about the
decidability of the the incidence and equality predicates. The classic
notion of duality between points and lines is formalized thanks to a
functor. The notion of 'flat' is defined and flats are characterized.
Fano's plane, the smallest projective plane is defined. We show that Fano's plane is desarguesian.
In the space:
We prove Desargues' theorem."""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/projective-geometry/archive/v8.7.0.tar.gz"
checksum: "md5=1dcd899580a116a0dfe1f650844352e4"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-projective-geometry.8.7.0 coq.dev</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is dev).
The following dependencies couldn't be met:
- coq-projective-geometry -> coq < 8.8~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-projective-geometry.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "535dc7ed0dc4f4238d20c502dd6414f7",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 228,
"avg_line_length": 42.95161290322581,
"alnum_prop": 0.5729127550381775,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "1e9f995634daf338baa5777daea0832ea55457b3",
"size": "7991",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.12.0-2.0.8/extra-dev/dev/projective-geometry/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionTabBarBase.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionTabBarBase (
QqStyleOptionTabBarBase(..)
,QqStyleOptionTabBarBase_nf(..)
,qselectedTabRect, selectedTabRect
,qsetSelectedTabRect, setSelectedTabRect
,qsetTabBarRect, setTabBarRect
,qtabBarRect, tabBarRect
,qStyleOptionTabBarBase_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QTabBar
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionTabBarBase x1 where
qStyleOptionTabBarBase :: x1 -> IO (QStyleOptionTabBarBase ())
instance QqStyleOptionTabBarBase (()) where
qStyleOptionTabBarBase ()
= withQStyleOptionTabBarBaseResult $
qtc_QStyleOptionTabBarBase
foreign import ccall "qtc_QStyleOptionTabBarBase" qtc_QStyleOptionTabBarBase :: IO (Ptr (TQStyleOptionTabBarBase ()))
instance QqStyleOptionTabBarBase ((QStyleOptionTabBarBase t1)) where
qStyleOptionTabBarBase (x1)
= withQStyleOptionTabBarBaseResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase1 cobj_x1
foreign import ccall "qtc_QStyleOptionTabBarBase1" qtc_QStyleOptionTabBarBase1 :: Ptr (TQStyleOptionTabBarBase t1) -> IO (Ptr (TQStyleOptionTabBarBase ()))
class QqStyleOptionTabBarBase_nf x1 where
qStyleOptionTabBarBase_nf :: x1 -> IO (QStyleOptionTabBarBase ())
instance QqStyleOptionTabBarBase_nf (()) where
qStyleOptionTabBarBase_nf ()
= withObjectRefResult $
qtc_QStyleOptionTabBarBase
instance QqStyleOptionTabBarBase_nf ((QStyleOptionTabBarBase t1)) where
qStyleOptionTabBarBase_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase1 cobj_x1
qselectedTabRect :: QStyleOptionTabBarBase a -> (()) -> IO (QRect ())
qselectedTabRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_selectedTabRect cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_selectedTabRect" qtc_QStyleOptionTabBarBase_selectedTabRect :: Ptr (TQStyleOptionTabBarBase a) -> IO (Ptr (TQRect ()))
selectedTabRect :: QStyleOptionTabBarBase a -> (()) -> IO (Rect)
selectedTabRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_selectedTabRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QStyleOptionTabBarBase_selectedTabRect_qth" qtc_QStyleOptionTabBarBase_selectedTabRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
qsetSelectedTabRect :: QStyleOptionTabBarBase a -> ((QRect t1)) -> IO ()
qsetSelectedTabRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase_setSelectedTabRect cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionTabBarBase_setSelectedTabRect" qtc_QStyleOptionTabBarBase_setSelectedTabRect :: Ptr (TQStyleOptionTabBarBase a) -> Ptr (TQRect t1) -> IO ()
setSelectedTabRect :: QStyleOptionTabBarBase a -> ((Rect)) -> IO ()
setSelectedTabRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStyleOptionTabBarBase_setSelectedTabRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QStyleOptionTabBarBase_setSelectedTabRect_qth" qtc_QStyleOptionTabBarBase_setSelectedTabRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetShape (QStyleOptionTabBarBase a) ((QTabBarShape)) where
setShape x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_setShape cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QStyleOptionTabBarBase_setShape" qtc_QStyleOptionTabBarBase_setShape :: Ptr (TQStyleOptionTabBarBase a) -> CLong -> IO ()
qsetTabBarRect :: QStyleOptionTabBarBase a -> ((QRect t1)) -> IO ()
qsetTabBarRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase_setTabBarRect cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionTabBarBase_setTabBarRect" qtc_QStyleOptionTabBarBase_setTabBarRect :: Ptr (TQStyleOptionTabBarBase a) -> Ptr (TQRect t1) -> IO ()
setTabBarRect :: QStyleOptionTabBarBase a -> ((Rect)) -> IO ()
setTabBarRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStyleOptionTabBarBase_setTabBarRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QStyleOptionTabBarBase_setTabBarRect_qth" qtc_QStyleOptionTabBarBase_setTabBarRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qshape (QStyleOptionTabBarBase a) (()) (IO (QTabBarShape)) where
shape x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_shape cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_shape" qtc_QStyleOptionTabBarBase_shape :: Ptr (TQStyleOptionTabBarBase a) -> IO CLong
qtabBarRect :: QStyleOptionTabBarBase a -> (()) -> IO (QRect ())
qtabBarRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_tabBarRect cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_tabBarRect" qtc_QStyleOptionTabBarBase_tabBarRect :: Ptr (TQStyleOptionTabBarBase a) -> IO (Ptr (TQRect ()))
tabBarRect :: QStyleOptionTabBarBase a -> (()) -> IO (Rect)
tabBarRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_tabBarRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QStyleOptionTabBarBase_tabBarRect_qth" qtc_QStyleOptionTabBarBase_tabBarRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
qStyleOptionTabBarBase_delete :: QStyleOptionTabBarBase a -> IO ()
qStyleOptionTabBarBase_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_delete cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_delete" qtc_QStyleOptionTabBarBase_delete :: Ptr (TQStyleOptionTabBarBase a) -> IO ()
| {
"content_hash": "b3429a81290392872515863c93006e38",
"timestamp": "",
"source": "github",
"line_count": 154,
"max_line_length": 208,
"avg_line_length": 43.48701298701299,
"alnum_prop": 0.7357025533821114,
"repo_name": "keera-studios/hsQt",
"id": "d0a66ff7f77583a920944a2743f88ad375979801",
"size": "6697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Qtc/Gui/QStyleOptionTabBarBase.hs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4327"
},
{
"name": "C",
"bytes": "2769338"
},
{
"name": "C++",
"bytes": "12337641"
},
{
"name": "Haskell",
"bytes": "18998024"
},
{
"name": "Perl",
"bytes": "28076"
},
{
"name": "Prolog",
"bytes": "527"
},
{
"name": "QMake",
"bytes": "4574"
},
{
"name": "Shell",
"bytes": "3752"
}
],
"symlink_target": ""
} |
<!DOCTYPE html >
<html>
<head>
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.dynamic.js" ></script>
<script src="../libraries/RGraph.common.key.js" ></script>
<script src="../libraries/RGraph.drawing.rect.js" ></script>
<script src="../libraries/RGraph.hbar.js" ></script>
<title>An example of a HBar chart with an interactive key</title>
<link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
<meta name="robots" content="noindex,nofollow" />
<meta name="description" content="An example of a HBar chart with an interactive key" />
</head>
<body>
<h1>An example of a HBar chart with an interactive key</h1>
<p>
The interactive key has been re-implemented as of June 2013 and added to more chart types.
</p>
<canvas id="cvs" width="600" height="550">[No canvas support]</canvas>
<script>
window.onload = function ()
{
var hbar = new RGraph.HBar({
id: 'cvs',
data: [[8,4,1],[4,8,8],[1,2,2],[3,3,4],[6,5,2],[5,8,8],[4,8,5]],
options: {
key: ['Jim','Jack','Joseph'],
keyInteractive: true,
labels: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
}
}).draw();
};
</script>
<p></p>
This goes in the documents header:
<pre class="code">
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.common.key.js"></script>
<script src="RGraph.drawing.rect.js"></script>
<script src="RGraph.hbar.js"></script>
</pre>
Put this where you want the chart to show up:
<pre class="code">
<canvas id="cvs" width="600" height="550">
[No canvas support]
</canvas>
</pre>
This is the code that generates the chart:
<pre class="code">
<script>
window.onload = function ()
{
var hbar = new RGraph.HBar({
id: 'cvs',
data: [[8,4,1],[4,8,8],[1,2,2],[3,3,4],[6,5,2],[5,8,8],[4,8,5]],
options: {
key: ['Jim','Jack','Joseph'],
keyInteractive: true,
labels: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
}
}).draw();
};
</script>
</pre>
<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>
<a href="./"><Back</a><br />
</body>
</html> | {
"content_hash": "267360927c6eb536b64a64012060c513",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 396,
"avg_line_length": 34.89473684210526,
"alnum_prop": 0.5734539969834087,
"repo_name": "LinkItONEDevGroup/LASS",
"id": "a7b3812d1f6c2f3ac5eadb236774ce361924e99d",
"size": "3315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IASS/IASS_BASIC/IASS_Server/html/RGraph/demos/hbar-interactive-key.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "9857"
},
{
"name": "C",
"bytes": "5326619"
},
{
"name": "C++",
"bytes": "2643352"
},
{
"name": "CMake",
"bytes": "5007"
},
{
"name": "CSS",
"bytes": "158490"
},
{
"name": "HTML",
"bytes": "1658027"
},
{
"name": "Hack",
"bytes": "5364"
},
{
"name": "Java",
"bytes": "16636"
},
{
"name": "JavaScript",
"bytes": "1970939"
},
{
"name": "Makefile",
"bytes": "908"
},
{
"name": "Objective-C",
"bytes": "24111"
},
{
"name": "PHP",
"bytes": "2973502"
},
{
"name": "Processing",
"bytes": "8909"
},
{
"name": "Python",
"bytes": "223297"
},
{
"name": "R",
"bytes": "915"
},
{
"name": "Ruby",
"bytes": "1230"
},
{
"name": "Shell",
"bytes": "12087"
},
{
"name": "TSQL",
"bytes": "4938"
}
],
"symlink_target": ""
} |
#include "BinaryDateTimeExpr.h"
#include<lang/log/LogLevel.h>
#include <commonlib/commonlib.h>
#include <lang/model/allmodel.h>
namespace IAS {
namespace Lang {
namespace Interpreter {
namespace Exe {
namespace Expr {
/*************************************************************************/
class BinaryDateTimeExprPlusDateTime : public BinaryDateTimeExpr {
public:
virtual ::IAS::DateTime evaluateDateTime(Context *pCtx) const{
IAS_TRACER;
return ::IAS::DateTime(ptrLeft->evaluateDateTime(pCtx) + ptrRight->evaluateDateTime(pCtx));
};
protected:
BinaryDateTimeExprPlusDateTime(Expr* pLeft, Expr* pRight):
BinaryDateTimeExpr(pLeft,pRight){}
friend class ::IAS::Factory<BinaryDateTimeExprPlusDateTime>;
};
/*************************************************************************/
class BinaryDateTimeExprMinusDateTime : public BinaryDateTimeExpr {
public:
virtual ::IAS::DateTime evaluateDateTime(Context *pCtx) const{
IAS_TRACER;
return ptrLeft->evaluateDateTime(pCtx) - ptrRight->evaluateDateTime(pCtx);
};
protected:
BinaryDateTimeExprMinusDateTime(Expr* pLeft, Expr* pRight):
BinaryDateTimeExpr(pLeft,pRight){}
friend class ::IAS::Factory<BinaryDateTimeExprMinusDateTime>;
};
/*************************************************************************/
BinaryDateTimeExpr::BinaryDateTimeExpr(Expr* pLeft, Expr* pRight):
BinaryExprFamily(pLeft,pRight){}
/*************************************************************************/
BinaryDateTimeExpr::~BinaryDateTimeExpr() throw(){
IAS_TRACER;
}
/*************************************************************************/
BinaryDateTimeExpr* BinaryDateTimeExpr::Create(Expr* pLeft, Expr* pRight, TypeInfoProxy aTypeInfoProxy){
IAS_TRACER;
IAS_DFT_FACTORY<BinaryDateTimeExpr>::PtrHolder ptrBinaryDateTimeExpr;
if(aTypeInfoProxy == &typeid(Model::Expr::AdditionNode)){
ptrBinaryDateTimeExpr = IAS_DFT_FACTORY<BinaryDateTimeExprPlusDateTime>::Create(pLeft,pRight);
}else if(aTypeInfoProxy == &typeid(Model::Expr::SubtractionNode)){
ptrBinaryDateTimeExpr = IAS_DFT_FACTORY<BinaryDateTimeExprMinusDateTime>::Create(pLeft,pRight);
}else{
IAS_THROW(InternalException(String("No operator for this node: ")+aTypeInfoProxy.ti->name()));
}
return ptrBinaryDateTimeExpr.pass();
}
/*************************************************************************/
}
}
}
}
}
| {
"content_hash": "e99558c17ca97c0fcc61d25e03fb93ce",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 104,
"avg_line_length": 33.2112676056338,
"alnum_prop": 0.6289228159457168,
"repo_name": "InvenireAude/IAS-Base-OSS",
"id": "d893fa7b4b1698315cd79199aad6beaadf5c6c55",
"size": "3040",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IAS-LangLib/src/lang/interpreter/exe/expr/BinaryDateTimeExpr.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "20541"
},
{
"name": "C++",
"bytes": "5910026"
},
{
"name": "Makefile",
"bytes": "29521"
},
{
"name": "Shell",
"bytes": "31721"
},
{
"name": "Yacc",
"bytes": "144670"
}
],
"symlink_target": ""
} |
<?php
class Model_login extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function login()
{
$user = $this->input->post('username');
$pw = $this->input->post('password');
$sql = "SELECT * FROM kasutaja WHERE username = ?;";
$query = $this->db->query($sql,array($user));
if($query->num_rows()!=1)
return false;
$result = $query->result();
if($result[0]->Password == md5($pw))
{
$result[0]->Password="";
$this->session->set_userdata('user',$result[0]);
return true;
}
echo "Wrong credentials";
return false;
}
}
?> | {
"content_hash": "d9fff53fb9714cd6d01f9cebfc88b7d5",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 54,
"avg_line_length": 21.379310344827587,
"alnum_prop": 0.5693548387096774,
"repo_name": "triint/valimised",
"id": "7ad20298fcf4eb2ac828916e32aab9b73be49173",
"size": "620",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/Model_login.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "2065"
},
{
"name": "HTML",
"bytes": "6049"
},
{
"name": "PHP",
"bytes": "1756560"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/compiler-notes.qdoc -->
<head>
<title>Qt 4.3: Compiler Notes</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Compiler Notes<br /><small></small></h1>
<p>This page contains information about the C++ compilers and tools used to build Qt on various platforms.</p>
<ul><li><a href="#gcc-most-platforms">GCC (most platforms)</a></li>
<ul><li><a href="#gcc-on-windows-mingw">GCC on Windows (MinGW)</a></li>
<li><a href="#gcc-4-0-0">gcc 4.0.0</a></li>
<li><a href="#hp-ux">HP-UX</a></li>
<li><a href="#solaris">Solaris</a></li>
<li><a href="#mac-os-x">Mac OS X</a></li>
<li><a href="#gcc-gcc-3-4-6-debian-3-4-6-5-on-amd64-x86-64">gcc (GCC) 3.4.6 (Debian 3.4.6-5) on AMD64 (x86_64)</a></li>
</ul>
<li><a href="#hp-ansi-c-acc">HP ANSI C++ (aCC)</a></li>
<li><a href="#intel-c-compiler">Intel C++ Compiler</a></li>
<ul><li><a href="#intel-c-compiler-for-linux">Intel C++ Compiler for Linux</a></li>
<li><a href="#known-issues-with-intel-c-compiler-for-linux">Known issues with Intel C++ Compiler for Linux</a></li>
<li><a href="#intel-c-compiler-windows-altix">Intel C++ Compiler (Windows, Altix)</a></li>
</ul>
<li><a href="#mipspro-irix">MIPSpro (IRIX)</a></li>
<li><a href="#forte-developer-sun-studio-solaris">Forte Developer / Sun Studio (Solaris)</a></li>
<ul><li><a href="#sun-studio">Sun Studio</a></li>
<li><a href="#sun-workshop-5-0">Sun WorkShop 5.0</a></li>
</ul>
<li><a href="#visual-studio-windows">Visual Studio (Windows)</a></li>
<li><a href="#ibm-xlc-aix">IBM xlC (AIX)</a></li>
<ul><li><a href="#visualage-c-for-aix-version-6-0">VisualAge C++ for AIX, Version 6.0</a></li>
</ul>
</ul>
<p>Please refer to the <a href="platform-notes-platforms.html">Platform Notes</a> for information on the platforms Qt is currently known to run on.</p>
<p>If you have anything to add to this list or any of the platform or compiler-specific pages, please submit it via the <a href="http://www.trolltech.com/developer/notes/platforms/bugreport-form">Bug Report Form</a>.</p>
<a name="gcc"></a><a name="gcc-most-platforms"></a>
<h3>GCC (most platforms)</h3>
<p>Trolltech supports building Qt with gcc 3.2 and later. Older versions of gcc are not recommended and not supported by Trolltech. They might or might not work.</p>
<a name="gcc-on-windows-mingw"></a>
<h4>GCC on Windows (MinGW)</h4>
<p>We have tested Qt with this compiler on Windows 2000 and Windows XP. The minimal version of MinGW supported is:</p>
<ul>
<li>gcc 3.4.2</li>
<li>mingw runtime 3.7</li>
<li>win32api 3.2</li>
<li>binutils 2.15.91</li>
<li>mingw32-make 3.80.0-3</li>
</ul>
<a name="gcc-4-0-0"></a>
<h4>gcc 4.0.0</h4>
<p>The released package of the compiler has some bugs that lead to miscompilations. We recommend using gcc 4.0.1 or later, or to use a recent CVS snapshot of the gcc 4.0 branch. The version of gcc 4.0.0 that is shipped with Mac OS X 10.4 "Tiger" is known to work with Qt/Mac.</p>
<a name="hp-ux"></a>
<h4>HP-UX</h4>
<p>The hpux-g++ platform is tested with gcc 3.4.3.</p>
<a name="solaris"></a>
<h4>Solaris</h4>
<p>Please use gcc 3.3.0 or better.</p>
<a name="mac-os-x"></a>
<h4>Mac OS X</h4>
<p>Please use the latest gcc 3.3 from Apple or better. The gcc 3.3 that is provided with Xcode 1.5 is known to generate bad code, use the November 2004 GCC 3.3 updater <a href="http://connect.apple.com">available from Apple</a>.</p>
<a name="gcc-gcc-3-4-6-debian-3-4-6-5-on-amd64-x86-64"></a>
<h4>gcc (GCC) 3.4.6 (Debian 3.4.6-5) on AMD64 (x86_64)</h4>
<p>This compiler is known to miscompile some parts of Qt when doing a release build. There are several workarounds:</p>
<ol type="1">
<li>Use a debug build instead.</li>
<li>For each miscompilation encountered, recompile the file, removing the -O2 option.</li>
<li>Add -fno-gcse to the <a href="qmake-variable-reference.html#qmake-cxxflags-release">QMAKE_CXXFLAGS_RELEASE</a>.</li>
</ol>
<a name="hp-ansi-c-acc"></a>
<h3>HP ANSI C++ (aCC)</h3>
<p>The hpux-acc-32 and hpux-acc-64 platforms are tested with aCC A.03.57. The hpuxi-acc-32 and hpuxi-acc-64 platforms are tested with aCC A.06.12.</p>
<a name="intel-c-compiler"></a>
<h3>Intel C++ Compiler</h3>
<a name="intel-c-compiler-for-linux"></a>
<h4>Intel C++ Compiler for Linux</h4>
<p>Trolltech currently tests the following compilers:</p>
<ul>
<li>Intel(R) C++ Compiler for applications running on IA-32, Version 10.1 Build 20080112 Package ID: l_cc_p_10.1.012</li>
<li>Intel(R) C++ Compiler for applications running on Intel(R) 64, Version 10.1 Build 20080112 Package ID: l_cc_p_10.1.012</li>
</ul>
<a name="known-issues-with-intel-c-compiler-for-linux"></a>
<h4>Known issues with Intel C++ Compiler for Linux</h4>
<ul>
<li>Precompiled header support does not work prior in version 10.0.025 and older. For these compilers, you should configure Qt with -no-pch. Precompiled header support works properly in version 10.0.026.</li>
<li>Version 10.0.026 for Intel 64 is known to miscompile qmake when building in release mode. For now, configure Qt with -debug. Version 10.1.008 and later can compile qmake in release mode.</li>
<li>Versions 10.1.008, 10.1.011, and 10.1.012 for both IA-32 and Intel 64 is known crash with "(0): internal error: 0_47021" when compiling Designer in release mode. For now, configure Qt with -debug. This issue has been reported to Intel and is awaiting resolution.</li>
</ul>
<a name="intel-c-compiler-windows-altix"></a>
<h4>Intel C++ Compiler (Windows, Altix)</h4>
<p>Qt 4 has been tested successfully with:</p>
<ul>
<li>Windows - Intel(R) C++ Compiler for 32-bit applications, Version 8.1 Build 20050309Z Package ID: W_CC_PC_8.1.026</li>
<li>Altix - Intel(R) C++ Itanium(R) Compiler for Itanium(R)-based applications Version 8.1 Build 20050406 Package ID: l_cc_pc_8.1.030</li>
</ul>
<p>We currently only test the Intel compiler on 32-bit Windows versions.</p>
<a name="mipspro-irix"></a>
<h3>MIPSpro (IRIX)</h3>
<p>Qt 4.x requires MIPSpro version 7.4.2m.</p>
<p>Note that MIPSpro version 7.4.4m is currently not supported, since it has introduced a number of problems that have not yet been resolved. We recommend using 7.4.2m for Qt development.</p>
<a name="sun-studio"></a><a name="forte-developer-sun-studio-solaris"></a>
<h3>Forte Developer / Sun Studio (Solaris)</h3>
<a name="sun-studio"></a>
<h4>Sun Studio</h4>
<p>Qt is tested using Sun Studio 9 and Sun Studio 10. Go to <a href="http://developers.sun.com/prodtech/cc/downloads/patches/index.html">Sun's website</a> to download the latest patches for your Sun compiler.</p>
<a name="sun-workshop-5-0"></a>
<h4>Sun WorkShop 5.0</h4>
<p>Sun WorkShop 5.0 is not supported with Qt 4.</p>
<a name="visual-studio-windows"></a>
<h3>Visual Studio (Windows)</h3>
<p>We do most of our Windows development on Windows XP, using Microsoft Visual Studio .NET 2003 and Visual Studio 2005 (both the 32- and 64-bit versions).</p>
<p>Qt works with the Standard Edition, the Professional Edition and Team System Edition of Visual Studio 2005.</p>
<p>We also test Qt 4 on Windows 98/Me, Windows NT and Windows 2000, with Microsoft Visual C++ 6.0 and Visual Studio .NET.</p>
<p>In order to use Qt with the Visual Studio 2005 Express Edition you need to download and install the platform SDK. Due to limitations in the Express Edition it is not possible for us to install the Qt Visual Studio Integration. You will need to use our command line tools to build Qt applications with this edition.</p>
<p>The Visual C++ Linker doesn't understand filenames with spaces (as in <tt>C:\Program files\Qt\</tt>) so you will have to move it to another place, or explicitly set the path yourself; for example:</p>
<pre> QTDIR=C:\Progra~1\Qt</pre>
<p>Visual C++ 6.0 requires Service Pack 5 to work correctly with Qt. If you are using Visual C++ version 6.0 we highly recommend that you update to SP5.</p>
<p>If you are experiencing strange problems with using special flags that modify the alignment of structure and union members (such as <tt>/Zp2</tt>) then you will need to recompile Qt with the flags set for the application as well.</p>
<p>If you're using Visual Studio .NET Standard Edition, you should be using the Qt binary package provided, and not the source package. As the Standard Edition does not optimize compiled code, your compiled version of Qt would perform suboptimally with respect to speed.</p>
<p>With Visual Studio 2005 Service Pack 1 a bug was introduced which causes Qt not to compile, this has been fixed with a hotfix available from Microsoft. See this <a href="http://www.trolltech.com/developer/knowledgebase/faq.2006-12-18.3281869860">Knowledge Base entry</a> for more information.</p>
<a name="xlc"></a><a name="ibm-xlc-aix"></a>
<h3>IBM xlC (AIX)</h3>
<p>The makeC++SharedLib utility must be in your PATH and be up to date to build shared libraries. From IBM's <a href="http://www.redbooks.ibm.com/abstracts/sg245674.html">C and C++ Application Development on AIX</a> Redbook:</p>
<ul>
<li>"The second step is to use the makeC++SharedLib command to create the shared object. The command has many optional arguments, but in its simplest form, can be used as follows:"<pre> /usr/vacpp/bin/makeC++SharedLib -o shr1.o cplussource1.o</pre>
</li>
<li>"The full path name to the command is not required; however, to avoid this, you will have to add the directory in which it is located to your PATH environment variable. The command is located in the /usr/vacpp/bin directory with the VisualAge C++ Professional for AIX, Version 5 compiler."</li>
</ul>
<a name="visualage-c-for-aix-version-6-0"></a>
<h4>VisualAge C++ for AIX, Version 6.0</h4>
<p>Make sure you have the <a href="http://www-1.ibm.com/support/search.wss?rs=32&tc=SSEP5D&dc=D400">latest upgrades</a> installed.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright © 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
| {
"content_hash": "c9c7dec952e563fb43eda2a29c0d6983",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 562,
"avg_line_length": 79.9375,
"alnum_prop": 0.708105290591608,
"repo_name": "misizeji/StudyNote_201308",
"id": "b203e30127153ae7e6daf1cd3b119c7bb3eee37a",
"size": "11511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webserver/html/compiler-notes.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "24904"
},
{
"name": "Batchfile",
"bytes": "344"
},
{
"name": "C",
"bytes": "38209826"
},
{
"name": "C++",
"bytes": "52779448"
},
{
"name": "CSS",
"bytes": "10599"
},
{
"name": "HTML",
"bytes": "38756865"
},
{
"name": "JavaScript",
"bytes": "11538"
},
{
"name": "Makefile",
"bytes": "160624"
},
{
"name": "QMake",
"bytes": "20539"
},
{
"name": "Shell",
"bytes": "6618"
}
],
"symlink_target": ""
} |
<!-- Binding configuration for the Heatmiser binding in openHAB -->
<binding>
<!-- Full name presented to the user -->
<name>Heatmiser network thermostats</name>
<!-- PID name used within the OSGi layer -->
<pid>heatmiser</pid>
<!-- Binding type: protocol, ui -->
<type>protocol</type>
<!-- Author -->
<author>Chris Jackson</author>
<!-- Current version of the binding to which the file is applicable -->
<version>1.3.0</version>
<!-- Minimum version of openHAB required to run this binding -->
<oh_version>1.3.0</oh_version>
<!-- Binding configuration settings -->
<binding.config>
<config.setting>
<name>refresh</name>
<label>Refresh Time</label>
<description>Set the refresh time in milliseconds.</description>
<optional>true</optional>
<defaultvalue>5000</defaultvalue>
<minimum>250</minimum>
<maximum>20000</maximum>
<values></values>
</config.setting>
</binding.config>
<!-- The following lines specify the communications interface settings. These may be repeated multiple times -->
<binding.interface>
<interface.setting>
<name>host</name>
<label>IP Address</label>
<description>Set the IP address of the interface.</description>
<optional>false</optional>
<defaultvalue></defaultvalue>
<minimum></minimum>
<maximum></maximum>
<values></values>
</interface.setting>
<interface.setting>
<name>port</name>
<label>IP Port</label>
<description>Set the IP Port number of the interface.</description>
<optional>true</optional>
<defaultvalue>1024</defaultvalue>
<minimum>1</minimum>
<maximum>65535</maximum>
<values></values>
</interface.setting>
</binding.interface>
<!-- Item binding configuration -->
<binding.items>
<binding.io>
<type>Input</type>
<description></description>
<parameters>
<parameter>
<name>interface</name>
<label>Communications Interface</label>
<description>Set the symbolic name of the communication interface.</description>
<optional>false</optional>
<defaultvalue></defaultvalue>
<minimum></minimum>
<maximum></maximum>
<values></values>
</parameter>
</parameters>
</binding.io>
</binding.items>
</binding>
| {
"content_hash": "3ae905d0add67f51a1a7f6281afa7a6c",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 116,
"avg_line_length": 37.15068493150685,
"alnum_prop": 0.556047197640118,
"repo_name": "automatizamos/RaspiOpenhab1",
"id": "7f6f18578bcbd74d7dd35fd1b9e6d0f3aff78e60",
"size": "2712",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "openhab/webapps/habmin/openhab/heatmiser.xml",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "23910"
},
{
"name": "CSS",
"bytes": "1250653"
},
{
"name": "Groff",
"bytes": "178"
},
{
"name": "HTML",
"bytes": "95628"
},
{
"name": "JavaScript",
"bytes": "6153216"
},
{
"name": "Perl",
"bytes": "9844"
},
{
"name": "Python",
"bytes": "3299"
},
{
"name": "Shell",
"bytes": "18377"
},
{
"name": "XSLT",
"bytes": "223304"
}
],
"symlink_target": ""
} |
use strict;
use warnings;
use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::Utils::SqlHelper;
use Getopt::Long;
use IO::Compress::Gzip qw(gzip $GzipError);
use Pod::Usage;
use Text::CSV;
my $OPTIONS = options();
my $DBA = _dba();
write_tsv();
compress();
sub options {
my $opts = {};
my @flags = qw(reg_conf=s database=s file=s overwrite gzip help man);
GetOptions($opts, @flags) or pod2usage(1);
_exit( undef, 0, 1) if $opts->{help};
_exit( undef, 0, 2) if $opts->{man};
_exit('No -database given', 1, 1) unless $opts->{database};
_exit('No -reg_conf given', 1, 1) unless $opts->{reg_conf};
_exit('No -file given', 1, 1) unless $opts->{file};
return $opts;
}
sub write_tsv {
my $file = $OPTIONS->{file};
_file($file);
open my $fh, '>', $file or confess("Cannot open $file for writing: $!");
my $tsv = Text::CSV->new({sep_char => "\t", eol => "\n"});
$tsv->print($fh, [qw(GeneTreeStableID EnsPeptideStableID EnsGeneStableID Canonical)]);
my $sql = <<'SQL';
SELECT
gtr.stable_id AS GeneTreeStableID,
gm.stable_id AS EnsGeneStableID,
pm.stable_id AS EnsPeptideStableID,
CASE m.member_id WHEN pm.member_id THEN 'Y' ELSE 'N' END AS Canonical
FROM
gene_tree_root gtr
JOIN gene_tree_node gtn ON (gtr.root_id=gtn.root_id)
JOIN member m ON (gtn.member_id=m.member_id)
JOIN member gm ON (m.gene_member_id=gm.member_id)
JOIN member pm ON (gm.member_id=pm.gene_member_id)
SQL
my $helper = Bio::EnsEMBL::Utils::SqlHelper->new(-DB_CONNECTION => $DBA->dbc());
$helper->execute_no_return(
-SQL => $sql,
-CALLBACK => sub {
my ($row) = @_;
$tsv->print($fh, $row);
return;
}
);
close($fh);
return;
}
sub compress {
return unless $OPTIONS->{gzip};
my $file = $OPTIONS->{file};
my $file_gz = $file.'.gz';
_file($file_gz);
my $status = gzip $file => $file_gz, AutoClose => 1
or die "gzip failed: $GzipError\n";
unlink $file;
return;
}
sub _dba {
my $registry = $OPTIONS->{reg_conf};
Bio::EnsEMBL::Registry->load_all($registry);
my $name = $OPTIONS->{database};
my $dba = Bio::EnsEMBL::Registry->get_DBAdaptor($name, 'compara');
_exit("No database adaptor found for ${name}. Check your settings and try again")
unless defined $dba;
return $dba;
}
sub _file {
my ($file) = @_;
if(-f $file) {
if($OPTIONS->{overwrite}) {
unlink $file;
}
else {
_exit("File already exists at ${file}. Remove before proceeeding", 2, 1);
}
}
return;
}
sub _exit {
my ($msg, $status, $verbose) = @_;
print STDERR $msg, "\n" if defined $msg;
pod2usage( -exitstatus => $status, -verbose => $verbose );
}
__END__
=pod
=head1 NAME
DumpGeneTreeIdToGenePepIds
=head1 SYNOPSIS
./DumpGeneTreeIdToGenePepIds.pl -reg_conf REG -database DB -file FILE [-gzip] [-overwrite] [ --help | --man ]
=head1 DESCRIPTION
=head1 OPTIONS
=over 8
=item B<--reg_conf>
Registry file to use
=item B<--database>
The database reference to use
=item B<--file>
File to write to. Will create gzipped version with .gz added
=item B<--overwrite>
If specified the script will remove any existing file
=item B<--gzip>
If specified will force the code to GZip the produced file and will
remove the uncompressed dump
=back
=cut
| {
"content_hash": "28bfc77aad08bef8fb55b4e3bbbd42cd",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 110,
"avg_line_length": 21.75496688741722,
"alnum_prop": 0.6280060882800609,
"repo_name": "dbolser-ebi/ensembl-compara",
"id": "8122705dbff5bc46cb35d442a748ed862fca2dd2",
"size": "3960",
"binary": false,
"copies": "1",
"ref": "refs/heads/release/75",
"path": "scripts/dumps/DumpGeneTreeIdToGenePepIds.pl",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "12586"
},
{
"name": "Perl",
"bytes": "5317199"
},
{
"name": "Shell",
"bytes": "6045"
},
{
"name": "Tcl",
"bytes": "2577"
}
],
"symlink_target": ""
} |
- First get an instance of oddworks up and running on your local machine: https://github.com/oddnetworks/oddworks (don't worry, it's easy!)
- Make sure your Roku is set up for development: https://blog.roku.com/developer/2016/02/04/developer-setup-guide/ Take note of your device password, you will need it later
- Create a copy this file: ```dev/targets/nasa/config/app_config.sample.json``` in the same folder
- Rename the copy to ```app_config.json```
- Add your roku x-access-token (found in the logs where you are running oddworks) to 'deviceAccessToken' and change the 'odd_service_endpoint' to your computer's IP address
#####2) Install using makefile:
```
> make install APPNAME=nasa ROKU_DEV_TARGET=roku_device_ip_address_here
```
You will be prompted for a password, enter your password from when you set up your Roku for development
To access the logs for debugging:
```
> telnet device_ip_address 8085
```
#####Screenshots and Manual build upload:
Open a browser and navigate to your Roku's ip address. Username: rokudev, Password: your_rokudev_password
### Deep Linking
####Param names for request from deep link:
- videos & livestreams: contentID=content_id_here&mediaType=video/livestream_here
- videoCollections: mediaType=videoCollections&collectionID=collection_id_here
- video inside a video collection: contentID=content_id_here&mediaType=videoCollections&collectionID=collection_id_here
Local Deeplink to a video example:
```
curl -d '' "http://your_roku_ip_here:8060/launch/dev?contentID=your_content_id_here&mediaType=videos"
```
Notes:
- *media types have an 's' at the end unless a livestream*
- *Deep link content shown before home page, when user backs out, home page loads*
| {
"content_hash": "e45556d8046093955917003d17b2e90d",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 172,
"avg_line_length": 48.82857142857143,
"alnum_prop": 0.7641895845523698,
"repo_name": "oddnetworks/odd-sample-apps",
"id": "49bf8b257190262af4d1ec5a44021d8398031789",
"size": "1810",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "roku/brightscript/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Brightscript",
"bytes": "121528"
},
{
"name": "Java",
"bytes": "100166"
},
{
"name": "Makefile",
"bytes": "9479"
},
{
"name": "Objective-C",
"bytes": "55418"
},
{
"name": "Swift",
"bytes": "168934"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import getopt
import os
import sys
import subprocess
VERSION = "pilprint 0.3/2003-05-05"
from PIL import Image
from PIL import PSDraw
letter = (1.0*72, 1.0*72, 7.5*72, 10.0*72)
def description(filepath, image):
title = os.path.splitext(os.path.split(filepath)[1])[0]
format = " (%dx%d "
if image.format:
format = " (" + image.format + " %dx%d "
return title + format % image.size + image.mode + ")"
if len(sys.argv) == 1:
print("PIL Print 0.3/2003-05-05 -- print image files")
print("Usage: pilprint files...")
print("Options:")
print(" -c colour printer (default is monochrome)")
print(" -d debug (show available drivers)")
print(" -p print via lpr (default is stdout)")
print(" -P <printer> same as -p but use given printer")
sys.exit(1)
try:
opt, argv = getopt.getopt(sys.argv[1:], "cdpP:")
except getopt.error as v:
print(v)
sys.exit(1)
printerArgs = [] # print to stdout
monochrome = 1 # reduce file size for most common case
for o, a in opt:
if o == "-d":
# debug: show available drivers
Image.init()
print(Image.ID)
sys.exit(1)
elif o == "-c":
# colour printer
monochrome = 0
elif o == "-p":
# default printer channel
printerArgs = ["lpr"]
elif o == "-P":
# printer channel
printerArgs = ["lpr", "-P%s" % a]
for filepath in argv:
try:
im = Image.open(filepath)
title = description(filepath, im)
if monochrome and im.mode not in ["1", "L"]:
im.draft("L", im.size)
im = im.convert("L")
if printerArgs:
p = subprocess.Popen(printerArgs, stdin=subprocess.PIPE)
fp = p.stdin
else:
fp = sys.stdout
ps = PSDraw.PSDraw(fp)
ps.begin_document()
ps.setfont("Helvetica-Narrow-Bold", 18)
ps.text((letter[0], letter[3]+24), title)
ps.setfont("Helvetica-Narrow-Bold", 8)
ps.text((letter[0], letter[1]-30), VERSION)
ps.image(letter, im)
ps.end_document()
if printerArgs:
fp.close()
except:
print("cannot print image", end=' ')
print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
| {
"content_hash": "7a1ea785488555c05613e354cfe53b19",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 68,
"avg_line_length": 26.359550561797754,
"alnum_prop": 0.5541346973572038,
"repo_name": "wuga214/Django-Wuga",
"id": "bfd66ab26c511e777135f5dfebe6a877dc69ec4a",
"size": "2633",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "env/bin/pilprint.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "119"
},
{
"name": "HTML",
"bytes": "15714"
},
{
"name": "Python",
"bytes": "29472"
}
],
"symlink_target": ""
} |
Run tests on each *distinct* tree in a revision list, skipping versions whose
contents have already been tested.
The 99% example is simply:
git test -v
By default it uses heuristics to try to determine what "local commits" to
test, but you can supply another ref spec. `git-test` looks at each commit and
checks the hash of the directory tree against the cache. You can also configure
a ref (usually a branch) to test against, per repo or or per branch.
From the point of view of `git-test`, a test can be any shell command and a
test is considered successful if that shell command returns with a `0` exit
status. This means `git-test` can be used both for specialised tests of a
single feature or failure mode or for running a comprehensive set of automated
tests. The cache is keyed on both directory tree and test, so it won't confuse
the unit tests with the integration tests, or a specific regression test.
## Motivation
An important design goal for `git-test` has been to make it convenient to use.
Ideally, you should have a work flow where you run your unit tests whenever
you save and run unit tests on all your local commits whenever you've done
something with version control.
For ease, `git-test` offers a few advantages over a simple for loop over a
`git rev-list`:
- By default it spends some effort on working out which commits to test.
- Cached results, which are keyed to tree contents, rather than commit. This
means that commits can be amended or reordered, but only content trees that
have never been tested before will be tested.
- Separate pre- and post-action hooks, the results of which don't actually
factor into the test result. (Useful if cleaning fails if there is nothing
to clean, for instance.)
- Configuration of housekeeping and verification steps using
- `git config`,
- environment variables or
- command line arguments
- Selective redo, for where you trust failures but not successes, vice versa,
or trust nothing.
- Save output (both `STDOUT` and `STDERR`) from cleaning and verifying to
an easily referenced symlink farm.
## Configure
Mostly just this:
git config test.verify "test command that returns nonzero on fail"
to default to testing against origin/master:
git config test.branch origin/master
to do the same, but for a single branch:
git config branch.mybranch.test parentbranch
## Self-Test
To try the test script with different shells:
for sh in /bin/dash /bin/bash /bin/ksh /bin/mksh /bin/pdksh; do
echo $sh
sh test.sh -s $sh
done
Note that since version 1.0.2, the shebang is set to `/bin/bash`. Other shells
are now supported on a "patches welcome" basis. (This is largely because I
couldn't find a shell I could run in my GNU/Linux environment that behaves
like the OS X (FreeBSD?) `sh` shell, which has very different behaviour from
all the others.)
To regression test properly:
rev=$(git rev-parse --short HEAD)
cp test.sh regressions_${rev}.sh
GIT_TEST_VERIFY="sh regressions_${rev}.sh" git test -v
(The reason for copying the script is to test each commit against the new
tests, and the reason for naming it based on the current commit is to key the
cache correctly.)
## Installation
You can just have the `git-test` script in your `PATH`, but there are other
options:
### Homebrew (on OS X)
If you have [Homebrew](http://brew.sh) installed, you can install
`git-test` with:
$ brew install git-test
### From source
Aside from the packaging, you can also install from source. It's a single
POSIX shell script that uses core git, so all that's required for plain `git
test` to work (besides git, of course) is that `git-test` needs to be
somewhere in your `PATH` (or `GIT_EXEC_PATH`).
You can install from source by doing the following:
$ install git-test /usr/local/bin
$ install git-test.1 /usr/local/share/man1
Or just add this directory to your `PATH` environment variable.
### Debian GNU/Linux
The usual
$ fakeroot debian/rules binary
Should give you a Debian package.
### Arch Linux
With Arch Linux, you can use the provided `PKGBUILD` file. Simply download the
file and run `makepkg` in the same directory as the file. It will always build
the latest `git` version of this package, even if you have an old checkout.
| {
"content_hash": "e4312fb923b4a120c035a5ab03a400c2",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 79,
"avg_line_length": 33.968503937007874,
"alnum_prop": 0.7461752433936022,
"repo_name": "spotify/git-test",
"id": "09bcfd172f64cb3cb1a5b1e4e3005a9ee749188f",
"size": "4347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Roff",
"bytes": "5840"
},
{
"name": "Shell",
"bytes": "25720"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>lazy-pcf: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.0 / lazy-pcf - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
lazy-pcf
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-24 00:13:48 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-24 00:13:48 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.07.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.07.1 Official release 4.07.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "http://www.cs.bell-labs.com/~felty/abstracts/ppcoq.html"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/lazyPCF"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: functional programming"
"keyword: lazy evaluation"
"keyword: operational semantics"
"keyword: type soundness"
"keyword: normal forms"
"category: Computer Science/Lambda Calculi"
]
authors: [
"Amy Felty"
"Jill Seaman"
]
bug-reports: "https://github.com/coq-contribs/lazy-pcf/issues"
dev-repo: "git+https://github.com/coq-contribs/lazy-pcf.git"
synopsis: "Subject Reduction for Lazy-PCF"
description: """
An Operational Semantics of Lazy Evaluation and a Proof
of Subject Reduction"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/lazy-pcf/archive/v8.10.0.tar.gz"
checksum: "md5=a6021c336b12ce49e81b08164bbe01bc"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-lazy-pcf.8.10.0 coq.8.7.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.0).
The following dependencies couldn't be met:
- coq-lazy-pcf -> coq >= 8.10
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-lazy-pcf.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "a7710fd9030e7377890b7b2663d9e410",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 159,
"avg_line_length": 39.73714285714286,
"alnum_prop": 0.5422778257118205,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "935d92771801efb3a922a6c4729d6fa9beef3f50",
"size": "6979",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.7.0/lazy-pcf/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
FOUNDATION_EXPORT double Pods_BannerViewExampleVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_BannerViewExampleVersionString[];
| {
"content_hash": "f33415d5a3c0761c76cea7ada926686f",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 76,
"avg_line_length": 46.666666666666664,
"alnum_prop": 0.8785714285714286,
"repo_name": "MagicLab-team/BannerView",
"id": "5f6bd448480120fcbabcf3d2fbf126bc15577fb7",
"size": "336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pods/Target Support Files/Pods-BannerViewExample/Pods-BannerViewExample-umbrella.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "503"
},
{
"name": "Ruby",
"bytes": "979"
},
{
"name": "Swift",
"bytes": "33431"
}
],
"symlink_target": ""
} |
Docker
======
Development environment has:
* stego-php: official [PHP 5.6 Docker](https://hub.docker.com/_/php/), [OpenSSH](https://www.openssh.com/), [Composer](https://getcomposer.org/)
Pre installation
----------------
Before start please be sure that was installed:
1. [Docker](https://docs.docker.com/engine/installation/)
2. [Compose](https://docs.docker.com/compose/install/)
Installation
------------
1. Set environment variable `HOST_IP` with your host machine IP, e.g. `export host_ip=192.168.0.104`
2. Run in application root `sudo docker-compose -f dev/docker/docker-compose.yml up`
3. Check containers `sudo docker-compose ps`
Containers
----------
### stego-php
#### SSH
SSH credentials:
1. user: `root`
2. password: `screencast`
3. ip: 0.0.0.0
4. port: 2231
To make connection via console simple run `ssh root@0.0.0.0 -p 2231`.
Usefull commands
----------------
* go to shell inside container `sudo docker-compose -f ./dev/docker/docker-compose.yml exec {{container-name}} bash`
* build container `sudo docker-compose -f ./dev/docker/docker-compose.yml build {{container-name}}`
* build container without caching `sudo docker-compose -f ./dev/docker/docker-compose.yml build --no-cache {{container-name}}`
_Note_: please substitute `{{container-name}}` by `stego-php`.
For more information please visit [Docker Compose Command-line Reference](https://docs.docker.com/compose/reference/).
Configuration IDE (PhpStorm)
----------------------------
### Remote interpreter
1. Use ssh connection to set php interpreter
2. PHP executable `/usr/local/bin/php`
3. Set "Path mappings": `host machine project root->/SteganographyKit`
More information is [here](https://confluence.jetbrains.com/display/PhpStorm/Working+with+Remote+PHP+Interpreters+in+PhpStorm).
### UnitTests
1. Configure UnitTest using remote interpreter.
2. Choose "Use custom autoload"
3. Set "Path to script": `/SteganographyKit/vendor/autoload.php`
4. Set "Default configuration file": `/SteganographyKit/dev/tests/phpunit.xml.dist`
More information is [here](https://confluence.jetbrains.com/display/PhpStorm/Running+PHPUnit+tests+over+SSH+on+a+remote+server+with+PhpStorm).
| {
"content_hash": "d57bab53b934fbf488f4e68c512f5615",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 144,
"avg_line_length": 35.04838709677419,
"alnum_prop": 0.7202024850437183,
"repo_name": "picamator/SteganographyKit",
"id": "55d86af9c09c35bb0ba8a70b9748e35ae50278c7",
"size": "2173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/docker/README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "84802"
},
{
"name": "Shell",
"bytes": "69"
}
],
"symlink_target": ""
} |
Matrix library
==============
This library provides simple matrix data structures and
associated operations. For ease of use, certain matrix
sizes have specialized subtypes, e.g. `Matrix3` for 3x3
matrices, `Vector` for nx1 matrices, and `Vector2` for 2x1
matrices. The subtypes define convenience functions (like
`Vector3.getX()`) or provide additional function overrides
with more concrete return types (like `Matrix3.mul(Vector3)`,
which returns `Vector3`).
Using
-----
The library resides in the central Maven repository with
group ID `hu.kazocsaba.math` and artifact ID `matrix`. If
you use a project management system which can fetch dependencies
from there, you can just add the library as a dependency. E.g.
in Maven:
<dependency>
<groupId>hu.kazocsaba.math</groupId>
<artifactId>matrix</artifactId>
<version>a.b.c</version>
</dependency>
You can also browse the [online javadoc](http://kazocsaba.github.com/matrix/apidocs/index.html).
Type safety
-----------
Classes of this library ensure that any `Matrix` object
that is created will implement the subtype that
matches its dimensions the closest. For example,
multiplying a 3x4 matrix and a 4x3 matrix will result in
a 3x3 matrix that can be cast to type `Matrix3`.
The type hierarchy is as follows:
* Matrix: root type, implemented by all matrix objects
* Matrix2: 2x2 matrix
* Matrix3: 3x3 matrix
* Vector: matrix with a single column
* Vector2: 2D vector (2x1 matrix)
* Vector3: 3D vector (3x1 matrix)
* Vector4: 4D vector (4x1 matrix)
New versions of the library might introduce new specialized
types.
Creating instances
------------------
Default implementations of the matrix types can be
constructed using the `MatrixFactory` class. Unless otherwise
noted in the documentation, all functions
of the `Matrix` interface and its subinterfaces must use
this factory to construct new instances.
Immutable implementations are also available. The contents
of matrices of type `ImmutableMatrix` are guaranteed to stay
the same as when they were constructed. Instances can be
created using `ImmutableMatrixFactory`.
NOTE: Matrices returned by `ImmutableMatrix` objects from `Matrix`
functions (e.g. `transpose()` or `plus()`) are _not_ immutable.
Custom implementation
---------------------
The `MatrixCore` class can be used to create a matrix backed by
a custom data structure. For example:
public class DiagonalMatrixCore extends MatrixCore {
private final double[] elements;
DiagonalMatrixCore(int size) {
// the actual dimensions of the matrix is 'size x size'
super(size, size);
elements = new double[size];
}
// the 'quick' functions can assume that the arguments have already been checked
@Override
public double getQuick(int row, int col) {
if (row==col)
return elements[row];
else
return 0;
}
@Override
public void setQuick(int row, int col, double value) {
if (row!=col) throw new UnsupportedOperationException();
elements[row]=value;
}
}
...
// create a 5x5 diagonal matrix
Matrix d=MatrixFactory.create(new DiagonalMatrixCore(5));
// the Matrix instance is strongly typed, like all instances created by the library
Matrix3 m=(Matrix3)MatrixFactory.create(new DiagonalMatrixCore(3));
Displaying matrices
-------------------
The `MatrixPrinter` class can be used to produce human-readable
representations of matrices.
| {
"content_hash": "3d978283e3fe895883b723292b2628ee",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 96,
"avg_line_length": 30,
"alnum_prop": 0.7433628318584071,
"repo_name": "kazocsaba/matrix",
"id": "0ab89abbf4c5d646ced722676db36adcc226ba32",
"size": "3390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "203828"
}
],
"symlink_target": ""
} |
export default ({ source }) => {
return source.split('\n').reduce((lines, line) => {
return lines.concat(line.split(' '));
}, []);
}
| {
"content_hash": "508d9634936af93b5fe01cb17fc2ed28",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 53,
"avg_line_length": 28.2,
"alnum_prop": 0.5531914893617021,
"repo_name": "Flaque/vx",
"id": "20b4fd985978d013162f48d175dc81988f5a1142",
"size": "141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/vx-demo/components/charts/flame/util/parseFoldedStack.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14998"
},
{
"name": "HTML",
"bytes": "141351"
},
{
"name": "JavaScript",
"bytes": "616760"
},
{
"name": "Makefile",
"bytes": "1344"
}
],
"symlink_target": ""
} |
@javax.xml.bind.annotation.XmlSchema(namespace = "hydrograph/ui/external/mapping")
package hydrograph.ui.external.mapping;
| {
"content_hash": "577915c27802c13de13b5b537c655dde",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 82,
"avg_line_length": 25.2,
"alnum_prop": 0.8015873015873016,
"repo_name": "capitalone/Hydrograph",
"id": "3e29b13248ac8b0cc79c91f66a68678eb638718a",
"size": "895",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hydrograph.ui/hydrograph.ui.common/src/main/java/hydrograph/ui/external/mapping/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "9581"
},
{
"name": "CSS",
"bytes": "162185"
},
{
"name": "HTML",
"bytes": "1036397"
},
{
"name": "Java",
"bytes": "10606203"
},
{
"name": "Scala",
"bytes": "1464765"
},
{
"name": "Shell",
"bytes": "12318"
}
],
"symlink_target": ""
} |
package com.bocekm.skycontrol.mavlink;
import java.lang.ref.WeakReference;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
import com.MAVLink.Messages.MAVLinkMessage;
import com.MAVLink.Messages.MAVLinkPacket;
import com.bocekm.skycontrol.SkyControlConst;
import com.bocekm.skycontrol.SkyControlUtils;
import com.bocekm.skycontrol.connection.Connection;
import com.bocekm.skycontrol.connection.ConnectionEvents.ConnectionEvent;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
/**
* {@link MavLinkClient} serves as a Mavlink communication client in client-server interface, where
* server is {@link MavLinkService}.
*/
public class MavLinkClient {
/** New MavLink message received from vehicle through {@link MavLinkService}. */
public static final int MSG_RECEIVED_PACKET = 0;
/** Indication that the Service requests to unbind itself from {@link MavLinkClient}. */
public static final int MSG_SELF_DESTROY_SERVICE = 1;
/**
* Context received from the caller which instantiates the {@link MavLinkClient}. It's used for
* binding the {@link MavLinkService}, so it shall be context of the application component, like
* an Activity.
*/
private Context mParent;
/**
* Handle to {@link Messenger} of the {@link MavLinkService}. It is used for sending messages to
* the service.
*/
private Messenger mServiceMessenger = null;
/**
* Handle to {@link Messenger} of this {@link MavLinkClient} class. It is used to get notified
* about new messages, mainly MavLink packets, sent by {@link MavLinkService}.
*/
private final Messenger mClientMessenger = new Messenger(new ClientIncomingHandler(this));
/** Whether the {@link MavLinkService} is bound to the {@link MavLinkClient#mParent}. */
private boolean mIsServiceBound;
/**
* Instantiates a new {@link MavLinkClient} object.
*
* @param context context of the parent
*/
public MavLinkClient(Context context) {
mParent = context;
}
/**
* Establish a connection with the MavLink service which uses the telemetry connected via USB.
*/
public void bindMavLinkService() {
// Get USB manager to check whether any USB device is connected
UsbManager manager = (UsbManager) mParent.getSystemService(Context.USB_SERVICE);
// Find the first available driver. It's unlikely to have more than one USB device
// connected.
UsbSerialDriver sDriver = UsbSerialProber.findFirstDevice(manager);
if (sDriver == null) {
// When no USB device is connected there's no point in binding the MavLinkService
SkyControlUtils.toast("No USB device found. Please (re)connect telemetry.",
Toast.LENGTH_SHORT);
Log.d(SkyControlConst.DEBUG_TAG, "No USB device connected");
return;
}
try {
// Bind the MavLinkService to the parent context
mIsServiceBound =
mParent.bindService(new Intent(mParent, MavLinkService.class),
mServiceConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT);
} catch (SecurityException e) {
throw new Error("Cannot bind service: " + e.getMessage());
}
if (!mIsServiceBound) {
Log.e(SkyControlConst.ERROR_TAG, "MavLink service not bound");
}
}
/**
* Unbinds the MavLink service.
*/
public void unbindMavLinkService() {
if (isServiceBound()) {
// Unbinding the service effectively destroys the service as the only connected client
// was this class
mParent.unbindService(mServiceConnection);
// Notify listeners about the event of unbound service
onServiceUnbound();
}
}
/**
* Handler of incoming messages from {@link MavLinkService}, mainly MavLink packets.
*/
private static class ClientIncomingHandler extends Handler {
/**
* Weak reference to the parent {@link MavLinkClient}. Reason for weak reference:
* http://www.androiddesignpatterns.com/2013/01/inner-class-handler-memory-leak.html
*/
private final WeakReference<MavLinkClient> mClientWeak;
/**
* Instantiates a new handler of messages coming from {@link MavLinkService}.
*
* @param client the parent {@link MavLinkClient}
*/
ClientIncomingHandler(MavLinkClient client) {
mClientWeak = new WeakReference<MavLinkClient>(client);
}
/*
* (non-Javadoc) Process messages coming from the bound service.
*
* @see android.os.Handler#handleMessage(android.os.Message)
*/
@Override
public void handleMessage(Message msg) {
MavLinkClient mClient = mClientWeak.get();
if (!mClient.isServiceBound())
// It may happen that request for service disconnect was placed by MavLinkClient but it not yet
// happened as service destruction is asynchronous.
return;
switch (msg.what) {
case MSG_RECEIVED_PACKET:
Bundle b = msg.getData();
MAVLinkMessage m = (MAVLinkMessage) b.getSerializable("packet");
// Pass the received packet to the packet handler, which notifies listeners
// about the new packet
Connection.get().getMavLinkMsgHandler().handleMessage(m);
break;
case MSG_SELF_DESTROY_SERVICE:
// The running service requests to be destroyed by unbinding this client from it
mClient.unbindMavLinkService();
break;
default:
super.handleMessage(msg);
}
}
}
/** Callbacks for service binding, passed to bindService(). */
private ServiceConnection mServiceConnection = new ServiceConnection() {
/*
* (non-Javadoc) Called when the connection with the service has been established, giving us
* the service object we can use to interact with the service.
*
* @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName,
* android.os.IBinder)
*/
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We are communicating with our service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mServiceMessenger = new Messenger(service);
// Monitor the service for as long as we are connected to it.
try {
Message msg = Message.obtain(null, MavLinkService.MSG_REGISTER_CLIENT);
msg.replyTo = mClientMessenger;
mServiceMessenger.send(msg);
onServiceBound();
} catch (RemoteException e) {
}
}
/*
* (non-Javadoc) Called when the connection with the service has been unexpectedly
* disconnected - that is, its process crashed.
*
* @see
* android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
*/
@Override
public void onServiceDisconnected(ComponentName arg0) {
// Call the same method which handles service unbinding to notify that the service is no
// longer running
onServiceUnbound();
}
};
/**
* Send MavLink packet to the vehicle.
*
* @param packet the MavLink packet to be sent
*/
public void sendMavPacket(MAVLinkPacket packet) {
if (mServiceMessenger == null) {
return;
}
// Create new empty message message type MSG_SEND_DATA specified
Message msg = Message.obtain(null, MavLinkService.MSG_SEND_DATA);
Bundle data = new Bundle();
// Attach MavLink packet to the message
data.putSerializable("msg", packet);
msg.setData(data);
try {
// Send the message to MavLinkService which is going to pass it to the vehicle using the
// telemetry
mServiceMessenger.send(msg);
} catch (RemoteException e) {
Log.e(SkyControlConst.ERROR_TAG, "Error sending MavLink packet with ID " + packet.msgid
+ ", " + e.getMessage(), e);
SkyControlUtils
.log("Error sending MavLink packet with ID " + packet.msgid + "\n", true);
onServiceUnbound();
}
}
/**
* Notify the listeners that the {@link MavLinkService} has been bound.
*/
private void onServiceBound() {
Connection.get().getEvents().onConnectionEvent(ConnectionEvent.SERVICE_BOUND);
}
/**
* Notify the listeners that the {@link MavLinkService} has been unbound.
*/
private void onServiceUnbound() {
mIsServiceBound = false;
Connection.get().getEvents().onConnectionEvent(ConnectionEvent.SERVICE_UNBOUND);
}
/**
* Check whether the {@link MavLinkService} has been bound.
*
* @return true if the {@link MavLinkService} is running, false otherwise
*/
public boolean isServiceBound() {
return mIsServiceBound;
}
/**
* Bind or unbind the {@link MavLinkService} based on the current state of the service. If it's
* running it will be unbound and the other way around.
*/
public void toggleConnectionState() {
if (isServiceBound()) {
unbindMavLinkService();
} else {
bindMavLinkService();
}
}
}
| {
"content_hash": "1d19fe6e4e59bf576bb012d86cbe9df9",
"timestamp": "",
"source": "github",
"line_count": 268,
"max_line_length": 111,
"avg_line_length": 39.29477611940298,
"alnum_prop": 0.6160858418003988,
"repo_name": "bocekm/SkyControl",
"id": "ce98f4e28c5a9407ad2964b696a576a0883faf45",
"size": "11157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SkyControl/SkyControl/src/com/bocekm/skycontrol/mavlink/MavLinkClient.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1150259"
},
{
"name": "Python",
"bytes": "48734"
}
],
"symlink_target": ""
} |
"""
This module provides decorator functions which can be applied to test objects
in order to skip those objects when certain conditions occur. A sample use case
is to detect if the platform is missing ``matplotlib``. If so, any test objects
which require ``matplotlib`` and decorated with ``@td.skip_if_no_mpl`` will be
skipped by ``pytest`` during the execution of the test suite.
To illustrate, after importing this module:
import pandas.util._test_decorators as td
The decorators can be applied to classes:
@td.skip_if_some_reason
class Foo:
...
Or individual functions:
@td.skip_if_some_reason
def test_foo():
...
For more information, refer to the ``pytest`` documentation on ``skipif``.
"""
from __future__ import annotations
from contextlib import contextmanager
import gc
import locale
from typing import (
Callable,
Generator,
)
import warnings
import numpy as np
import pytest
from pandas._config import get_option
from pandas._typing import F
from pandas.compat import (
IS64,
is_platform_windows,
)
from pandas.compat._optional import import_optional_dependency
from pandas.core.computation.expressions import (
NUMEXPR_INSTALLED,
USE_NUMEXPR,
)
from pandas.util.version import Version
def safe_import(mod_name: str, min_version: str | None = None):
"""
Parameters
----------
mod_name : str
Name of the module to be imported
min_version : str, default None
Minimum required version of the specified mod_name
Returns
-------
object
The imported module if successful, or False
"""
with warnings.catch_warnings():
# Suppress warnings that we can't do anything about,
# e.g. from aiohttp
warnings.filterwarnings(
"ignore",
category=DeprecationWarning,
module="aiohttp",
message=".*decorator is deprecated since Python 3.8.*",
)
# fastparquet import accesses pd.Int64Index
warnings.filterwarnings(
"ignore",
category=FutureWarning,
module="fastparquet",
message=".*Int64Index.*",
)
warnings.filterwarnings(
"ignore",
category=DeprecationWarning,
message="distutils Version classes are deprecated.*",
)
try:
mod = __import__(mod_name)
except ImportError:
return False
if not min_version:
return mod
else:
import sys
try:
version = getattr(sys.modules[mod_name], "__version__")
except AttributeError:
# xlrd uses a capitalized attribute name
version = getattr(sys.modules[mod_name], "__VERSION__")
if version and Version(version) >= Version(min_version):
return mod
return False
def _skip_if_no_mpl() -> bool:
mod = safe_import("matplotlib")
if mod:
mod.use("Agg")
return False
else:
return True
def _skip_if_not_us_locale() -> bool:
lang, _ = locale.getlocale()
if lang != "en_US":
return True
return False
def _skip_if_no_scipy() -> bool:
return not (
safe_import("scipy.stats")
and safe_import("scipy.sparse")
and safe_import("scipy.interpolate")
and safe_import("scipy.signal")
)
# TODO(pytest#7469): return type, _pytest.mark.structures.MarkDecorator is not public
# https://github.com/pytest-dev/pytest/issues/7469
def skip_if_installed(package: str):
"""
Skip a test if a package is installed.
Parameters
----------
package : str
The name of the package.
"""
return pytest.mark.skipif(
safe_import(package), reason=f"Skipping because {package} is installed."
)
# TODO(pytest#7469): return type, _pytest.mark.structures.MarkDecorator is not public
# https://github.com/pytest-dev/pytest/issues/7469
def skip_if_no(package: str, min_version: str | None = None):
"""
Generic function to help skip tests when required packages are not
present on the testing system.
This function returns a pytest mark with a skip condition that will be
evaluated during test collection. An attempt will be made to import the
specified ``package`` and optionally ensure it meets the ``min_version``
The mark can be used as either a decorator for a test function or to be
applied to parameters in pytest.mark.parametrize calls or parametrized
fixtures.
If the import and version check are unsuccessful, then the test function
(or test case when used in conjunction with parametrization) will be
skipped.
Parameters
----------
package: str
The name of the required package.
min_version: str or None, default None
Optional minimum version of the package.
Returns
-------
_pytest.mark.structures.MarkDecorator
a pytest.mark.skipif to use as either a test decorator or a
parametrization mark.
"""
msg = f"Could not import '{package}'"
if min_version:
msg += f" satisfying a min_version of {min_version}"
return pytest.mark.skipif(
not safe_import(package, min_version=min_version), reason=msg
)
skip_if_no_mpl = pytest.mark.skipif(
_skip_if_no_mpl(), reason="Missing matplotlib dependency"
)
skip_if_mpl = pytest.mark.skipif(not _skip_if_no_mpl(), reason="matplotlib is present")
skip_if_32bit = pytest.mark.skipif(not IS64, reason="skipping for 32 bit")
skip_if_windows = pytest.mark.skipif(is_platform_windows(), reason="Running on Windows")
skip_if_not_us_locale = pytest.mark.skipif(
_skip_if_not_us_locale(),
reason=f"Specific locale is set {locale.getlocale()[0]}",
)
skip_if_no_scipy = pytest.mark.skipif(
_skip_if_no_scipy(), reason="Missing SciPy requirement"
)
skip_if_no_ne = pytest.mark.skipif(
not USE_NUMEXPR,
reason=f"numexpr enabled->{USE_NUMEXPR}, installed->{NUMEXPR_INSTALLED}",
)
# TODO(pytest#7469): return type, _pytest.mark.structures.MarkDecorator is not public
# https://github.com/pytest-dev/pytest/issues/7469
def skip_if_np_lt(ver_str: str, *args, reason: str | None = None):
if reason is None:
reason = f"NumPy {ver_str} or greater required"
return pytest.mark.skipif(
Version(np.__version__) < Version(ver_str),
*args,
reason=reason,
)
def parametrize_fixture_doc(*args) -> Callable[[F], F]:
"""
Intended for use as a decorator for parametrized fixture,
this function will wrap the decorated function with a pytest
``parametrize_fixture_doc`` mark. That mark will format
initial fixture docstring by replacing placeholders {0}, {1} etc
with parameters passed as arguments.
Parameters
----------
args: iterable
Positional arguments for docstring.
Returns
-------
function
The decorated function wrapped within a pytest
``parametrize_fixture_doc`` mark
"""
def documented_fixture(fixture):
fixture.__doc__ = fixture.__doc__.format(*args)
return fixture
return documented_fixture
def check_file_leaks(func) -> Callable:
"""
Decorate a test function to check that we are not leaking file descriptors.
"""
with file_leak_context():
return func
@contextmanager
def file_leak_context() -> Generator[None, None, None]:
"""
ContextManager analogue to check_file_leaks.
"""
psutil = safe_import("psutil")
if not psutil or is_platform_windows():
# Checking for file leaks can hang on Windows CI
yield
else:
proc = psutil.Process()
flist = proc.open_files()
conns = proc.connections()
try:
yield
finally:
gc.collect()
flist2 = proc.open_files()
# on some builds open_files includes file position, which we _dont_
# expect to remain unchanged, so we need to compare excluding that
flist_ex = [(x.path, x.fd) for x in flist]
flist2_ex = [(x.path, x.fd) for x in flist2]
assert set(flist2_ex) <= set(flist_ex), (flist2, flist)
conns2 = proc.connections()
assert conns2 == conns, (conns2, conns)
def async_mark():
try:
import_optional_dependency("pytest_asyncio")
async_mark = pytest.mark.asyncio
except ImportError:
async_mark = pytest.mark.skip(reason="Missing dependency pytest-asyncio")
return async_mark
def mark_array_manager_not_yet_implemented(request) -> None:
mark = pytest.mark.xfail(reason="Not yet implemented for ArrayManager")
request.node.add_marker(mark)
skip_array_manager_not_yet_implemented = pytest.mark.xfail(
get_option("mode.data_manager") == "array",
reason="Not yet implemented for ArrayManager",
)
skip_array_manager_invalid_test = pytest.mark.skipif(
get_option("mode.data_manager") == "array",
reason="Test that relies on BlockManager internals or specific behaviour",
)
| {
"content_hash": "f9ea87fa83cc9fd90f3eeb34c945fd4f",
"timestamp": "",
"source": "github",
"line_count": 314,
"max_line_length": 88,
"avg_line_length": 28.802547770700638,
"alnum_prop": 0.6493808049535603,
"repo_name": "pandas-dev/pandas",
"id": "33830e96342f3c207650e16ccdf8a97926374b6d",
"size": "9044",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "pandas/util/_test_decorators.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "512"
},
{
"name": "C",
"bytes": "366145"
},
{
"name": "CSS",
"bytes": "1800"
},
{
"name": "Cython",
"bytes": "1186787"
},
{
"name": "Dockerfile",
"bytes": "1411"
},
{
"name": "HTML",
"bytes": "456531"
},
{
"name": "Python",
"bytes": "18778786"
},
{
"name": "Shell",
"bytes": "10369"
},
{
"name": "Smarty",
"bytes": "8486"
},
{
"name": "XSLT",
"bytes": "1196"
}
],
"symlink_target": ""
} |
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "tree.h"
#include "rtl.h"
#include "function.h"
#include "basic-block.h"
#include "expr.h"
#include "diagnostic.h"
#include "tree-flow.h"
#include "timevar.h"
#include "tree-dump.h"
#include "tree-pass.h"
#include "langhooks.h"
/* This file implements return value optimizations for functions which
return aggregate types.
Basically this pass searches the function for return statements which
return a local aggregate. When converted to RTL such statements will
generate a copy from the local aggregate to final return value destination
mandated by the target's ABI.
That copy can often be avoided by directly constructing the return value
into the final destination mandated by the target's ABI.
This is basically a generic equivalent to the C++ front-end's
Named Return Value optimization. */
struct nrv_data
{
/* This is the temporary (a VAR_DECL) which appears in all of
this function's RETURN_EXPR statements. */
tree var;
/* This is the function's RESULT_DECL. We will replace all occurrences
of VAR with RESULT_DECL when we apply this optimization. */
tree result;
};
static tree finalize_nrv_r (tree *, int *, void *);
/* Callback for the tree walker.
If TP refers to a RETURN_EXPR, then set the expression being returned
to nrv_data->result.
If TP refers to nrv_data->var, then replace nrv_data->var with
nrv_data->result.
If we reach a node where we know all the subtrees are uninteresting,
then set *WALK_SUBTREES to zero. */
static tree
finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
{
struct nrv_data *dp = (struct nrv_data *)data;
/* No need to walk into types. */
if (TYPE_P (*tp))
*walk_subtrees = 0;
/* Otherwise replace all occurrences of VAR with RESULT. */
else if (*tp == dp->var)
*tp = dp->result;
/* Keep iterating. */
return NULL_TREE;
}
/* Main entry point for return value optimizations.
If this function always returns the same local variable, and that
local variable is an aggregate type, then replace the variable with
the function's DECL_RESULT.
This is the equivalent of the C++ named return value optimization
applied to optimized trees in a language independent form. If we
ever encounter languages which prevent this kind of optimization,
then we could either have the languages register the optimization or
we could change the gating function to check the current language. */
static unsigned int
tree_nrv (void)
{
tree result = DECL_RESULT (current_function_decl);
tree result_type = TREE_TYPE (result);
tree found = NULL;
basic_block bb;
block_stmt_iterator bsi;
struct nrv_data data;
/* If this function does not return an aggregate type in memory, then
there is nothing to do. */
if (!aggregate_value_p (result, current_function_decl))
return 0;
/* Look through each block for assignments to the RESULT_DECL. */
FOR_EACH_BB (bb)
{
for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
{
tree stmt = bsi_stmt (bsi);
tree ret_expr;
if (TREE_CODE (stmt) == RETURN_EXPR)
{
/* In a function with an aggregate return value, the
gimplifier has changed all non-empty RETURN_EXPRs to
return the RESULT_DECL. */
ret_expr = TREE_OPERAND (stmt, 0);
if (ret_expr)
gcc_assert (ret_expr == result);
}
else if (TREE_CODE (stmt) == MODIFY_EXPR
&& TREE_OPERAND (stmt, 0) == result)
{
ret_expr = TREE_OPERAND (stmt, 1);
/* Now verify that this return statement uses the same value
as any previously encountered return statement. */
if (found != NULL)
{
/* If we found a return statement using a different variable
than previous return statements, then we can not perform
NRV optimizations. */
if (found != ret_expr)
return 0;
}
else
found = ret_expr;
/* The returned value must be a local automatic variable of the
same type and alignment as the function's result. */
if (TREE_CODE (found) != VAR_DECL
|| TREE_THIS_VOLATILE (found)
|| DECL_CONTEXT (found) != current_function_decl
|| TREE_STATIC (found)
|| TREE_ADDRESSABLE (found)
|| DECL_ALIGN (found) > DECL_ALIGN (result)
|| !lang_hooks.types_compatible_p (TREE_TYPE (found),
result_type))
return 0;
}
else if (TREE_CODE (stmt) == MODIFY_EXPR)
{
tree addr = get_base_address (TREE_OPERAND (stmt, 0));
/* If there's any MODIFY of component of RESULT,
then bail out. */
if (addr && addr == result)
return 0;
}
}
}
if (!found)
return 0;
/* If dumping details, then note once and only the NRV replacement. */
if (dump_file && (dump_flags & TDF_DETAILS))
{
fprintf (dump_file, "NRV Replaced: ");
print_generic_expr (dump_file, found, dump_flags);
fprintf (dump_file, " with: ");
print_generic_expr (dump_file, result, dump_flags);
fprintf (dump_file, "\n");
}
/* At this point we know that all the return statements return the
same local which has suitable attributes for NRV. Copy debugging
information from FOUND to RESULT. */
DECL_NAME (result) = DECL_NAME (found);
DECL_SOURCE_LOCATION (result) = DECL_SOURCE_LOCATION (found);
DECL_ABSTRACT_ORIGIN (result) = DECL_ABSTRACT_ORIGIN (found);
TREE_ADDRESSABLE (result) = TREE_ADDRESSABLE (found);
/* Now walk through the function changing all references to VAR to be
RESULT. */
data.var = found;
data.result = result;
FOR_EACH_BB (bb)
{
for (bsi = bsi_start (bb); !bsi_end_p (bsi); )
{
tree *tp = bsi_stmt_ptr (bsi);
/* If this is a copy from VAR to RESULT, remove it. */
if (TREE_CODE (*tp) == MODIFY_EXPR
&& TREE_OPERAND (*tp, 0) == result
&& TREE_OPERAND (*tp, 1) == found)
bsi_remove (&bsi, true);
else
{
walk_tree (tp, finalize_nrv_r, &data, 0);
bsi_next (&bsi);
}
}
}
/* FOUND is no longer used. Ensure it gets removed. */
var_ann (found)->used = 0;
return 0;
}
struct tree_opt_pass pass_nrv =
{
"nrv", /* name */
NULL, /* gate */
tree_nrv, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
TV_TREE_NRV, /* tv_id */
PROP_cfg, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
TODO_dump_func | TODO_ggc_collect, /* todo_flags_finish */
0 /* letter */
};
/* Determine (pessimistically) whether DEST is available for NRV
optimization, where DEST is expected to be the LHS of a modify
expression where the RHS is a function returning an aggregate.
We search for a base VAR_DECL and look to see if it, or any of its
subvars are clobbered. Note that we could do better, for example, by
attempting to doing points-to analysis on INDIRECT_REFs. */
static bool
dest_safe_for_nrv_p (tree dest)
{
switch (TREE_CODE (dest))
{
case VAR_DECL:
{
subvar_t subvar;
if (is_call_clobbered (dest))
return false;
for (subvar = get_subvars_for_var (dest);
subvar;
subvar = subvar->next)
if (is_call_clobbered (subvar->var))
return false;
return true;
}
case ARRAY_REF:
case COMPONENT_REF:
return dest_safe_for_nrv_p (TREE_OPERAND (dest, 0));
default:
return false;
}
}
/* Walk through the function looking for MODIFY_EXPRs with calls that
return in memory on the RHS. For each of these, determine whether it is
safe to pass the address of the LHS as the return slot, and mark the
call appropriately if so.
The NRV shares the return slot with a local variable in the callee; this
optimization shares the return slot with the target of the call within
the caller. If the NRV is performed (which we can't know in general),
this optimization is safe if the address of the target has not
escaped prior to the call. If it has, modifications to the local
variable will produce visible changes elsewhere, as in PR c++/19317. */
static unsigned int
execute_return_slot_opt (void)
{
basic_block bb;
FOR_EACH_BB (bb)
{
block_stmt_iterator i;
for (i = bsi_start (bb); !bsi_end_p (i); bsi_next (&i))
{
tree stmt = bsi_stmt (i);
tree call;
if (TREE_CODE (stmt) == MODIFY_EXPR
&& (call = TREE_OPERAND (stmt, 1),
TREE_CODE (call) == CALL_EXPR)
&& !CALL_EXPR_RETURN_SLOT_OPT (call)
&& aggregate_value_p (call, call))
/* Check if the location being assigned to is
call-clobbered. */
CALL_EXPR_RETURN_SLOT_OPT (call) =
dest_safe_for_nrv_p (TREE_OPERAND (stmt, 0)) ? 1 : 0;
}
}
return 0;
}
struct tree_opt_pass pass_return_slot =
{
"retslot", /* name */
NULL, /* gate */
execute_return_slot_opt, /* execute */
NULL, /* sub */
NULL, /* next */
0, /* static_pass_number */
0, /* tv_id */
PROP_ssa | PROP_alias, /* properties_required */
0, /* properties_provided */
0, /* properties_destroyed */
0, /* todo_flags_start */
0, /* todo_flags_finish */
0 /* letter */
};
| {
"content_hash": "05ed3a0db26661c6731c59e3e7ad1aa3",
"timestamp": "",
"source": "github",
"line_count": 311,
"max_line_length": 77,
"avg_line_length": 29.958199356913184,
"alnum_prop": 0.6401202103681443,
"repo_name": "jrobhoward/SCADAbase",
"id": "e7801abdf3257600c5f67a74e6149594e0da801a",
"size": "10114",
"binary": false,
"copies": "21",
"ref": "refs/heads/SCADAbase",
"path": "contrib/gcc/tree-nrv.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "62471"
},
{
"name": "Assembly",
"bytes": "4615704"
},
{
"name": "Awk",
"bytes": "273794"
},
{
"name": "Batchfile",
"bytes": "20333"
},
{
"name": "C",
"bytes": "457666547"
},
{
"name": "C++",
"bytes": "91495356"
},
{
"name": "CMake",
"bytes": "17632"
},
{
"name": "CSS",
"bytes": "104220"
},
{
"name": "ChucK",
"bytes": "39"
},
{
"name": "D",
"bytes": "6321"
},
{
"name": "DIGITAL Command Language",
"bytes": "10638"
},
{
"name": "DTrace",
"bytes": "1904158"
},
{
"name": "Emacs Lisp",
"bytes": "32010"
},
{
"name": "EmberScript",
"bytes": "286"
},
{
"name": "Forth",
"bytes": "204603"
},
{
"name": "GAP",
"bytes": "72078"
},
{
"name": "Groff",
"bytes": "32376243"
},
{
"name": "HTML",
"bytes": "5776268"
},
{
"name": "Haskell",
"bytes": "2458"
},
{
"name": "IGOR Pro",
"bytes": "6510"
},
{
"name": "Java",
"bytes": "112547"
},
{
"name": "KRL",
"bytes": "4950"
},
{
"name": "Lex",
"bytes": "425858"
},
{
"name": "Limbo",
"bytes": "4037"
},
{
"name": "Logos",
"bytes": "179088"
},
{
"name": "Makefile",
"bytes": "12750766"
},
{
"name": "Mathematica",
"bytes": "21782"
},
{
"name": "Max",
"bytes": "4105"
},
{
"name": "Module Management System",
"bytes": "816"
},
{
"name": "Objective-C",
"bytes": "1571960"
},
{
"name": "PHP",
"bytes": "2471"
},
{
"name": "PLSQL",
"bytes": "96552"
},
{
"name": "PLpgSQL",
"bytes": "2212"
},
{
"name": "Perl",
"bytes": "3947402"
},
{
"name": "Perl6",
"bytes": "122803"
},
{
"name": "PostScript",
"bytes": "152255"
},
{
"name": "Prolog",
"bytes": "42792"
},
{
"name": "Protocol Buffer",
"bytes": "54964"
},
{
"name": "Python",
"bytes": "381066"
},
{
"name": "R",
"bytes": "764"
},
{
"name": "Rebol",
"bytes": "738"
},
{
"name": "Ruby",
"bytes": "67015"
},
{
"name": "Scheme",
"bytes": "5087"
},
{
"name": "Scilab",
"bytes": "196"
},
{
"name": "Shell",
"bytes": "10963470"
},
{
"name": "SourcePawn",
"bytes": "2293"
},
{
"name": "SuperCollider",
"bytes": "80208"
},
{
"name": "Tcl",
"bytes": "7102"
},
{
"name": "TeX",
"bytes": "720582"
},
{
"name": "VimL",
"bytes": "19597"
},
{
"name": "XS",
"bytes": "17496"
},
{
"name": "XSLT",
"bytes": "4564"
},
{
"name": "Yacc",
"bytes": "1881915"
}
],
"symlink_target": ""
} |
import React, { PropTypes } from 'react';
import { stitch } from 'keo';
import DocumentTitle from 'react-document-title';
import config from '../config';
/**
* @constant propTypes
* @type {Object}
*/
const propTypes = {
title: PropTypes.string.isRequired,
children: PropTypes.element.isRequired
};
/**
* @method render
* @param {Object} props
* @return {XML}
*/
const render = ({ props }) => {
return (
<DocumentTitle title={`${config.title} - ${props.title}`}>
{props.children}
</DocumentTitle>
);
};
export default stitch({ propTypes, render });
| {
"content_hash": "722213f9706a05f3eb6ce98ab0c9ccca",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 66,
"avg_line_length": 20.133333333333333,
"alnum_prop": 0.6192052980132451,
"repo_name": "Wildhoney/Dory",
"id": "a1efca1cdc12400705a284cc12d85f88b513ad93",
"size": "604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/components/document-title.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12052"
},
{
"name": "HTML",
"bytes": "797"
},
{
"name": "JavaScript",
"bytes": "49896"
},
{
"name": "XSLT",
"bytes": "3398"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81_goodB2G.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-81_goodB2G.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: fscanf Read data from the console using fscanf()
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81.h"
#define HELLO_STRING "hello"
namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81
{
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81_goodB2G::action(size_t data) const
{
{
char * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING) && data < 100)
{
myString = (char *)malloc(data*sizeof(char));
if (myString == NULL) {exit(-1);}
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
}
#endif /* OMITGOOD */
| {
"content_hash": "d4c62726a135d2c90422144fb3cca9ef",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 109,
"avg_line_length": 37.05882352941177,
"alnum_prop": 0.6571428571428571,
"repo_name": "JianpingZeng/xcc",
"id": "fd4ebd65def0925ac7dbd4a737c43a2f28cb1599",
"size": "1890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_fscanf_81_goodB2G.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
@charset "UTF-8";
/* speech */
.speech { opacity: 0; transition: all .3s; }
.mode-speech-start .speech { opacity: 1; }
.mode-nl-loaded .speech,
.mode-nl-repeat .speech{ opacity: 0; transform: translate(-100px, 0); }
/* speech in/out */
.mode-speech-in .speech-mic { animation: speech-in .8s infinite alternate; }
@keyframes speech-in {
0% {
border-width: 0;
}
100% {
border-width: 40px;
}
}
.mode-speech-out .speech-mic { animation: speech-out .3s forwards; }
@keyframes speech-out {
0% {
opacity: 1;
transform: scale(1);
}
100% {
opacity: 0;
transform: scale(0);
}
}
/* nl loaded */
.nl-inner { transition: none; }
.nl-word { opacity: 0; transform: translate(100px, 0); transition: none; }
.nl-tag,
.nl-pos { opacity: 0; transform: translate(0, 100px); transition: none; }
.nl-label { opacity: 0; transition: none; }
.nl-depend dd { opacity: 0; transform: scale(0, 1); transition: none; }
.mode-nl-loaded .nl-word { opacity: 1; transform: translate(0, 0); transition: all .4s; }
.mode-nl-loaded .nl-tag,
.mode-nl-loaded .nl-pos { opacity: 1; transform: translate(0, 0); transition: all .4s; }
.mode-nl-loaded .nl-label { opacity: 1; transition: all .4s; }
.mode-nl-loaded .nl-depend dd { opacity: 0.4; transform: scale(1, 1); transition: opacity 1s, transform 1s; }
.mode-nl-repeat .nl-inner { opacity: 0; transition: all .4s; }
/* nl */
.nl { transition: all .3s; }
.mode-force-start .nl { opacity: 0; transform: scale(0.5); }
/* force */
.force { transition: all .3s; }
.mode-plot-end .force { opacity: 0; transform: scale(0); }
/* plot */
.plot dd { transform: scale(0); transition: all .3s cubic-bezier(0.175, 0.885, 0.32, 1.275); ; }
.mode-plot-start .plot dd { transform: scale(1); }
.mode-plot-end .plot dd { transform: scale(0); transition-delay: 0s!important; }
.mode-plot-end .plot dd.nearest { transform: scale(5); opacity: 1; transition: all .3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
.plot dd { animation: plot 1s infinite alternate; }
@keyframes plot {
0% {
opacity: 0.6;
}
50%, 100% {
opacity: 0.8;
}
}
.mode-stat-end .plot dd { opacity: 0.8; animation: none; }
/* cam */
.cam { opacity: 0; transform: scale(0.8); transition: all .3s; }
.mode-cam-start .cam { opacity: 1; transform: scale(1); }
.mode-cam-start .plot dd.nearest { opacity: 0; transform: scale(0); }
.mode-cam-start polygon { animation: cam 100s linear forwards; }
@keyframes cam {
0% {
stroke-dashoffset: 10000;
}
100% {
stroke-dashoffset: 0;
}
}
/* thanks */
.thanks { height: 0; }
.thanks div { opacity: 0; transform: translate(100px, 0); transition: all .3s; }
.mode-thanks-start .thanks { height: 100%; }
.mode-thanks-start .cam { opacity: 0; }
.mode-thanks-start .thanks div:nth-child(1) { opacity: 1; transform: translate(0, 0); }
.mode-thanks-end .thanks div:nth-child(1) { opacity: 0; transform: translate(-100px, 0); }
.mode-thanks-end .thanks div:nth-child(2) { opacity: 1; transform: translate(0, 0); }
.mode-thanks-btn .thanks div:nth-child(2) { opacity: 0; transform: translate(-100px, 0); }
.mode-thanks-btn .thanks div:nth-child(3) { opacity: 1; transform: translate(0, 0); }
/* sorry */
.sorry { height: 0; opacity: 0; }
.mode-sorry-p .speech,
.mode-sorry-p .nl,
.mode-sorry-p .cam,
.mode-sorry-p .plot,
.mode-sorry-p .force { height: 0; opacity: 0; }
.mode-sorry-p .sorry { height: 100%; opacity: 1; }
/* loading */
.loading { height: 0; opacity: 0; transition: opacity .3s; }
.mode-loading .loading { height: 100%; opacity: 1; }
.spinner i { animation: spinner 1.4s infinite ease-in-out both; }
.spinner i:nth-child(1) { animation-delay: -0.32s; }
.spinner i:nth-child(2) { animation-delay: -0.16s; }
@keyframes spinner {
0%, 80%, 100% {
transform: scale(0);
}
40% {
transform: scale(1.0);
}
}
/* cap */
.cap { transition-delay: .3s; }
.cap-init p { opacity: 0; transform: translate(0, 100px); transition: all .3s; }
.cap-init p:nth-child(2) { transition-delay: .1s; }
.cap-steps { height: 0; opacity: 0; transition: opacity .3s; }
.mode-cap-init .cap-init p { opacity: 1; transform: translate(0, 0); }
.mode-cap-steps .cap-init { display: none; }
.mode-cap-steps .cap-steps { height: 100%; opacity: 1; }
.cap-images dd { animation: cap .3s both; }
.mode-train .cap { height: 0; }
.mode-train .cap-steps { opacity: 0; }
@keyframes cap {
0% {
opacity: 0;
transform: translate(0, 100px);
}
100% {
opacity: 1;
transform: translate(0, 0);
}
}
/* train */
.train { height: 0; }
.train-txt { opacity: 0; transform: translate(100px, 0); transition: all .3s; }
.train-v3 { opacity: 0; transform: translate(-100px, 0); transition: all 1s; }
.mode-train .train { height: 100%; }
.mode-train .train-txt { opacity: 1; transform: translate(0, 0); }
.mode-train-v3 .train-v3 { opacity: 1; transform: translate(0, 0); }
.mode-train .train-txt { animation: trainTxt 2s infinite alternate; }
@keyframes trainTxt {
0% {
opacity: 0;
}
60%, 100% {
opacity: 1;
}
}
.train-v3 rect { animation: v3 300s linear forwards; }
@keyframes v3 {
0% {
stroke-dashoffset: 30000;
}
100% {
stroke-dashoffset: 0;
}
}
/* status */
.stat { height: 0; opacity: 0; transform: translate(-100px, 0); transition: opacity 1s, transform 1s; }
.mode-stat .cap,
.mode-stat .train { display: none; }
.mode-stat .stat { height: 100%; opacity: 1; transform: translate(0, 0); }
.stat-btn { height: 0; opacity: 0; transition: opacity .3s; }
.mode-stat-end .stat-btn { height: 100%; opacity: 1; }
/* sorry */
.mode-sorry-t-start .loading,
.mode-sorry-t-start .cap,
.mode-sorry-t-start .train { height: 0; opacity: 0; }
.mode-sorry-t-end .sorry { height: 100%; opacity: 1; }
| {
"content_hash": "d3775628b47484f17d98ce22e1e07b28",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 129,
"avg_line_length": 33.707317073170735,
"alnum_prop": 0.6579232995658466,
"repo_name": "BrainPad/FindYourCandy",
"id": "0c32909ff2e095f4a37a950bf0a587abdbdefd4a",
"size": "5528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webapp/candysorter/static/css/anim.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "16598"
},
{
"name": "HTML",
"bytes": "4980"
},
{
"name": "JavaScript",
"bytes": "17392"
},
{
"name": "Python",
"bytes": "150187"
},
{
"name": "Shell",
"bytes": "297"
}
],
"symlink_target": ""
} |
class HomeController < ApplicationController
layout 'home'
def controller_error
nil.foo
render(:text => 'did not fail')
end
def model_error
s = StoredException.new
s.failure
render(:text => 'did not fail')
end
def view_error
end
def syntax_error
eval("arr = [")
render(:text => 'did not fail')
end
end
| {
"content_hash": "6de5329dc4542ffc539d292efd6d8d38",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 44,
"avg_line_length": 16,
"alnum_prop": 0.6306818181818182,
"repo_name": "Unitech/rails_exception_handler",
"id": "3bf43070177ee32d6b2ffcda4f4c631359a850e7",
"size": "352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/testapp_30/app/controllers/home_controller.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
module Aws::Batch
# @api private
module ClientApi
include Seahorse::Model
ArrayJobDependency = Shapes::StringShape.new(name: 'ArrayJobDependency')
ArrayJobStatusSummary = Shapes::MapShape.new(name: 'ArrayJobStatusSummary')
ArrayProperties = Shapes::StructureShape.new(name: 'ArrayProperties')
ArrayPropertiesDetail = Shapes::StructureShape.new(name: 'ArrayPropertiesDetail')
ArrayPropertiesSummary = Shapes::StructureShape.new(name: 'ArrayPropertiesSummary')
AssignPublicIp = Shapes::StringShape.new(name: 'AssignPublicIp')
AttemptContainerDetail = Shapes::StructureShape.new(name: 'AttemptContainerDetail')
AttemptDetail = Shapes::StructureShape.new(name: 'AttemptDetail')
AttemptDetails = Shapes::ListShape.new(name: 'AttemptDetails')
Boolean = Shapes::BooleanShape.new(name: 'Boolean')
CEState = Shapes::StringShape.new(name: 'CEState')
CEStatus = Shapes::StringShape.new(name: 'CEStatus')
CEType = Shapes::StringShape.new(name: 'CEType')
CRAllocationStrategy = Shapes::StringShape.new(name: 'CRAllocationStrategy')
CRType = Shapes::StringShape.new(name: 'CRType')
CRUpdateAllocationStrategy = Shapes::StringShape.new(name: 'CRUpdateAllocationStrategy')
CancelJobRequest = Shapes::StructureShape.new(name: 'CancelJobRequest')
CancelJobResponse = Shapes::StructureShape.new(name: 'CancelJobResponse')
ClientException = Shapes::StructureShape.new(name: 'ClientException')
ComputeEnvironmentDetail = Shapes::StructureShape.new(name: 'ComputeEnvironmentDetail')
ComputeEnvironmentDetailList = Shapes::ListShape.new(name: 'ComputeEnvironmentDetailList')
ComputeEnvironmentOrder = Shapes::StructureShape.new(name: 'ComputeEnvironmentOrder')
ComputeEnvironmentOrders = Shapes::ListShape.new(name: 'ComputeEnvironmentOrders')
ComputeResource = Shapes::StructureShape.new(name: 'ComputeResource')
ComputeResourceUpdate = Shapes::StructureShape.new(name: 'ComputeResourceUpdate')
ContainerDetail = Shapes::StructureShape.new(name: 'ContainerDetail')
ContainerOverrides = Shapes::StructureShape.new(name: 'ContainerOverrides')
ContainerProperties = Shapes::StructureShape.new(name: 'ContainerProperties')
ContainerSummary = Shapes::StructureShape.new(name: 'ContainerSummary')
CreateComputeEnvironmentRequest = Shapes::StructureShape.new(name: 'CreateComputeEnvironmentRequest')
CreateComputeEnvironmentResponse = Shapes::StructureShape.new(name: 'CreateComputeEnvironmentResponse')
CreateJobQueueRequest = Shapes::StructureShape.new(name: 'CreateJobQueueRequest')
CreateJobQueueResponse = Shapes::StructureShape.new(name: 'CreateJobQueueResponse')
CreateSchedulingPolicyRequest = Shapes::StructureShape.new(name: 'CreateSchedulingPolicyRequest')
CreateSchedulingPolicyResponse = Shapes::StructureShape.new(name: 'CreateSchedulingPolicyResponse')
DeleteComputeEnvironmentRequest = Shapes::StructureShape.new(name: 'DeleteComputeEnvironmentRequest')
DeleteComputeEnvironmentResponse = Shapes::StructureShape.new(name: 'DeleteComputeEnvironmentResponse')
DeleteJobQueueRequest = Shapes::StructureShape.new(name: 'DeleteJobQueueRequest')
DeleteJobQueueResponse = Shapes::StructureShape.new(name: 'DeleteJobQueueResponse')
DeleteSchedulingPolicyRequest = Shapes::StructureShape.new(name: 'DeleteSchedulingPolicyRequest')
DeleteSchedulingPolicyResponse = Shapes::StructureShape.new(name: 'DeleteSchedulingPolicyResponse')
DeregisterJobDefinitionRequest = Shapes::StructureShape.new(name: 'DeregisterJobDefinitionRequest')
DeregisterJobDefinitionResponse = Shapes::StructureShape.new(name: 'DeregisterJobDefinitionResponse')
DescribeComputeEnvironmentsRequest = Shapes::StructureShape.new(name: 'DescribeComputeEnvironmentsRequest')
DescribeComputeEnvironmentsResponse = Shapes::StructureShape.new(name: 'DescribeComputeEnvironmentsResponse')
DescribeJobDefinitionsRequest = Shapes::StructureShape.new(name: 'DescribeJobDefinitionsRequest')
DescribeJobDefinitionsResponse = Shapes::StructureShape.new(name: 'DescribeJobDefinitionsResponse')
DescribeJobQueuesRequest = Shapes::StructureShape.new(name: 'DescribeJobQueuesRequest')
DescribeJobQueuesResponse = Shapes::StructureShape.new(name: 'DescribeJobQueuesResponse')
DescribeJobsRequest = Shapes::StructureShape.new(name: 'DescribeJobsRequest')
DescribeJobsResponse = Shapes::StructureShape.new(name: 'DescribeJobsResponse')
DescribeSchedulingPoliciesRequest = Shapes::StructureShape.new(name: 'DescribeSchedulingPoliciesRequest')
DescribeSchedulingPoliciesResponse = Shapes::StructureShape.new(name: 'DescribeSchedulingPoliciesResponse')
Device = Shapes::StructureShape.new(name: 'Device')
DeviceCgroupPermission = Shapes::StringShape.new(name: 'DeviceCgroupPermission')
DeviceCgroupPermissions = Shapes::ListShape.new(name: 'DeviceCgroupPermissions')
DevicesList = Shapes::ListShape.new(name: 'DevicesList')
EFSAuthorizationConfig = Shapes::StructureShape.new(name: 'EFSAuthorizationConfig')
EFSAuthorizationConfigIAM = Shapes::StringShape.new(name: 'EFSAuthorizationConfigIAM')
EFSTransitEncryption = Shapes::StringShape.new(name: 'EFSTransitEncryption')
EFSVolumeConfiguration = Shapes::StructureShape.new(name: 'EFSVolumeConfiguration')
Ec2Configuration = Shapes::StructureShape.new(name: 'Ec2Configuration')
Ec2ConfigurationList = Shapes::ListShape.new(name: 'Ec2ConfigurationList')
EksAttemptContainerDetail = Shapes::StructureShape.new(name: 'EksAttemptContainerDetail')
EksAttemptContainerDetails = Shapes::ListShape.new(name: 'EksAttemptContainerDetails')
EksAttemptDetail = Shapes::StructureShape.new(name: 'EksAttemptDetail')
EksAttemptDetails = Shapes::ListShape.new(name: 'EksAttemptDetails')
EksConfiguration = Shapes::StructureShape.new(name: 'EksConfiguration')
EksContainer = Shapes::StructureShape.new(name: 'EksContainer')
EksContainerDetail = Shapes::StructureShape.new(name: 'EksContainerDetail')
EksContainerDetails = Shapes::ListShape.new(name: 'EksContainerDetails')
EksContainerEnvironmentVariable = Shapes::StructureShape.new(name: 'EksContainerEnvironmentVariable')
EksContainerEnvironmentVariables = Shapes::ListShape.new(name: 'EksContainerEnvironmentVariables')
EksContainerOverride = Shapes::StructureShape.new(name: 'EksContainerOverride')
EksContainerOverrideList = Shapes::ListShape.new(name: 'EksContainerOverrideList')
EksContainerResourceRequirements = Shapes::StructureShape.new(name: 'EksContainerResourceRequirements')
EksContainerSecurityContext = Shapes::StructureShape.new(name: 'EksContainerSecurityContext')
EksContainerVolumeMount = Shapes::StructureShape.new(name: 'EksContainerVolumeMount')
EksContainerVolumeMounts = Shapes::ListShape.new(name: 'EksContainerVolumeMounts')
EksContainers = Shapes::ListShape.new(name: 'EksContainers')
EksEmptyDir = Shapes::StructureShape.new(name: 'EksEmptyDir')
EksHostPath = Shapes::StructureShape.new(name: 'EksHostPath')
EksLimits = Shapes::MapShape.new(name: 'EksLimits')
EksPodProperties = Shapes::StructureShape.new(name: 'EksPodProperties')
EksPodPropertiesDetail = Shapes::StructureShape.new(name: 'EksPodPropertiesDetail')
EksPodPropertiesOverride = Shapes::StructureShape.new(name: 'EksPodPropertiesOverride')
EksProperties = Shapes::StructureShape.new(name: 'EksProperties')
EksPropertiesDetail = Shapes::StructureShape.new(name: 'EksPropertiesDetail')
EksPropertiesOverride = Shapes::StructureShape.new(name: 'EksPropertiesOverride')
EksRequests = Shapes::MapShape.new(name: 'EksRequests')
EksSecret = Shapes::StructureShape.new(name: 'EksSecret')
EksVolume = Shapes::StructureShape.new(name: 'EksVolume')
EksVolumes = Shapes::ListShape.new(name: 'EksVolumes')
EnvironmentVariables = Shapes::ListShape.new(name: 'EnvironmentVariables')
EvaluateOnExit = Shapes::StructureShape.new(name: 'EvaluateOnExit')
EvaluateOnExitList = Shapes::ListShape.new(name: 'EvaluateOnExitList')
FairsharePolicy = Shapes::StructureShape.new(name: 'FairsharePolicy')
FargatePlatformConfiguration = Shapes::StructureShape.new(name: 'FargatePlatformConfiguration')
Float = Shapes::FloatShape.new(name: 'Float')
Host = Shapes::StructureShape.new(name: 'Host')
ImageIdOverride = Shapes::StringShape.new(name: 'ImageIdOverride')
ImageType = Shapes::StringShape.new(name: 'ImageType')
Integer = Shapes::IntegerShape.new(name: 'Integer')
JQState = Shapes::StringShape.new(name: 'JQState')
JQStatus = Shapes::StringShape.new(name: 'JQStatus')
JobDefinition = Shapes::StructureShape.new(name: 'JobDefinition')
JobDefinitionList = Shapes::ListShape.new(name: 'JobDefinitionList')
JobDefinitionType = Shapes::StringShape.new(name: 'JobDefinitionType')
JobDependency = Shapes::StructureShape.new(name: 'JobDependency')
JobDependencyList = Shapes::ListShape.new(name: 'JobDependencyList')
JobDetail = Shapes::StructureShape.new(name: 'JobDetail')
JobDetailList = Shapes::ListShape.new(name: 'JobDetailList')
JobExecutionTimeoutMinutes = Shapes::IntegerShape.new(name: 'JobExecutionTimeoutMinutes')
JobQueueDetail = Shapes::StructureShape.new(name: 'JobQueueDetail')
JobQueueDetailList = Shapes::ListShape.new(name: 'JobQueueDetailList')
JobStatus = Shapes::StringShape.new(name: 'JobStatus')
JobSummary = Shapes::StructureShape.new(name: 'JobSummary')
JobSummaryList = Shapes::ListShape.new(name: 'JobSummaryList')
JobTimeout = Shapes::StructureShape.new(name: 'JobTimeout')
KeyValuePair = Shapes::StructureShape.new(name: 'KeyValuePair')
KeyValuesPair = Shapes::StructureShape.new(name: 'KeyValuesPair')
KubernetesVersion = Shapes::StringShape.new(name: 'KubernetesVersion')
LaunchTemplateSpecification = Shapes::StructureShape.new(name: 'LaunchTemplateSpecification')
LinuxParameters = Shapes::StructureShape.new(name: 'LinuxParameters')
ListJobsFilterList = Shapes::ListShape.new(name: 'ListJobsFilterList')
ListJobsRequest = Shapes::StructureShape.new(name: 'ListJobsRequest')
ListJobsResponse = Shapes::StructureShape.new(name: 'ListJobsResponse')
ListSchedulingPoliciesRequest = Shapes::StructureShape.new(name: 'ListSchedulingPoliciesRequest')
ListSchedulingPoliciesResponse = Shapes::StructureShape.new(name: 'ListSchedulingPoliciesResponse')
ListTagsForResourceRequest = Shapes::StructureShape.new(name: 'ListTagsForResourceRequest')
ListTagsForResourceResponse = Shapes::StructureShape.new(name: 'ListTagsForResourceResponse')
LogConfiguration = Shapes::StructureShape.new(name: 'LogConfiguration')
LogConfigurationOptionsMap = Shapes::MapShape.new(name: 'LogConfigurationOptionsMap')
LogDriver = Shapes::StringShape.new(name: 'LogDriver')
Long = Shapes::IntegerShape.new(name: 'Long')
MountPoint = Shapes::StructureShape.new(name: 'MountPoint')
MountPoints = Shapes::ListShape.new(name: 'MountPoints')
NetworkConfiguration = Shapes::StructureShape.new(name: 'NetworkConfiguration')
NetworkInterface = Shapes::StructureShape.new(name: 'NetworkInterface')
NetworkInterfaceList = Shapes::ListShape.new(name: 'NetworkInterfaceList')
NodeDetails = Shapes::StructureShape.new(name: 'NodeDetails')
NodeOverrides = Shapes::StructureShape.new(name: 'NodeOverrides')
NodeProperties = Shapes::StructureShape.new(name: 'NodeProperties')
NodePropertiesSummary = Shapes::StructureShape.new(name: 'NodePropertiesSummary')
NodePropertyOverride = Shapes::StructureShape.new(name: 'NodePropertyOverride')
NodePropertyOverrides = Shapes::ListShape.new(name: 'NodePropertyOverrides')
NodeRangeProperties = Shapes::ListShape.new(name: 'NodeRangeProperties')
NodeRangeProperty = Shapes::StructureShape.new(name: 'NodeRangeProperty')
OrchestrationType = Shapes::StringShape.new(name: 'OrchestrationType')
ParametersMap = Shapes::MapShape.new(name: 'ParametersMap')
PlatformCapability = Shapes::StringShape.new(name: 'PlatformCapability')
PlatformCapabilityList = Shapes::ListShape.new(name: 'PlatformCapabilityList')
Quantity = Shapes::StringShape.new(name: 'Quantity')
RegisterJobDefinitionRequest = Shapes::StructureShape.new(name: 'RegisterJobDefinitionRequest')
RegisterJobDefinitionResponse = Shapes::StructureShape.new(name: 'RegisterJobDefinitionResponse')
ResourceRequirement = Shapes::StructureShape.new(name: 'ResourceRequirement')
ResourceRequirements = Shapes::ListShape.new(name: 'ResourceRequirements')
ResourceType = Shapes::StringShape.new(name: 'ResourceType')
RetryAction = Shapes::StringShape.new(name: 'RetryAction')
RetryStrategy = Shapes::StructureShape.new(name: 'RetryStrategy')
SchedulingPolicyDetail = Shapes::StructureShape.new(name: 'SchedulingPolicyDetail')
SchedulingPolicyDetailList = Shapes::ListShape.new(name: 'SchedulingPolicyDetailList')
SchedulingPolicyListingDetail = Shapes::StructureShape.new(name: 'SchedulingPolicyListingDetail')
SchedulingPolicyListingDetailList = Shapes::ListShape.new(name: 'SchedulingPolicyListingDetailList')
Secret = Shapes::StructureShape.new(name: 'Secret')
SecretList = Shapes::ListShape.new(name: 'SecretList')
ServerException = Shapes::StructureShape.new(name: 'ServerException')
ShareAttributes = Shapes::StructureShape.new(name: 'ShareAttributes')
ShareAttributesList = Shapes::ListShape.new(name: 'ShareAttributesList')
String = Shapes::StringShape.new(name: 'String')
StringList = Shapes::ListShape.new(name: 'StringList')
SubmitJobRequest = Shapes::StructureShape.new(name: 'SubmitJobRequest')
SubmitJobResponse = Shapes::StructureShape.new(name: 'SubmitJobResponse')
TagKey = Shapes::StringShape.new(name: 'TagKey')
TagKeysList = Shapes::ListShape.new(name: 'TagKeysList')
TagResourceRequest = Shapes::StructureShape.new(name: 'TagResourceRequest')
TagResourceResponse = Shapes::StructureShape.new(name: 'TagResourceResponse')
TagValue = Shapes::StringShape.new(name: 'TagValue')
TagrisTagsMap = Shapes::MapShape.new(name: 'TagrisTagsMap')
TagsMap = Shapes::MapShape.new(name: 'TagsMap')
TerminateJobRequest = Shapes::StructureShape.new(name: 'TerminateJobRequest')
TerminateJobResponse = Shapes::StructureShape.new(name: 'TerminateJobResponse')
Tmpfs = Shapes::StructureShape.new(name: 'Tmpfs')
TmpfsList = Shapes::ListShape.new(name: 'TmpfsList')
Ulimit = Shapes::StructureShape.new(name: 'Ulimit')
Ulimits = Shapes::ListShape.new(name: 'Ulimits')
UntagResourceRequest = Shapes::StructureShape.new(name: 'UntagResourceRequest')
UntagResourceResponse = Shapes::StructureShape.new(name: 'UntagResourceResponse')
UpdateComputeEnvironmentRequest = Shapes::StructureShape.new(name: 'UpdateComputeEnvironmentRequest')
UpdateComputeEnvironmentResponse = Shapes::StructureShape.new(name: 'UpdateComputeEnvironmentResponse')
UpdateJobQueueRequest = Shapes::StructureShape.new(name: 'UpdateJobQueueRequest')
UpdateJobQueueResponse = Shapes::StructureShape.new(name: 'UpdateJobQueueResponse')
UpdatePolicy = Shapes::StructureShape.new(name: 'UpdatePolicy')
UpdateSchedulingPolicyRequest = Shapes::StructureShape.new(name: 'UpdateSchedulingPolicyRequest')
UpdateSchedulingPolicyResponse = Shapes::StructureShape.new(name: 'UpdateSchedulingPolicyResponse')
Volume = Shapes::StructureShape.new(name: 'Volume')
Volumes = Shapes::ListShape.new(name: 'Volumes')
ArrayJobStatusSummary.key = Shapes::ShapeRef.new(shape: String)
ArrayJobStatusSummary.value = Shapes::ShapeRef.new(shape: Integer)
ArrayProperties.add_member(:size, Shapes::ShapeRef.new(shape: Integer, location_name: "size"))
ArrayProperties.struct_class = Types::ArrayProperties
ArrayPropertiesDetail.add_member(:status_summary, Shapes::ShapeRef.new(shape: ArrayJobStatusSummary, location_name: "statusSummary"))
ArrayPropertiesDetail.add_member(:size, Shapes::ShapeRef.new(shape: Integer, location_name: "size"))
ArrayPropertiesDetail.add_member(:index, Shapes::ShapeRef.new(shape: Integer, location_name: "index"))
ArrayPropertiesDetail.struct_class = Types::ArrayPropertiesDetail
ArrayPropertiesSummary.add_member(:size, Shapes::ShapeRef.new(shape: Integer, location_name: "size"))
ArrayPropertiesSummary.add_member(:index, Shapes::ShapeRef.new(shape: Integer, location_name: "index"))
ArrayPropertiesSummary.struct_class = Types::ArrayPropertiesSummary
AttemptContainerDetail.add_member(:container_instance_arn, Shapes::ShapeRef.new(shape: String, location_name: "containerInstanceArn"))
AttemptContainerDetail.add_member(:task_arn, Shapes::ShapeRef.new(shape: String, location_name: "taskArn"))
AttemptContainerDetail.add_member(:exit_code, Shapes::ShapeRef.new(shape: Integer, location_name: "exitCode"))
AttemptContainerDetail.add_member(:reason, Shapes::ShapeRef.new(shape: String, location_name: "reason"))
AttemptContainerDetail.add_member(:log_stream_name, Shapes::ShapeRef.new(shape: String, location_name: "logStreamName"))
AttemptContainerDetail.add_member(:network_interfaces, Shapes::ShapeRef.new(shape: NetworkInterfaceList, location_name: "networkInterfaces"))
AttemptContainerDetail.struct_class = Types::AttemptContainerDetail
AttemptDetail.add_member(:container, Shapes::ShapeRef.new(shape: AttemptContainerDetail, location_name: "container"))
AttemptDetail.add_member(:started_at, Shapes::ShapeRef.new(shape: Long, location_name: "startedAt"))
AttemptDetail.add_member(:stopped_at, Shapes::ShapeRef.new(shape: Long, location_name: "stoppedAt"))
AttemptDetail.add_member(:status_reason, Shapes::ShapeRef.new(shape: String, location_name: "statusReason"))
AttemptDetail.struct_class = Types::AttemptDetail
AttemptDetails.member = Shapes::ShapeRef.new(shape: AttemptDetail)
CancelJobRequest.add_member(:job_id, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobId"))
CancelJobRequest.add_member(:reason, Shapes::ShapeRef.new(shape: String, required: true, location_name: "reason"))
CancelJobRequest.struct_class = Types::CancelJobRequest
CancelJobResponse.struct_class = Types::CancelJobResponse
ClientException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "message"))
ClientException.struct_class = Types::ClientException
ComputeEnvironmentDetail.add_member(:compute_environment_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "computeEnvironmentName"))
ComputeEnvironmentDetail.add_member(:compute_environment_arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "computeEnvironmentArn"))
ComputeEnvironmentDetail.add_member(:unmanagedv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "unmanagedvCpus"))
ComputeEnvironmentDetail.add_member(:ecs_cluster_arn, Shapes::ShapeRef.new(shape: String, location_name: "ecsClusterArn"))
ComputeEnvironmentDetail.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
ComputeEnvironmentDetail.add_member(:type, Shapes::ShapeRef.new(shape: CEType, location_name: "type"))
ComputeEnvironmentDetail.add_member(:state, Shapes::ShapeRef.new(shape: CEState, location_name: "state"))
ComputeEnvironmentDetail.add_member(:status, Shapes::ShapeRef.new(shape: CEStatus, location_name: "status"))
ComputeEnvironmentDetail.add_member(:status_reason, Shapes::ShapeRef.new(shape: String, location_name: "statusReason"))
ComputeEnvironmentDetail.add_member(:compute_resources, Shapes::ShapeRef.new(shape: ComputeResource, location_name: "computeResources"))
ComputeEnvironmentDetail.add_member(:service_role, Shapes::ShapeRef.new(shape: String, location_name: "serviceRole"))
ComputeEnvironmentDetail.add_member(:update_policy, Shapes::ShapeRef.new(shape: UpdatePolicy, location_name: "updatePolicy"))
ComputeEnvironmentDetail.add_member(:eks_configuration, Shapes::ShapeRef.new(shape: EksConfiguration, location_name: "eksConfiguration"))
ComputeEnvironmentDetail.add_member(:container_orchestration_type, Shapes::ShapeRef.new(shape: OrchestrationType, location_name: "containerOrchestrationType"))
ComputeEnvironmentDetail.add_member(:uuid, Shapes::ShapeRef.new(shape: String, location_name: "uuid"))
ComputeEnvironmentDetail.struct_class = Types::ComputeEnvironmentDetail
ComputeEnvironmentDetailList.member = Shapes::ShapeRef.new(shape: ComputeEnvironmentDetail)
ComputeEnvironmentOrder.add_member(:order, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "order"))
ComputeEnvironmentOrder.add_member(:compute_environment, Shapes::ShapeRef.new(shape: String, required: true, location_name: "computeEnvironment"))
ComputeEnvironmentOrder.struct_class = Types::ComputeEnvironmentOrder
ComputeEnvironmentOrders.member = Shapes::ShapeRef.new(shape: ComputeEnvironmentOrder)
ComputeResource.add_member(:type, Shapes::ShapeRef.new(shape: CRType, required: true, location_name: "type"))
ComputeResource.add_member(:allocation_strategy, Shapes::ShapeRef.new(shape: CRAllocationStrategy, location_name: "allocationStrategy"))
ComputeResource.add_member(:minv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "minvCpus"))
ComputeResource.add_member(:maxv_cpus, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "maxvCpus"))
ComputeResource.add_member(:desiredv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "desiredvCpus"))
ComputeResource.add_member(:instance_types, Shapes::ShapeRef.new(shape: StringList, location_name: "instanceTypes"))
ComputeResource.add_member(:image_id, Shapes::ShapeRef.new(shape: String, deprecated: true, location_name: "imageId", metadata: {"deprecatedMessage"=>"This field is deprecated, use ec2Configuration[].imageIdOverride instead."}))
ComputeResource.add_member(:subnets, Shapes::ShapeRef.new(shape: StringList, required: true, location_name: "subnets"))
ComputeResource.add_member(:security_group_ids, Shapes::ShapeRef.new(shape: StringList, location_name: "securityGroupIds"))
ComputeResource.add_member(:ec2_key_pair, Shapes::ShapeRef.new(shape: String, location_name: "ec2KeyPair"))
ComputeResource.add_member(:instance_role, Shapes::ShapeRef.new(shape: String, location_name: "instanceRole"))
ComputeResource.add_member(:tags, Shapes::ShapeRef.new(shape: TagsMap, location_name: "tags"))
ComputeResource.add_member(:placement_group, Shapes::ShapeRef.new(shape: String, location_name: "placementGroup"))
ComputeResource.add_member(:bid_percentage, Shapes::ShapeRef.new(shape: Integer, location_name: "bidPercentage"))
ComputeResource.add_member(:spot_iam_fleet_role, Shapes::ShapeRef.new(shape: String, location_name: "spotIamFleetRole"))
ComputeResource.add_member(:launch_template, Shapes::ShapeRef.new(shape: LaunchTemplateSpecification, location_name: "launchTemplate"))
ComputeResource.add_member(:ec2_configuration, Shapes::ShapeRef.new(shape: Ec2ConfigurationList, location_name: "ec2Configuration"))
ComputeResource.struct_class = Types::ComputeResource
ComputeResourceUpdate.add_member(:minv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "minvCpus"))
ComputeResourceUpdate.add_member(:maxv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "maxvCpus"))
ComputeResourceUpdate.add_member(:desiredv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "desiredvCpus"))
ComputeResourceUpdate.add_member(:subnets, Shapes::ShapeRef.new(shape: StringList, location_name: "subnets"))
ComputeResourceUpdate.add_member(:security_group_ids, Shapes::ShapeRef.new(shape: StringList, location_name: "securityGroupIds"))
ComputeResourceUpdate.add_member(:allocation_strategy, Shapes::ShapeRef.new(shape: CRUpdateAllocationStrategy, location_name: "allocationStrategy"))
ComputeResourceUpdate.add_member(:instance_types, Shapes::ShapeRef.new(shape: StringList, location_name: "instanceTypes"))
ComputeResourceUpdate.add_member(:ec2_key_pair, Shapes::ShapeRef.new(shape: String, location_name: "ec2KeyPair"))
ComputeResourceUpdate.add_member(:instance_role, Shapes::ShapeRef.new(shape: String, location_name: "instanceRole"))
ComputeResourceUpdate.add_member(:tags, Shapes::ShapeRef.new(shape: TagsMap, location_name: "tags"))
ComputeResourceUpdate.add_member(:placement_group, Shapes::ShapeRef.new(shape: String, location_name: "placementGroup"))
ComputeResourceUpdate.add_member(:bid_percentage, Shapes::ShapeRef.new(shape: Integer, location_name: "bidPercentage"))
ComputeResourceUpdate.add_member(:launch_template, Shapes::ShapeRef.new(shape: LaunchTemplateSpecification, location_name: "launchTemplate"))
ComputeResourceUpdate.add_member(:ec2_configuration, Shapes::ShapeRef.new(shape: Ec2ConfigurationList, location_name: "ec2Configuration"))
ComputeResourceUpdate.add_member(:update_to_latest_image_version, Shapes::ShapeRef.new(shape: Boolean, location_name: "updateToLatestImageVersion"))
ComputeResourceUpdate.add_member(:type, Shapes::ShapeRef.new(shape: CRType, location_name: "type"))
ComputeResourceUpdate.add_member(:image_id, Shapes::ShapeRef.new(shape: String, location_name: "imageId"))
ComputeResourceUpdate.struct_class = Types::ComputeResourceUpdate
ContainerDetail.add_member(:image, Shapes::ShapeRef.new(shape: String, location_name: "image"))
ContainerDetail.add_member(:vcpus, Shapes::ShapeRef.new(shape: Integer, location_name: "vcpus"))
ContainerDetail.add_member(:memory, Shapes::ShapeRef.new(shape: Integer, location_name: "memory"))
ContainerDetail.add_member(:command, Shapes::ShapeRef.new(shape: StringList, location_name: "command"))
ContainerDetail.add_member(:job_role_arn, Shapes::ShapeRef.new(shape: String, location_name: "jobRoleArn"))
ContainerDetail.add_member(:execution_role_arn, Shapes::ShapeRef.new(shape: String, location_name: "executionRoleArn"))
ContainerDetail.add_member(:volumes, Shapes::ShapeRef.new(shape: Volumes, location_name: "volumes"))
ContainerDetail.add_member(:environment, Shapes::ShapeRef.new(shape: EnvironmentVariables, location_name: "environment"))
ContainerDetail.add_member(:mount_points, Shapes::ShapeRef.new(shape: MountPoints, location_name: "mountPoints"))
ContainerDetail.add_member(:readonly_root_filesystem, Shapes::ShapeRef.new(shape: Boolean, location_name: "readonlyRootFilesystem"))
ContainerDetail.add_member(:ulimits, Shapes::ShapeRef.new(shape: Ulimits, location_name: "ulimits"))
ContainerDetail.add_member(:privileged, Shapes::ShapeRef.new(shape: Boolean, location_name: "privileged"))
ContainerDetail.add_member(:user, Shapes::ShapeRef.new(shape: String, location_name: "user"))
ContainerDetail.add_member(:exit_code, Shapes::ShapeRef.new(shape: Integer, location_name: "exitCode"))
ContainerDetail.add_member(:reason, Shapes::ShapeRef.new(shape: String, location_name: "reason"))
ContainerDetail.add_member(:container_instance_arn, Shapes::ShapeRef.new(shape: String, location_name: "containerInstanceArn"))
ContainerDetail.add_member(:task_arn, Shapes::ShapeRef.new(shape: String, location_name: "taskArn"))
ContainerDetail.add_member(:log_stream_name, Shapes::ShapeRef.new(shape: String, location_name: "logStreamName"))
ContainerDetail.add_member(:instance_type, Shapes::ShapeRef.new(shape: String, location_name: "instanceType"))
ContainerDetail.add_member(:network_interfaces, Shapes::ShapeRef.new(shape: NetworkInterfaceList, location_name: "networkInterfaces"))
ContainerDetail.add_member(:resource_requirements, Shapes::ShapeRef.new(shape: ResourceRequirements, location_name: "resourceRequirements"))
ContainerDetail.add_member(:linux_parameters, Shapes::ShapeRef.new(shape: LinuxParameters, location_name: "linuxParameters"))
ContainerDetail.add_member(:log_configuration, Shapes::ShapeRef.new(shape: LogConfiguration, location_name: "logConfiguration"))
ContainerDetail.add_member(:secrets, Shapes::ShapeRef.new(shape: SecretList, location_name: "secrets"))
ContainerDetail.add_member(:network_configuration, Shapes::ShapeRef.new(shape: NetworkConfiguration, location_name: "networkConfiguration"))
ContainerDetail.add_member(:fargate_platform_configuration, Shapes::ShapeRef.new(shape: FargatePlatformConfiguration, location_name: "fargatePlatformConfiguration"))
ContainerDetail.struct_class = Types::ContainerDetail
ContainerOverrides.add_member(:vcpus, Shapes::ShapeRef.new(shape: Integer, deprecated: true, location_name: "vcpus", metadata: {"deprecatedMessage"=>"This field is deprecated, use resourceRequirements instead."}))
ContainerOverrides.add_member(:memory, Shapes::ShapeRef.new(shape: Integer, deprecated: true, location_name: "memory", metadata: {"deprecatedMessage"=>"This field is deprecated, use resourceRequirements instead."}))
ContainerOverrides.add_member(:command, Shapes::ShapeRef.new(shape: StringList, location_name: "command"))
ContainerOverrides.add_member(:instance_type, Shapes::ShapeRef.new(shape: String, location_name: "instanceType"))
ContainerOverrides.add_member(:environment, Shapes::ShapeRef.new(shape: EnvironmentVariables, location_name: "environment"))
ContainerOverrides.add_member(:resource_requirements, Shapes::ShapeRef.new(shape: ResourceRequirements, location_name: "resourceRequirements"))
ContainerOverrides.struct_class = Types::ContainerOverrides
ContainerProperties.add_member(:image, Shapes::ShapeRef.new(shape: String, location_name: "image"))
ContainerProperties.add_member(:vcpus, Shapes::ShapeRef.new(shape: Integer, deprecated: true, location_name: "vcpus", metadata: {"deprecatedMessage"=>"This field is deprecated, use resourceRequirements instead."}))
ContainerProperties.add_member(:memory, Shapes::ShapeRef.new(shape: Integer, deprecated: true, location_name: "memory", metadata: {"deprecatedMessage"=>"This field is deprecated, use resourceRequirements instead."}))
ContainerProperties.add_member(:command, Shapes::ShapeRef.new(shape: StringList, location_name: "command"))
ContainerProperties.add_member(:job_role_arn, Shapes::ShapeRef.new(shape: String, location_name: "jobRoleArn"))
ContainerProperties.add_member(:execution_role_arn, Shapes::ShapeRef.new(shape: String, location_name: "executionRoleArn"))
ContainerProperties.add_member(:volumes, Shapes::ShapeRef.new(shape: Volumes, location_name: "volumes"))
ContainerProperties.add_member(:environment, Shapes::ShapeRef.new(shape: EnvironmentVariables, location_name: "environment"))
ContainerProperties.add_member(:mount_points, Shapes::ShapeRef.new(shape: MountPoints, location_name: "mountPoints"))
ContainerProperties.add_member(:readonly_root_filesystem, Shapes::ShapeRef.new(shape: Boolean, location_name: "readonlyRootFilesystem"))
ContainerProperties.add_member(:privileged, Shapes::ShapeRef.new(shape: Boolean, location_name: "privileged"))
ContainerProperties.add_member(:ulimits, Shapes::ShapeRef.new(shape: Ulimits, location_name: "ulimits"))
ContainerProperties.add_member(:user, Shapes::ShapeRef.new(shape: String, location_name: "user"))
ContainerProperties.add_member(:instance_type, Shapes::ShapeRef.new(shape: String, location_name: "instanceType"))
ContainerProperties.add_member(:resource_requirements, Shapes::ShapeRef.new(shape: ResourceRequirements, location_name: "resourceRequirements"))
ContainerProperties.add_member(:linux_parameters, Shapes::ShapeRef.new(shape: LinuxParameters, location_name: "linuxParameters"))
ContainerProperties.add_member(:log_configuration, Shapes::ShapeRef.new(shape: LogConfiguration, location_name: "logConfiguration"))
ContainerProperties.add_member(:secrets, Shapes::ShapeRef.new(shape: SecretList, location_name: "secrets"))
ContainerProperties.add_member(:network_configuration, Shapes::ShapeRef.new(shape: NetworkConfiguration, location_name: "networkConfiguration"))
ContainerProperties.add_member(:fargate_platform_configuration, Shapes::ShapeRef.new(shape: FargatePlatformConfiguration, location_name: "fargatePlatformConfiguration"))
ContainerProperties.struct_class = Types::ContainerProperties
ContainerSummary.add_member(:exit_code, Shapes::ShapeRef.new(shape: Integer, location_name: "exitCode"))
ContainerSummary.add_member(:reason, Shapes::ShapeRef.new(shape: String, location_name: "reason"))
ContainerSummary.struct_class = Types::ContainerSummary
CreateComputeEnvironmentRequest.add_member(:compute_environment_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "computeEnvironmentName"))
CreateComputeEnvironmentRequest.add_member(:type, Shapes::ShapeRef.new(shape: CEType, required: true, location_name: "type"))
CreateComputeEnvironmentRequest.add_member(:state, Shapes::ShapeRef.new(shape: CEState, location_name: "state"))
CreateComputeEnvironmentRequest.add_member(:unmanagedv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "unmanagedvCpus"))
CreateComputeEnvironmentRequest.add_member(:compute_resources, Shapes::ShapeRef.new(shape: ComputeResource, location_name: "computeResources"))
CreateComputeEnvironmentRequest.add_member(:service_role, Shapes::ShapeRef.new(shape: String, location_name: "serviceRole"))
CreateComputeEnvironmentRequest.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
CreateComputeEnvironmentRequest.add_member(:eks_configuration, Shapes::ShapeRef.new(shape: EksConfiguration, location_name: "eksConfiguration"))
CreateComputeEnvironmentRequest.struct_class = Types::CreateComputeEnvironmentRequest
CreateComputeEnvironmentResponse.add_member(:compute_environment_name, Shapes::ShapeRef.new(shape: String, location_name: "computeEnvironmentName"))
CreateComputeEnvironmentResponse.add_member(:compute_environment_arn, Shapes::ShapeRef.new(shape: String, location_name: "computeEnvironmentArn"))
CreateComputeEnvironmentResponse.struct_class = Types::CreateComputeEnvironmentResponse
CreateJobQueueRequest.add_member(:job_queue_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueueName"))
CreateJobQueueRequest.add_member(:state, Shapes::ShapeRef.new(shape: JQState, location_name: "state"))
CreateJobQueueRequest.add_member(:scheduling_policy_arn, Shapes::ShapeRef.new(shape: String, location_name: "schedulingPolicyArn"))
CreateJobQueueRequest.add_member(:priority, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "priority"))
CreateJobQueueRequest.add_member(:compute_environment_order, Shapes::ShapeRef.new(shape: ComputeEnvironmentOrders, required: true, location_name: "computeEnvironmentOrder"))
CreateJobQueueRequest.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
CreateJobQueueRequest.struct_class = Types::CreateJobQueueRequest
CreateJobQueueResponse.add_member(:job_queue_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueueName"))
CreateJobQueueResponse.add_member(:job_queue_arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueueArn"))
CreateJobQueueResponse.struct_class = Types::CreateJobQueueResponse
CreateSchedulingPolicyRequest.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
CreateSchedulingPolicyRequest.add_member(:fairshare_policy, Shapes::ShapeRef.new(shape: FairsharePolicy, location_name: "fairsharePolicy"))
CreateSchedulingPolicyRequest.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
CreateSchedulingPolicyRequest.struct_class = Types::CreateSchedulingPolicyRequest
CreateSchedulingPolicyResponse.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
CreateSchedulingPolicyResponse.add_member(:arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "arn"))
CreateSchedulingPolicyResponse.struct_class = Types::CreateSchedulingPolicyResponse
DeleteComputeEnvironmentRequest.add_member(:compute_environment, Shapes::ShapeRef.new(shape: String, required: true, location_name: "computeEnvironment"))
DeleteComputeEnvironmentRequest.struct_class = Types::DeleteComputeEnvironmentRequest
DeleteComputeEnvironmentResponse.struct_class = Types::DeleteComputeEnvironmentResponse
DeleteJobQueueRequest.add_member(:job_queue, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueue"))
DeleteJobQueueRequest.struct_class = Types::DeleteJobQueueRequest
DeleteJobQueueResponse.struct_class = Types::DeleteJobQueueResponse
DeleteSchedulingPolicyRequest.add_member(:arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "arn"))
DeleteSchedulingPolicyRequest.struct_class = Types::DeleteSchedulingPolicyRequest
DeleteSchedulingPolicyResponse.struct_class = Types::DeleteSchedulingPolicyResponse
DeregisterJobDefinitionRequest.add_member(:job_definition, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinition"))
DeregisterJobDefinitionRequest.struct_class = Types::DeregisterJobDefinitionRequest
DeregisterJobDefinitionResponse.struct_class = Types::DeregisterJobDefinitionResponse
DescribeComputeEnvironmentsRequest.add_member(:compute_environments, Shapes::ShapeRef.new(shape: StringList, location_name: "computeEnvironments"))
DescribeComputeEnvironmentsRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: Integer, location_name: "maxResults"))
DescribeComputeEnvironmentsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
DescribeComputeEnvironmentsRequest.struct_class = Types::DescribeComputeEnvironmentsRequest
DescribeComputeEnvironmentsResponse.add_member(:compute_environments, Shapes::ShapeRef.new(shape: ComputeEnvironmentDetailList, location_name: "computeEnvironments"))
DescribeComputeEnvironmentsResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
DescribeComputeEnvironmentsResponse.struct_class = Types::DescribeComputeEnvironmentsResponse
DescribeJobDefinitionsRequest.add_member(:job_definitions, Shapes::ShapeRef.new(shape: StringList, location_name: "jobDefinitions"))
DescribeJobDefinitionsRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: Integer, location_name: "maxResults"))
DescribeJobDefinitionsRequest.add_member(:job_definition_name, Shapes::ShapeRef.new(shape: String, location_name: "jobDefinitionName"))
DescribeJobDefinitionsRequest.add_member(:status, Shapes::ShapeRef.new(shape: String, location_name: "status"))
DescribeJobDefinitionsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
DescribeJobDefinitionsRequest.struct_class = Types::DescribeJobDefinitionsRequest
DescribeJobDefinitionsResponse.add_member(:job_definitions, Shapes::ShapeRef.new(shape: JobDefinitionList, location_name: "jobDefinitions"))
DescribeJobDefinitionsResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
DescribeJobDefinitionsResponse.struct_class = Types::DescribeJobDefinitionsResponse
DescribeJobQueuesRequest.add_member(:job_queues, Shapes::ShapeRef.new(shape: StringList, location_name: "jobQueues"))
DescribeJobQueuesRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: Integer, location_name: "maxResults"))
DescribeJobQueuesRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
DescribeJobQueuesRequest.struct_class = Types::DescribeJobQueuesRequest
DescribeJobQueuesResponse.add_member(:job_queues, Shapes::ShapeRef.new(shape: JobQueueDetailList, location_name: "jobQueues"))
DescribeJobQueuesResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
DescribeJobQueuesResponse.struct_class = Types::DescribeJobQueuesResponse
DescribeJobsRequest.add_member(:jobs, Shapes::ShapeRef.new(shape: StringList, required: true, location_name: "jobs"))
DescribeJobsRequest.struct_class = Types::DescribeJobsRequest
DescribeJobsResponse.add_member(:jobs, Shapes::ShapeRef.new(shape: JobDetailList, location_name: "jobs"))
DescribeJobsResponse.struct_class = Types::DescribeJobsResponse
DescribeSchedulingPoliciesRequest.add_member(:arns, Shapes::ShapeRef.new(shape: StringList, required: true, location_name: "arns"))
DescribeSchedulingPoliciesRequest.struct_class = Types::DescribeSchedulingPoliciesRequest
DescribeSchedulingPoliciesResponse.add_member(:scheduling_policies, Shapes::ShapeRef.new(shape: SchedulingPolicyDetailList, location_name: "schedulingPolicies"))
DescribeSchedulingPoliciesResponse.struct_class = Types::DescribeSchedulingPoliciesResponse
Device.add_member(:host_path, Shapes::ShapeRef.new(shape: String, required: true, location_name: "hostPath"))
Device.add_member(:container_path, Shapes::ShapeRef.new(shape: String, location_name: "containerPath"))
Device.add_member(:permissions, Shapes::ShapeRef.new(shape: DeviceCgroupPermissions, location_name: "permissions"))
Device.struct_class = Types::Device
DeviceCgroupPermissions.member = Shapes::ShapeRef.new(shape: DeviceCgroupPermission)
DevicesList.member = Shapes::ShapeRef.new(shape: Device)
EFSAuthorizationConfig.add_member(:access_point_id, Shapes::ShapeRef.new(shape: String, location_name: "accessPointId"))
EFSAuthorizationConfig.add_member(:iam, Shapes::ShapeRef.new(shape: EFSAuthorizationConfigIAM, location_name: "iam"))
EFSAuthorizationConfig.struct_class = Types::EFSAuthorizationConfig
EFSVolumeConfiguration.add_member(:file_system_id, Shapes::ShapeRef.new(shape: String, required: true, location_name: "fileSystemId"))
EFSVolumeConfiguration.add_member(:root_directory, Shapes::ShapeRef.new(shape: String, location_name: "rootDirectory"))
EFSVolumeConfiguration.add_member(:transit_encryption, Shapes::ShapeRef.new(shape: EFSTransitEncryption, location_name: "transitEncryption"))
EFSVolumeConfiguration.add_member(:transit_encryption_port, Shapes::ShapeRef.new(shape: Integer, location_name: "transitEncryptionPort"))
EFSVolumeConfiguration.add_member(:authorization_config, Shapes::ShapeRef.new(shape: EFSAuthorizationConfig, location_name: "authorizationConfig"))
EFSVolumeConfiguration.struct_class = Types::EFSVolumeConfiguration
Ec2Configuration.add_member(:image_type, Shapes::ShapeRef.new(shape: ImageType, required: true, location_name: "imageType"))
Ec2Configuration.add_member(:image_id_override, Shapes::ShapeRef.new(shape: ImageIdOverride, location_name: "imageIdOverride"))
Ec2Configuration.add_member(:image_kubernetes_version, Shapes::ShapeRef.new(shape: KubernetesVersion, location_name: "imageKubernetesVersion"))
Ec2Configuration.struct_class = Types::Ec2Configuration
Ec2ConfigurationList.member = Shapes::ShapeRef.new(shape: Ec2Configuration)
EksAttemptContainerDetail.add_member(:exit_code, Shapes::ShapeRef.new(shape: Integer, location_name: "exitCode"))
EksAttemptContainerDetail.add_member(:reason, Shapes::ShapeRef.new(shape: String, location_name: "reason"))
EksAttemptContainerDetail.struct_class = Types::EksAttemptContainerDetail
EksAttemptContainerDetails.member = Shapes::ShapeRef.new(shape: EksAttemptContainerDetail)
EksAttemptDetail.add_member(:containers, Shapes::ShapeRef.new(shape: EksAttemptContainerDetails, location_name: "containers"))
EksAttemptDetail.add_member(:pod_name, Shapes::ShapeRef.new(shape: String, location_name: "podName"))
EksAttemptDetail.add_member(:node_name, Shapes::ShapeRef.new(shape: String, location_name: "nodeName"))
EksAttemptDetail.add_member(:started_at, Shapes::ShapeRef.new(shape: Long, location_name: "startedAt"))
EksAttemptDetail.add_member(:stopped_at, Shapes::ShapeRef.new(shape: Long, location_name: "stoppedAt"))
EksAttemptDetail.add_member(:status_reason, Shapes::ShapeRef.new(shape: String, location_name: "statusReason"))
EksAttemptDetail.struct_class = Types::EksAttemptDetail
EksAttemptDetails.member = Shapes::ShapeRef.new(shape: EksAttemptDetail)
EksConfiguration.add_member(:eks_cluster_arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "eksClusterArn"))
EksConfiguration.add_member(:kubernetes_namespace, Shapes::ShapeRef.new(shape: String, required: true, location_name: "kubernetesNamespace"))
EksConfiguration.struct_class = Types::EksConfiguration
EksContainer.add_member(:name, Shapes::ShapeRef.new(shape: String, location_name: "name"))
EksContainer.add_member(:image, Shapes::ShapeRef.new(shape: String, required: true, location_name: "image"))
EksContainer.add_member(:image_pull_policy, Shapes::ShapeRef.new(shape: String, location_name: "imagePullPolicy"))
EksContainer.add_member(:command, Shapes::ShapeRef.new(shape: StringList, location_name: "command"))
EksContainer.add_member(:args, Shapes::ShapeRef.new(shape: StringList, location_name: "args"))
EksContainer.add_member(:env, Shapes::ShapeRef.new(shape: EksContainerEnvironmentVariables, location_name: "env"))
EksContainer.add_member(:resources, Shapes::ShapeRef.new(shape: EksContainerResourceRequirements, location_name: "resources"))
EksContainer.add_member(:volume_mounts, Shapes::ShapeRef.new(shape: EksContainerVolumeMounts, location_name: "volumeMounts"))
EksContainer.add_member(:security_context, Shapes::ShapeRef.new(shape: EksContainerSecurityContext, location_name: "securityContext"))
EksContainer.struct_class = Types::EksContainer
EksContainerDetail.add_member(:name, Shapes::ShapeRef.new(shape: String, location_name: "name"))
EksContainerDetail.add_member(:image, Shapes::ShapeRef.new(shape: String, location_name: "image"))
EksContainerDetail.add_member(:image_pull_policy, Shapes::ShapeRef.new(shape: String, location_name: "imagePullPolicy"))
EksContainerDetail.add_member(:command, Shapes::ShapeRef.new(shape: StringList, location_name: "command"))
EksContainerDetail.add_member(:args, Shapes::ShapeRef.new(shape: StringList, location_name: "args"))
EksContainerDetail.add_member(:env, Shapes::ShapeRef.new(shape: EksContainerEnvironmentVariables, location_name: "env"))
EksContainerDetail.add_member(:resources, Shapes::ShapeRef.new(shape: EksContainerResourceRequirements, location_name: "resources"))
EksContainerDetail.add_member(:exit_code, Shapes::ShapeRef.new(shape: Integer, location_name: "exitCode"))
EksContainerDetail.add_member(:reason, Shapes::ShapeRef.new(shape: String, location_name: "reason"))
EksContainerDetail.add_member(:volume_mounts, Shapes::ShapeRef.new(shape: EksContainerVolumeMounts, location_name: "volumeMounts"))
EksContainerDetail.add_member(:security_context, Shapes::ShapeRef.new(shape: EksContainerSecurityContext, location_name: "securityContext"))
EksContainerDetail.struct_class = Types::EksContainerDetail
EksContainerDetails.member = Shapes::ShapeRef.new(shape: EksContainerDetail)
EksContainerEnvironmentVariable.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
EksContainerEnvironmentVariable.add_member(:value, Shapes::ShapeRef.new(shape: String, location_name: "value"))
EksContainerEnvironmentVariable.struct_class = Types::EksContainerEnvironmentVariable
EksContainerEnvironmentVariables.member = Shapes::ShapeRef.new(shape: EksContainerEnvironmentVariable)
EksContainerOverride.add_member(:image, Shapes::ShapeRef.new(shape: String, location_name: "image"))
EksContainerOverride.add_member(:command, Shapes::ShapeRef.new(shape: StringList, location_name: "command"))
EksContainerOverride.add_member(:args, Shapes::ShapeRef.new(shape: StringList, location_name: "args"))
EksContainerOverride.add_member(:env, Shapes::ShapeRef.new(shape: EksContainerEnvironmentVariables, location_name: "env"))
EksContainerOverride.add_member(:resources, Shapes::ShapeRef.new(shape: EksContainerResourceRequirements, location_name: "resources"))
EksContainerOverride.struct_class = Types::EksContainerOverride
EksContainerOverrideList.member = Shapes::ShapeRef.new(shape: EksContainerOverride)
EksContainerResourceRequirements.add_member(:limits, Shapes::ShapeRef.new(shape: EksLimits, location_name: "limits"))
EksContainerResourceRequirements.add_member(:requests, Shapes::ShapeRef.new(shape: EksRequests, location_name: "requests"))
EksContainerResourceRequirements.struct_class = Types::EksContainerResourceRequirements
EksContainerSecurityContext.add_member(:run_as_user, Shapes::ShapeRef.new(shape: Long, location_name: "runAsUser"))
EksContainerSecurityContext.add_member(:run_as_group, Shapes::ShapeRef.new(shape: Long, location_name: "runAsGroup"))
EksContainerSecurityContext.add_member(:privileged, Shapes::ShapeRef.new(shape: Boolean, location_name: "privileged"))
EksContainerSecurityContext.add_member(:read_only_root_filesystem, Shapes::ShapeRef.new(shape: Boolean, location_name: "readOnlyRootFilesystem"))
EksContainerSecurityContext.add_member(:run_as_non_root, Shapes::ShapeRef.new(shape: Boolean, location_name: "runAsNonRoot"))
EksContainerSecurityContext.struct_class = Types::EksContainerSecurityContext
EksContainerVolumeMount.add_member(:name, Shapes::ShapeRef.new(shape: String, location_name: "name"))
EksContainerVolumeMount.add_member(:mount_path, Shapes::ShapeRef.new(shape: String, location_name: "mountPath"))
EksContainerVolumeMount.add_member(:read_only, Shapes::ShapeRef.new(shape: Boolean, location_name: "readOnly"))
EksContainerVolumeMount.struct_class = Types::EksContainerVolumeMount
EksContainerVolumeMounts.member = Shapes::ShapeRef.new(shape: EksContainerVolumeMount)
EksContainers.member = Shapes::ShapeRef.new(shape: EksContainer)
EksEmptyDir.add_member(:medium, Shapes::ShapeRef.new(shape: String, location_name: "medium"))
EksEmptyDir.add_member(:size_limit, Shapes::ShapeRef.new(shape: Quantity, location_name: "sizeLimit"))
EksEmptyDir.struct_class = Types::EksEmptyDir
EksHostPath.add_member(:path, Shapes::ShapeRef.new(shape: String, location_name: "path"))
EksHostPath.struct_class = Types::EksHostPath
EksLimits.key = Shapes::ShapeRef.new(shape: String)
EksLimits.value = Shapes::ShapeRef.new(shape: Quantity)
EksPodProperties.add_member(:service_account_name, Shapes::ShapeRef.new(shape: String, location_name: "serviceAccountName"))
EksPodProperties.add_member(:host_network, Shapes::ShapeRef.new(shape: Boolean, location_name: "hostNetwork"))
EksPodProperties.add_member(:dns_policy, Shapes::ShapeRef.new(shape: String, location_name: "dnsPolicy"))
EksPodProperties.add_member(:containers, Shapes::ShapeRef.new(shape: EksContainers, location_name: "containers"))
EksPodProperties.add_member(:volumes, Shapes::ShapeRef.new(shape: EksVolumes, location_name: "volumes"))
EksPodProperties.struct_class = Types::EksPodProperties
EksPodPropertiesDetail.add_member(:service_account_name, Shapes::ShapeRef.new(shape: String, location_name: "serviceAccountName"))
EksPodPropertiesDetail.add_member(:host_network, Shapes::ShapeRef.new(shape: Boolean, location_name: "hostNetwork"))
EksPodPropertiesDetail.add_member(:dns_policy, Shapes::ShapeRef.new(shape: String, location_name: "dnsPolicy"))
EksPodPropertiesDetail.add_member(:containers, Shapes::ShapeRef.new(shape: EksContainerDetails, location_name: "containers"))
EksPodPropertiesDetail.add_member(:volumes, Shapes::ShapeRef.new(shape: EksVolumes, location_name: "volumes"))
EksPodPropertiesDetail.add_member(:pod_name, Shapes::ShapeRef.new(shape: String, location_name: "podName"))
EksPodPropertiesDetail.add_member(:node_name, Shapes::ShapeRef.new(shape: String, location_name: "nodeName"))
EksPodPropertiesDetail.struct_class = Types::EksPodPropertiesDetail
EksPodPropertiesOverride.add_member(:containers, Shapes::ShapeRef.new(shape: EksContainerOverrideList, location_name: "containers"))
EksPodPropertiesOverride.struct_class = Types::EksPodPropertiesOverride
EksProperties.add_member(:pod_properties, Shapes::ShapeRef.new(shape: EksPodProperties, location_name: "podProperties"))
EksProperties.struct_class = Types::EksProperties
EksPropertiesDetail.add_member(:pod_properties, Shapes::ShapeRef.new(shape: EksPodPropertiesDetail, location_name: "podProperties"))
EksPropertiesDetail.struct_class = Types::EksPropertiesDetail
EksPropertiesOverride.add_member(:pod_properties, Shapes::ShapeRef.new(shape: EksPodPropertiesOverride, location_name: "podProperties"))
EksPropertiesOverride.struct_class = Types::EksPropertiesOverride
EksRequests.key = Shapes::ShapeRef.new(shape: String)
EksRequests.value = Shapes::ShapeRef.new(shape: Quantity)
EksSecret.add_member(:secret_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "secretName"))
EksSecret.add_member(:optional, Shapes::ShapeRef.new(shape: Boolean, location_name: "optional"))
EksSecret.struct_class = Types::EksSecret
EksVolume.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
EksVolume.add_member(:host_path, Shapes::ShapeRef.new(shape: EksHostPath, location_name: "hostPath"))
EksVolume.add_member(:empty_dir, Shapes::ShapeRef.new(shape: EksEmptyDir, location_name: "emptyDir"))
EksVolume.add_member(:secret, Shapes::ShapeRef.new(shape: EksSecret, location_name: "secret"))
EksVolume.struct_class = Types::EksVolume
EksVolumes.member = Shapes::ShapeRef.new(shape: EksVolume)
EnvironmentVariables.member = Shapes::ShapeRef.new(shape: KeyValuePair)
EvaluateOnExit.add_member(:on_status_reason, Shapes::ShapeRef.new(shape: String, location_name: "onStatusReason"))
EvaluateOnExit.add_member(:on_reason, Shapes::ShapeRef.new(shape: String, location_name: "onReason"))
EvaluateOnExit.add_member(:on_exit_code, Shapes::ShapeRef.new(shape: String, location_name: "onExitCode"))
EvaluateOnExit.add_member(:action, Shapes::ShapeRef.new(shape: RetryAction, required: true, location_name: "action"))
EvaluateOnExit.struct_class = Types::EvaluateOnExit
EvaluateOnExitList.member = Shapes::ShapeRef.new(shape: EvaluateOnExit)
FairsharePolicy.add_member(:share_decay_seconds, Shapes::ShapeRef.new(shape: Integer, location_name: "shareDecaySeconds"))
FairsharePolicy.add_member(:compute_reservation, Shapes::ShapeRef.new(shape: Integer, location_name: "computeReservation"))
FairsharePolicy.add_member(:share_distribution, Shapes::ShapeRef.new(shape: ShareAttributesList, location_name: "shareDistribution"))
FairsharePolicy.struct_class = Types::FairsharePolicy
FargatePlatformConfiguration.add_member(:platform_version, Shapes::ShapeRef.new(shape: String, location_name: "platformVersion"))
FargatePlatformConfiguration.struct_class = Types::FargatePlatformConfiguration
Host.add_member(:source_path, Shapes::ShapeRef.new(shape: String, location_name: "sourcePath"))
Host.struct_class = Types::Host
JobDefinition.add_member(:job_definition_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinitionName"))
JobDefinition.add_member(:job_definition_arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinitionArn"))
JobDefinition.add_member(:revision, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "revision"))
JobDefinition.add_member(:status, Shapes::ShapeRef.new(shape: String, location_name: "status"))
JobDefinition.add_member(:type, Shapes::ShapeRef.new(shape: String, required: true, location_name: "type"))
JobDefinition.add_member(:scheduling_priority, Shapes::ShapeRef.new(shape: Integer, location_name: "schedulingPriority"))
JobDefinition.add_member(:parameters, Shapes::ShapeRef.new(shape: ParametersMap, location_name: "parameters"))
JobDefinition.add_member(:retry_strategy, Shapes::ShapeRef.new(shape: RetryStrategy, location_name: "retryStrategy"))
JobDefinition.add_member(:container_properties, Shapes::ShapeRef.new(shape: ContainerProperties, location_name: "containerProperties"))
JobDefinition.add_member(:timeout, Shapes::ShapeRef.new(shape: JobTimeout, location_name: "timeout"))
JobDefinition.add_member(:node_properties, Shapes::ShapeRef.new(shape: NodeProperties, location_name: "nodeProperties"))
JobDefinition.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
JobDefinition.add_member(:propagate_tags, Shapes::ShapeRef.new(shape: Boolean, location_name: "propagateTags"))
JobDefinition.add_member(:platform_capabilities, Shapes::ShapeRef.new(shape: PlatformCapabilityList, location_name: "platformCapabilities"))
JobDefinition.add_member(:eks_properties, Shapes::ShapeRef.new(shape: EksProperties, location_name: "eksProperties"))
JobDefinition.add_member(:container_orchestration_type, Shapes::ShapeRef.new(shape: OrchestrationType, location_name: "containerOrchestrationType"))
JobDefinition.struct_class = Types::JobDefinition
JobDefinitionList.member = Shapes::ShapeRef.new(shape: JobDefinition)
JobDependency.add_member(:job_id, Shapes::ShapeRef.new(shape: String, location_name: "jobId"))
JobDependency.add_member(:type, Shapes::ShapeRef.new(shape: ArrayJobDependency, location_name: "type"))
JobDependency.struct_class = Types::JobDependency
JobDependencyList.member = Shapes::ShapeRef.new(shape: JobDependency)
JobDetail.add_member(:job_arn, Shapes::ShapeRef.new(shape: String, location_name: "jobArn"))
JobDetail.add_member(:job_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobName"))
JobDetail.add_member(:job_id, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobId"))
JobDetail.add_member(:job_queue, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueue"))
JobDetail.add_member(:status, Shapes::ShapeRef.new(shape: JobStatus, required: true, location_name: "status"))
JobDetail.add_member(:share_identifier, Shapes::ShapeRef.new(shape: String, location_name: "shareIdentifier"))
JobDetail.add_member(:scheduling_priority, Shapes::ShapeRef.new(shape: Integer, location_name: "schedulingPriority"))
JobDetail.add_member(:attempts, Shapes::ShapeRef.new(shape: AttemptDetails, location_name: "attempts"))
JobDetail.add_member(:status_reason, Shapes::ShapeRef.new(shape: String, location_name: "statusReason"))
JobDetail.add_member(:created_at, Shapes::ShapeRef.new(shape: Long, location_name: "createdAt"))
JobDetail.add_member(:retry_strategy, Shapes::ShapeRef.new(shape: RetryStrategy, location_name: "retryStrategy"))
JobDetail.add_member(:started_at, Shapes::ShapeRef.new(shape: Long, required: true, location_name: "startedAt"))
JobDetail.add_member(:stopped_at, Shapes::ShapeRef.new(shape: Long, location_name: "stoppedAt"))
JobDetail.add_member(:depends_on, Shapes::ShapeRef.new(shape: JobDependencyList, location_name: "dependsOn"))
JobDetail.add_member(:job_definition, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinition"))
JobDetail.add_member(:parameters, Shapes::ShapeRef.new(shape: ParametersMap, location_name: "parameters"))
JobDetail.add_member(:container, Shapes::ShapeRef.new(shape: ContainerDetail, location_name: "container"))
JobDetail.add_member(:node_details, Shapes::ShapeRef.new(shape: NodeDetails, location_name: "nodeDetails"))
JobDetail.add_member(:node_properties, Shapes::ShapeRef.new(shape: NodeProperties, location_name: "nodeProperties"))
JobDetail.add_member(:array_properties, Shapes::ShapeRef.new(shape: ArrayPropertiesDetail, location_name: "arrayProperties"))
JobDetail.add_member(:timeout, Shapes::ShapeRef.new(shape: JobTimeout, location_name: "timeout"))
JobDetail.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
JobDetail.add_member(:propagate_tags, Shapes::ShapeRef.new(shape: Boolean, location_name: "propagateTags"))
JobDetail.add_member(:platform_capabilities, Shapes::ShapeRef.new(shape: PlatformCapabilityList, location_name: "platformCapabilities"))
JobDetail.add_member(:eks_properties, Shapes::ShapeRef.new(shape: EksPropertiesDetail, location_name: "eksProperties"))
JobDetail.add_member(:eks_attempts, Shapes::ShapeRef.new(shape: EksAttemptDetails, location_name: "eksAttempts"))
JobDetail.struct_class = Types::JobDetail
JobDetailList.member = Shapes::ShapeRef.new(shape: JobDetail)
JobQueueDetail.add_member(:job_queue_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueueName"))
JobQueueDetail.add_member(:job_queue_arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueueArn"))
JobQueueDetail.add_member(:state, Shapes::ShapeRef.new(shape: JQState, required: true, location_name: "state"))
JobQueueDetail.add_member(:scheduling_policy_arn, Shapes::ShapeRef.new(shape: String, location_name: "schedulingPolicyArn"))
JobQueueDetail.add_member(:status, Shapes::ShapeRef.new(shape: JQStatus, location_name: "status"))
JobQueueDetail.add_member(:status_reason, Shapes::ShapeRef.new(shape: String, location_name: "statusReason"))
JobQueueDetail.add_member(:priority, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "priority"))
JobQueueDetail.add_member(:compute_environment_order, Shapes::ShapeRef.new(shape: ComputeEnvironmentOrders, required: true, location_name: "computeEnvironmentOrder"))
JobQueueDetail.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
JobQueueDetail.struct_class = Types::JobQueueDetail
JobQueueDetailList.member = Shapes::ShapeRef.new(shape: JobQueueDetail)
JobSummary.add_member(:job_arn, Shapes::ShapeRef.new(shape: String, location_name: "jobArn"))
JobSummary.add_member(:job_id, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobId"))
JobSummary.add_member(:job_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobName"))
JobSummary.add_member(:created_at, Shapes::ShapeRef.new(shape: Long, location_name: "createdAt"))
JobSummary.add_member(:status, Shapes::ShapeRef.new(shape: JobStatus, location_name: "status"))
JobSummary.add_member(:status_reason, Shapes::ShapeRef.new(shape: String, location_name: "statusReason"))
JobSummary.add_member(:started_at, Shapes::ShapeRef.new(shape: Long, location_name: "startedAt"))
JobSummary.add_member(:stopped_at, Shapes::ShapeRef.new(shape: Long, location_name: "stoppedAt"))
JobSummary.add_member(:container, Shapes::ShapeRef.new(shape: ContainerSummary, location_name: "container"))
JobSummary.add_member(:array_properties, Shapes::ShapeRef.new(shape: ArrayPropertiesSummary, location_name: "arrayProperties"))
JobSummary.add_member(:node_properties, Shapes::ShapeRef.new(shape: NodePropertiesSummary, location_name: "nodeProperties"))
JobSummary.add_member(:job_definition, Shapes::ShapeRef.new(shape: String, location_name: "jobDefinition"))
JobSummary.struct_class = Types::JobSummary
JobSummaryList.member = Shapes::ShapeRef.new(shape: JobSummary)
JobTimeout.add_member(:attempt_duration_seconds, Shapes::ShapeRef.new(shape: Integer, location_name: "attemptDurationSeconds"))
JobTimeout.struct_class = Types::JobTimeout
KeyValuePair.add_member(:name, Shapes::ShapeRef.new(shape: String, location_name: "name"))
KeyValuePair.add_member(:value, Shapes::ShapeRef.new(shape: String, location_name: "value"))
KeyValuePair.struct_class = Types::KeyValuePair
KeyValuesPair.add_member(:name, Shapes::ShapeRef.new(shape: String, location_name: "name"))
KeyValuesPair.add_member(:values, Shapes::ShapeRef.new(shape: StringList, location_name: "values"))
KeyValuesPair.struct_class = Types::KeyValuesPair
LaunchTemplateSpecification.add_member(:launch_template_id, Shapes::ShapeRef.new(shape: String, location_name: "launchTemplateId"))
LaunchTemplateSpecification.add_member(:launch_template_name, Shapes::ShapeRef.new(shape: String, location_name: "launchTemplateName"))
LaunchTemplateSpecification.add_member(:version, Shapes::ShapeRef.new(shape: String, location_name: "version"))
LaunchTemplateSpecification.struct_class = Types::LaunchTemplateSpecification
LinuxParameters.add_member(:devices, Shapes::ShapeRef.new(shape: DevicesList, location_name: "devices"))
LinuxParameters.add_member(:init_process_enabled, Shapes::ShapeRef.new(shape: Boolean, location_name: "initProcessEnabled"))
LinuxParameters.add_member(:shared_memory_size, Shapes::ShapeRef.new(shape: Integer, location_name: "sharedMemorySize"))
LinuxParameters.add_member(:tmpfs, Shapes::ShapeRef.new(shape: TmpfsList, location_name: "tmpfs"))
LinuxParameters.add_member(:max_swap, Shapes::ShapeRef.new(shape: Integer, location_name: "maxSwap"))
LinuxParameters.add_member(:swappiness, Shapes::ShapeRef.new(shape: Integer, location_name: "swappiness"))
LinuxParameters.struct_class = Types::LinuxParameters
ListJobsFilterList.member = Shapes::ShapeRef.new(shape: KeyValuesPair)
ListJobsRequest.add_member(:job_queue, Shapes::ShapeRef.new(shape: String, location_name: "jobQueue"))
ListJobsRequest.add_member(:array_job_id, Shapes::ShapeRef.new(shape: String, location_name: "arrayJobId"))
ListJobsRequest.add_member(:multi_node_job_id, Shapes::ShapeRef.new(shape: String, location_name: "multiNodeJobId"))
ListJobsRequest.add_member(:job_status, Shapes::ShapeRef.new(shape: JobStatus, location_name: "jobStatus"))
ListJobsRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: Integer, location_name: "maxResults"))
ListJobsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
ListJobsRequest.add_member(:filters, Shapes::ShapeRef.new(shape: ListJobsFilterList, location_name: "filters"))
ListJobsRequest.struct_class = Types::ListJobsRequest
ListJobsResponse.add_member(:job_summary_list, Shapes::ShapeRef.new(shape: JobSummaryList, required: true, location_name: "jobSummaryList"))
ListJobsResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
ListJobsResponse.struct_class = Types::ListJobsResponse
ListSchedulingPoliciesRequest.add_member(:max_results, Shapes::ShapeRef.new(shape: Integer, location_name: "maxResults"))
ListSchedulingPoliciesRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
ListSchedulingPoliciesRequest.struct_class = Types::ListSchedulingPoliciesRequest
ListSchedulingPoliciesResponse.add_member(:scheduling_policies, Shapes::ShapeRef.new(shape: SchedulingPolicyListingDetailList, location_name: "schedulingPolicies"))
ListSchedulingPoliciesResponse.add_member(:next_token, Shapes::ShapeRef.new(shape: String, location_name: "nextToken"))
ListSchedulingPoliciesResponse.struct_class = Types::ListSchedulingPoliciesResponse
ListTagsForResourceRequest.add_member(:resource_arn, Shapes::ShapeRef.new(shape: String, required: true, location: "uri", location_name: "resourceArn"))
ListTagsForResourceRequest.struct_class = Types::ListTagsForResourceRequest
ListTagsForResourceResponse.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
ListTagsForResourceResponse.struct_class = Types::ListTagsForResourceResponse
LogConfiguration.add_member(:log_driver, Shapes::ShapeRef.new(shape: LogDriver, required: true, location_name: "logDriver"))
LogConfiguration.add_member(:options, Shapes::ShapeRef.new(shape: LogConfigurationOptionsMap, location_name: "options"))
LogConfiguration.add_member(:secret_options, Shapes::ShapeRef.new(shape: SecretList, location_name: "secretOptions"))
LogConfiguration.struct_class = Types::LogConfiguration
LogConfigurationOptionsMap.key = Shapes::ShapeRef.new(shape: String)
LogConfigurationOptionsMap.value = Shapes::ShapeRef.new(shape: String)
MountPoint.add_member(:container_path, Shapes::ShapeRef.new(shape: String, location_name: "containerPath"))
MountPoint.add_member(:read_only, Shapes::ShapeRef.new(shape: Boolean, location_name: "readOnly"))
MountPoint.add_member(:source_volume, Shapes::ShapeRef.new(shape: String, location_name: "sourceVolume"))
MountPoint.struct_class = Types::MountPoint
MountPoints.member = Shapes::ShapeRef.new(shape: MountPoint)
NetworkConfiguration.add_member(:assign_public_ip, Shapes::ShapeRef.new(shape: AssignPublicIp, location_name: "assignPublicIp"))
NetworkConfiguration.struct_class = Types::NetworkConfiguration
NetworkInterface.add_member(:attachment_id, Shapes::ShapeRef.new(shape: String, location_name: "attachmentId"))
NetworkInterface.add_member(:ipv6_address, Shapes::ShapeRef.new(shape: String, location_name: "ipv6Address"))
NetworkInterface.add_member(:private_ipv_4_address, Shapes::ShapeRef.new(shape: String, location_name: "privateIpv4Address"))
NetworkInterface.struct_class = Types::NetworkInterface
NetworkInterfaceList.member = Shapes::ShapeRef.new(shape: NetworkInterface)
NodeDetails.add_member(:node_index, Shapes::ShapeRef.new(shape: Integer, location_name: "nodeIndex"))
NodeDetails.add_member(:is_main_node, Shapes::ShapeRef.new(shape: Boolean, location_name: "isMainNode"))
NodeDetails.struct_class = Types::NodeDetails
NodeOverrides.add_member(:num_nodes, Shapes::ShapeRef.new(shape: Integer, location_name: "numNodes"))
NodeOverrides.add_member(:node_property_overrides, Shapes::ShapeRef.new(shape: NodePropertyOverrides, location_name: "nodePropertyOverrides"))
NodeOverrides.struct_class = Types::NodeOverrides
NodeProperties.add_member(:num_nodes, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "numNodes"))
NodeProperties.add_member(:main_node, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "mainNode"))
NodeProperties.add_member(:node_range_properties, Shapes::ShapeRef.new(shape: NodeRangeProperties, required: true, location_name: "nodeRangeProperties"))
NodeProperties.struct_class = Types::NodeProperties
NodePropertiesSummary.add_member(:is_main_node, Shapes::ShapeRef.new(shape: Boolean, location_name: "isMainNode"))
NodePropertiesSummary.add_member(:num_nodes, Shapes::ShapeRef.new(shape: Integer, location_name: "numNodes"))
NodePropertiesSummary.add_member(:node_index, Shapes::ShapeRef.new(shape: Integer, location_name: "nodeIndex"))
NodePropertiesSummary.struct_class = Types::NodePropertiesSummary
NodePropertyOverride.add_member(:target_nodes, Shapes::ShapeRef.new(shape: String, required: true, location_name: "targetNodes"))
NodePropertyOverride.add_member(:container_overrides, Shapes::ShapeRef.new(shape: ContainerOverrides, location_name: "containerOverrides"))
NodePropertyOverride.struct_class = Types::NodePropertyOverride
NodePropertyOverrides.member = Shapes::ShapeRef.new(shape: NodePropertyOverride)
NodeRangeProperties.member = Shapes::ShapeRef.new(shape: NodeRangeProperty)
NodeRangeProperty.add_member(:target_nodes, Shapes::ShapeRef.new(shape: String, required: true, location_name: "targetNodes"))
NodeRangeProperty.add_member(:container, Shapes::ShapeRef.new(shape: ContainerProperties, location_name: "container"))
NodeRangeProperty.struct_class = Types::NodeRangeProperty
ParametersMap.key = Shapes::ShapeRef.new(shape: String)
ParametersMap.value = Shapes::ShapeRef.new(shape: String)
PlatformCapabilityList.member = Shapes::ShapeRef.new(shape: PlatformCapability)
RegisterJobDefinitionRequest.add_member(:job_definition_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinitionName"))
RegisterJobDefinitionRequest.add_member(:type, Shapes::ShapeRef.new(shape: JobDefinitionType, required: true, location_name: "type"))
RegisterJobDefinitionRequest.add_member(:parameters, Shapes::ShapeRef.new(shape: ParametersMap, location_name: "parameters"))
RegisterJobDefinitionRequest.add_member(:scheduling_priority, Shapes::ShapeRef.new(shape: Integer, location_name: "schedulingPriority"))
RegisterJobDefinitionRequest.add_member(:container_properties, Shapes::ShapeRef.new(shape: ContainerProperties, location_name: "containerProperties"))
RegisterJobDefinitionRequest.add_member(:node_properties, Shapes::ShapeRef.new(shape: NodeProperties, location_name: "nodeProperties"))
RegisterJobDefinitionRequest.add_member(:retry_strategy, Shapes::ShapeRef.new(shape: RetryStrategy, location_name: "retryStrategy"))
RegisterJobDefinitionRequest.add_member(:propagate_tags, Shapes::ShapeRef.new(shape: Boolean, location_name: "propagateTags"))
RegisterJobDefinitionRequest.add_member(:timeout, Shapes::ShapeRef.new(shape: JobTimeout, location_name: "timeout"))
RegisterJobDefinitionRequest.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
RegisterJobDefinitionRequest.add_member(:platform_capabilities, Shapes::ShapeRef.new(shape: PlatformCapabilityList, location_name: "platformCapabilities"))
RegisterJobDefinitionRequest.add_member(:eks_properties, Shapes::ShapeRef.new(shape: EksProperties, location_name: "eksProperties"))
RegisterJobDefinitionRequest.struct_class = Types::RegisterJobDefinitionRequest
RegisterJobDefinitionResponse.add_member(:job_definition_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinitionName"))
RegisterJobDefinitionResponse.add_member(:job_definition_arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinitionArn"))
RegisterJobDefinitionResponse.add_member(:revision, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "revision"))
RegisterJobDefinitionResponse.struct_class = Types::RegisterJobDefinitionResponse
ResourceRequirement.add_member(:value, Shapes::ShapeRef.new(shape: String, required: true, location_name: "value"))
ResourceRequirement.add_member(:type, Shapes::ShapeRef.new(shape: ResourceType, required: true, location_name: "type"))
ResourceRequirement.struct_class = Types::ResourceRequirement
ResourceRequirements.member = Shapes::ShapeRef.new(shape: ResourceRequirement)
RetryStrategy.add_member(:attempts, Shapes::ShapeRef.new(shape: Integer, location_name: "attempts"))
RetryStrategy.add_member(:evaluate_on_exit, Shapes::ShapeRef.new(shape: EvaluateOnExitList, location_name: "evaluateOnExit"))
RetryStrategy.struct_class = Types::RetryStrategy
SchedulingPolicyDetail.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
SchedulingPolicyDetail.add_member(:arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "arn"))
SchedulingPolicyDetail.add_member(:fairshare_policy, Shapes::ShapeRef.new(shape: FairsharePolicy, location_name: "fairsharePolicy"))
SchedulingPolicyDetail.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
SchedulingPolicyDetail.struct_class = Types::SchedulingPolicyDetail
SchedulingPolicyDetailList.member = Shapes::ShapeRef.new(shape: SchedulingPolicyDetail)
SchedulingPolicyListingDetail.add_member(:arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "arn"))
SchedulingPolicyListingDetail.struct_class = Types::SchedulingPolicyListingDetail
SchedulingPolicyListingDetailList.member = Shapes::ShapeRef.new(shape: SchedulingPolicyListingDetail)
Secret.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
Secret.add_member(:value_from, Shapes::ShapeRef.new(shape: String, required: true, location_name: "valueFrom"))
Secret.struct_class = Types::Secret
SecretList.member = Shapes::ShapeRef.new(shape: Secret)
ServerException.add_member(:message, Shapes::ShapeRef.new(shape: String, location_name: "message"))
ServerException.struct_class = Types::ServerException
ShareAttributes.add_member(:share_identifier, Shapes::ShapeRef.new(shape: String, required: true, location_name: "shareIdentifier"))
ShareAttributes.add_member(:weight_factor, Shapes::ShapeRef.new(shape: Float, location_name: "weightFactor"))
ShareAttributes.struct_class = Types::ShareAttributes
ShareAttributesList.member = Shapes::ShapeRef.new(shape: ShareAttributes)
StringList.member = Shapes::ShapeRef.new(shape: String)
SubmitJobRequest.add_member(:job_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobName"))
SubmitJobRequest.add_member(:job_queue, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueue"))
SubmitJobRequest.add_member(:share_identifier, Shapes::ShapeRef.new(shape: String, location_name: "shareIdentifier"))
SubmitJobRequest.add_member(:scheduling_priority_override, Shapes::ShapeRef.new(shape: Integer, location_name: "schedulingPriorityOverride"))
SubmitJobRequest.add_member(:array_properties, Shapes::ShapeRef.new(shape: ArrayProperties, location_name: "arrayProperties"))
SubmitJobRequest.add_member(:depends_on, Shapes::ShapeRef.new(shape: JobDependencyList, location_name: "dependsOn"))
SubmitJobRequest.add_member(:job_definition, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobDefinition"))
SubmitJobRequest.add_member(:parameters, Shapes::ShapeRef.new(shape: ParametersMap, location_name: "parameters"))
SubmitJobRequest.add_member(:container_overrides, Shapes::ShapeRef.new(shape: ContainerOverrides, location_name: "containerOverrides"))
SubmitJobRequest.add_member(:node_overrides, Shapes::ShapeRef.new(shape: NodeOverrides, location_name: "nodeOverrides"))
SubmitJobRequest.add_member(:retry_strategy, Shapes::ShapeRef.new(shape: RetryStrategy, location_name: "retryStrategy"))
SubmitJobRequest.add_member(:propagate_tags, Shapes::ShapeRef.new(shape: Boolean, location_name: "propagateTags"))
SubmitJobRequest.add_member(:timeout, Shapes::ShapeRef.new(shape: JobTimeout, location_name: "timeout"))
SubmitJobRequest.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, location_name: "tags"))
SubmitJobRequest.add_member(:eks_properties_override, Shapes::ShapeRef.new(shape: EksPropertiesOverride, location_name: "eksPropertiesOverride"))
SubmitJobRequest.struct_class = Types::SubmitJobRequest
SubmitJobResponse.add_member(:job_arn, Shapes::ShapeRef.new(shape: String, location_name: "jobArn"))
SubmitJobResponse.add_member(:job_name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobName"))
SubmitJobResponse.add_member(:job_id, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobId"))
SubmitJobResponse.struct_class = Types::SubmitJobResponse
TagKeysList.member = Shapes::ShapeRef.new(shape: TagKey)
TagResourceRequest.add_member(:resource_arn, Shapes::ShapeRef.new(shape: String, required: true, location: "uri", location_name: "resourceArn"))
TagResourceRequest.add_member(:tags, Shapes::ShapeRef.new(shape: TagrisTagsMap, required: true, location_name: "tags"))
TagResourceRequest.struct_class = Types::TagResourceRequest
TagResourceResponse.struct_class = Types::TagResourceResponse
TagrisTagsMap.key = Shapes::ShapeRef.new(shape: TagKey)
TagrisTagsMap.value = Shapes::ShapeRef.new(shape: TagValue)
TagsMap.key = Shapes::ShapeRef.new(shape: String)
TagsMap.value = Shapes::ShapeRef.new(shape: String)
TerminateJobRequest.add_member(:job_id, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobId"))
TerminateJobRequest.add_member(:reason, Shapes::ShapeRef.new(shape: String, required: true, location_name: "reason"))
TerminateJobRequest.struct_class = Types::TerminateJobRequest
TerminateJobResponse.struct_class = Types::TerminateJobResponse
Tmpfs.add_member(:container_path, Shapes::ShapeRef.new(shape: String, required: true, location_name: "containerPath"))
Tmpfs.add_member(:size, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "size"))
Tmpfs.add_member(:mount_options, Shapes::ShapeRef.new(shape: StringList, location_name: "mountOptions"))
Tmpfs.struct_class = Types::Tmpfs
TmpfsList.member = Shapes::ShapeRef.new(shape: Tmpfs)
Ulimit.add_member(:hard_limit, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "hardLimit"))
Ulimit.add_member(:name, Shapes::ShapeRef.new(shape: String, required: true, location_name: "name"))
Ulimit.add_member(:soft_limit, Shapes::ShapeRef.new(shape: Integer, required: true, location_name: "softLimit"))
Ulimit.struct_class = Types::Ulimit
Ulimits.member = Shapes::ShapeRef.new(shape: Ulimit)
UntagResourceRequest.add_member(:resource_arn, Shapes::ShapeRef.new(shape: String, required: true, location: "uri", location_name: "resourceArn"))
UntagResourceRequest.add_member(:tag_keys, Shapes::ShapeRef.new(shape: TagKeysList, required: true, location: "querystring", location_name: "tagKeys"))
UntagResourceRequest.struct_class = Types::UntagResourceRequest
UntagResourceResponse.struct_class = Types::UntagResourceResponse
UpdateComputeEnvironmentRequest.add_member(:compute_environment, Shapes::ShapeRef.new(shape: String, required: true, location_name: "computeEnvironment"))
UpdateComputeEnvironmentRequest.add_member(:state, Shapes::ShapeRef.new(shape: CEState, location_name: "state"))
UpdateComputeEnvironmentRequest.add_member(:unmanagedv_cpus, Shapes::ShapeRef.new(shape: Integer, location_name: "unmanagedvCpus"))
UpdateComputeEnvironmentRequest.add_member(:compute_resources, Shapes::ShapeRef.new(shape: ComputeResourceUpdate, location_name: "computeResources"))
UpdateComputeEnvironmentRequest.add_member(:service_role, Shapes::ShapeRef.new(shape: String, location_name: "serviceRole"))
UpdateComputeEnvironmentRequest.add_member(:update_policy, Shapes::ShapeRef.new(shape: UpdatePolicy, location_name: "updatePolicy"))
UpdateComputeEnvironmentRequest.struct_class = Types::UpdateComputeEnvironmentRequest
UpdateComputeEnvironmentResponse.add_member(:compute_environment_name, Shapes::ShapeRef.new(shape: String, location_name: "computeEnvironmentName"))
UpdateComputeEnvironmentResponse.add_member(:compute_environment_arn, Shapes::ShapeRef.new(shape: String, location_name: "computeEnvironmentArn"))
UpdateComputeEnvironmentResponse.struct_class = Types::UpdateComputeEnvironmentResponse
UpdateJobQueueRequest.add_member(:job_queue, Shapes::ShapeRef.new(shape: String, required: true, location_name: "jobQueue"))
UpdateJobQueueRequest.add_member(:state, Shapes::ShapeRef.new(shape: JQState, location_name: "state"))
UpdateJobQueueRequest.add_member(:scheduling_policy_arn, Shapes::ShapeRef.new(shape: String, location_name: "schedulingPolicyArn"))
UpdateJobQueueRequest.add_member(:priority, Shapes::ShapeRef.new(shape: Integer, location_name: "priority"))
UpdateJobQueueRequest.add_member(:compute_environment_order, Shapes::ShapeRef.new(shape: ComputeEnvironmentOrders, location_name: "computeEnvironmentOrder"))
UpdateJobQueueRequest.struct_class = Types::UpdateJobQueueRequest
UpdateJobQueueResponse.add_member(:job_queue_name, Shapes::ShapeRef.new(shape: String, location_name: "jobQueueName"))
UpdateJobQueueResponse.add_member(:job_queue_arn, Shapes::ShapeRef.new(shape: String, location_name: "jobQueueArn"))
UpdateJobQueueResponse.struct_class = Types::UpdateJobQueueResponse
UpdatePolicy.add_member(:terminate_jobs_on_update, Shapes::ShapeRef.new(shape: Boolean, location_name: "terminateJobsOnUpdate"))
UpdatePolicy.add_member(:job_execution_timeout_minutes, Shapes::ShapeRef.new(shape: JobExecutionTimeoutMinutes, location_name: "jobExecutionTimeoutMinutes"))
UpdatePolicy.struct_class = Types::UpdatePolicy
UpdateSchedulingPolicyRequest.add_member(:arn, Shapes::ShapeRef.new(shape: String, required: true, location_name: "arn"))
UpdateSchedulingPolicyRequest.add_member(:fairshare_policy, Shapes::ShapeRef.new(shape: FairsharePolicy, location_name: "fairsharePolicy"))
UpdateSchedulingPolicyRequest.struct_class = Types::UpdateSchedulingPolicyRequest
UpdateSchedulingPolicyResponse.struct_class = Types::UpdateSchedulingPolicyResponse
Volume.add_member(:host, Shapes::ShapeRef.new(shape: Host, location_name: "host"))
Volume.add_member(:name, Shapes::ShapeRef.new(shape: String, location_name: "name"))
Volume.add_member(:efs_volume_configuration, Shapes::ShapeRef.new(shape: EFSVolumeConfiguration, location_name: "efsVolumeConfiguration"))
Volume.struct_class = Types::Volume
Volumes.member = Shapes::ShapeRef.new(shape: Volume)
# @api private
API = Seahorse::Model::Api.new.tap do |api|
api.version = "2016-08-10"
api.metadata = {
"apiVersion" => "2016-08-10",
"endpointPrefix" => "batch",
"jsonVersion" => "1.1",
"protocol" => "rest-json",
"serviceAbbreviation" => "AWS Batch",
"serviceFullName" => "AWS Batch",
"serviceId" => "Batch",
"signatureVersion" => "v4",
"uid" => "batch-2016-08-10",
}
api.add_operation(:cancel_job, Seahorse::Model::Operation.new.tap do |o|
o.name = "CancelJob"
o.http_method = "POST"
o.http_request_uri = "/v1/canceljob"
o.input = Shapes::ShapeRef.new(shape: CancelJobRequest)
o.output = Shapes::ShapeRef.new(shape: CancelJobResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:create_compute_environment, Seahorse::Model::Operation.new.tap do |o|
o.name = "CreateComputeEnvironment"
o.http_method = "POST"
o.http_request_uri = "/v1/createcomputeenvironment"
o.input = Shapes::ShapeRef.new(shape: CreateComputeEnvironmentRequest)
o.output = Shapes::ShapeRef.new(shape: CreateComputeEnvironmentResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:create_job_queue, Seahorse::Model::Operation.new.tap do |o|
o.name = "CreateJobQueue"
o.http_method = "POST"
o.http_request_uri = "/v1/createjobqueue"
o.input = Shapes::ShapeRef.new(shape: CreateJobQueueRequest)
o.output = Shapes::ShapeRef.new(shape: CreateJobQueueResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:create_scheduling_policy, Seahorse::Model::Operation.new.tap do |o|
o.name = "CreateSchedulingPolicy"
o.http_method = "POST"
o.http_request_uri = "/v1/createschedulingpolicy"
o.input = Shapes::ShapeRef.new(shape: CreateSchedulingPolicyRequest)
o.output = Shapes::ShapeRef.new(shape: CreateSchedulingPolicyResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:delete_compute_environment, Seahorse::Model::Operation.new.tap do |o|
o.name = "DeleteComputeEnvironment"
o.http_method = "POST"
o.http_request_uri = "/v1/deletecomputeenvironment"
o.input = Shapes::ShapeRef.new(shape: DeleteComputeEnvironmentRequest)
o.output = Shapes::ShapeRef.new(shape: DeleteComputeEnvironmentResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:delete_job_queue, Seahorse::Model::Operation.new.tap do |o|
o.name = "DeleteJobQueue"
o.http_method = "POST"
o.http_request_uri = "/v1/deletejobqueue"
o.input = Shapes::ShapeRef.new(shape: DeleteJobQueueRequest)
o.output = Shapes::ShapeRef.new(shape: DeleteJobQueueResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:delete_scheduling_policy, Seahorse::Model::Operation.new.tap do |o|
o.name = "DeleteSchedulingPolicy"
o.http_method = "POST"
o.http_request_uri = "/v1/deleteschedulingpolicy"
o.input = Shapes::ShapeRef.new(shape: DeleteSchedulingPolicyRequest)
o.output = Shapes::ShapeRef.new(shape: DeleteSchedulingPolicyResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:deregister_job_definition, Seahorse::Model::Operation.new.tap do |o|
o.name = "DeregisterJobDefinition"
o.http_method = "POST"
o.http_request_uri = "/v1/deregisterjobdefinition"
o.input = Shapes::ShapeRef.new(shape: DeregisterJobDefinitionRequest)
o.output = Shapes::ShapeRef.new(shape: DeregisterJobDefinitionResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:describe_compute_environments, Seahorse::Model::Operation.new.tap do |o|
o.name = "DescribeComputeEnvironments"
o.http_method = "POST"
o.http_request_uri = "/v1/describecomputeenvironments"
o.input = Shapes::ShapeRef.new(shape: DescribeComputeEnvironmentsRequest)
o.output = Shapes::ShapeRef.new(shape: DescribeComputeEnvironmentsResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:describe_job_definitions, Seahorse::Model::Operation.new.tap do |o|
o.name = "DescribeJobDefinitions"
o.http_method = "POST"
o.http_request_uri = "/v1/describejobdefinitions"
o.input = Shapes::ShapeRef.new(shape: DescribeJobDefinitionsRequest)
o.output = Shapes::ShapeRef.new(shape: DescribeJobDefinitionsResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:describe_job_queues, Seahorse::Model::Operation.new.tap do |o|
o.name = "DescribeJobQueues"
o.http_method = "POST"
o.http_request_uri = "/v1/describejobqueues"
o.input = Shapes::ShapeRef.new(shape: DescribeJobQueuesRequest)
o.output = Shapes::ShapeRef.new(shape: DescribeJobQueuesResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:describe_jobs, Seahorse::Model::Operation.new.tap do |o|
o.name = "DescribeJobs"
o.http_method = "POST"
o.http_request_uri = "/v1/describejobs"
o.input = Shapes::ShapeRef.new(shape: DescribeJobsRequest)
o.output = Shapes::ShapeRef.new(shape: DescribeJobsResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:describe_scheduling_policies, Seahorse::Model::Operation.new.tap do |o|
o.name = "DescribeSchedulingPolicies"
o.http_method = "POST"
o.http_request_uri = "/v1/describeschedulingpolicies"
o.input = Shapes::ShapeRef.new(shape: DescribeSchedulingPoliciesRequest)
o.output = Shapes::ShapeRef.new(shape: DescribeSchedulingPoliciesResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:list_jobs, Seahorse::Model::Operation.new.tap do |o|
o.name = "ListJobs"
o.http_method = "POST"
o.http_request_uri = "/v1/listjobs"
o.input = Shapes::ShapeRef.new(shape: ListJobsRequest)
o.output = Shapes::ShapeRef.new(shape: ListJobsResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:list_scheduling_policies, Seahorse::Model::Operation.new.tap do |o|
o.name = "ListSchedulingPolicies"
o.http_method = "POST"
o.http_request_uri = "/v1/listschedulingpolicies"
o.input = Shapes::ShapeRef.new(shape: ListSchedulingPoliciesRequest)
o.output = Shapes::ShapeRef.new(shape: ListSchedulingPoliciesResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
o[:pager] = Aws::Pager.new(
limit_key: "max_results",
tokens: {
"next_token" => "next_token"
}
)
end)
api.add_operation(:list_tags_for_resource, Seahorse::Model::Operation.new.tap do |o|
o.name = "ListTagsForResource"
o.http_method = "GET"
o.http_request_uri = "/v1/tags/{resourceArn}"
o.input = Shapes::ShapeRef.new(shape: ListTagsForResourceRequest)
o.output = Shapes::ShapeRef.new(shape: ListTagsForResourceResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:register_job_definition, Seahorse::Model::Operation.new.tap do |o|
o.name = "RegisterJobDefinition"
o.http_method = "POST"
o.http_request_uri = "/v1/registerjobdefinition"
o.input = Shapes::ShapeRef.new(shape: RegisterJobDefinitionRequest)
o.output = Shapes::ShapeRef.new(shape: RegisterJobDefinitionResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:submit_job, Seahorse::Model::Operation.new.tap do |o|
o.name = "SubmitJob"
o.http_method = "POST"
o.http_request_uri = "/v1/submitjob"
o.input = Shapes::ShapeRef.new(shape: SubmitJobRequest)
o.output = Shapes::ShapeRef.new(shape: SubmitJobResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:tag_resource, Seahorse::Model::Operation.new.tap do |o|
o.name = "TagResource"
o.http_method = "POST"
o.http_request_uri = "/v1/tags/{resourceArn}"
o.input = Shapes::ShapeRef.new(shape: TagResourceRequest)
o.output = Shapes::ShapeRef.new(shape: TagResourceResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:terminate_job, Seahorse::Model::Operation.new.tap do |o|
o.name = "TerminateJob"
o.http_method = "POST"
o.http_request_uri = "/v1/terminatejob"
o.input = Shapes::ShapeRef.new(shape: TerminateJobRequest)
o.output = Shapes::ShapeRef.new(shape: TerminateJobResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:untag_resource, Seahorse::Model::Operation.new.tap do |o|
o.name = "UntagResource"
o.http_method = "DELETE"
o.http_request_uri = "/v1/tags/{resourceArn}"
o.input = Shapes::ShapeRef.new(shape: UntagResourceRequest)
o.output = Shapes::ShapeRef.new(shape: UntagResourceResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:update_compute_environment, Seahorse::Model::Operation.new.tap do |o|
o.name = "UpdateComputeEnvironment"
o.http_method = "POST"
o.http_request_uri = "/v1/updatecomputeenvironment"
o.input = Shapes::ShapeRef.new(shape: UpdateComputeEnvironmentRequest)
o.output = Shapes::ShapeRef.new(shape: UpdateComputeEnvironmentResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:update_job_queue, Seahorse::Model::Operation.new.tap do |o|
o.name = "UpdateJobQueue"
o.http_method = "POST"
o.http_request_uri = "/v1/updatejobqueue"
o.input = Shapes::ShapeRef.new(shape: UpdateJobQueueRequest)
o.output = Shapes::ShapeRef.new(shape: UpdateJobQueueResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
api.add_operation(:update_scheduling_policy, Seahorse::Model::Operation.new.tap do |o|
o.name = "UpdateSchedulingPolicy"
o.http_method = "POST"
o.http_request_uri = "/v1/updateschedulingpolicy"
o.input = Shapes::ShapeRef.new(shape: UpdateSchedulingPolicyRequest)
o.output = Shapes::ShapeRef.new(shape: UpdateSchedulingPolicyResponse)
o.errors << Shapes::ShapeRef.new(shape: ClientException)
o.errors << Shapes::ShapeRef.new(shape: ServerException)
end)
end
end
end
| {
"content_hash": "d78d5007ef72f179d3da675c20ecf135",
"timestamp": "",
"source": "github",
"line_count": 1297,
"max_line_length": 232,
"avg_line_length": 76.27525057825751,
"alnum_prop": 0.7622031962316409,
"repo_name": "aws/aws-sdk-ruby",
"id": "3dc349155cec0a9c4085efaf1cf5b390568078e0",
"size": "99171",
"binary": false,
"copies": "1",
"ref": "refs/heads/version-3",
"path": "gems/aws-sdk-batch/lib/aws-sdk-batch/client_api.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Gherkin",
"bytes": "109092"
},
{
"name": "HTML",
"bytes": "1253"
},
{
"name": "JavaScript",
"bytes": "10266"
},
{
"name": "Mustache",
"bytes": "51225"
},
{
"name": "Ruby",
"bytes": "183956484"
}
],
"symlink_target": ""
} |
#include "web/EditorClientImpl.h"
#include "core/editing/SelectionType.h"
#include "public/web/WebContentSettingsClient.h"
#include "public/web/WebFrameClient.h"
#include "public/web/WebViewClient.h"
#include "web/WebLocalFrameImpl.h"
#include "web/WebViewImpl.h"
namespace blink {
EditorClientImpl::EditorClientImpl(WebViewImpl* webview) : m_webView(webview) {}
EditorClientImpl::~EditorClientImpl() {}
void EditorClientImpl::respondToChangedSelection(LocalFrame* frame,
SelectionType selectionType) {
WebLocalFrameImpl* webFrame = WebLocalFrameImpl::fromFrame(frame);
if (webFrame->client())
webFrame->client()->didChangeSelection(selectionType != RangeSelection);
}
void EditorClientImpl::respondToChangedContents() {
if (m_webView->client())
m_webView->client()->didChangeContents();
}
bool EditorClientImpl::canCopyCut(LocalFrame* frame, bool defaultValue) const {
WebLocalFrameImpl* webFrame = WebLocalFrameImpl::fromFrame(frame);
if (!webFrame->contentSettingsClient())
return defaultValue;
return webFrame->contentSettingsClient()->allowWriteToClipboard(defaultValue);
}
bool EditorClientImpl::canPaste(LocalFrame* frame, bool defaultValue) const {
WebLocalFrameImpl* webFrame = WebLocalFrameImpl::fromFrame(frame);
if (!webFrame->contentSettingsClient())
return defaultValue;
return webFrame->contentSettingsClient()->allowReadFromClipboard(
defaultValue);
}
bool EditorClientImpl::handleKeyboardEvent(LocalFrame* frame) {
WebLocalFrameImpl* webFrame = WebLocalFrameImpl::fromFrame(frame);
return webFrame->client()->handleCurrentKeyboardEvent();
}
} // namespace blink
| {
"content_hash": "779ef70b75777d5c1ccfa79d162e38cd",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 80,
"avg_line_length": 33.7,
"alnum_prop": 0.7578635014836795,
"repo_name": "google-ar/WebARonARCore",
"id": "680a97a3a832dd00d22dff190c71fa5c073a584c",
"size": "3100",
"binary": false,
"copies": "5",
"ref": "refs/heads/webarcore_57.0.2987.5",
"path": "third_party/WebKit/Source/web/EditorClientImpl.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package net.bytebuddy.matcher;
import net.bytebuddy.instrumentation.ByteCodeElement;
import net.bytebuddy.instrumentation.ModifierReviewable;
import net.bytebuddy.instrumentation.attribute.annotation.AnnotationDescription;
import net.bytebuddy.instrumentation.method.MethodDescription;
import net.bytebuddy.instrumentation.type.TypeDescription;
import net.bytebuddy.test.utility.JavaVersionRule;
import net.bytebuddy.test.utility.PrecompiledTypeClassLoader;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.objectweb.asm.Opcodes;
import java.io.IOException;
import java.io.Serializable;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.SQLException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;
public class ElementMatchersTest {
private static final String FOO = "foo", BAR = "bar";
private static final String SINGLE_DEFAULT_METHOD = "net.bytebuddy.test.precompiled.SingleDefaultMethodInterface";
@Rule
public MethodRule javaVersionRule = new JavaVersionRule();
private ClassLoader classLoader;
@Before
public void setUp() throws Exception {
classLoader = new PrecompiledTypeClassLoader(getClass().getClassLoader());
}
@Test
public void testIs() throws Exception {
Object value = new Object();
assertThat(ElementMatchers.is(value).matches(value), is(true));
assertThat(ElementMatchers.is(value).matches(new Object()), is(false));
assertThat(ElementMatchers.is((Object) null).matches(null), is(true));
assertThat(ElementMatchers.is((Object) null).matches(new Object()), is(false));
}
@Test
public void testIsType() throws Exception {
assertThat(ElementMatchers.is(Object.class).matches(new TypeDescription.ForLoadedType(Object.class)), is(true));
assertThat(ElementMatchers.is(String.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(false));
}
@Test
public void testIsMethodOrConstructor() throws Exception {
assertThat(ElementMatchers.is(Object.class.getDeclaredMethod("toString"))
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(true));
assertThat(ElementMatchers.is(Object.class.getDeclaredMethod("toString"))
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(false));
assertThat(ElementMatchers.is(Object.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(true));
assertThat(ElementMatchers.is(Object.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(false));
}
@Test
public void testIsAnnotation() throws Exception {
AnnotationDescription annotationDescription = new TypeDescription.ForLoadedType(IsAnnotatedWith.class)
.getDeclaredAnnotations().ofType(IsAnnotatedWithAnnotation.class);
assertThat(ElementMatchers.is(IsAnnotatedWith.class.getAnnotation(IsAnnotatedWithAnnotation.class))
.matches(annotationDescription), is(true));
assertThat(ElementMatchers.is(Other.class.getAnnotation(OtherAnnotation.class)).matches(annotationDescription),
is(false));
}
@Test
public void testNot() throws Exception {
Object value = new Object();
@SuppressWarnings("unchecked")
ElementMatcher<Object> elementMatcher = mock(ElementMatcher.class);
when(elementMatcher.matches(value)).thenReturn(true);
assertThat(ElementMatchers.not(elementMatcher).matches(value), is(false));
verify(elementMatcher).matches(value);
Object otherValue = new Object();
assertThat(ElementMatchers.not(elementMatcher).matches(otherValue), is(true));
verify(elementMatcher).matches(otherValue);
verifyNoMoreInteractions(elementMatcher);
}
@Test
public void testAny() throws Exception {
assertThat(ElementMatchers.any().matches(new Object()), is(true));
}
@Test
public void testAnyType() throws Exception {
assertThat(ElementMatchers.anyOf(Object.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(true));
assertThat(ElementMatchers.anyOf(String.class, Object.class)
.matches(new TypeDescription.ForLoadedType(Object.class)), is(true));
assertThat(ElementMatchers.anyOf(String.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(false));
}
@Test
public void testAnyMethodOrConstructor() throws Exception {
Method toString = Object.class.getDeclaredMethod("toString"), hashCode = Object.class
.getDeclaredMethod("hashCode");
assertThat(ElementMatchers.anyOf(toString)
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(true));
assertThat(ElementMatchers.anyOf(toString, hashCode)
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(true));
assertThat(ElementMatchers.anyOf(toString)
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(false));
assertThat(ElementMatchers.anyOf(Object.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(true));
assertThat(ElementMatchers
.anyOf(Object.class.getDeclaredConstructor(), String.class.getDeclaredConstructor(String.class))
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(true));
assertThat(ElementMatchers.anyOf(Object.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(false));
}
@Test
public void testAnyAnnotation() throws Exception {
AnnotationDescription annotationDescription = new TypeDescription.ForLoadedType(IsAnnotatedWith.class)
.getDeclaredAnnotations().ofType(IsAnnotatedWithAnnotation.class);
assertThat(ElementMatchers.anyOf(IsAnnotatedWith.class.getAnnotation(IsAnnotatedWithAnnotation.class))
.matches(annotationDescription), is(true));
assertThat(ElementMatchers.anyOf(IsAnnotatedWith.class.getAnnotation(IsAnnotatedWithAnnotation.class),
Other.class.getAnnotation(OtherAnnotation.class)).matches(annotationDescription), is(true));
assertThat(
ElementMatchers.anyOf(Other.class.getAnnotation(OtherAnnotation.class)).matches(annotationDescription),
is(false));
}
@Test
public void testNone() throws Exception {
assertThat(ElementMatchers.none().matches(new Object()), is(false));
}
@Test
public void testNoneType() throws Exception {
assertThat(ElementMatchers.noneOf(Object.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(false));
assertThat(ElementMatchers.noneOf(String.class, Object.class)
.matches(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(ElementMatchers.noneOf(String.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(true));
}
@Test
public void testNoneMethodOrConstructor() throws Exception {
Method toString = Object.class.getDeclaredMethod("toString"), hashCode = Object.class
.getDeclaredMethod("hashCode");
assertThat(ElementMatchers.noneOf(toString)
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
assertThat(ElementMatchers.noneOf(toString, hashCode)
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
assertThat(ElementMatchers.noneOf(toString)
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(true));
assertThat(ElementMatchers.noneOf(Object.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(false));
assertThat(ElementMatchers
.noneOf(Object.class.getDeclaredConstructor(), String.class.getDeclaredConstructor(String.class))
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(false));
assertThat(ElementMatchers.noneOf(Object.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(true));
}
@Test
public void testNoneAnnotation() throws Exception {
AnnotationDescription annotationDescription = new TypeDescription.ForLoadedType(IsAnnotatedWith.class)
.getDeclaredAnnotations().ofType(IsAnnotatedWithAnnotation.class);
assertThat(ElementMatchers.noneOf(IsAnnotatedWith.class.getAnnotation(IsAnnotatedWithAnnotation.class))
.matches(annotationDescription), is(false));
assertThat(ElementMatchers.noneOf(IsAnnotatedWith.class.getAnnotation(IsAnnotatedWithAnnotation.class),
Other.class.getAnnotation(OtherAnnotation.class)).matches(annotationDescription), is(false));
assertThat(
ElementMatchers.noneOf(Other.class.getAnnotation(OtherAnnotation.class)).matches(annotationDescription),
is(true));
}
@Test
public void testAnyOf() throws Exception {
Object value = new Object(), otherValue = new Object();
assertThat(ElementMatchers.anyOf(value, otherValue).matches(value), is(true));
assertThat(ElementMatchers.anyOf(value, otherValue).matches(otherValue), is(true));
assertThat(ElementMatchers.anyOf(value, otherValue).matches(new Object()), is(false));
}
@Test
public void testNoneOf() throws Exception {
Object value = new Object(), otherValue = new Object();
assertThat(ElementMatchers.noneOf(value, otherValue).matches(value), is(false));
assertThat(ElementMatchers.noneOf(value, otherValue).matches(otherValue), is(false));
assertThat(ElementMatchers.noneOf(value, otherValue).matches(new Object()), is(true));
}
@Test
public void testNamed() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.named(FOO).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.named(FOO.toUpperCase()).matches(byteCodeElement), is(false));
assertThat(ElementMatchers.named(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNamedIgnoreCase() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.namedIgnoreCase(FOO).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.namedIgnoreCase(FOO.toUpperCase()).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.namedIgnoreCase(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameStartsWith() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameStartsWith(FOO.substring(0, 2)).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameStartsWith(FOO.substring(0, 2).toUpperCase()).matches(byteCodeElement),
is(false));
assertThat(ElementMatchers.nameStartsWith(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameStartsWithIgnoreCase() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameStartsWithIgnoreCase(FOO.substring(0, 2)).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameStartsWithIgnoreCase(FOO.substring(0, 2).toUpperCase()).matches(byteCodeElement),
is(true));
assertThat(ElementMatchers.nameStartsWithIgnoreCase(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameEndsWith() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameEndsWith(FOO.substring(1)).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameEndsWith(FOO.substring(1).toUpperCase()).matches(byteCodeElement), is(false));
assertThat(ElementMatchers.nameEndsWith(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameEndsWithIgnoreCase() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameEndsWithIgnoreCase(FOO.substring(1)).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameEndsWithIgnoreCase(FOO.substring(1).toUpperCase()).matches(byteCodeElement),
is(true));
assertThat(ElementMatchers.nameEndsWithIgnoreCase(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameContains() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameContains(FOO.substring(1, 2)).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameContains(FOO.substring(1, 2).toUpperCase()).matches(byteCodeElement), is(false));
assertThat(ElementMatchers.nameContains(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameContainsIgnoreCase() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameContainsIgnoreCase(FOO.substring(1, 2)).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameContainsIgnoreCase(FOO.substring(1, 2).toUpperCase()).matches(byteCodeElement),
is(true));
assertThat(ElementMatchers.nameContainsIgnoreCase(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testNameMatches() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getSourceCodeName()).thenReturn(FOO);
assertThat(ElementMatchers.nameMatches("^" + FOO + "$").matches(byteCodeElement), is(true));
assertThat(ElementMatchers.nameMatches(FOO.toUpperCase()).matches(byteCodeElement), is(false));
assertThat(ElementMatchers.nameMatches(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testHasDescriptor() throws Exception {
ByteCodeElement byteCodeElement = mock(ByteCodeElement.class);
when(byteCodeElement.getDescriptor()).thenReturn(FOO);
assertThat(ElementMatchers.hasDescriptor(FOO).matches(byteCodeElement), is(true));
assertThat(ElementMatchers.hasDescriptor(FOO.toUpperCase()).matches(byteCodeElement), is(false));
assertThat(ElementMatchers.hasDescriptor(BAR).matches(byteCodeElement), is(false));
}
@Test
public void testIsDeclaredBy() throws Exception {
assertThat(ElementMatchers.isDeclaredBy(IsDeclaredBy.class)
.matches(new TypeDescription.ForLoadedType(IsDeclaredBy.Inner.class)), is(true));
assertThat(ElementMatchers.isDeclaredBy(IsDeclaredBy.class).matches(mock(ByteCodeElement.class)), is(false));
assertThat(ElementMatchers.isDeclaredBy(Object.class).matches(mock(ByteCodeElement.class)), is(false));
}
@Test
public void testIsVisibleTo() throws Exception {
assertThat(
ElementMatchers.isVisibleTo(Object.class).matches(new TypeDescription.ForLoadedType(IsVisibleTo.class)),
is(true));
assertThat(ElementMatchers.isVisibleTo(Object.class)
.matches(new TypeDescription.ForLoadedType(IsNotVisibleTo.class)), is(false));
}
@Test
public void testIsAnnotatedWith() throws Exception {
assertThat(ElementMatchers.isAnnotatedWith(IsAnnotatedWithAnnotation.class)
.matches(new TypeDescription.ForLoadedType(IsAnnotatedWith.class)), is(true));
assertThat(ElementMatchers.isAnnotatedWith(IsAnnotatedWithAnnotation.class)
.matches(new TypeDescription.ForLoadedType(Object.class)), is(false));
}
@Test
public void testIsPublic() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_PUBLIC);
assertThat(ElementMatchers.isPublic().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isPublic().matches(mock(ModifierReviewable.class)), is(false));
}
@Test
public void testIsProtected() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_PROTECTED);
assertThat(ElementMatchers.isProtected().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isProtected().matches(mock(ModifierReviewable.class)), is(false));
}
@Test
public void testIsPackagePrivate() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers())
.thenReturn(Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED);
assertThat(ElementMatchers.isPackagePrivate().matches(mock(ModifierReviewable.class)), is(true));
assertThat(ElementMatchers.isPackagePrivate().matches(modifierReviewable), is(false));
}
@Test
public void testIsPrivate() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_PRIVATE);
assertThat(ElementMatchers.isPrivate().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isPrivate().matches(mock(ModifierReviewable.class)), is(false));
}
@Test
public void testIsFinal() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_FINAL);
assertThat(ElementMatchers.isFinal().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isFinal().matches(mock(ModifierReviewable.class)), is(false));
}
@Test
public void testIsStatic() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_STATIC);
assertThat(ElementMatchers.isStatic().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isStatic().matches(mock(ModifierReviewable.class)), is(false));
}
@Test
public void testIsSynthetic() throws Exception {
ModifierReviewable modifierReviewable = mock(ModifierReviewable.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_SYNTHETIC);
assertThat(ElementMatchers.isSynthetic().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isSynthetic().matches(mock(ModifierReviewable.class)), is(false));
}
@Test
public void testIsSynchronized() throws Exception {
MethodDescription methodDescription = mock(MethodDescription.class);
when(methodDescription.getModifiers()).thenReturn(Opcodes.ACC_SYNCHRONIZED);
assertThat(ElementMatchers.isSynchronized().matches(methodDescription), is(true));
assertThat(ElementMatchers.isSynchronized().matches(mock(MethodDescription.class)), is(false));
}
@Test
public void testIsNative() throws Exception {
MethodDescription methodDescription = mock(MethodDescription.class);
when(methodDescription.getModifiers()).thenReturn(Opcodes.ACC_NATIVE);
assertThat(ElementMatchers.isNative().matches(methodDescription), is(true));
assertThat(ElementMatchers.isNative().matches(mock(MethodDescription.class)), is(false));
}
@Test
public void testIsStrict() throws Exception {
MethodDescription methodDescription = mock(MethodDescription.class);
when(methodDescription.getModifiers()).thenReturn(Opcodes.ACC_STRICT);
assertThat(ElementMatchers.isStrict().matches(methodDescription), is(true));
assertThat(ElementMatchers.isStrict().matches(mock(MethodDescription.class)), is(false));
}
@Test
public void testIsVarArgs() throws Exception {
MethodDescription modifierReviewable = mock(MethodDescription.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_VARARGS);
assertThat(ElementMatchers.isVarArgs().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isVarArgs().matches(mock(MethodDescription.class)), is(false));
}
@Test
public void testIsBridge() throws Exception {
MethodDescription modifierReviewable = mock(MethodDescription.class);
when(modifierReviewable.getModifiers()).thenReturn(Opcodes.ACC_BRIDGE);
assertThat(ElementMatchers.isBridge().matches(modifierReviewable), is(true));
assertThat(ElementMatchers.isBridge().matches(mock(MethodDescription.class)), is(false));
}
@Test
public void testIsMethod() throws Exception {
assertThat(ElementMatchers.is(IsEqual.class.getDeclaredMethod(FOO))
.matches(new MethodDescription.ForLoadedMethod(IsEqual.class.getDeclaredMethod(FOO))), is(true));
assertThat(ElementMatchers.is(IsEqual.class.getDeclaredMethod(FOO)).matches(mock(MethodDescription.class)),
is(false));
assertThat(ElementMatchers.is(IsEqual.class.getDeclaredConstructor())
.matches(new MethodDescription.ForLoadedConstructor(IsEqual.class.getDeclaredConstructor())), is(true));
assertThat(ElementMatchers.is(IsEqual.class.getDeclaredConstructor()).matches(mock(MethodDescription.class)),
is(false));
}
@Test
public void testReturns() throws Exception {
assertThat(ElementMatchers.returns(void.class)
.matches(new MethodDescription.ForLoadedMethod(Returns.class.getDeclaredMethod(FOO))), is(true));
assertThat(ElementMatchers.returns(void.class)
.matches(new MethodDescription.ForLoadedMethod(Returns.class.getDeclaredMethod(BAR))), is(false));
assertThat(ElementMatchers.returns(String.class)
.matches(new MethodDescription.ForLoadedMethod(Returns.class.getDeclaredMethod(BAR))), is(true));
assertThat(ElementMatchers.returns(String.class)
.matches(new MethodDescription.ForLoadedMethod(Returns.class.getDeclaredMethod(FOO))), is(false));
}
@Test
public void testTakesArguments() throws Exception {
assertThat(ElementMatchers.takesArguments(Void.class).matches(new MethodDescription.ForLoadedMethod(TakesArguments.class.getDeclaredMethod(FOO, Void.class))), is(true));
assertThat(ElementMatchers.takesArguments(Void.class, Object.class).matches(new MethodDescription.ForLoadedMethod(TakesArguments.class.getDeclaredMethod(FOO, Void.class))), is(false));
assertThat(ElementMatchers.takesArguments(String.class, int.class).matches(new MethodDescription.ForLoadedMethod(TakesArguments.class.getDeclaredMethod(BAR, String.class, int.class))), is(true));
assertThat(ElementMatchers.takesArguments(String.class, Integer.class).matches(new MethodDescription.ForLoadedMethod(TakesArguments.class.getDeclaredMethod(BAR, String.class, int.class))), is(false));
}
@Test
public void testTakesArgumentsLength() throws Exception {
assertThat(ElementMatchers.takesArguments(1).matches(
new MethodDescription.ForLoadedMethod(TakesArguments.class.getDeclaredMethod(FOO, Void.class))),
is(true));
assertThat(ElementMatchers.takesArguments(2).matches(
new MethodDescription.ForLoadedMethod(TakesArguments.class.getDeclaredMethod(FOO, Void.class))),
is(false));
assertThat(ElementMatchers.takesArguments(2).matches(new MethodDescription.ForLoadedMethod(
TakesArguments.class.getDeclaredMethod(BAR, String.class, int.class))), is(true));
assertThat(ElementMatchers.takesArguments(3).matches(new MethodDescription.ForLoadedMethod(
TakesArguments.class.getDeclaredMethod(BAR, String.class, int.class))), is(false));
}
@Test
public void testCanThrow() throws Exception {
assertThat(ElementMatchers.canThrow(IOException.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(FOO))), is(true));
assertThat(ElementMatchers.canThrow(SQLException.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(FOO))), is(false));
assertThat(ElementMatchers.canThrow(Error.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(FOO))), is(true));
assertThat(ElementMatchers.canThrow(RuntimeException.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(FOO))), is(true));
assertThat(ElementMatchers.canThrow(IOException.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(BAR))), is(false));
assertThat(ElementMatchers.canThrow(SQLException.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(BAR))), is(false));
assertThat(ElementMatchers.canThrow(Error.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(BAR))), is(true));
assertThat(ElementMatchers.canThrow(RuntimeException.class)
.matches(new MethodDescription.ForLoadedMethod(CanThrow.class.getDeclaredMethod(BAR))), is(true));
}
@Test(expected = IllegalArgumentException.class)
@SuppressWarnings("unchecked")
public void testCanThrowValidates() throws Exception {
ElementMatchers.canThrow((Class) Object.class);
}
@Test
public void testSortIsMethod() throws Exception {
assertThat(ElementMatchers.isMethod()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(true));
assertThat(ElementMatchers.isMethod()
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(false));
assertThat(ElementMatchers.isMethod()
.matches(MethodDescription.Latent.typeInitializerOf(mock(TypeDescription.class))), is(false));
}
@Test
public void testSortIsConstructor() throws Exception {
assertThat(ElementMatchers.isConstructor()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
assertThat(ElementMatchers.isConstructor()
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(true));
assertThat(ElementMatchers.isConstructor()
.matches(MethodDescription.Latent.typeInitializerOf(mock(TypeDescription.class))), is(false));
}
@Test
@JavaVersionRule.Enforce(8)
public void testIsDefaultMethod() throws Exception {
assertThat(ElementMatchers.isDefaultMethod().matches(new MethodDescription.ForLoadedMethod(
classLoader.loadClass(SINGLE_DEFAULT_METHOD).getDeclaredMethod(FOO))), is(true));
assertThat(ElementMatchers.isDefaultMethod()
.matches(new MethodDescription.ForLoadedMethod(Runnable.class.getDeclaredMethod("run"))), is(false));
}
@Test
public void testSortIsTypeInitializer() throws Exception {
assertThat(ElementMatchers.isTypeInitializer()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
assertThat(ElementMatchers.isTypeInitializer()
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(false));
assertThat(ElementMatchers.isTypeInitializer()
.matches(MethodDescription.Latent.typeInitializerOf(mock(TypeDescription.class))), is(true));
}
@Test
public void testSortIsVisibilityBridge() throws Exception {
assertThat(ElementMatchers.isVisibilityBridge()
.matches(
new MethodDescription.ForLoadedMethod(IsVisibilityBridge.class.getDeclaredMethod(FOO))),
is(true));
assertThat(ElementMatchers.isVisibilityBridge()
.matches(new MethodDescription.ForLoadedMethod(
IsBridge.class.getDeclaredMethod(FOO, Object.class))),
is(false));
assertThat(ElementMatchers.isVisibilityBridge()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
}
@Test
public void testSortIsBridge() throws Exception {
assertThat(ElementMatchers.isBridge()
.matches(
new MethodDescription.ForLoadedMethod(IsVisibilityBridge.class.getDeclaredMethod(FOO))),
is(true));
assertThat(ElementMatchers.isBridge()
.matches(new MethodDescription.ForLoadedMethod(
IsBridge.class.getDeclaredMethod(FOO, Object.class))),
is(true));
assertThat(ElementMatchers.isBridge()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
}
@Test
public void testIsOverridable() throws Exception {
assertThat(ElementMatchers.isOverridable()
.matches(new MethodDescription.ForLoadedMethod(IsOverridable.class.getDeclaredMethod("baz"))),
is(true));
assertThat(ElementMatchers.isOverridable()
.matches(new MethodDescription.ForLoadedMethod(IsOverridable.class.getDeclaredMethod("foo"))),
is(false));
assertThat(ElementMatchers.isOverridable()
.matches(new MethodDescription.ForLoadedMethod(IsOverridable.class.getDeclaredMethod("bar"))),
is(false));
assertThat(ElementMatchers.isOverridable()
.matches(new MethodDescription.ForLoadedMethod(IsOverridable.class.getDeclaredMethod("qux"))),
is(false));
assertThat(ElementMatchers.isOverridable()
.matches(new MethodDescription.ForLoadedConstructor(
IsOverridable.class.getDeclaredConstructor())),
is(false));
}
@Test
public void testIsDefaultFinalizer() throws Exception {
assertThat(ElementMatchers.isDefaultFinalizer()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("finalize"))), is(true));
assertThat(ElementMatchers.isDefaultFinalizer()
.matches(new MethodDescription.ForLoadedMethod(
ObjectMethods.class.getDeclaredMethod("finalize"))),
is(false));
assertThat(ElementMatchers.isDefaultFinalizer()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
}
@Test
public void testIsFinalizer() throws Exception {
assertThat(ElementMatchers.isFinalizer()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("finalize"))), is(true));
assertThat(ElementMatchers.isFinalizer()
.matches(new MethodDescription.ForLoadedMethod(
ObjectMethods.class.getDeclaredMethod("finalize"))),
is(true));
assertThat(ElementMatchers.isFinalizer()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(false));
}
@Test
public void testIsHashCode() throws Exception {
assertThat(ElementMatchers.isHashCode()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("hashCode"))), is(true));
assertThat(ElementMatchers.isHashCode()
.matches(new MethodDescription.ForLoadedMethod(
ObjectMethods.class.getDeclaredMethod("hashCode"))),
is(true));
assertThat(ElementMatchers.isHashCode()
.matches(new MethodDescription.ForLoadedMethod(Runnable.class.getDeclaredMethod("run"))), is(false));
}
@Test
public void testIsEquals() throws Exception {
assertThat(ElementMatchers.isEquals()
.matches(new MethodDescription.ForLoadedMethod(
Object.class.getDeclaredMethod("equals", Object.class))),
is(true));
assertThat(ElementMatchers.isEquals().matches(
new MethodDescription.ForLoadedMethod(
ObjectMethods.class.getDeclaredMethod("equals", Object.class))),
is(true));
assertThat(ElementMatchers.isEquals()
.matches(new MethodDescription.ForLoadedMethod(Runnable.class.getDeclaredMethod("run"))), is(false));
}
@Test
public void testIsClone() throws Exception {
assertThat(ElementMatchers.isClone()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("clone"))), is(true));
assertThat(ElementMatchers.isClone()
.matches(new MethodDescription.ForLoadedMethod(ObjectMethods.class.getDeclaredMethod("clone"))),
is(true));
assertThat(ElementMatchers.isClone()
.matches(new MethodDescription.ForLoadedMethod(Runnable.class.getDeclaredMethod("run"))), is(false));
}
@Test
public void testIsToString() throws Exception {
assertThat(ElementMatchers.isToString()
.matches(new MethodDescription.ForLoadedMethod(Object.class.getDeclaredMethod("toString"))), is(true));
assertThat(ElementMatchers.isToString()
.matches(new MethodDescription.ForLoadedMethod(
ObjectMethods.class.getDeclaredMethod("toString"))),
is(true));
assertThat(ElementMatchers.isToString()
.matches(new MethodDescription.ForLoadedMethod(Runnable.class.getDeclaredMethod("run"))), is(false));
}
@Test
public void testIsDefaultConstructor() throws Exception {
assertThat(ElementMatchers.isDefaultConstructor()
.matches(new MethodDescription.ForLoadedConstructor(Object.class.getDeclaredConstructor())), is(true));
assertThat(ElementMatchers.isDefaultConstructor()
.matches(new MethodDescription.ForLoadedConstructor(
String.class.getDeclaredConstructor(String.class))),
is(false));
assertThat(ElementMatchers.isDefaultConstructor()
.matches(new MethodDescription.ForLoadedMethod(Runnable.class.getDeclaredMethod("run"))), is(false));
}
@Test
public void testIsGetter() throws Exception {
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("getFoo"))), is(false));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("isQux"))), is(true));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("getQux"))), is(true));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("isBar"))), is(true));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("getBar"))), is(true));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("isBaz"))), is(false));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("getBaz"))), is(true));
assertThat(ElementMatchers.isGetter()
.matches(new MethodDescription.ForLoadedMethod(
Getters.class.getDeclaredMethod("getBaz", Void.class))),
is(false));
assertThat(ElementMatchers.isGetter(String.class)
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("getBaz"))), is(true));
assertThat(ElementMatchers.isGetter(Void.class)
.matches(new MethodDescription.ForLoadedMethod(Getters.class.getDeclaredMethod("getBaz"))), is(false));
}
@Test
public void testIsSetter() throws Exception {
assertThat(ElementMatchers.isSetter()
.matches(new MethodDescription.ForLoadedMethod(Setters.class.getDeclaredMethod("setFoo"))), is(false));
assertThat(ElementMatchers.isSetter().matches(
new MethodDescription.ForLoadedMethod(
Setters.class.getDeclaredMethod("setBar", boolean.class))),
is(true));
assertThat(ElementMatchers.isSetter().matches(
new MethodDescription.ForLoadedMethod(
Setters.class.getDeclaredMethod("setQux", Boolean.class))),
is(true));
assertThat(ElementMatchers.isSetter().matches(
new MethodDescription.ForLoadedMethod(Setters.class.getDeclaredMethod("setBaz", String.class))),
is(true));
assertThat(ElementMatchers.isSetter().matches(new MethodDescription.ForLoadedMethod(
Setters.class.getDeclaredMethod("setBaz", String.class, Void.class))), is(false));
assertThat(ElementMatchers.isSetter(String.class).matches(
new MethodDescription.ForLoadedMethod(Setters.class.getDeclaredMethod("setBaz", String.class))),
is(true));
assertThat(ElementMatchers.isSetter(Void.class).matches(
new MethodDescription.ForLoadedMethod(Setters.class.getDeclaredMethod("setBaz", String.class))),
is(false));
}
@Test
public void testisSpecializationOf() throws Exception {
MethodDescription methodDescription = new MethodDescription.ForLoadedMethod(
IsSpecialization.class.getDeclaredMethod(FOO, Number.class));
assertThat(ElementMatchers.isSpecializationOf(methodDescription).matches(
new MethodDescription.ForLoadedMethod(
IsSpecialization.class.getDeclaredMethod(FOO, Number.class))),
is(true));
assertThat(ElementMatchers.isSpecializationOf(methodDescription).matches(
new MethodDescription.ForLoadedMethod(
IsSpecialization.class.getDeclaredMethod(FOO, Integer.class))),
is(true));
assertThat(ElementMatchers.isSpecializationOf(methodDescription).matches(
new MethodDescription.ForLoadedMethod(
IsSpecialization.class.getDeclaredMethod(FOO, String.class))),
is(false));
assertThat(ElementMatchers.isSpecializationOf(methodDescription).matches(
new MethodDescription.ForLoadedMethod(
IsSpecialization.class.getDeclaredMethod(BAR, Integer.class))),
is(false));
}
@Test
public void testIsSubOrSuperType() throws Exception {
assertThat(ElementMatchers.isSubTypeOf(String.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(false));
assertThat(ElementMatchers.isSubTypeOf(Object.class).matches(new TypeDescription.ForLoadedType(String.class)),
is(true));
assertThat(ElementMatchers.isSubTypeOf(Serializable.class)
.matches(new TypeDescription.ForLoadedType(String.class)), is(true));
assertThat(ElementMatchers.isSuperTypeOf(Object.class).matches(new TypeDescription.ForLoadedType(String.class)),
is(false));
assertThat(ElementMatchers.isSuperTypeOf(String.class).matches(new TypeDescription.ForLoadedType(Object.class)),
is(true));
assertThat(ElementMatchers.isSuperTypeOf(String.class)
.matches(new TypeDescription.ForLoadedType(Serializable.class)), is(true));
}
@Test
public void testIsAnnotatedInheritedWith() throws Exception {
assertThat(ElementMatchers.inheritsAnnotation(OtherAnnotation.class)
.matches(new TypeDescription.ForLoadedType(OtherInherited.class)), is(true));
assertThat(ElementMatchers.isAnnotatedWith(OtherAnnotation.class)
.matches(new TypeDescription.ForLoadedType(OtherInherited.class)), is(false));
}
@Test
public void testDeclaresField() throws Exception {
assertThat(ElementMatchers.declaresField(ElementMatchers.isAnnotatedWith(OtherAnnotation.class))
.matches(new TypeDescription.ForLoadedType(DeclaresFieldOrMethod.class)), is(true));
assertThat(ElementMatchers.declaresField(ElementMatchers.isAnnotatedWith(OtherAnnotation.class))
.matches(new TypeDescription.ForLoadedType(Object.class)), is(false));
assertThat(ElementMatchers.declaresMethod(ElementMatchers.isAnnotatedWith(OtherAnnotation.class))
.matches(new TypeDescription.ForLoadedType(DeclaresFieldOrMethod.class)), is(true));
assertThat(ElementMatchers.declaresMethod(ElementMatchers.isAnnotatedWith(OtherAnnotation.class))
.matches(new TypeDescription.ForLoadedType(Object.class)), is(false));
}
@Test
public void testIsBootstrapClassLoader() throws Exception {
assertThat(ElementMatchers.isBootstrapClassLoader().matches(null), is(true));
assertThat(ElementMatchers.isBootstrapClassLoader().matches(mock(ClassLoader.class)), is(false));
}
@Test
public void testIsSystemClassLoader() throws Exception {
assertThat(ElementMatchers.isSystemClassLoader().matches(ClassLoader.getSystemClassLoader()), is(true));
assertThat(ElementMatchers.isSystemClassLoader().matches(null), is(false));
assertThat(ElementMatchers.isSystemClassLoader().matches(ClassLoader.getSystemClassLoader().getParent()), is(false));
assertThat(ElementMatchers.isSystemClassLoader().matches(mock(ClassLoader.class)), is(false));
}
@Test
public void testIsExtensionClassLoader() throws Exception {
assertThat(ElementMatchers.isExtensionClassLoader().matches(ClassLoader.getSystemClassLoader().getParent()), is(true));
assertThat(ElementMatchers.isExtensionClassLoader().matches(ClassLoader.getSystemClassLoader()), is(false));
assertThat(ElementMatchers.isExtensionClassLoader().matches(null), is(false));
assertThat(ElementMatchers.isExtensionClassLoader().matches(mock(ClassLoader.class)), is(false));
}
@Test
public void testIsChildOf() throws Exception {
ClassLoader parent = new URLClassLoader(new URL[0], null);
assertThat(ElementMatchers.isChildOf(parent).matches(new URLClassLoader(new URL[0], parent)), is(true));
assertThat(ElementMatchers.isChildOf(parent).matches(new URLClassLoader(new URL[0], null)), is(false));
assertThat(ElementMatchers.isChildOf(parent).matches(null), is(false));
assertThat(ElementMatchers.isChildOf(null).matches(mock(ClassLoader.class)), is(true));
}
@Test
public void testIsParentOf() throws Exception {
ClassLoader parent = new URLClassLoader(new URL[0], null);
assertThat(ElementMatchers.isParentOf(new URLClassLoader(new URL[0], parent)).matches(parent), is(true));
assertThat(ElementMatchers.isParentOf(new URLClassLoader(new URL[0], null)).matches(parent), is(false));
assertThat(ElementMatchers.isParentOf(null).matches(new URLClassLoader(new URL[0], null)), is(false));
assertThat(ElementMatchers.isParentOf(null).matches(null), is(true));
assertThat(ElementMatchers.isParentOf(mock(ClassLoader.class)).matches(null), is(true));
}
@Test(expected = UnsupportedOperationException.class)
public void testConstructorIsHidden() throws Exception {
assertThat(Modifier.isPrivate(ElementMatchers.class.getDeclaredConstructor().getModifiers()), is(true));
Constructor<?> constructor = ElementMatchers.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
fail();
} catch (InvocationTargetException e) {
throw (UnsupportedOperationException) e.getCause();
}
}
@Retention(RetentionPolicy.RUNTIME)
private @interface IsAnnotatedWithAnnotation {
}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface OtherAnnotation {
}
private static class IsDeclaredBy {
static class Inner {
/* empty */
}
}
public static class IsVisibleTo {
/* empty */
}
private static class IsNotVisibleTo {
/* empty */
}
@IsAnnotatedWithAnnotation
private static class IsAnnotatedWith {
}
private static abstract class IsEqual {
abstract void foo();
}
private static abstract class Returns {
abstract void foo();
abstract String bar();
}
private static abstract class TakesArguments {
abstract void foo(Void a);
abstract void bar(String a, int b);
}
private static abstract class CanThrow {
protected abstract void foo() throws IOException;
protected abstract void bar();
}
static class VisibilityBridgeBase {
public void foo() {
/* empty */
}
}
public abstract static class IsVisibilityBridge extends VisibilityBridgeBase {
/* empty */
}
public static class BridgeBase<T> {
public void foo(T arg) {
/* empty */
}
}
public static class IsBridge extends BridgeBase<Void> {
@Override
public void foo(Void arg) {
/* empty */
}
}
private static class ObjectMethods {
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return super.toString();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}
public static class IsOverridable {
public static void bar() {
/* empty */
}
private void foo() {
/* empty */
}
public final void qux() {
/* empty */
}
public void baz() {
/* empty */
}
}
public static class Getters {
public void getFoo() {
/* empty */
}
public Boolean isBar() {
return null;
}
public boolean isQux() {
return false;
}
public Boolean getBar() {
return null;
}
public boolean getQux() {
return false;
}
public String isBaz() {
return null;
}
public String getBaz() {
return null;
}
public String getBaz(Void argument) {
return null;
}
}
public static class Setters {
public void setFoo() {
/* empty */
}
public void setBar(boolean argument) {
/* empty */
}
public void setQux(Boolean argument) {
/* empty */
}
public void setBaz(String argument) {
/* empty */
}
public void setBaz(String argument, Void argument2) {
/* empty */
}
}
@OtherAnnotation
public static class Other {
}
public static class OtherInherited extends Other {
}
public static class IsSpecialization {
public Number foo(Number argument) {
return null;
}
public Number foo(Integer argument) {
return null;
}
public Number foo(String argument) {
return null;
}
public Integer bar(Integer argument) {
return null;
}
}
public static class DeclaresFieldOrMethod {
@OtherAnnotation
Void field;
@OtherAnnotation
void method() {
}
}
}
| {
"content_hash": "a9857e5b6875d1f73d771aaaaa3c8532",
"timestamp": "",
"source": "github",
"line_count": 1061,
"max_line_length": 208,
"avg_line_length": 48.17624882186617,
"alnum_prop": 0.6869412109948156,
"repo_name": "RobAustin/byte-buddy",
"id": "b282d132ee4488651d132eec6394bee80c57db33",
"size": "51115",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "byte-buddy-dep/src/test/java/net/bytebuddy/matcher/ElementMatchersTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4219030"
}
],
"symlink_target": ""
} |
define([
'jquery',
'../utils'
], function ($, Utils) {
function AttachBody (decorated, $element, options) {
this.$dropdownParent = options.get('dropdownParent') || $(document.body);
decorated.call(this, $element, options);
}
AttachBody.prototype.bind = function (decorated, container, $container) {
var self = this;
var setupResultsEvents = false;
decorated.call(this, container, $container);
container.on('open', function () {
self._showDropdown();
self._attachPositioningHandler(container);
if (!setupResultsEvents) {
setupResultsEvents = true;
container.on('results:all', function () {
self._positionDropdown();
self._resizeDropdown();
});
container.on('results:append', function () {
self._positionDropdown();
self._resizeDropdown();
});
}
});
container.on('close', function () {
self._hideDropdown();
self._detachPositioningHandler(container);
});
this.$dropdownContainer.on('mousedown', function (evt) {
evt.stopPropagation();
});
};
AttachBody.prototype.destroy = function (decorated) {
decorated.call(this);
this.$dropdownContainer.remove();
};
AttachBody.prototype.position = function (decorated, $dropdown, $container) {
// Clone all of the container classes
$dropdown.attr('class', $container.attr('class'));
$dropdown.removeClass('select2');
$dropdown.addClass('select2-container--open');
$dropdown.css({
position: 'absolute',
top: -999999
});
this.$container = $container;
};
AttachBody.prototype.render = function (decorated) {
var $container = $('<span></span>');
var $dropdown = decorated.call(this);
$container.append($dropdown);
this.$dropdownContainer = $container;
return $container;
};
AttachBody.prototype._hideDropdown = function (decorated) {
this.$dropdownContainer.detach();
};
AttachBody.prototype._attachPositioningHandler =
function (decorated, container) {
var self = this;
var scrollEvent = 'scroll.select2.' + container.id;
var resizeEvent = 'resize.select2.' + container.id;
var orientationEvent = 'orientationchange.select2.' + container.id;
var $watchers = this.$container.parents().filter(Utils.hasScroll);
$watchers.each(function () {
$(this).data('select2-scroll-position', {
x: $(this).scrollLeft(),
y: $(this).scrollTop()
});
});
// bug in ie prevents scrolling
/*$watchers.on(scrollEvent, function (ev) {
var position = $(this).data('select2-scroll-position');
$(this).scrollTop(position.y);
});*/
$(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent,
function (e) {
self._positionDropdown();
self._resizeDropdown();
});
};
AttachBody.prototype._detachPositioningHandler =
function (decorated, container) {
var scrollEvent = 'scroll.select2.' + container.id;
var resizeEvent = 'resize.select2.' + container.id;
var orientationEvent = 'orientationchange.select2.' + container.id;
var $watchers = this.$container.parents().filter(Utils.hasScroll);
$watchers.off(scrollEvent);
$(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent);
};
AttachBody.prototype._positionDropdown = function () {
var $window = $(window);
var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above');
var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below');
var newDirection = null;
var offset = this.$container.offset();
offset.bottom = offset.top + this.$container.outerHeight(false);
var container = {
height: this.$container.outerHeight(false)
};
container.top = offset.top;
container.bottom = offset.top + container.height;
var dropdown = {
height: this.$dropdown.outerHeight(false)
};
var viewport = {
top: $window.scrollTop(),
bottom: $window.scrollTop() + $window.height()
};
var enoughRoomAbove = viewport.top < (offset.top - dropdown.height);
var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height);
var css = {
left: offset.left,
top: container.bottom
};
// Determine what the parent element is to use for calciulating the offset
var $offsetParent = this.$dropdownParent;
// For statically positoned elements, we need to get the element
// that is determining the offset
if ($offsetParent.css('position') === 'static') {
$offsetParent = $offsetParent.offsetParent();
}
var parentOffset = $offsetParent.offset();
css.top -= parentOffset.top;
css.left -= parentOffset.left;
if (!isCurrentlyAbove && !isCurrentlyBelow) {
newDirection = 'below';
}
if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) {
newDirection = 'above';
} else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) {
newDirection = 'below';
}
if (newDirection == 'above' ||
(isCurrentlyAbove && newDirection !== 'below')) {
css.top = container.top - parentOffset.top - dropdown.height;
}
if (newDirection != null) {
this.$dropdown
.removeClass('select2-dropdown--below select2-dropdown--above')
.addClass('select2-dropdown--' + newDirection);
this.$container
.removeClass('select2-container--below select2-container--above')
.addClass('select2-container--' + newDirection);
}
this.$dropdownContainer.css(css);
};
AttachBody.prototype._resizeDropdown = function () {
var css = {
width: this.$container.outerWidth(false) + 'px'
};
if (this.options.get('dropdownAutoWidth')) {
css.minWidth = css.width;
css.position = 'relative';
css.width = 'auto';
}
this.$dropdown.css(css);
};
AttachBody.prototype._showDropdown = function (decorated) {
this.$dropdownContainer.appendTo(this.$dropdownParent);
this._positionDropdown();
this._resizeDropdown();
};
return AttachBody;
});
| {
"content_hash": "405d65863c66b40755b18f7b77934953",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 79,
"avg_line_length": 27.77927927927928,
"alnum_prop": 0.6359656234798119,
"repo_name": "iestruch/select2",
"id": "67f1b6d59930093b7ac82cff5a981917791e057b",
"size": "6167",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/select2/dropdown/attachBody.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15260"
},
{
"name": "HTML",
"bytes": "4808"
},
{
"name": "JavaScript",
"bytes": "304800"
}
],
"symlink_target": ""
} |
'use strict';
// jquery
require('jquery');
require('bootstrap');
require('availity-uikit');
require('select2');
require('velocity');
require('moment');
require('bootstrap-datepicker');
require('jquery.inputmask');
require('blueimp-file-upload');
// utils
require('lodash');
require('tracekit');
// angular
require('angular');
require('angular-sanitize');
require('angular-ui-router');
require('angular-shims-placeholder');
require('blueimp-file-upload-angular');
// availity
require('availity-angular');
// css
require('angular/angular-csp.css');
| {
"content_hash": "c2be5957de7981eddcf7e8a6397fd236",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 39,
"avg_line_length": 18.433333333333334,
"alnum_prop": 0.7179023508137432,
"repo_name": "OUNAVCON/WeatherWeb",
"id": "37007ba8defd27fc1e0a86fa060dfcaeae9957ec",
"size": "553",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "org.weather.AVui/app/project/app/vendor.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "542"
},
{
"name": "CSS",
"bytes": "1564"
},
{
"name": "HTML",
"bytes": "11323"
},
{
"name": "Java",
"bytes": "30876"
},
{
"name": "JavaScript",
"bytes": "42948"
},
{
"name": "Shell",
"bytes": "3406"
},
{
"name": "TypeScript",
"bytes": "11382"
}
],
"symlink_target": ""
} |
package org.elasticsearch.xpack.sql.action;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.xpack.sql.proto.ColumnInfo;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Formats {@link SqlQueryResponse} for the CLI. {@linkplain Writeable} so
* that its state can be saved between pages of results.
*/
public class CliFormatter implements Writeable {
/**
* The minimum width for any column in the formatted results.
*/
private static final int MIN_COLUMN_WIDTH = 15;
private int[] width;
/**
* Create a new {@linkplain CliFormatter} for formatting responses similar
* to the provided columns and rows.
*/
public CliFormatter(List<ColumnInfo> columns, List<List<Object>> rows) {
// Figure out the column widths:
// 1. Start with the widths of the column names
width = new int[columns.size()];
for (int i = 0; i < width.length; i++) {
// TODO read the width from the data type?
width[i] = Math.max(MIN_COLUMN_WIDTH, columns.get(i).name().length());
}
// 2. Expand columns to fit the largest value
for (List<Object> row : rows) {
for (int i = 0; i < width.length; i++) {
// TODO are we sure toString is correct here? What about dates that come back as longs.
// Tracked by https://github.com/elastic/x-pack-elasticsearch/issues/3081
width[i] = Math.max(width[i], Objects.toString(row.get(i)).length());
}
}
}
public CliFormatter(StreamInput in) throws IOException {
width = in.readIntArray();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeIntArray(width);
}
/**
* Format the provided {@linkplain SqlQueryResponse} for the CLI
* including the header lines.
*/
public String formatWithHeader(List<ColumnInfo> columns, List<List<Object>> rows) {
// The header lines
StringBuilder sb = new StringBuilder(estimateSize(rows.size() + 2));
for (int i = 0; i < width.length; i++) {
if (i > 0) {
sb.append('|');
}
String name = columns.get(i).name();
// left padding
int leftPadding = (width[i] - name.length()) / 2;
for (int j = 0; j < leftPadding; j++) {
sb.append(' ');
}
sb.append(name);
// right padding
for (int j = 0; j < width[i] - name.length() - leftPadding; j++) {
sb.append(' ');
}
}
sb.append('\n');
for (int i = 0; i < width.length; i++) {
if (i > 0) {
sb.append('+');
}
for (int j = 0; j < width[i]; j++) {
sb.append('-'); // emdash creates issues
}
}
sb.append('\n');
/* Now format the results. Sadly, this means that column
* widths are entirely determined by the first batch of
* results. */
return formatWithoutHeader(sb, rows);
}
/**
* Format the provided {@linkplain SqlQueryResponse} for the CLI
* without the header lines.
*/
public String formatWithoutHeader(List<List<Object>> rows) {
return formatWithoutHeader(new StringBuilder(estimateSize(rows.size())), rows);
}
private String formatWithoutHeader(StringBuilder sb, List<List<Object>> rows) {
for (List<Object> row : rows) {
for (int i = 0; i < width.length; i++) {
if (i > 0) {
sb.append('|');
}
// TODO are we sure toString is correct here? What about dates that come back as longs.
// Tracked by https://github.com/elastic/x-pack-elasticsearch/issues/3081
String string = Objects.toString(row.get(i));
if (string.length() <= width[i]) {
// Pad
sb.append(string);
int padding = width[i] - string.length();
for (int p = 0; p < padding; p++) {
sb.append(' ');
}
} else {
// Trim
sb.append(string.substring(0, width[i] - 1));
sb.append('~');
}
}
sb.append('\n');
}
return sb.toString();
}
/**
* Pick a good estimate of the buffer size needed to contain the rows.
*/
int estimateSize(int rows) {
/* Each column has either a '|' or a '\n' after it
* so initialize size to number of columns then add
* up the actual widths of each column. */
int rowWidthEstimate = width.length;
for (int w : width) {
rowWidthEstimate += w;
}
return rowWidthEstimate * rows;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CliFormatter that = (CliFormatter) o;
return Arrays.equals(width, that.width);
}
@Override
public int hashCode() {
return Arrays.hashCode(width);
}
}
| {
"content_hash": "a62af61091b32b1a2ebd08dab6c2b53e",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 103,
"avg_line_length": 33.61349693251534,
"alnum_prop": 0.5418872056944698,
"repo_name": "gfyoung/elasticsearch",
"id": "c773e75aa18be203adaefee7c2352ec43f20e08e",
"size": "5720",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "x-pack/plugin/sql/sql-action/src/main/java/org/elasticsearch/xpack/sql/action/CliFormatter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "13592"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "330070"
},
{
"name": "HTML",
"bytes": "2186"
},
{
"name": "Java",
"bytes": "42238459"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "54395"
},
{
"name": "Shell",
"bytes": "108747"
}
],
"symlink_target": ""
} |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/menu"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_margin="@dimen/cycle_view_pager_view_padding"
android:background="@drawable/menu_bg"
android:contentDescription="@string/menu_btn"
android:gravity="center"
android:maxLines="2"
android:textColor="@color/black"
android:textSize="18sp">
</TextView>
</LinearLayout> | {
"content_hash": "15edb6dfb63de8ffdabce4e9a3ba4867",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 72,
"avg_line_length": 37.64705882352941,
"alnum_prop": 0.64375,
"repo_name": "androiddevelop/CycleViewPager",
"id": "a9fe2a46c8df9edb3b0d26fecca58c582b8d0164",
"size": "640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cycle-view-pager-example/src/main/res/layout/example_cycleviewpager_main_item.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "47197"
}
],
"symlink_target": ""
} |
package org.olat.data.registration;
import java.util.Date;
import java.util.List;
import org.hibernate.Hibernate;
import org.olat.data.basesecurity.Identity;
import org.olat.data.commons.database.DB;
import org.olat.system.commons.encoder.Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
* Description:
*
* @author Sabina Jeger, Christian Guretzki
*/
@Repository
public class RegistrationDaoImpl implements RegistrationDao {
@Autowired
private DB database;
private RegistrationDaoImpl() {
}
/**
* A temporary key is created
*
* @param email
* address of new user
* @param ip
* address of new user
* @param action
* REGISTRATION or PWCHANGE
* @return TemporaryKey
*/
@Override
public TemporaryKeyImpl createTemporaryKeyByEmail(final String email, final String ip, final String action) {
TemporaryKeyImpl tk = null;
// check if the user is already registered
// we also try to find it in the temporarykey list
final List tks = database.find("from org.olat.data.registration.TemporaryKeyImpl as r where r.emailAddress = ?", email, Hibernate.STRING);
if ((tks == null) || (tks.size() != 1)) { // no user found, create a new one
tk = register(email, ip, action);
} else {
tk = (TemporaryKeyImpl) tks.get(0);
}
return tk;
}
/**
* deletes a TemporaryKey
*
* @param key
* the temporary key to be deleted
* @return true if successfully deleted
*/
@Override
public void deleteTemporaryKey(final TemporaryKeyImpl key) {
database.deleteObject(key);
}
/**
* returns an existing TemporaryKey by a given email address or null if none found
*
* @param email
* @return the found temporary key or null if none is found
*/
@Override
public TemporaryKeyImpl loadTemporaryKeyByEmail(final String email) {
final List tks = database.find("from r in class org.olat.data.registration.TemporaryKeyImpl where r.emailAddress = ?", email, Hibernate.STRING);
if (tks.size() == 1) {
return (TemporaryKeyImpl) tks.get(0);
} else {
return null;
}
}
/**
* returns an existing list of TemporaryKey by a given action or null if none found
*
* @param action
* @return the found temporary key or null if none is found
*/
@Override
public List<TemporaryKey> loadTemporaryKeyByAction(final String action) {
final List<TemporaryKey> tks = database.find("from r in class org.olat.data.registration.TemporaryKeyImpl where r.regAction = ?", action, Hibernate.STRING);
if (tks.size() > 0) {
return tks;
} else {
return null;
}
}
/**
* Looks for a TemporaryKey by a given registrationkey
*
* @param regkey
* the encrypted registrationkey
* @return the found TemporaryKey or null if none is found
*/
@Override
public TemporaryKeyImpl loadTemporaryKeyByRegistrationKey(final String regkey) {
final List tks = database.find("from r in class org.olat.data.registration.TemporaryKeyImpl where r.registrationKey = ?", regkey, Hibernate.STRING);
if (tks.size() == 1) {
return (TemporaryKeyImpl) tks.get(0);
} else {
return null;
}
}
/**
* Creates a TemporaryKey and saves it permanently
*
* @param emailaddress
* @param ipaddress
* @param action
* REGISTRATION or PWCHANGE
* @return newly created temporary key
*/
@Override
public TemporaryKeyImpl register(final String emailaddress, final String ipaddress, final String action) {
final String today = new Date().toString();
final String encryptMe = Encoder.encrypt(emailaddress + ipaddress + today);
final TemporaryKeyImpl tk = new TemporaryKeyImpl(emailaddress, ipaddress, encryptMe, action);
database.saveObject(tk);
return tk;
}
/**
* Get a list of all users that did already confirm the disclaimer
*
* @return
*/
@Override
public List<Identity> getIdentitiesWithConfirmedDisclaimer() {
final List<Identity> identities = database
.find("select distinct ident from org.olat.data.basesecurity.Identity as ident, org.olat.data.properties.PropertyImpl as prop "
+ "where prop.identity=ident and prop.category='user' and prop.name='dislaimer_accepted'");
return identities;
}
}
| {
"content_hash": "85a7c3efd4d660dddc42836460288ab7",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 164,
"avg_line_length": 32.54794520547945,
"alnum_prop": 0.6342592592592593,
"repo_name": "huihoo/olat",
"id": "db474c8003aadf2cfc695ff8e080b009fea9f257",
"size": "5548",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "OLAT-LMS/src/main/java/org/olat/data/registration/RegistrationDaoImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "24445"
},
{
"name": "AspectJ",
"bytes": "36132"
},
{
"name": "CSS",
"bytes": "2135670"
},
{
"name": "HTML",
"bytes": "2950677"
},
{
"name": "Java",
"bytes": "50804277"
},
{
"name": "JavaScript",
"bytes": "31237972"
},
{
"name": "PLSQL",
"bytes": "64492"
},
{
"name": "Perl",
"bytes": "10717"
},
{
"name": "Shell",
"bytes": "79994"
},
{
"name": "XSLT",
"bytes": "186520"
}
],
"symlink_target": ""
} |
<?php
include('../includes/master.inc.php');
include('../includes/class.template.php');
if ($Auth->loggedIn())
redirect(WEB_ROOT . 'backend/action.php');
if (!empty($_POST['username'])) {
if ($Auth->login($_POST['username'], base64_decode($_POST['password']))) {
if (isset($_REQUEST['r']) && strlen($_REQUEST['r']) > 0)
redirect($_REQUEST['r']);
else
redirect(WEB_ROOT . 'backend/action.php');
}
else
$Error->add('username', "<p class='body_text error'>We're sorry, you have entered an incorrect username and password. Please try again.</p>");
}
$username = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$template = new Template();
?>
<html>
<?php
$headerExtras['js'] = array('image-script.js', 'base64.js', 'login.js');
?>
<?php ob_start(); ?>
<form id="loginForm" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<h1 class="ribbon">Login</h1>
<?php echo $Error ?>
<table id="login">
<tr>
<td><label for="username" class="body_text">Username:</label></td>
<td><input type="text" name="username" maxlength="40" value="<?php echo $username; ?>"></td>
</tr>
<tr>
<td><label for="password" class="body_text">Password:</label></td>
<td><input type="password" name="pass" id="pass" maxlength="50"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input class="button" type="submit" name="submit" value="Login"></td>
</tr>
</table>
<input type="hidden" name="r" value="<?php echo htmlspecialchars(@$_REQUEST['r']); ?>" id="r">
<input type="hidden" id="password" name="password" value="">
</form>
<?php
$leftCol = ob_get_clean();
ob_start();
?>
<h1 class="ribbon">Welcome!</h1>
<p class="body_text">
Please log in on the left with the username and password you have
been provided. If you have forgotten your username/password or have
other technical difficulties, please contact the system administrator for
assistance.
</p>
<?php
$rightCol = ob_get_clean();
$template->setStyle('twoColumn');
$template->setTitle('Login');
$template->setHeaderExtras($headerExtras);
$template->setleftCol($leftCol);
$template->setrightCol($rightCol);
$template->output();
?> | {
"content_hash": "9044c2a5c706b4b03986ecda52ee75fa",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 150,
"avg_line_length": 35.388888888888886,
"alnum_prop": 0.5474882260596546,
"repo_name": "lkorth/MVHPC",
"id": "c15dac5981ef3eaed94e52795855baa8cb9d3d0f",
"size": "2548",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/login.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39505"
},
{
"name": "Java",
"bytes": "14870"
},
{
"name": "JavaScript",
"bytes": "361574"
},
{
"name": "PHP",
"bytes": "500595"
},
{
"name": "Python",
"bytes": "2778"
},
{
"name": "Shell",
"bytes": "31"
}
],
"symlink_target": ""
} |
/* (C) 2015 Tom Wright. */
int show_whitespace;
void initcurses(void);
void clrscreen(void);
void present(void);
int scroll_line(void);
void set_scroll(int n);
void adjust_scroll(int delta);
/* Get window boundaries */
char *winstart(void);
char *winend(void);
int winrows(void);
int wincols(void);
int screenlines(char *start);
char *skipscreenlines(char *start, int lines);
void drawmodeline(char *filename, char *mode);
void drawtext(void);
void drawdisamb(char c, int lvl, int toskip);
void drawlinelbls(int lvl, int off);
void drawlineoverlay(void);
void drawmessage(char *msg);
void drawyanks(void);
void draw_eof(void);
int skips(int lvl);
int onlymatch(char c, int lvl, int toskip);
int count(char c);
int countwithin(char *start, char *end, char c);
void refresh_bounds(void);
void movecursor(char *p);
| {
"content_hash": "d3d67b4d844c7a4800137184dec93e9f",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 48,
"avg_line_length": 20.575,
"alnum_prop": 0.7290400972053463,
"repo_name": "TheTomster/lwe",
"id": "fde27b5013a921a2f0ef1957ce8d29b91162428d",
"size": "823",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "draw.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "43828"
},
{
"name": "C++",
"bytes": "668"
},
{
"name": "Makefile",
"bytes": "865"
},
{
"name": "Roff",
"bytes": "2026"
}
],
"symlink_target": ""
} |
using DDW.V2D;
using Microsoft.Xna.Framework.Graphics;
using V2DRuntime.Attributes;
using Box2D.XNA;
using SharpNeatLib.Maths;
using System;
namespace Sleepwalker.Components
{
public class TiltElevator : V2DSprite
{
[RevoluteJointAttribute(lowerAngle = -.1f, upperAngle = .1f, enableLimit = true)]
public RevoluteJoint rj;
[RevoluteJointAttribute(lowerAngle = -.1f, upperAngle = .1f, enableLimit = true)]
public RevoluteJoint rt;
[PrismaticJointAttribute(enableMotor = true, maxMotorForce = 80000, motorSpeed = -5)]
public PrismaticJoint pj;
[V2DSpriteAttribute(isSensor = true)]
public V2DSprite[] buildBeam;
[V2DSpriteAttribute(isSensor = true)]
public V2DSprite[] invBeam;
[V2DSpriteAttribute()]
public V2DSprite seesawBeam;
private int speed = 5;
private int direction = 1;
private static Random rnd = new Random((int)DateTime.Now.Ticks);
public TiltElevator(Texture2D texture, V2DInstance instance) : base(texture, instance)
{
}
public int Speed {
get { return speed; }
set
{
speed = value;
direction = rnd.Next(2) > .5 ? 1 : -1;
pj.SetMotorSpeed(speed * direction);
}
}
public override void Initialize()
{
base.Initialize();
}
public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
{
base.Update(gameTime);
if (pj != null)
{
if (pj._limitState == LimitState.AtUpper && direction == 1)
{
direction = -1;
pj.SetMotorSpeed(speed * direction);
}
else if (pj._limitState == LimitState.AtLower && direction == -1)
{
direction = 1;
pj.SetMotorSpeed(speed * direction);
}
}
}
}
}
| {
"content_hash": "2419c5b6768c918c4c86846888369eaa",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 94,
"avg_line_length": 28.81081081081081,
"alnum_prop": 0.525797373358349,
"repo_name": "debreuil/SleepwalkerGame",
"id": "4d3e270e66025940052fc50461bd6b1a0b5dd161",
"size": "2134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SleepWalker/Components/TiltElevator.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "162883"
}
],
"symlink_target": ""
} |
<?php
function getMicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ((float) $usec + (float) $sec);
}
function getIPAddress($getlast = false) {
$ip = extractProxiedIP($getlast);
if (!empty($ip)) {
return $ip;
}
if (getenv('HTTP_CLIENT_IP')) {
return getenv('HTTP_CLIENT_IP');
}
return $_SERVER['REMOTE_ADDR'];
}
function extractProxiedIP($getlast = false) {
$forwardedAddr = extractAllProxiedIPs();
if ($getlast) {
$forwardedAddr = array_reverse($forwardedAddr);
}
return $forwardedAddr[0];
}
function extractAllProxiedIPs() {
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$forwardedAddr = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
$ips = array();
foreach ($forwardedAddr as $ip) {
$ip = trim($ip);
$long = ip2long($ip);
if ($long > 0) {
$ips[] = long2ip($long);
}
}
return $ips;
}
return array();
}
function encrypt($originalPassword) {
return sha1($originalPassword);
}
function localStoreMember($member) {
$cookie = base64_encode(serialize($member));
$expired_time = time() + 604800;
setcookie('member', $cookie, $expired_time, '/');
$_SESSION['member'] = $member;
}
?>
| {
"content_hash": "bcef7f51bd27df19196997022c06f793",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 72,
"avg_line_length": 23.5,
"alnum_prop": 0.5592705167173252,
"repo_name": "yuzhe10/simpleplan",
"id": "74c3e795be20a90f0857c65f916c2858afeeda52",
"size": "1500",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "includes/functions/common.fun.inc.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "5348"
},
{
"name": "HTML",
"bytes": "6480"
},
{
"name": "JavaScript",
"bytes": "49965"
},
{
"name": "PHP",
"bytes": "78912"
}
],
"symlink_target": ""
} |
package org.apache.ignite.ml.math.decompositions;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.Vector;
import org.apache.ignite.ml.math.exceptions.CardinalityException;
import org.apache.ignite.ml.math.exceptions.SingularMatrixException;
import org.apache.ignite.ml.math.impls.matrix.DenseLocalOnHeapMatrix;
import org.apache.ignite.ml.math.impls.matrix.PivotedMatrixView;
import org.apache.ignite.ml.math.impls.vector.DenseLocalOnHeapVector;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Tests for {@link LUDecomposition}.
*/
public class LUDecompositionTest {
/** */
private Matrix testL;
/** */
private Matrix testU;
/** */
private Matrix testP;
/** */
private Matrix testMatrix;
/** */
private int[] rawPivot;
/** */
@Before
public void setUp() {
double[][] rawMatrix = new double[][] {
{2.0d, 1.0d, 1.0d, 0.0d},
{4.0d, 3.0d, 3.0d, 1.0d},
{8.0d, 7.0d, 9.0d, 5.0d},
{6.0d, 7.0d, 9.0d, 8.0d}};
double[][] rawL = {
{1.0d, 0.0d, 0.0d, 0.0d},
{3.0d / 4.0d, 1.0d, 0.0d, 0.0d},
{1.0d / 2.0d, -2.0d / 7.0d, 1.0d, 0.0d},
{1.0d / 4.0d, -3.0d / 7.0d, 1.0d / 3.0d, 1.0d}};
double[][] rawU = {
{8.0d, 7.0d, 9.0d, 5.0d},
{0.0d, 7.0d / 4.0d, 9.0d / 4.0d, 17.0d / 4.0d},
{0.0d, 0.0d, -6.0d / 7.0d, -2.0d / 7.0d},
{0.0d, 0.0d, 0.0d, 2.0d / 3.0d}};
double[][] rawP = new double[][] {
{0, 0, 1.0d, 0},
{0, 0, 0, 1.0d},
{0, 1.0d, 0, 0},
{1.0d, 0, 0, 0}};
rawPivot = new int[] {3, 4, 2, 1};
testMatrix = new DenseLocalOnHeapMatrix(rawMatrix);
testL = new DenseLocalOnHeapMatrix(rawL);
testU = new DenseLocalOnHeapMatrix(rawU);
testP = new DenseLocalOnHeapMatrix(rawP);
}
/** */
@Test
public void getL() throws Exception {
Matrix luDecompositionL = new LUDecomposition(testMatrix).getL();
assertEquals("Unexpected row size.", testL.rowSize(), luDecompositionL.rowSize());
assertEquals("Unexpected column size.", testL.columnSize(), luDecompositionL.columnSize());
for (int i = 0; i < testL.rowSize(); i++)
for (int j = 0; j < testL.columnSize(); j++)
assertEquals("Unexpected value at (" + i + "," + j + ").",
testL.getX(i, j), luDecompositionL.getX(i, j), 0.0000001d);
luDecompositionL.destroy();
}
/** */
@Test
public void getU() throws Exception {
Matrix luDecompositionU = new LUDecomposition(testMatrix).getU();
assertEquals("Unexpected row size.", testU.rowSize(), luDecompositionU.rowSize());
assertEquals("Unexpected column size.", testU.columnSize(), luDecompositionU.columnSize());
for (int i = 0; i < testU.rowSize(); i++)
for (int j = 0; j < testU.columnSize(); j++)
assertEquals("Unexpected value at (" + i + "," + j + ").",
testU.getX(i, j), luDecompositionU.getX(i, j), 0.0000001d);
luDecompositionU.destroy();
}
/** */
@Test
public void getP() throws Exception {
Matrix luDecompositionP = new LUDecomposition(testMatrix).getP();
assertEquals("Unexpected row size.", testP.rowSize(), luDecompositionP.rowSize());
assertEquals("Unexpected column size.", testP.columnSize(), luDecompositionP.columnSize());
for (int i = 0; i < testP.rowSize(); i++)
for (int j = 0; j < testP.columnSize(); j++)
assertEquals("Unexpected value at (" + i + "," + j + ").",
testP.getX(i, j), luDecompositionP.getX(i, j), 0.0000001d);
luDecompositionP.destroy();
}
/** */
@Test
public void getPivot() throws Exception {
Vector pivot = new LUDecomposition(testMatrix).getPivot();
assertEquals("Unexpected pivot size.", rawPivot.length, pivot.size());
for (int i = 0; i < testU.rowSize(); i++)
assertEquals("Unexpected value at " + i, rawPivot[i], (int)pivot.get(i) + 1);
}
/**
* Test for {@link DecompositionSupport} features.
*/
@Test
public void decompositionSupportTest() {
LUDecomposition dec = new LUDecomposition(new PivotedMatrixView(testMatrix));
Matrix luDecompositionL = dec.getL();
assertEquals("Unexpected L row size.", testL.rowSize(), luDecompositionL.rowSize());
assertEquals("Unexpected L column size.", testL.columnSize(), luDecompositionL.columnSize());
for (int i = 0; i < testL.rowSize(); i++)
for (int j = 0; j < testL.columnSize(); j++)
assertEquals("Unexpected L value at (" + i + "," + j + ").",
testL.getX(i, j), luDecompositionL.getX(i, j), 0.0000001d);
Matrix luDecompositionU = dec.getU();
assertEquals("Unexpected U row size.", testU.rowSize(), luDecompositionU.rowSize());
assertEquals("Unexpected U column size.", testU.columnSize(), luDecompositionU.columnSize());
for (int i = 0; i < testU.rowSize(); i++)
for (int j = 0; j < testU.columnSize(); j++)
assertEquals("Unexpected U value at (" + i + "," + j + ").",
testU.getX(i, j), luDecompositionU.getX(i, j), 0.0000001d);
Matrix luDecompositionP = dec.getP();
assertEquals("Unexpected P row size.", testP.rowSize(), luDecompositionP.rowSize());
assertEquals("Unexpected P column size.", testP.columnSize(), luDecompositionP.columnSize());
for (int i = 0; i < testP.rowSize(); i++)
for (int j = 0; j < testP.columnSize(); j++)
assertEquals("Unexpected P value at (" + i + "," + j + ").",
testP.getX(i, j), luDecompositionP.getX(i, j), 0.0000001d);
dec.destroy();
}
/** */
@Test
public void singularDeterminant() throws Exception {
assertEquals("Unexpected determinant for singular matrix decomposition.",
0d, new LUDecomposition(new DenseLocalOnHeapMatrix(2, 2)).determinant(), 0d);
}
/** */
@Test(expected = CardinalityException.class)
public void solveVecWrongSize() throws Exception {
new LUDecomposition(testMatrix).solve(new DenseLocalOnHeapVector(testMatrix.rowSize() + 1));
}
/** */
@Test(expected = SingularMatrixException.class)
public void solveVecSingularMatrix() throws Exception {
new LUDecomposition(new DenseLocalOnHeapMatrix(testMatrix.rowSize(), testMatrix.rowSize()))
.solve(new DenseLocalOnHeapVector(testMatrix.rowSize()));
}
/** */
@Test
public void solveVec() throws Exception {
Vector sol = new LUDecomposition(new PivotedMatrixView(testMatrix))
.solve(new DenseLocalOnHeapVector(testMatrix.rowSize()));
assertEquals("Wrong solution vector size.", testMatrix.rowSize(), sol.size());
for (int i = 0; i < sol.size(); i++)
assertEquals("Unexpected value at index " + i, 0d, sol.getX(i), 0.0000001d);
}
/** */
@Test(expected = CardinalityException.class)
public void solveMtxWrongSize() throws Exception {
new LUDecomposition(testMatrix).solve(
new DenseLocalOnHeapMatrix(testMatrix.rowSize() + 1, testMatrix.rowSize()));
}
/** */
@Test(expected = SingularMatrixException.class)
public void solveMtxSingularMatrix() throws Exception {
new LUDecomposition(new DenseLocalOnHeapMatrix(testMatrix.rowSize(), testMatrix.rowSize()))
.solve(new DenseLocalOnHeapMatrix(testMatrix.rowSize(), testMatrix.rowSize()));
}
/** */
@Test
public void solveMtx() throws Exception {
Matrix sol = new LUDecomposition(new PivotedMatrixView(testMatrix))
.solve(new DenseLocalOnHeapMatrix(testMatrix.rowSize(), testMatrix.rowSize()));
assertEquals("Wrong solution matrix row size.", testMatrix.rowSize(), sol.rowSize());
assertEquals("Wrong solution matrix column size.", testMatrix.rowSize(), sol.columnSize());
for (int row = 0; row < sol.rowSize(); row++)
for (int col = 0; col < sol.columnSize(); col++)
assertEquals("Unexpected P value at (" + row + "," + col + ").",
0d, sol.getX(row, col), 0.0000001d);
}
/** */
@Test(expected = AssertionError.class)
public void nullMatrixTest() {
new LUDecomposition(null);
}
/** */
@Test(expected = CardinalityException.class)
public void nonSquareMatrixTest() {
new LUDecomposition(new DenseLocalOnHeapMatrix(2, 3));
}
}
| {
"content_hash": "bd7d03f965bb763f99a695cd478317af",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 101,
"avg_line_length": 37.4468085106383,
"alnum_prop": 0.5930681818181818,
"repo_name": "pperalta/ignite",
"id": "fc76c39cacc57fe1cf28edb0bd3246a63bd3e821",
"size": "9602",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/ml/src/test/java/org/apache/ignite/ml/math/decompositions/LUDecompositionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "39783"
},
{
"name": "C",
"bytes": "7463"
},
{
"name": "C#",
"bytes": "4030613"
},
{
"name": "C++",
"bytes": "2132957"
},
{
"name": "CSS",
"bytes": "98406"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "411123"
},
{
"name": "Java",
"bytes": "24428314"
},
{
"name": "JavaScript",
"bytes": "963263"
},
{
"name": "M4",
"bytes": "5528"
},
{
"name": "Makefile",
"bytes": "99146"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "PowerShell",
"bytes": "6281"
},
{
"name": "Scala",
"bytes": "681399"
},
{
"name": "Shell",
"bytes": "577613"
},
{
"name": "Smalltalk",
"bytes": "1908"
}
],
"symlink_target": ""
} |
package org.zaproxy.zap.extension.ascan;
import java.util.Date;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.HostProcess;
import org.parosproxy.paros.core.scanner.Plugin;
/**
* Class for Visual Plugin Progress management
*/
public class ScanProgressItem {
// Inner constants for status management
public static final int STATUS_PENDING = 0x01;
public static final int STATUS_RUNNING = 0x02;
public static final int STATUS_COMPLETED = 0x03;
private HostProcess hProcess;
private Plugin plugin;
private int status;
/**
*
* @param plugin
* @param status
*/
public ScanProgressItem(HostProcess hProcess, Plugin plugin, int status) {
this.hProcess = hProcess;
this.plugin = plugin;
this.status = status;
}
/**
*
* @return
*/
public String getNameLabel() {
return plugin.getName();
}
/**
*
* @return
*/
public String getAttackStrenghtLabel() {
return Constant.messages.getString("ascan.policy.level." + plugin.getAttackStrength().name().toLowerCase());
}
/**
*
* @return
*/
public String getStatusLabel() {
switch (status) {
case STATUS_COMPLETED:
return Constant.messages.getString("ascan.progress.label.completed");
case STATUS_RUNNING:
return Constant.messages.getString("ascan.progress.label.running");
case STATUS_PENDING:
return Constant.messages.getString("ascan.progress.label.pending");
}
return "";
}
public long getElapsedTime() {
if ((status == STATUS_PENDING) || (plugin.getTimeStarted() == null)) {
return -1;
}
Date end = (plugin.getTimeFinished() == null) ? new Date() : plugin.getTimeFinished();
return (end.getTime() - plugin.getTimeStarted().getTime());
}
/**
* Get back the percentage of completion.
*
* @return the percentage value from 0 to 100
*/
public int getProgressPercentage() {
// Implemented using node counts...
if (isRunning()) {
int progress = (hProcess.getTestCurrentCount(plugin) * 100) / hProcess.getTestTotalCount();
// Make sure not return 100 (or more) if still running...
// That might happen if more nodes are being scanned that the ones enumerated at the beginning.
return progress >= 100 ? 99 : progress;
} else if (isCompleted()) {
return 100;
} else {
return 0;
}
}
/**
*
* @return
*/
public boolean isRunning() {
return (status == STATUS_RUNNING);
}
/**
*
* @return
*/
public boolean isCompleted() {
return (status == STATUS_COMPLETED);
}
/**
* Tells whether or not the plugin was skipped.
*
* @return {@code true} if the plugin was skipped, {@code false} otherwise.
* @since 2.4.0
* @see #getSkippedReason()
*/
public boolean isSkipped() {
return hProcess.isSkipped(plugin);
}
/**
* Gets the reason why the plugin was skipped.
*
* @return the reason why the plugin was skipped, might be {@code null} if there's no reason
* @since TODO add version
* @see #isSkipped()
*/
public String getSkippedReason() {
return hProcess.getSkippedReason(plugin);
}
public void skip() {
if (isRunning()) {
hProcess.pluginSkipped(plugin, Constant.messages.getString("ascan.progress.label.skipped.reason.user"));
}
}
/**
*
* @return
*/
protected Plugin getPlugin() {
return plugin;
}
public int getReqCount() {
return hProcess.getPluginRequestCount(plugin.getId());
}
@Override
public String toString() {
return Integer.toString(getProgressPercentage());
}
}
| {
"content_hash": "37a3adb3bd3aed34323883ffe606a173",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 116,
"avg_line_length": 25.474683544303797,
"alnum_prop": 0.5850931677018634,
"repo_name": "GillesMoris/OSS",
"id": "429984280799f6973e00b2a79aa4f043c2c8e57e",
"size": "4773",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/zaproxy/zap/extension/ascan/ScanProgressItem.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "184"
},
{
"name": "HTML",
"bytes": "3966192"
},
{
"name": "Java",
"bytes": "8169772"
},
{
"name": "JavaScript",
"bytes": "161857"
},
{
"name": "Lex",
"bytes": "7594"
},
{
"name": "PHP",
"bytes": "118474"
},
{
"name": "Perl",
"bytes": "3826"
},
{
"name": "Python",
"bytes": "54211"
},
{
"name": "Shell",
"bytes": "5827"
},
{
"name": "XSLT",
"bytes": "30697"
}
],
"symlink_target": ""
} |
package org.apache.spark.ml.dsl.utils
import RecursiveEitherAsUnionToJSONSpike.{InclusiveOpt, _}
import com.tribbloids.spookystuff.testutils.FunSpecx
import org.apache.spark.ml.dsl.utils.messaging.{MessageReader, MessageWriter}
import org.scalatest.Ignore
import org.slf4j.LoggerFactory
object RecursiveEitherAsUnionToJSONSpike {
type ||[A, B] = Either[A, B]
type Union = String || Test2 || Test1
case class Test1(
str: String,
int: Int
)
case class Test2(
d: Double
)
case class Inclusive(v: Union, x: String)
case class InclusiveOpt(v: Option[Union], x: String)
}
@Ignore
class RecursiveEitherAsUnionToJSONSpike extends FunSpecx {
val u1: Union = Right(Test1("abc", 2))
val u2: Union = Left(Right(Test2(3.2)))
val u3: Union = Left(Left("def"))
it("JSON <=> Union of arity 3") {
Seq(u1, u2, u3).foreach { u =>
val json = MessageWriter(u).prettyJSON
LoggerFactory.getLogger(this.getClass).info(json)
val back = new MessageReader[Union].fromJSON(json)
assert(back == u)
}
}
it("JSON <=> case class with Union of arity 3") {
Seq(u1, u2, u3).foreach { u =>
val inclusie = Inclusive(u, "xyz")
val json = MessageWriter(inclusie).prettyJSON
LoggerFactory.getLogger(this.getClass).info(json)
val back = new MessageReader[Inclusive].fromJSON(json)
assert(back == inclusie)
}
}
it("JSON <=> case class with Option[Union] of arity 3") {
val proto = Seq(u1, u2, u3).map { u =>
InclusiveOpt(Some(u), "xyz")
} :+ InclusiveOpt(None, "z")
proto
.foreach { opt =>
val json = MessageWriter(opt).prettyJSON
LoggerFactory.getLogger(this.getClass).info(json)
val back = new MessageReader[InclusiveOpt].fromJSON(json)
assert(back == opt)
}
val exclusive = InclusiveOpt(None, "xyz")
}
}
| {
"content_hash": "9262e197d2335ae34e5acdd9e1bbaec5",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 77,
"avg_line_length": 25.97222222222222,
"alnum_prop": 0.6556149732620321,
"repo_name": "tribbloid/spookystuff",
"id": "2943ee6159096003583cafc10d33f06d2f8f7904",
"size": "1870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "parent/mldsl/src/test/scala/org/apache/spark/ml/dsl/utils/RecursiveEitherAsUnionToJSONSpike.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "247067"
},
{
"name": "Java",
"bytes": "41120"
},
{
"name": "JavaScript",
"bytes": "154949"
},
{
"name": "Kotlin",
"bytes": "19326"
},
{
"name": "Python",
"bytes": "38856"
},
{
"name": "Scala",
"bytes": "1456793"
},
{
"name": "Shell",
"bytes": "5579"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace RasterEditor.EditorMenu
{
public class ShowEditsButton : ESRI.ArcGIS.Desktop.AddIns.Button
{
public ShowEditsButton()
{
this.Enabled = false;
this.Caption = "Hide Edits";
}
/// <summary>
/// Get or set a value indicating whether the ShowEditsButton is enabled.
/// </summary>
public bool IsEnabled
{
set { this.Enabled = value; }
get { return this.Enabled; }
}
protected override void OnClick()
{
try
{
if (Editor.ShowEdits)
{
// Hide Edits
Display.ClearEdits();
this.Caption = "Show Edits";
}
else
{
// Show Edits
Display.DrawEditionBox();
this.Caption = "Hide Edits";
}
Editor.ShowEdits = !Editor.ShowEdits;
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Unfortunately, the application meets an error.\n\nSource: {0}\nSite: {1}\nMessage: {2}", ex.Source, ex.TargetSite, ex.Message), "Error");
}
}
}
}
| {
"content_hash": "adb144cf10eef4a1fa5e7743a27b3a68",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 184,
"avg_line_length": 27.745098039215687,
"alnum_prop": 0.4812720848056537,
"repo_name": "haoliangyu/ares",
"id": "9fb8846caef01df5b1ecd20a8d19a2ca6c814322",
"size": "1417",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ARES/EditorMenu/ShowEditsButton.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "263662"
}
],
"symlink_target": ""
} |
class ContainerController < ApplicationController
include ContainersCommonMixin
include Mixins::BreadcrumbsMixin
before_action :check_privileges
before_action :get_session_data
after_action :cleanup_action
after_action :set_session_data
def show_list
process_show_list(:named_scope => :active)
end
private
def textual_group_list
[%i[properties relationships smart_management], %i[env limits]]
end
helper_method :textual_group_list
def breadcrumbs_options
{
:breadcrumbs => [
{:title => _("Compute")},
{:title => _("Containers")},
{:title => _("Containers"), :url => controller_url},
],
}
end
menu_section :cnt
feature_for_actions "#{controller_name}_show_list", *ADV_SEARCH_ACTIONS
feature_for_actions "#{controller_name}_timeline", :tl_chooser
feature_for_actions "#{controller_name}_perf", :perf_top_chart
end
| {
"content_hash": "49597f77810276a95a5d1c9b6ee855fd",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 73,
"avg_line_length": 25.194444444444443,
"alnum_prop": 0.6780595369349504,
"repo_name": "ManageIQ/manageiq-ui-classic",
"id": "d7463849aa127814d52a0a8bb03c34f041703137",
"size": "907",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/container_controller.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "181"
},
{
"name": "HTML",
"bytes": "1292"
},
{
"name": "Haml",
"bytes": "1139195"
},
{
"name": "JavaScript",
"bytes": "1956794"
},
{
"name": "Ruby",
"bytes": "5623827"
},
{
"name": "SCSS",
"bytes": "114797"
},
{
"name": "Shell",
"bytes": "1480"
}
],
"symlink_target": ""
} |
function last(array) {
return array[array.length - 1]
}
let brackets = {
/**
* Parse string to nodes tree
*/
parse(str) {
let current = ['']
let stack = [current]
for (let sym of str) {
if (sym === '(') {
current = ['']
last(stack).push(current)
stack.push(current)
continue
}
if (sym === ')') {
stack.pop()
current = last(stack)
current.push('')
continue
}
current[current.length - 1] += sym
}
return stack[0]
},
/**
* Generate output string by nodes tree
*/
stringify(ast) {
let result = ''
for (let i of ast) {
if (typeof i === 'object') {
result += `(${brackets.stringify(i)})`
continue
}
result += i
}
return result
}
}
module.exports = brackets
| {
"content_hash": "e790de55a6d30d9d0d3cdee862c0472c",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 46,
"avg_line_length": 16.647058823529413,
"alnum_prop": 0.4840989399293286,
"repo_name": "postcss/autoprefixer",
"id": "3bb1dad4a9a74f70af7bb9b40635a1af2af920ad",
"size": "849",
"binary": false,
"copies": "11",
"ref": "refs/heads/main",
"path": "lib/brackets.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "150975"
},
{
"name": "JavaScript",
"bytes": "258459"
}
],
"symlink_target": ""
} |
package org.apache.ambari.server.controller.internal;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
import org.apache.ambari.server.controller.spi.ClusterController;
import org.apache.ambari.server.controller.spi.ExtendedResourceProvider;
import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
import org.apache.ambari.server.controller.spi.NoSuchResourceException;
import org.apache.ambari.server.controller.spi.PageRequest;
import org.apache.ambari.server.controller.spi.PageResponse;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.PropertyProvider;
import org.apache.ambari.server.controller.spi.ProviderModule;
import org.apache.ambari.server.controller.spi.QueryResponse;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.RequestStatus;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.Resource.Type;
import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
import org.apache.ambari.server.controller.spi.ResourcePredicateEvaluator;
import org.apache.ambari.server.controller.spi.ResourceProvider;
import org.apache.ambari.server.controller.spi.Schema;
import org.apache.ambari.server.controller.spi.SortRequest;
import org.apache.ambari.server.controller.spi.SortRequestProperty;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
import org.apache.ambari.server.controller.utilities.PredicateBuilder;
import org.apache.ambari.server.controller.utilities.PredicateHelper;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default cluster controller implementation.
*/
public class ClusterControllerImpl implements ClusterController {
private final static Logger LOG =
LoggerFactory.getLogger(ClusterControllerImpl.class);
/**
* Module of providers for this controller.
*/
private final ProviderModule providerModule;
/**
* Map of resource providers keyed by resource type.
*/
private final Map<Resource.Type, ExtendedResourceProviderWrapper> resourceProviders =
new HashMap<>();
/**
* Map of property provider lists keyed by resource type.
*/
private final Map<Resource.Type, List<PropertyProvider>> propertyProviders =
new HashMap<>();
/**
* Map of schemas keyed by resource type.
*/
private final Map<Resource.Type, Schema> schemas =
new HashMap<>();
/**
* Resource comparator.
*/
private final ResourceComparator comparator = new ResourceComparator();
/**
* Predicate evaluator
*/
private static final DefaultResourcePredicateEvaluator
DEFAULT_RESOURCE_PREDICATE_EVALUATOR =
new DefaultResourcePredicateEvaluator();
// ----- Constructors ------------------------------------------------------
public ClusterControllerImpl(ProviderModule providerModule) {
this.providerModule = providerModule;
}
// ----- ClusterController -------------------------------------------------
@Override
public Predicate getAmendedPredicate(Type type, Predicate predicate) {
ExtendedResourceProviderWrapper provider = ensureResourceProviderWrapper(type);
ensurePropertyProviders(type);
return provider.getAmendedPredicate(predicate);
}
@Override
public QueryResponse getResources(Type type, Request request, Predicate predicate)
throws UnsupportedPropertyException, NoSuchResourceException,
NoSuchParentResourceException, SystemException {
QueryResponse queryResponse = null;
ExtendedResourceProviderWrapper provider = ensureResourceProviderWrapper(type);
ensurePropertyProviders(type);
if (provider != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Using resource provider {} for request type {}", provider.getClass().getName(), type);
}
// make sure that the providers can satisfy the request
checkProperties(type, request, predicate);
// get the resources
queryResponse = provider.queryForResources(request, predicate);
}
return queryResponse == null ? new QueryResponseImpl(Collections.emptySet()) : queryResponse;
}
@Override
public Set<Resource> populateResources(Type type,
Set<Resource> resources,
Request request,
Predicate predicate) throws SystemException {
Set<Resource> keepers = resources;
List<PropertyProvider> propertyProviders = ensurePropertyProviders(type);
for (PropertyProvider propertyProvider : propertyProviders) {
if (providesRequestProperties(propertyProvider, request, predicate)) {
keepers = propertyProvider.populateResources(keepers, request, predicate);
}
}
return keepers;
}
@Override
public Iterable<Resource> getIterable(Type type, QueryResponse queryResponse,
Request request, Predicate predicate,
PageRequest pageRequest,
SortRequest sortRequest)
throws NoSuchParentResourceException, UnsupportedPropertyException, NoSuchResourceException, SystemException {
return getPage(type, queryResponse, request, predicate, pageRequest, sortRequest).getIterable();
}
@Override
public PageResponse getPage(Type type, QueryResponse queryResponse,
Request request, Predicate predicate,
PageRequest pageRequest, SortRequest sortRequest)
throws UnsupportedPropertyException,
SystemException,
NoSuchResourceException,
NoSuchParentResourceException {
Set<Resource> providerResources = queryResponse.getResources();
ExtendedResourceProviderWrapper provider = ensureResourceProviderWrapper(type);
int totalCount = 0;
Set<Resource> resources = providerResources;
if (!providerResources.isEmpty()) {
// determine if the provider has already paged & sorted the results
boolean providerAlreadyPaged = queryResponse.isPagedResponse();
boolean providerAlreadySorted = queryResponse.isSortedResponse();
// conditionally create a comparator if there is a sort
Comparator<Resource> resourceComparator = comparator;
if (null != sortRequest) {
checkSortRequestProperties(sortRequest, type, provider);
resourceComparator = new ResourceComparator(sortRequest);
}
// if the provider did not already sort the set, then sort it based
// on the comparator
if (!providerAlreadySorted) {
TreeSet<Resource> sortedResources = new TreeSet<>(
resourceComparator);
sortedResources.addAll(providerResources);
resources = sortedResources;
}
// start out assuming that the results are not paged and that
// the total count is the size of the provider resources
totalCount = resources.size();
// conditionally page the results
if (null != pageRequest && !providerAlreadyPaged) {
switch (pageRequest.getStartingPoint()) {
case Beginning:
return getPageFromOffset(pageRequest.getPageSize(), 0, resources,
predicate, provider);
case End:
return getPageToOffset(pageRequest.getPageSize(), -1, resources,
predicate, provider);
case OffsetStart:
return getPageFromOffset(pageRequest.getPageSize(),
pageRequest.getOffset(), resources, predicate, provider);
case OffsetEnd:
return getPageToOffset(pageRequest.getPageSize(),
pageRequest.getOffset(), resources, predicate, provider);
case PredicateStart:
case PredicateEnd:
// TODO : need to support the following cases for pagination
break;
default:
break;
}
} else if (providerAlreadyPaged) {
totalCount = queryResponse.getTotalResourceCount();
}
}
return new PageResponseImpl(new ResourceIterable(resources, predicate,
provider), 0, null, null, totalCount);
}
/**
* Check whether properties specified with a @SortRequest are supported by
* the @ResourceProvider.
*
* @param sortRequest @SortRequest
* @param type @Type
* @param provider @ResourceProvider
* @throws UnsupportedPropertyException
*/
private void checkSortRequestProperties(SortRequest sortRequest, Type type,
ResourceProvider provider) throws UnsupportedPropertyException {
Set<String> requestPropertyIds = provider.checkPropertyIds(
new HashSet<>(sortRequest.getPropertyIds()));
if (requestPropertyIds.size() > 0) {
List<PropertyProvider> propertyProviders = ensurePropertyProviders(type);
for (PropertyProvider propertyProvider : propertyProviders) {
requestPropertyIds = propertyProvider.checkPropertyIds(requestPropertyIds);
if (requestPropertyIds.size() == 0) {
return;
}
}
throw new UnsupportedPropertyException(type, requestPropertyIds);
}
}
@Override
public Schema getSchema(Type type) {
Schema schema = schemas.get(type);
if (schema == null) {
synchronized (schemas) {
schema = schemas.get(type);
if (schema == null) {
schema = new SchemaImpl(ensureResourceProvider(type));
schemas.put(type, schema);
}
}
}
return schema;
}
@Override
public RequestStatus createResources(Type type, Request request)
throws UnsupportedPropertyException,
SystemException,
ResourceAlreadyExistsException,
NoSuchParentResourceException {
ResourceProvider provider = ensureResourceProvider(type);
if (provider != null) {
checkProperties(type, request, null);
return provider.createResources(request);
}
return null;
}
@Override
public RequestStatus updateResources(Type type, Request request, Predicate predicate)
throws UnsupportedPropertyException,
SystemException,
NoSuchResourceException,
NoSuchParentResourceException {
ResourceProvider provider = ensureResourceProvider(type);
if (provider != null) {
if (!checkProperties(type, request, predicate)) {
predicate = resolvePredicate(type, predicate);
if (predicate == null) {
return null;
}
}
return provider.updateResources(request, predicate);
}
return null;
}
@Override
public RequestStatus deleteResources(Type type, Request request, Predicate predicate)
throws UnsupportedPropertyException,
SystemException,
NoSuchResourceException,
NoSuchParentResourceException {
ResourceProvider provider = ensureResourceProvider(type);
if (provider != null) {
if (!checkProperties(type, null, predicate)) {
predicate = resolvePredicate(type, predicate);
if (predicate == null) {
return null;
}
}
return provider.deleteResources(request, predicate);
}
return null;
}
/**
* Provides a non-wrapped resource provider..
*
* @param type type of resource provider to obtain
* @return a non-wrapped resource provider
*/
@Override
public ResourceProvider ensureResourceProvider(Type type) {
//todo: in some cases it is necessary to down cast the returned resource provider
//todo: to a concrete type. Perhaps we can provided a 'T getDelegate()' method
//todo: on the wrapper so no casting would be necessary.
ExtendedResourceProviderWrapper providerWrapper = ensureResourceProviderWrapper(type);
return providerWrapper == null ? null : providerWrapper.resourceProvider;
}
// ----- helper methods ----------------------------------------------------
/**
* Get the extended resource provider for the given type, creating it if required.
*
* @param type the resource type
*
* @return the resource provider
*/
private ExtendedResourceProviderWrapper ensureResourceProviderWrapper(Type type) {
synchronized (resourceProviders) {
if (!resourceProviders.containsKey(type)) {
resourceProviders.put(type, new ExtendedResourceProviderWrapper(providerModule.getResourceProvider(type)));
}
}
return resourceProviders.get(type);
}
/**
* Get an iterable set of resources filtered by the given request and
* predicate objects.
*
* @param type type of resources
* @param request the request
* @param predicate the predicate object which filters which resources are returned
*
* @return a page response representing the requested page of resources
*
* @throws UnsupportedPropertyException thrown if the request or predicate contain
* unsupported property ids
* @throws SystemException an internal exception occurred
* @throws NoSuchResourceException no matching resource(s) found
* @throws NoSuchParentResourceException a specified parent resource doesn't exist
*/
protected Iterable<Resource> getResourceIterable(Type type, Request request,
Predicate predicate)
throws UnsupportedPropertyException,
SystemException,
NoSuchParentResourceException,
NoSuchResourceException {
return getResources(type, request, predicate, null, null).getIterable();
}
/**
* Get a page of resources filtered by the given request, predicate objects and
* page request.
*
* @param type type of resources
* @param request the request
* @param predicate the predicate object which filters which resources are returned
* @param pageRequest the page request for a paginated response
*
* @return a page response representing the requested page of resources
*
* @throws UnsupportedPropertyException thrown if the request or predicate contain
* unsupported property ids
* @throws SystemException an internal exception occurred
* @throws NoSuchResourceException no matching resource(s) found
* @throws NoSuchParentResourceException a specified parent resource doesn't exist
*/
protected PageResponse getResources(Type type, Request request, Predicate predicate,
PageRequest pageRequest, SortRequest sortRequest)
throws UnsupportedPropertyException,
SystemException,
NoSuchResourceException,
NoSuchParentResourceException {
QueryResponse queryResponse = getResources(type, request, predicate);
populateResources(type, queryResponse.getResources(), request, predicate);
return getPage(type, queryResponse, request, predicate, pageRequest, sortRequest);
}
/**
* Check to make sure that all the property ids specified in the given request and
* predicate are supported by the resource provider or property providers for the
* given type.
*
* @param type the resource type
* @param request the request
* @param predicate the predicate
*
* @return true if all of the properties specified in the request and predicate are supported by
* the resource provider for the given type; false if any of the properties specified in
* the request and predicate are not supported by the resource provider but are supported
* by a property provider for the given type.
*
* @throws UnsupportedPropertyException thrown if any of the properties specified in the request
* and predicate are not supported by either the resource
* provider or a property provider for the given type
*/
private boolean checkProperties(Type type, Request request, Predicate predicate)
throws UnsupportedPropertyException {
Set<String> requestPropertyIds = request == null ? new HashSet<>() :
PropertyHelper.getAssociatedPropertyIds(request);
if (predicate != null) {
requestPropertyIds.addAll(PredicateHelper.getPropertyIds(predicate));
}
if (requestPropertyIds.size() > 0) {
ResourceProvider provider = ensureResourceProvider(type);
requestPropertyIds = provider.checkPropertyIds(requestPropertyIds);
if (requestPropertyIds.size() > 0) {
List<PropertyProvider> propertyProviders = ensurePropertyProviders(type);
for (PropertyProvider propertyProvider : propertyProviders) {
requestPropertyIds = propertyProvider.checkPropertyIds(requestPropertyIds);
if (requestPropertyIds.size() == 0) {
return false;
}
}
throw new UnsupportedPropertyException(type, requestPropertyIds);
}
}
return true;
}
/**
* Check to see if any of the property ids specified in the given request and
* predicate are handled by an associated property provider. if so, then use
* the given predicate to obtain a new predicate that can be completely
* processed by an update or delete operation on a resource provider for
* the given resource type. This means that the new predicate should only
* reference the key property ids for this type.
*
* @param type the resource type
* @param predicate the predicate
*
* @return the given predicate if a new one is not required; a new predicate if required
*
* @throws UnsupportedPropertyException thrown if any of the properties specified in the request
* and predicate are not supported by either the resource
* provider or a property provider for the given type
*
* @throws SystemException thrown for internal exceptions
* @throws NoSuchResourceException if the resource that is requested doesn't exist
* @throws NoSuchParentResourceException if a parent resource of the requested resource doesn't exist
*/
private Predicate resolvePredicate(Type type, Predicate predicate)
throws UnsupportedPropertyException,
SystemException,
NoSuchResourceException,
NoSuchParentResourceException{
ResourceProvider provider = ensureResourceProvider(type);
Set<String> keyPropertyIds = new HashSet<>(provider.getKeyPropertyIds().values());
Request readRequest = PropertyHelper.getReadRequest(keyPropertyIds);
Iterable<Resource> resources = getResourceIterable(type, readRequest, predicate);
PredicateBuilder pb = new PredicateBuilder();
PredicateBuilder.PredicateBuilderWithPredicate pbWithPredicate = null;
for (Resource resource : resources) {
if (pbWithPredicate != null) {
pb = pbWithPredicate.or();
}
pb = pb.begin();
pbWithPredicate = null;
for (String keyPropertyId : keyPropertyIds) {
if (pbWithPredicate != null) {
pb = pbWithPredicate.and();
}
pbWithPredicate =
pb.property(keyPropertyId).equals((Comparable) resource.getPropertyValue(keyPropertyId));
}
if (pbWithPredicate != null) {
pbWithPredicate = pbWithPredicate.end();
}
}
return pbWithPredicate == null ? null : pbWithPredicate.toPredicate();
}
/**
* Indicates whether or not the given property provider can service the given request.
*
* @param provider the property provider
* @param request the request
* @param predicate the predicate
*
* @return true if the given provider can service the request
*/
private boolean providesRequestProperties(PropertyProvider provider, Request request, Predicate predicate) {
Set<String> requestPropertyIds = new HashSet<>(request.getPropertyIds());
if (requestPropertyIds.size() == 0) {
return true;
}
requestPropertyIds.addAll(PredicateHelper.getPropertyIds(predicate));
int size = requestPropertyIds.size();
return size > provider.checkPropertyIds(requestPropertyIds).size();
}
/**
* Get the list of property providers for the given type.
*
* @param type the resource type
*
* @return the list of property providers
*/
private List<PropertyProvider> ensurePropertyProviders(Type type) {
synchronized (propertyProviders) {
if (!propertyProviders.containsKey(type)) {
List<PropertyProvider> providers = providerModule.getPropertyProviders(type);
propertyProviders.put(type,
providers == null ? Collections.emptyList() : providers);
}
}
return propertyProviders.get(type);
}
/**
* Evaluate the predicate and create a list of filtered resources
*
* @param resourceIterable @ResourceIterable
* @return @LinkedList of filtered resources
*/
private LinkedList<Resource> getEvaluatedResources(ResourceIterable
resourceIterable) {
LinkedList<Resource> resources = new LinkedList<>();
if (resourceIterable != null) {
for (Resource resource : resourceIterable) {
resources.add(resource);
}
}
return resources;
}
/**
* Get one page of resources from the given set of resources starting at the given offset.
*
* @param pageSize the page size
* @param offset the offset
* @param resources the set of resources
* @param predicate the predicate
*
* @return a page response containing a page of resources
*/
private PageResponse getPageFromOffset(int pageSize, int offset,
Set<Resource> resources,
Predicate predicate,
ResourcePredicateEvaluator evaluator) {
int currentOffset = 0;
Resource previous = null;
Set<Resource> pageResources = new LinkedHashSet<>();
LinkedList<Resource> filteredResources =
getEvaluatedResources(new ResourceIterable(resources, predicate, evaluator));
Iterator<Resource> iterator = filteredResources.iterator();
// skip till offset
while (currentOffset < offset && iterator.hasNext()) {
previous = iterator.next();
++currentOffset;
}
// get a page worth of resources
for (int i = 0; i < pageSize && iterator.hasNext(); ++i) {
pageResources.add(iterator.next());
}
return new PageResponseImpl(pageResources,
currentOffset,
previous,
iterator.hasNext() ? iterator.next() : null,
filteredResources.size()
);
}
/**
* Get one page of resources from the given set of resources ending at the given offset.
*
* @param pageSize the page size
* @param offset the offset; -1 indicates the end of the resource set
* @param resources the set of resources
* @param predicate the predicate
*
* @return a page response containing a page of resources
*/
private PageResponse getPageToOffset(int pageSize, int offset,
Set<Resource> resources,
Predicate predicate,
ResourcePredicateEvaluator evaluator) {
int currentOffset = resources.size() - 1;
Resource next = null;
List<Resource> pageResources = new LinkedList<>();
LinkedList<Resource> filteredResources =
getEvaluatedResources(new ResourceIterable(resources, predicate, evaluator));
Iterator<Resource> iterator = filteredResources.descendingIterator();
if (offset != -1) {
// skip till offset
while (currentOffset > offset && iterator.hasNext()) {
next = iterator.next();
--currentOffset;
}
}
// get a page worth of resources
for (int i = 0; i < pageSize && iterator.hasNext(); ++i) {
pageResources.add(0, iterator.next());
--currentOffset;
}
return new PageResponseImpl(pageResources,
currentOffset + 1,
iterator.hasNext() ? iterator.next() : null,
next,
filteredResources.size()
);
}
/**
* Get the associated resource comparator.
*
* @return the resource comparator
*/
protected Comparator<Resource> getComparator() {
return comparator;
}
// ----- ResourceIterable inner class --------------------------------------
private static class ResourceIterable implements Iterable<Resource> {
/**
* The resources to iterate over.
*/
private final Set<Resource> resources;
/**
* The predicate used to filter the set.
*/
private final Predicate predicate;
/**
* The predicate evaluator.
*/
private final ResourcePredicateEvaluator evaluator;
// ----- Constructors ----------------------------------------------------
/**
* Create a ResourceIterable.
*
* @param resources the set of resources to iterate over
* @param predicate the predicate used to filter the set of resources
* @param evaluator the evaluator used to evaluate with the given predicate
*/
private ResourceIterable(Set<Resource> resources, Predicate predicate,
ResourcePredicateEvaluator evaluator) {
this.resources = resources;
this.predicate = predicate;
this.evaluator = evaluator;
}
// ----- Iterable --------------------------------------------------------
@Override
public Iterator<Resource> iterator() {
return new ResourceIterator(resources, predicate, evaluator);
}
}
// ----- ResourceIterator inner class --------------------------------------
private static class ResourceIterator implements Iterator<Resource> {
/**
* The underlying iterator.
*/
private final Iterator<Resource> iterator;
/**
* The predicate used to filter the resource being iterated over.
*/
private final Predicate predicate;
/**
* The next resource.
*/
private Resource nextResource;
/**
* The predicate evaluator.
*/
private final ResourcePredicateEvaluator evaluator;
// ----- Constructors ----------------------------------------------------
/**
* Create a new ResourceIterator.
*
* @param resources the set of resources to iterate over
* @param predicate the predicate used to filter the set of resources
* @param evaluator the evaluator used to evaluate with the given predicate
*/
private ResourceIterator(Set<Resource> resources, Predicate predicate,
ResourcePredicateEvaluator evaluator) {
iterator = resources.iterator();
this.predicate = predicate;
this.evaluator = evaluator;
nextResource = getNextResource();
}
// ----- Iterator --------------------------------------------------------
@Override
public boolean hasNext() {
return nextResource != null;
}
@Override
public Resource next() {
if (nextResource == null) {
throw new NoSuchElementException("Iterator has no more elements.");
}
Resource currentResource = nextResource;
nextResource = getNextResource();
return currentResource;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported.");
}
// ----- helper methods --------------------------------------------------
/**
* Get the next resource.
*
* @return the next resource.
*/
private Resource getNextResource() {
while (iterator.hasNext()) {
Resource next = iterator.next();
if (predicate == null || evaluator.evaluate(predicate, next)) {
return next;
}
}
return null;
}
}
// ----- ResourceComparator inner class ------------------------------------
protected class ResourceComparator implements Comparator<Resource> {
SortRequest sortRequest;
/**
* Default comparator
*/
protected ResourceComparator() {
}
/**
* Sort by properties.
* @param sortRequest @SortRequest to sort by.
*/
protected ResourceComparator(SortRequest sortRequest) {
this.sortRequest = sortRequest;
}
@Override
public int compare(Resource resource1, Resource resource2) {
Type resourceType = resource1.getType();
// compare based on resource type
int compVal = resourceType.compareTo(resource2.getType());
// compare based on requested properties
if (compVal == 0 && sortRequest != null) {
for (SortRequestProperty property : sortRequest.getProperties()) {
compVal = compareValues(
resource1.getPropertyValue(property.getPropertyId()),
resource2.getPropertyValue(property.getPropertyId()),
property.getOrder());
if (compVal != 0) {
return compVal;
}
}
}
// compare based on resource key properties
if (compVal == 0) {
Schema schema = getSchema(resourceType);
for (Type type : schema.getKeyTypes()) {
String keyPropertyId = schema.getKeyPropertyId(type);
if (keyPropertyId != null) {
compVal = compareValues(resource1.getPropertyValue(keyPropertyId),
resource2.getPropertyValue(keyPropertyId));
if (compVal != 0 ) {
return compVal;
}
}
}
}
// compare based on the resource strings
return resource1.toString().compareTo(resource2.toString());
}
// compare two values and account for null
@SuppressWarnings("unchecked")
private int compareValues(Object val1, Object val2) {
if (val1 == null || val2 == null) {
return val1 == null && val2 == null ? 0 : val1 == null ? -1 : 1;
}
if (val1 instanceof Comparable) {
try {
return ((Comparable) val1).compareTo(val2);
} catch (ClassCastException e) {
return 0;
}
}
return 0;
}
// compare two values respecting order specifier
private int compareValues(Object val1, Object val2, SortRequest.Order order) {
if (order == SortRequest.Order.ASC) {
return compareValues(val1, val2);
} else {
return -1 * compareValues(val1, val2);
}
}
}
// ----- inner class : ExtendedResourceProviderWrapper ---------------------
/**
* Wrapper class that allows the cluster controller to treat all resource providers the same.
*/
private static class ExtendedResourceProviderWrapper implements ExtendedResourceProvider, ResourcePredicateEvaluator {
/**
* The delegate resource provider.
*/
private final ResourceProvider resourceProvider;
/**
* The delegate predicate evaluator. {@code null} if the given delegate resource provider is not an
* instance of {@link ResourcePredicateEvaluator}
*/
private final ResourcePredicateEvaluator evaluator;
/**
* The delegate extended resource provider. {@code null} if the given delegate resource provider is not an
* instance of {@link ExtendedResourceProvider}
*/
private final ExtendedResourceProvider extendedResourceProvider;
// ----- Constructors ----------------------------------------------------
/**
* Constructor.
*
* @param resourceProvider the delegate resource provider
*/
public ExtendedResourceProviderWrapper(ResourceProvider resourceProvider) {
this.resourceProvider = resourceProvider;
extendedResourceProvider = resourceProvider instanceof ExtendedResourceProvider ?
(ExtendedResourceProvider) resourceProvider : null;
evaluator = resourceProvider instanceof ResourcePredicateEvaluator ?
(ResourcePredicateEvaluator) resourceProvider : DEFAULT_RESOURCE_PREDICATE_EVALUATOR;
}
/**
* @return the amended predicate, or {@code null} to use the provided one
*/
public Predicate getAmendedPredicate(Predicate predicate) {
if (ReadOnlyResourceProvider.class.isInstance(resourceProvider)) {
return ((ReadOnlyResourceProvider) resourceProvider).amendPredicate(predicate);
} else {
return null;
}
}
// ----- ExtendedResourceProvider ----------------------------------------
@Override
public QueryResponse queryForResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
return extendedResourceProvider == null ?
new QueryResponseImpl(resourceProvider.getResources(request, predicate)) :
extendedResourceProvider.queryForResources(request, predicate);
}
// ----- ResourceProvider ------------------------------------------------
@Override
public RequestStatus createResources(Request request)
throws SystemException, UnsupportedPropertyException,
ResourceAlreadyExistsException, NoSuchParentResourceException {
return resourceProvider.createResources(request);
}
@Override
public Set<Resource> getResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
return resourceProvider.getResources(request, predicate);
}
@Override
public RequestStatus updateResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
return resourceProvider.updateResources(request, predicate);
}
@Override
public RequestStatus deleteResources(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
return resourceProvider.deleteResources(request, predicate);
}
@Override
public Map<Type, String> getKeyPropertyIds() {
return resourceProvider.getKeyPropertyIds();
}
@Override
public Set<String> checkPropertyIds(Set<String> propertyIds) {
return resourceProvider.checkPropertyIds(propertyIds);
}
// ----- ResourcePredicateEvaluator --------------------------------------
@Override
public boolean evaluate(Predicate predicate, Resource resource) {
return evaluator.evaluate(predicate, resource);
}
}
}
| {
"content_hash": "c546822b31eabaaa0d3629ff9f08dea7",
"timestamp": "",
"source": "github",
"line_count": 999,
"max_line_length": 120,
"avg_line_length": 35.067067067067065,
"alnum_prop": 0.6647065540077643,
"repo_name": "sekikn/ambari",
"id": "4e1ce6bf29f88268321fbcf751b276b351ef1d0c",
"size": "35837",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClusterControllerImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22734"
},
{
"name": "C",
"bytes": "109499"
},
{
"name": "C#",
"bytes": "182799"
},
{
"name": "CSS",
"bytes": "616806"
},
{
"name": "CoffeeScript",
"bytes": "4323"
},
{
"name": "Dockerfile",
"bytes": "8117"
},
{
"name": "HTML",
"bytes": "3725781"
},
{
"name": "Handlebars",
"bytes": "1594385"
},
{
"name": "Java",
"bytes": "26670585"
},
{
"name": "JavaScript",
"bytes": "14647486"
},
{
"name": "Jinja",
"bytes": "147938"
},
{
"name": "Less",
"bytes": "303080"
},
{
"name": "Makefile",
"bytes": "2407"
},
{
"name": "PHP",
"bytes": "149648"
},
{
"name": "PLpgSQL",
"bytes": "298247"
},
{
"name": "PowerShell",
"bytes": "2047735"
},
{
"name": "Python",
"bytes": "7226684"
},
{
"name": "R",
"bytes": "1457"
},
{
"name": "Shell",
"bytes": "350773"
},
{
"name": "TSQL",
"bytes": "42351"
},
{
"name": "Vim Script",
"bytes": "5813"
},
{
"name": "sed",
"bytes": "1133"
}
],
"symlink_target": ""
} |
namespace foundation { class Dictionary; }
namespace foundation { class DictionaryArray; }
namespace renderer { class BSSRDF; }
namespace renderer { class ParamArray; }
namespace renderer
{
//
// BSSRDF factory interface.
//
class APPLESEED_DLLSYMBOL IBSSRDFFactory
: public foundation::NonCopyable
{
public:
// Destructor.
virtual ~IBSSRDFFactory() {}
// Return a string identifying this BSSRDF model.
virtual const char* get_model() const = 0;
// Return metadata for this BSSRDF model.
virtual foundation::Dictionary get_model_metadata() const = 0;
// Return metadata for the inputs of this BSSRDF model.
virtual foundation::DictionaryArray get_input_metadata() const = 0;
// Create a new BSSRDF instance.
virtual foundation::auto_release_ptr<BSSRDF> create(
const char* name,
const ParamArray& params) const = 0;
};
} // namespace renderer
#endif // !APPLESEED_RENDERER_MODELING_BSSRDF_IBSSRDFFACTORY_H
| {
"content_hash": "18180c886b85e910833a074fff190df9",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 71,
"avg_line_length": 27.243243243243242,
"alnum_prop": 0.689484126984127,
"repo_name": "docwhite/appleseed",
"id": "6482b6fc3ab094f79051ba92194d10d58ad7bda1",
"size": "2672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/appleseed/renderer/modeling/bssrdf/ibssrdffactory.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "68"
},
{
"name": "C",
"bytes": "313136"
},
{
"name": "C++",
"bytes": "8800117"
},
{
"name": "CMake",
"bytes": "101766"
},
{
"name": "HTML",
"bytes": "33275"
},
{
"name": "Makefile",
"bytes": "717"
},
{
"name": "Objective-C",
"bytes": "5971"
},
{
"name": "Python",
"bytes": "271840"
},
{
"name": "Shell",
"bytes": "3170"
}
],
"symlink_target": ""
} |
static int l_lovrTextureNewView(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
TextureViewInfo info = { .parent = texture };
info.type = luax_checkenum(L, 2, TextureType, NULL);
info.layerIndex = luaL_optinteger(L, 3, 1) - 1;
info.layerCount = luaL_optinteger(L, 4, 1);
info.levelIndex = luaL_optinteger(L, 5, 1) - 1;
info.levelCount = luaL_optinteger(L, 6, 0);
Texture* view = lovrTextureCreateView(&info);
luax_pushtype(L, Texture, view);
lovrRelease(view, lovrTextureDestroy);
return 1;
}
static int l_lovrTextureIsView(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
lua_pushboolean(L, !!lovrTextureGetInfo(texture)->parent);
return 1;
}
static int l_lovrTextureGetParent(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
luax_pushtype(L, Texture, info->parent);
return 1;
}
static int l_lovrTextureGetType(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
luax_pushenum(L, TextureType, info->type);
return 1;
}
static int l_lovrTextureGetFormat(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
luax_pushenum(L, TextureFormat, info->format);
return 1;
}
static int l_lovrTextureGetWidth(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
lua_pushinteger(L, info->width);
return 1;
}
static int l_lovrTextureGetHeight(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
lua_pushinteger(L, info->height);
return 1;
}
static int l_lovrTextureGetLayerCount(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
lua_pushinteger(L, info->layers);
return 1;
}
static int l_lovrTextureGetDimensions(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
lua_pushinteger(L, info->width);
lua_pushinteger(L, info->height);
lua_pushinteger(L, info->layers);
return 3;
}
static int l_lovrTextureGetMipmapCount(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
lua_pushinteger(L, info->mipmaps);
return 1;
}
static int l_lovrTextureGetSampleCount(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
lua_pushinteger(L, info->samples);
return 1;
}
static int l_lovrTextureHasUsage(lua_State* L) {
Texture* texture = luax_checktype(L, 1, Texture);
const TextureInfo* info = lovrTextureGetInfo(texture);
luaL_checkany(L, 2);
int top = lua_gettop(L);
for (int i = 2; i <= top; i++) {
int bit = luax_checkenum(L, i, TextureUsage, NULL);
if (~info->usage & (1 << bit)) {
lua_pushboolean(L, false);
}
}
lua_pushboolean(L, true);
return 1;
}
const luaL_Reg lovrTexture[] = {
{ "newView", l_lovrTextureNewView },
{ "isView", l_lovrTextureIsView },
{ "getParent", l_lovrTextureGetParent },
{ "getType", l_lovrTextureGetType },
{ "getFormat", l_lovrTextureGetFormat },
{ "getWidth", l_lovrTextureGetWidth },
{ "getHeight", l_lovrTextureGetHeight },
{ "getLayerCount", l_lovrTextureGetLayerCount },
{ "getDimensions", l_lovrTextureGetDimensions },
{ "getMipmapCount", l_lovrTextureGetMipmapCount },
{ "getSampleCount", l_lovrTextureGetSampleCount },
{ "hasUsage ", l_lovrTextureHasUsage },
{ NULL, NULL }
};
| {
"content_hash": "d883ebe63c03bbe0444a0ebf91175e08",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 60,
"avg_line_length": 32.391304347826086,
"alnum_prop": 0.7030872483221476,
"repo_name": "bjornbytes/lovr",
"id": "758d7870f880d823a470156350f4460d23da72ab",
"size": "3830",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/api/l_graphics_texture.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6095917"
},
{
"name": "CMake",
"bytes": "30453"
},
{
"name": "GLSL",
"bytes": "17169"
},
{
"name": "HTML",
"bytes": "2948"
},
{
"name": "Java",
"bytes": "908"
},
{
"name": "JavaScript",
"bytes": "14746"
},
{
"name": "Lua",
"bytes": "27486"
},
{
"name": "Shell",
"bytes": "85"
}
],
"symlink_target": ""
} |
<?php
namespace SellerLabs\Nucleus\View\Common;
use SellerLabs\Nucleus\View\Interfaces\RenderableInterface;
use SellerLabs\Nucleus\View\Node;
/**
* Class Option.
*
* @author Eduardo Trujillo <ed@sellerlabs.com>
* @package SellerLabs\Nucleus\View\Common
*/
class Option extends Node
{
/**
* Construct an instance of a Option.
*
* @param string[] $attributes
* @param string|RenderableInterface|string[]|RenderableInterface[] $content
*/
public function __construct($attributes, $content = '')
{
parent::__construct('option', $attributes, $content);
}
}
| {
"content_hash": "9344482903ec690052d876a4f0df8e04",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 80,
"avg_line_length": 21.821428571428573,
"alnum_prop": 0.67430441898527,
"repo_name": "sellerlabs/nucleus",
"id": "bd95381c4daf790053106526be721bb9730e0f7c",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SellerLabs/Nucleus/View/Common/Option.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "441057"
},
{
"name": "Shell",
"bytes": "483"
}
],
"symlink_target": ""
} |
package simple;
public class Customer5b extends Customer5Base
{
}
| {
"content_hash": "5872d49295108595d81b860e1b09f341",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 45,
"avg_line_length": 9.857142857142858,
"alnum_prop": 0.782608695652174,
"repo_name": "sergiomt/judal",
"id": "bc44960afcfe6693b1a4402d31f4ad5e17e8bcdb",
"size": "1559",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "jdo/jibx/build/test/simple/Customer5b.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "90031"
},
{
"name": "HTML",
"bytes": "16385675"
},
{
"name": "Java",
"bytes": "12605276"
},
{
"name": "JavaScript",
"bytes": "4165"
},
{
"name": "Scala",
"bytes": "101736"
}
],
"symlink_target": ""
} |
namespace BasicCompiler.Core
{
using System;
using System.Diagnostics;
/// <summary>
/// An AST tree.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Ast : IEquatable<Ast>
{
/// <summary>
/// Initializes a new instance of the <see cref="Ast"/> class.
/// </summary>
/// <param name="root">The root of this tree.</param>
public Ast(AstNode root)
{
// TODO: This is a temp workaround for the .NET CLI apparently not supporting
// C# 7 yet. Once it does, write this as an arrow expression.
Root = root;
}
/// <summary>
/// Gets the root of this tree.
/// </summary>
public AstNode Root { get; }
internal string DebuggerDisplay => $"Root: {{ {Root.DebuggerDisplay} }}";
/// <summary>
/// Does a depth-first traversal of this tree.
/// </summary>
/// <param name="visitor">The AST visitor used to traverse this tree.</param>
public void Accept(IAstVisitor visitor) => Root.Accept(visitor);
public override bool Equals(object obj) => obj is Ast ast && Equals(ast);
// TODO: Add equality operators to both classes. (What classes?)
public bool Equals(Ast other) => other?.Root != null && Root.Equals(other.Root);
public override int GetHashCode()
{
throw new NotImplementedException();
}
}
}
| {
"content_hash": "f7387b3049543d0c458c878e8613315e",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 89,
"avg_line_length": 33.21739130434783,
"alnum_prop": 0.5510471204188482,
"repo_name": "jamesqo/BasicCompiler",
"id": "33759963d41bfc6a62cdd728612008fc30c8f23e",
"size": "1530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BasicCompiler.Core/Ast.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "55359"
}
],
"symlink_target": ""
} |
#include <assert.h>
#include "cmn_qosProvider.h"
#include "vortex_os.h"
#include "os_report.h"
#include "c_metabase.h"
#include "c_base.h"
#include "c_typebase.h"
#include "c_field.h"
#include "c_collection.h"
#include "u_user.h"
#include "u_types.h"
#include "cf_config.h"
#include "cfg_parser.h"
#include "ut_collection.h"
#define QOS_DATABASE_SIZE (2 * 1024 * 1024)
/* Included load functions; the load-functions are generated with
* idlpp -m SPLLOAD. */
#include "dds_builtinTopicsSplLoad.c"
#include "dds_dcps_builtintopicsSplLoad.c"
#include "dds_namedQosTypesSplLoad.c"
/* Default QoS's in database-format (sequences and strings are NULL!) */
#include "qp_defaultQos.h"
#define DDS_TAG "dds"
#define PROFILE_TAG "qos_profile"
/* 'DDS for lightweigth CCM v1.1' mandates "participant_qos"; the provided
* example and xsd use "domainparticipant_qos". We follow the example. */
#define DPQOS_TAG "domainparticipant_qos"
#define TQOS_TAG "topic_qos"
#define PUBQOS_TAG "publisher_qos"
#define SUBQOS_TAG "subscriber_qos"
#define DWQOS_TAG "datawriter_qos"
#define DRQOS_TAG "datareader_qos"
#if 0
static int level;
#define QP_TRACE(t) t
#else
#define QP_TRACE(t)
#endif
C_CLASS(qp_entityAttr);
C_STRUCT (qp_entityAttr) {
c_object defaultQosTmplt;
c_type qosSampleType;
cmn_qpCopyOut copyOut;
ut_table qosTable; /* (char *, c_object) */
};
C_STRUCT(cmn_qosProvider) {
c_base baseAddr;
c_char * defaultProfile;
cf_element rootElement;
C_STRUCT (qp_entityAttr) dpQosAttr;
C_STRUCT (qp_entityAttr) tQosAttr;
C_STRUCT (qp_entityAttr) pubQosAttr;
C_STRUCT (qp_entityAttr) subQosAttr;
C_STRUCT (qp_entityAttr) dwQosAttr;
C_STRUCT (qp_entityAttr) drQosAttr;
};
typedef enum {
QP_SCOPE_NONE,
QP_SCOPE_DDS,
QP_SCOPE_PROFILE,
QP_SCOPE_QOSPOLICY
} qp_parseScope;
C_CLASS(qp_parseContext);
C_STRUCT(qp_parseContext) {
cmn_qosProvider qosProvider;
c_field currentField;
c_type currentFieldType;
c_object qosSample;
ut_table qosTable;
qp_parseScope scope;
const char * name;
};
typedef struct {
const char * name;
const char * value;
} ConstantValuePair;
static const ConstantValuePair ApiConstants[] = {
{ "LENGTH_UNLIMITED", "-1" },
{ "DURATION_INFINITE_SEC", "2147483647" },
{ "DURATION_INFINITE_NSEC", "2147483647" },
{ "DURATION_ZERO_SEC", "0" },
{ "DURATION_ZERO_NSEC", "0" }
};
/**************************************************************
* Private functions
**************************************************************/
static const char *
substituteConstants(
const char *xmlValue)
__attribute__((nonnull))
__attribute__((pure));
static cmn_qpResult
processElement(
cf_element element,
C_STRUCT(qp_parseContext) ctx)
__attribute__((nonnull));
static cmn_qpResult
processContainedElements(
c_iter elements,
C_STRUCT(qp_parseContext) ctx);
static cmn_qpResult
processElementData(
cf_data data,
C_STRUCT(qp_parseContext) ctx)
__attribute__((nonnull));
static cmn_qpResult
processAttribute(
cf_attribute attribute,
qp_parseContext ctx)
__attribute__((nonnull));
static cmn_qpResult
processContainedAttributes(
c_iter attributes,
qp_parseContext ctx)
__attribute__((nonnull(2)));
static cmn_qpResult
prepareQosSample(
const char *qosName,
qp_entityAttr attr,
qp_parseContext ctx)
__attribute__((nonnull));
static void
unloadEntityQosAttributes(
qp_entityAttr attr)
__attribute__((nonnull));
static void
unloadQosProviderQosAttributes(
cmn_qosProvider _this)
__attribute__((nonnull));
/* loadQosSampleType: load qosSample type into the database. */
#undef c_metaObject /* Undef casting macro to avoid ambiguity with return type of function pointer. */
typedef c_metaObject (*qp_fnLoadQosSampleType)(c_base base);
typedef void(*qp_shallowClone)(void *from, void *to);
static cmn_qpResult
loadEntityQosAttributes(
cmn_qosProvider _this,
qp_fnLoadQosSampleType loadQosSample,
const C_STRUCT(cmn_qosInputAttr) *inputAttr,
qp_shallowClone shallowClone,
c_voidp defaultQos,
qp_entityAttr outputAttr)
__attribute__((nonnull));
static cmn_qpResult
loadQosProviderQosAttributes(
cmn_qosProvider _this,
const C_STRUCT(cmn_qosProviderInputAttr) *attr)
__attribute__((nonnull));
/* Table routines */
static os_equality
cmn_qosCompareByName (
void *o1,
void *o2,
void *unused)
__attribute__((nonnull(1,2)))
__attribute__((pure));
static void
cmn_qosTablefreeKey (
void *o,
void *unused)
__attribute__((nonnull(1)));
static void
cmn_qosTablefreeData (
void *o,
void *unused)
__attribute__((nonnull(1)));
static c_object
cmn_qosTableLookup(
ut_table t,
const c_char *defaultProfile,
const c_char *id)
__attribute__((nonnull(1,2)));
static os_equality
cmn_qosCompareByName (
void *o1,
void *o2,
void *unused)
{
int result;
OS_UNUSED_ARG(unused);
assert(o1);
assert(o2);
result = strcmp((const char *)o1, (const char *)o2);
if(result < 0){
return OS_LT;
} else if (result > 0) {
return OS_GT;
} else {
return OS_EQ;
}
}
static void
cmn_qosTablefreeKey (
void *o,
void *unused)
{
assert(o);
OS_UNUSED_ARG(unused);
os_free(o);
}
static void
cmn_qosTablefreeData (
void *o,
void *unused)
{
assert(o);
OS_UNUSED_ARG(unused);
c_free(o);
}
static c_object
cmn_qosTableLookup(
ut_table t,
const c_char *defaultProfile,
const c_char *id)
{
c_object qos = NULL;
const c_char * normalized = NULL;
const c_char * normalizedDefaultProfile;
assert(t);
assert(defaultProfile);
normalizedDefaultProfile = strncmp("::", defaultProfile, strlen("::")) == 0 ? defaultProfile + strlen("::") : defaultProfile;
if(id) {
normalized = strncmp("::", id, strlen("::")) == 0 ? id + strlen("::") : id;
if(id != normalized){
/* Fully-qualified name */
qos = ut_get(ut_collection(t), (void *)normalized);
} else {
c_char fullname[256];
c_char *fn = fullname;
int len;
if((len = snprintf(fn, sizeof(fullname), "%s::%s", normalizedDefaultProfile, id)) >= (int) sizeof(fullname)) {
fn = os_malloc((size_t) len + 1);
(void) snprintf(fn, (size_t) len + 1, "%s::%s", normalizedDefaultProfile, id);
}
qos = ut_get(ut_collection(t), (void *)fn);
if(fn != fullname) {
os_free(fn);
}
}
} else {
/* Empty qosName in default profile */
qos = ut_get(ut_collection(t), (void *)normalizedDefaultProfile);
}
if (qos == NULL) {
OS_REPORT(OS_ERROR, "QosProvider", QP_RESULT_NO_DATA,
"Could not find Qos value for profile: \"%s\" and id: \"%s\".",
defaultProfile,
(id == NULL ? "not specified" : id));
}
return qos;
}
static const char *
substituteConstants(
const char *xmlValue)
{
size_t i;
assert(xmlValue);
for (i = 0; i < sizeof(ApiConstants)/sizeof(ConstantValuePair); i++) {
if (strcmp(xmlValue, ApiConstants[i].name) == 0) return ApiConstants[i].value;
}
return xmlValue;
}
static cmn_qpResult
prepareQosSample(
const char *qosName,
qp_entityAttr attr,
qp_parseContext ctx)
{
cmn_qpResult result;
const c_type qosSampleType = attr->qosSampleType;
assert(qosSampleType);
assert(qosName);
assert(ctx);
ctx->scope = QP_SCOPE_QOSPOLICY;
ctx->qosSample = c_new(qosSampleType);
c_cloneIn(qosSampleType, attr->defaultQosTmplt, &ctx->qosSample);
ctx->currentField = c_fieldNew(qosSampleType, qosName);
if (ctx->currentField == NULL){
result = QP_RESULT_OUT_OF_MEMORY;
goto err_fieldNew;
}
ctx->currentFieldType = c_fieldType(ctx->currentField);
assert(ctx->currentFieldType);
ctx->qosTable = attr->qosTable;
return QP_RESULT_OK;
/* Error handling */
err_fieldNew:
c_free(ctx->qosSample);
ctx->qosSample = NULL;
return result;
}
static cmn_qpResult
processAttribute(
cf_attribute attribute,
qp_parseContext ctx)
{
cmn_qpResult result = QP_RESULT_OK;
const c_char *name = cf_nodeGetName((cf_node)attribute);
c_value value = cf_attributeValue(attribute);
assert(value.kind == V_STRING);
switch (ctx->scope)
{
case QP_SCOPE_PROFILE:
if (strcmp(name, "name") == 0) {
ctx->name = value.is.String;
} else if (strcmp(name, "base_name") == 0){
/* TODO: process base_name */
OS_REPORT(
OS_INFO,
"cmn_qosProvider::processAttribute",
3,
"Attribute (\"%s\") not yet supported for a <qos_profile> element...",
name);
} else if (strcmp(name, "topic_filter") != 0){ /* topic_filter has no meaning here */
result = QP_RESULT_UNKNOWN_ARGUMENT;
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processAttribute",
3,
"Unknown attribute (\"%s\") for a <qos_profile> element...",
name);
}
break;
case QP_SCOPE_QOSPOLICY:
if (strcmp(name, "name") == 0) {
ctx->name = value.is.String;
} else if (strcmp(name, "base_name") == 0){
/* TODO: process base_name */
OS_REPORT(
OS_INFO,
"cmn_qosProvider::processAttribute",
3,
"Attribute (\"%s\") not yet supported for a qos element...",
name);
} else {
result = QP_RESULT_UNKNOWN_ARGUMENT;
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processAttribute",
3,
"Unknown attribute (\"%s\") for a <(" DPQOS_TAG "|" TQOS_TAG "|" PUBQOS_TAG "|" SUBQOS_TAG "|" DWQOS_TAG "|" DRQOS_TAG ")_qos> element...",
name);
}
break;
default:
result = QP_RESULT_UNKNOWN_ARGUMENT;
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processAttribute",
3,
"Element specifies an unknown attribute (\"%s\")...",
name);
}
return result;
}
static cmn_qpResult
processContainedAttributes(
c_iter attributes,
qp_parseContext ctx)
{
cmn_qpResult result = QP_RESULT_OK;
cf_attribute attribute;
assert(ctx);
while ((attribute = (cf_attribute) c_iterTakeFirst(attributes)) != NULL && result == QP_RESULT_OK)
{
result = processAttribute(attribute, ctx);
}
c_iterFree(attributes);
return result;
}
static cmn_qpResult
processElementData(
cf_data data,
C_STRUCT(qp_parseContext) ctx)
{
cmn_qpResult result;
char first;
assert(data);
first = cf_dataValue(data).is.String[0];
if(strcmp(cf_node(data)->name, "#text") == 0 &&
(first == '\0' || first == '\n' || first == '<' || first == ' '))
{
/* Skip comments */
result = QP_RESULT_OK;
} else {
c_value xmlValue = cf_dataValue(data);
c_value qosValue = c_fieldValue(ctx.currentField, ctx.qosSample);
const char *actualValue = substituteConstants(xmlValue.is.String);
if (c_imageValue(actualValue, &qosValue, ctx.currentFieldType)) {
c_fieldAssign(ctx.currentField, ctx.qosSample, qosValue);
result = QP_RESULT_OK;
} else {
result = QP_RESULT_ILLEGAL_VALUE;
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processElementData",
3,
"Illegal value (\"%s\") for qosPolicy field \"%s\"...",
xmlValue.is.String,
c_fieldName(ctx.currentField));
}
}
return result;
}
static cmn_qpResult
processContainedElements(
c_iter elements,
C_STRUCT(qp_parseContext) ctx)
{
cmn_qpResult result = QP_RESULT_OK;
cf_node node;
while ((node = (cf_node) c_iterTakeFirst(elements)) != NULL && result == QP_RESULT_OK)
{
cf_kind kind = cf_nodeKind(node);
switch(kind) {
case CF_ELEMENT:
result = processElement(cf_element(node), ctx);
break;
case CF_DATA:
result = processElementData(cf_data(node), ctx);
break;
default:
assert(0);
break;
}
}
/* Elements of iter elements don't have to be freed, so no worries that iter
* is potentially not empty here. */
c_iterFree(elements);
return result;
}
static cmn_qpResult
processElement(
cf_element element,
C_STRUCT(qp_parseContext) ctx)
{
cmn_qpResult result = QP_RESULT_OK;
const c_char *name = cf_nodeGetName((cf_node)element);
assert(name);
assert(ctx.qosProvider->defaultProfile);
/* Enforce the opening <dds> tag. */
switch(ctx.scope)
{
case QP_SCOPE_NONE:
if (strcmp(name, DDS_TAG) == 0) {
ctx.scope = QP_SCOPE_DDS;
QP_TRACE(printf("%*sBEGIN " DDS_TAG "\n", level++ * 2, ""));
result = processContainedElements(cf_elementGetChilds(element), ctx);
QP_TRACE(printf("%*sEND " DDS_TAG "\n", --level * 2, ""));
} else {
QP_TRACE(printf("ERROR: Unrecognized top-level element ('%s'), expected top-level element '%s'\n", name, DDS_TAG));
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processElement",
3,
"Unrecognized top-level element (\"%s\"), expected top-level element \"%s\"...",
name,
DDS_TAG);
return QP_RESULT_UNEXPECTED_ELEMENT;
}
break;
case QP_SCOPE_DDS:
if (strcmp(name, PROFILE_TAG) == 0) {
ctx.scope = QP_SCOPE_PROFILE;
/* Fetch the (required according to Annex C of the
* 'DDS for Lightweight CCM, v1.1' specification) name of the
* current profile and store it in the current ctx. */
if((result = processContainedAttributes(cf_elementGetAttributes(element), &ctx)) != QP_RESULT_OK){
return result;
}
if(!ctx.name){
QP_TRACE(printf("ERROR: Element <" PROFILE_TAG "> has no 'name' attribute, which is mandatory.\n"));
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processElement",
3,
"Element <" PROFILE_TAG "> has no 'name' attribute, which is mandatory...");
return QP_RESULT_PARSE_ERROR;
}
QP_TRACE(printf("%*sBEGIN " PROFILE_TAG " '%s'\n", level++ * 2, "", ctx.name));
result = processContainedElements(cf_elementGetChilds(element), ctx);
QP_TRACE(printf("%*sEND " PROFILE_TAG " '%s'\n", --level * 2, "", ctx.name));
break; /* Only break when new scope has been determined. */
}
/* Fall-through intentional !! */
case QP_SCOPE_PROFILE:
if (strcmp(name, DPQOS_TAG) == 0) {
result = prepareQosSample(DPQOS_TAG, &ctx.qosProvider->dpQosAttr, &ctx);
} else if (strcmp(name, TQOS_TAG) == 0) {
result = prepareQosSample(TQOS_TAG, &ctx.qosProvider->tQosAttr, &ctx);
} else if (strcmp(name, PUBQOS_TAG) == 0) {
result = prepareQosSample(PUBQOS_TAG, &ctx.qosProvider->pubQosAttr, &ctx);
} else if (strcmp(name, SUBQOS_TAG) == 0) {
result = prepareQosSample(SUBQOS_TAG, &ctx.qosProvider->subQosAttr, &ctx);
} else if (strcmp(name, DWQOS_TAG) == 0) {
result = prepareQosSample(DWQOS_TAG, &ctx.qosProvider->dwQosAttr, &ctx);
} else if (strcmp(name, DRQOS_TAG) == 0) {
result = prepareQosSample(DRQOS_TAG, &ctx.qosProvider->drQosAttr, &ctx);
} else {
return QP_RESULT_UNEXPECTED_ELEMENT;
}
if(result == QP_RESULT_OK){
const char * profileName = ctx.name;
ctx.name = NULL;
/* Fetch the (required according to Annex C of the
* 'DDS for Lightweight CCM, v1.1' specification, but optional
* according to the rest of the document) name of the
* current qos and store it in the current ctx.
* In this case we ignore the schema and follow the rest of the
* specification (including Annex D). */
if((result = processContainedAttributes(cf_elementGetAttributes(element), &ctx)) != QP_RESULT_OK){
return result;
}
QP_TRACE(printf("%*sBEGIN %s (profile: '%s', name: '%s')\n",
level++ * 2, "",
name,
profileName ? profileName : "(null)",
ctx.name ? ctx.name : "(null)"));
if((result = processContainedElements(cf_elementGetChilds(element), ctx)) != QP_RESULT_OK){
return result;
}
{
char * qosName;
os_size_t len = 0;
if(profileName){
len += strlen(profileName);
} else {
len += strlen(ctx.qosProvider->defaultProfile);
}
if(ctx.name) {
len += strlen(ctx.name);
len += 2;
}
qosName = os_malloc(len + 1);
if(profileName){
sprintf(qosName, "%s%s%s", profileName, ctx.name ? "::" : "", ctx.name ? ctx.name : "");
} else {
if(*ctx.qosProvider->defaultProfile == '\0'){
sprintf(qosName, "%s", ctx.name ? ctx.name : "");
} else {
sprintf(qosName, "%s%s%s", ctx.qosProvider->defaultProfile, ctx.name ? "::" : "", ctx.name ? ctx.name : "");
}
}
if((ut_tableInsert(ctx.qosTable, qosName, ctx.qosSample /* transfer ref */)) == 0){
OS_REPORT(OS_INFO,
"cmn_qosProvider::processElement",
3,
"Identification for QoS '%s' is not unique...", /* TODO: report filename as well? */
qosName);
QP_TRACE(printf("%*sEND %s (%p), not stored under '%s'\n", --level * 2, "", name, (void *)ctx.qosSample, qosName));
c_free(ctx.qosSample);
os_free(qosName);
} else {
QP_TRACE(printf("%*sEND %s (%p), stored under '%s'\n", --level * 2, "", name, (void *)ctx.qosSample, qosName));
}
}
c_free(ctx.currentField);
c_free(ctx.currentFieldType);
}
break;
case QP_SCOPE_QOSPOLICY:
{
c_type at;
c_field unscopedField = c_fieldNew(ctx.currentFieldType, name);
if (unscopedField) {
QP_TRACE(printf("%*sBEGIN field '%s'\n", level++ * 2, "", name));
ctx.currentFieldType = c_fieldType(unscopedField);
if (ctx.currentField) {
ctx.currentField = c_fieldConcat(ctx.currentField, unscopedField);
c_free(unscopedField);
} else {
ctx.currentField = unscopedField;
}
at = c_typeActualType(ctx.currentFieldType);
if(c_baseObjectKind(at) == M_COLLECTION && c_collectionTypeKind(at) == OSPL_C_SEQUENCE) {
if(c_baseObjectKind(c_collectionTypeSubType(at)) == M_COLLECTION && c_collectionTypeKind(c_collectionTypeSubType(at)) == OSPL_C_STRING){
QP_TRACE(printf("%*sBEGIN SEQUENCE<%s> field '%s'\n", level++ * 2, "", c_metaName(c_collectionTypeSubType(at)), name));
{
c_iter elements = cf_elementGetChilds(element);
cmn_qpResult result = QP_RESULT_OK;
cf_node node;
c_string *strings = NULL;
c_ulong used, len;
len = used = 0;
while ((node = (cf_node) c_iterTakeFirst(elements)) != NULL && result == QP_RESULT_OK)
{
cf_kind kind = cf_nodeKind(node);
if(kind == CF_ELEMENT && strcmp("element", cf_nodeGetName(node)) == 0){
c_iter stringElement = cf_elementGetChilds(cf_element(node));
cf_node stringNode;
while ((stringNode = (cf_node) c_iterTakeFirst(stringElement)) != NULL && result == QP_RESULT_OK) {
if(cf_nodeKind(stringNode) == CF_DATA){
if(used == len) {
len += 16;
strings = os_realloc(strings, sizeof(*strings) * len);
}
if(result == QP_RESULT_OK){
strings[used++] = cf_dataValue((cf_data(stringNode))).is.String;
}
}
}
c_iterFree(stringElement);
} else {
/* TODO: report malformed XML */
result = QP_RESULT_PARSE_ERROR;
}
}
c_iterFree(elements);
if(used > 0) {
c_base base = c_getBase(at);
c_ulong i;
c_string *seq = (c_string*)c_newBaseArrayObject(c_collectionType(at), used);
for(i = 0; i < used; i++){
seq[i] = c_stringNew(base, strings[used - i - 1]);
QP_TRACE(printf("%*s'%s'\n", (level+1) * 2, "", seq[i]));
}
os_free(strings);
c_fieldAssign(ctx.currentField, ctx.qosSample, c_objectValue(seq));
c_free(seq);
}
}
QP_TRACE(printf("%*sEND SEQUENCE<%s> field '%s'\n", --level * 2, "", c_metaName(c_collectionTypeSubType(at)), name));
} else {
QP_TRACE(printf("%*sSKIPPING SEQUENCE<%s> field '%s'\n", level * 2, "", c_metaName(c_collectionTypeSubType(at)), name));
}
} else {
if((result = processContainedElements(cf_elementGetChilds(element), ctx)) != QP_RESULT_OK){
return result;
}
}
QP_TRACE(printf("%*sEND field '%s'\n", --level * 2, "", name));
c_free(ctx.currentField);
} else {
if ((strcmp(c_fieldName(ctx.currentField), DWQOS_TAG) == 0) &&
(strcmp(name, "durability_service") == 0)) {
QP_TRACE(printf("SKIPPING: Unsupported element '%s' inside qosPolicy field '%s'\n", name, c_fieldName(ctx.currentField)));
result = QP_RESULT_OK;
OS_REPORT(
OS_INFO,
"cmn_qosProvider::processElement",
3,
"Policy '%s' cannot be a member of " DWQOS_TAG " (it is applicable to " TQOS_TAG " only). OpenSpliceDDS will ignore this policy.",
name);
} else {
QP_TRACE(printf("ERROR: Unrecognized element '%s' inside qosPolicy field '%s'\n", name, c_fieldName(ctx.currentField)));
result = QP_RESULT_UNKNOWN_ELEMENT;
OS_REPORT(
OS_ERROR,
"cmn_qosProvider::processElement",
3,
"Unrecognized element (\"%s\") inside qosPolicy field \"%s\"...",
name,
c_fieldName(ctx.currentField));
}
}
break;
}
default:
assert(0);
}
return result;
}
static cmn_qpResult
checkQosProviderAttrIsSane (
const C_STRUCT(cmn_qosProviderInputAttr) *attr)
{
if(!attr) goto err_attr;
if(!attr->participantQos.copyOut) goto err_attr;
if(!attr->topicQos.copyOut) goto err_attr;
if(!attr->publisherQos.copyOut) goto err_attr;
if(!attr->dataWriterQos.copyOut) goto err_attr;
if(!attr->subscriberQos.copyOut) goto err_attr;
if(!attr->dataReaderQos.copyOut) goto err_attr;
return QP_RESULT_OK;
err_attr:
return QP_RESULT_ILL_PARAM;
}
static void
unloadEntityQosAttributes(
qp_entityAttr attr)
{
assert(attr);
c_free(attr->defaultQosTmplt);
c_free(attr->qosSampleType);
ut_tableFree(attr->qosTable);
}
static void
unloadQosProviderQosAttributes(
cmn_qosProvider _this)
{
unloadEntityQosAttributes(&_this->drQosAttr);
unloadEntityQosAttributes(&_this->dwQosAttr);
unloadEntityQosAttributes(&_this->subQosAttr);
unloadEntityQosAttributes(&_this->pubQosAttr);
unloadEntityQosAttributes(&_this->tQosAttr);
unloadEntityQosAttributes(&_this->dpQosAttr);
}
static cmn_qpResult
loadEntityQosAttributes(
cmn_qosProvider _this,
qp_fnLoadQosSampleType loadQosSample,
const C_STRUCT(cmn_qosInputAttr) *inputAttr,
qp_shallowClone shallowClone,
c_voidp defaultQos,
qp_entityAttr outputAttr)
{
assert(_this);
assert(loadQosSample);
assert(inputAttr);
assert(shallowClone);
assert(defaultQos);
assert(outputAttr);
if((outputAttr->qosTable = (ut_table)ut_tableNew(cmn_qosCompareByName, NULL, cmn_qosTablefreeKey, NULL, cmn_qosTablefreeData, NULL)) == NULL){
OS_REPORT(OS_ERROR, "loadEntityQosAttributes", 1, "Out of memory. Failed to allocate storage for QoS.");
goto err_table;
}
if((outputAttr->qosSampleType = c_type(loadQosSample(_this->baseAddr))) == NULL){
OS_REPORT(OS_ERROR, "loadEntityQosAttributes", 1, "Out of memory. Failed to allocate QoS sample-type.");
goto err_sampleType;
}
if((outputAttr->defaultQosTmplt = c_new(outputAttr->qosSampleType)) == NULL){
OS_REPORT(OS_ERROR, "loadEntityQosAttributes", 1, "Out of memory. Failed to allocate QoS template.");
goto err_qosTmplt;
}
shallowClone(defaultQos, outputAttr->defaultQosTmplt);
outputAttr->copyOut = inputAttr->copyOut;
return QP_RESULT_OK;
/* Error handling */
err_qosTmplt:
c_free(outputAttr->qosSampleType);
err_sampleType:
/* Guaranteed empty, so no free-functions needed */
ut_tableFree(outputAttr->qosTable);
err_table:
return QP_RESULT_OUT_OF_MEMORY;
}
static void
qp_NamedDomainParticipantQos__shallowClone(
void *_from,
void *_to)
{
struct _DDS_NamedDomainParticipantQos *from = (struct _DDS_NamedDomainParticipantQos *)_from;
struct _DDS_NamedDomainParticipantQos *to = (struct _DDS_NamedDomainParticipantQos *)_to;
*to = *from;
}
static void
qp_NamedTopicQos__shallowClone(
void *_from,
void *_to)
{
struct _DDS_NamedTopicQos *from = (struct _DDS_NamedTopicQos *)_from;
struct _DDS_NamedTopicQos *to = (struct _DDS_NamedTopicQos *)_to;
*to = *from;
}
static void
qp_NamedPublisherQos__shallowClone(
void *_from,
void *_to)
{
struct _DDS_NamedPublisherQos *from = (struct _DDS_NamedPublisherQos *)_from;
struct _DDS_NamedPublisherQos *to = (struct _DDS_NamedPublisherQos *)_to;
*to = *from;
}
static void
qp_NamedSubscriberQos__shallowClone(
void *_from,
void *_to)
{
struct _DDS_NamedSubscriberQos *from = (struct _DDS_NamedSubscriberQos *)_from;
struct _DDS_NamedSubscriberQos *to = (struct _DDS_NamedSubscriberQos *)_to;
*to = *from;
}
static void
qp_NamedDataWriterQos__shallowClone(
void *_from,
void *_to)
{
struct _DDS_NamedDataWriterQos *from = (struct _DDS_NamedDataWriterQos *)_from;
struct _DDS_NamedDataWriterQos *to = (struct _DDS_NamedDataWriterQos *)_to;
*to = *from;
}
static void
qp_NamedDataReaderQos__shallowClone(
void *_from,
void *_to)
{
struct _DDS_NamedDataReaderQos *from = (struct _DDS_NamedDataReaderQos *)_from;
struct _DDS_NamedDataReaderQos *to = (struct _DDS_NamedDataReaderQos *)_to;
*to = *from;
}
static cmn_qpResult
loadQosProviderQosAttributes(
cmn_qosProvider _this,
const C_STRUCT(cmn_qosProviderInputAttr) *attr)
{
cmn_qpResult result;
c_voidp qos;
assert(_this);
assert(checkQosProviderAttrIsSane (attr) == QP_RESULT_OK);
qos = (c_voidp)&qp_NamedDomainParticipantQos_default; /* Discard const */
result = loadEntityQosAttributes(_this, __DDS_NamedDomainParticipantQos__load, &attr->participantQos, qp_NamedDomainParticipantQos__shallowClone, qos, &_this->dpQosAttr);
if (result == QP_RESULT_OK) {
qos = (c_voidp)&qp_NamedTopicQos_default; /* Discard const */
result = loadEntityQosAttributes(_this, __DDS_NamedTopicQos__load, &attr->topicQos, qp_NamedTopicQos__shallowClone, qos, &_this->tQosAttr);
}
if (result == QP_RESULT_OK) {
qos = (c_voidp)&qp_NamedPublisherQos_default; /* Discard const */
result = loadEntityQosAttributes(_this, __DDS_NamedPublisherQos__load, &attr->publisherQos, qp_NamedPublisherQos__shallowClone, qos, &_this->pubQosAttr);
}
if (result == QP_RESULT_OK) {
qos = (c_voidp)&qp_NamedSubscriberQos_default; /* Discard const */
result = loadEntityQosAttributes(_this, __DDS_NamedSubscriberQos__load, &attr->subscriberQos, qp_NamedSubscriberQos__shallowClone, qos, &_this->subQosAttr);
}
if (result == QP_RESULT_OK) {
qos = (c_voidp)&qp_NamedDataWriterQos_default; /* Discard const */
result = loadEntityQosAttributes(_this, __DDS_NamedDataWriterQos__load, &attr->dataWriterQos, qp_NamedDataWriterQos__shallowClone, qos, &_this->dwQosAttr);
}
if (result == QP_RESULT_OK) {
qos = (c_voidp)&qp_NamedDataReaderQos_default; /* Discard const */
result = loadEntityQosAttributes(_this, __DDS_NamedDataReaderQos__load, &attr->dataReaderQos, qp_NamedDataReaderQos__shallowClone, qos, &_this->drQosAttr);
}
if (result != QP_RESULT_OK) {
unloadQosProviderQosAttributes(_this);
}
return result;
}
/**************************************************************
* constructor/destructor
**************************************************************/
cmn_qosProvider
cmn_qosProviderNew(
const c_char *uri,
const c_char *profile,
const C_STRUCT(cmn_qosProviderInputAttr) *attr)
{
cfgprs_status s;
cmn_qosProvider _this;
const c_char *normalizedProfile = "";
if(uri == NULL){
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 3, "Illegal parameter; parameter 'uri' may not be NULL.");
goto err_illegalParameter;
}
if(checkQosProviderAttrIsSane (attr) != QP_RESULT_OK){
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 3, "Illegal parameter; parameter 'attr' may not be NULL and all fields must be initialized.");
goto err_illegalParameter;
}
/* First make sure the user layer is initialized to allow Thread-specific
* memory for error reporting. */
if (u_userInitialise() != U_RESULT_OK) {
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 1, "Error. Initialisation of user-layer failed.");
goto err_userInitialize;
}
_this = os_malloc (C_SIZEOF(cmn_qosProvider));
memset(_this, 0, C_SIZEOF(cmn_qosProvider));
if(profile){
normalizedProfile = strncmp("::", profile, strlen("::")) == 0 ? profile + strlen("::") : profile;
}
_this->defaultProfile = os_strdup(normalizedProfile);
if((s = cfg_parse_ospl(uri, &_this->rootElement)) != CFGPRS_OK){
assert((s == CFGPRS_NO_INPUT) || (s == CFGPRS_ERROR));
if (s == CFGPRS_NO_INPUT) {
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 3, "Could not open XML file referred to by '%s'.", uri);
} else {
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 3, "The XML file referred to by '%s' does not parse correctly.", uri);
}
goto err_cfg_parse;
}
/* Create a heap database */
if((_this->baseAddr = c_create("QOSProvider", NULL, QOS_DATABASE_SIZE, 0)) == NULL){
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 1, "Out of memory. Failed to allocate heap database.");
goto err_c_create;
}
if (loadQosProviderQosAttributes(_this, attr) != QP_RESULT_OK){
OS_REPORT(OS_ERROR, "cmn_qosProviderNew", 1, "Out of memory. Failed to load QosProvider QosAttributes in heap database.");
goto err_loadAttributes;
}
/* Parse the tree */
{
C_STRUCT(qp_parseContext) ctx;
ctx.qosProvider = _this;
ctx.currentField = NULL;
ctx.currentFieldType = NULL;
ctx.qosSample = NULL;
ctx.scope = QP_SCOPE_NONE;
ctx.name = NULL;
ctx.qosTable = NULL;
if (processElement(_this->rootElement, ctx) != QP_RESULT_OK) {
/* ErrorReport already generated during recursive parse tree walk. */
goto err_process;
}
}
return _this;
/* Error handling */
err_process:
unloadQosProviderQosAttributes(_this);
err_loadAttributes:
c_destroy(_this->baseAddr);
err_c_create:
if (_this->rootElement) {
cf_elementFree(_this->rootElement);
}
err_cfg_parse:
os_free(_this->defaultProfile);
os_free(_this);
/* No undo for u_userInitialise */
err_userInitialize:
err_illegalParameter:
return NULL;
}
void
cmn_qosProviderFree(
cmn_qosProvider _this)
{
if (_this) {
unloadQosProviderQosAttributes(_this);
if (_this->baseAddr) {
c_destroy(_this->baseAddr);
}
if (_this->rootElement) {
cf_elementFree(_this->rootElement);
}
os_free(_this->defaultProfile);
os_free (_this);
}
}
/**************************************************************
* Public functions
**************************************************************/
cmn_qpResult
cmn_qosProviderGetParticipantQos(
cmn_qosProvider _this,
const c_char *id,
c_voidp qos)
{
c_object q;
assert(_this);
assert(_this->defaultProfile);
assert(qos);
if((q = cmn_qosTableLookup(_this->dpQosAttr.qosTable, _this->defaultProfile, id)) != NULL){
_this->dpQosAttr.copyOut(q, qos);
return QP_RESULT_OK;
} else {
return QP_RESULT_NO_DATA;
}
}
cmn_qpResult
cmn_qosProviderGetParticipantQosType(
cmn_qosProvider _this,
c_type *type)
{
assert(_this);
assert(type);
*type = c_keep(_this->dpQosAttr.qosSampleType);
return *type ? QP_RESULT_OK : QP_RESULT_NO_DATA;
}
cmn_qpResult
cmn_qosProviderGetTopicQos(
cmn_qosProvider _this,
const c_char *id,
c_voidp qos)
{
c_object q;
assert(_this);
assert(_this->defaultProfile);
assert(qos);
if((q = cmn_qosTableLookup(_this->tQosAttr.qosTable, _this->defaultProfile, id)) != NULL){
_this->tQosAttr.copyOut(q, qos);
return QP_RESULT_OK;
} else {
return QP_RESULT_NO_DATA;
}
}
cmn_qpResult
cmn_qosProviderGetTopicQosType(
cmn_qosProvider _this,
c_type *type)
{
assert(_this);
assert(type);
*type = c_keep(_this->tQosAttr.qosSampleType);
return *type ? QP_RESULT_OK : QP_RESULT_NO_DATA;
}
cmn_qpResult
cmn_qosProviderGetPublisherQos(
cmn_qosProvider _this,
const c_char *id,
c_voidp qos)
{
c_object q;
assert(_this);
assert(_this->defaultProfile);
assert(qos);
if((q = cmn_qosTableLookup(_this->pubQosAttr.qosTable, _this->defaultProfile, id)) != NULL){
_this->pubQosAttr.copyOut(q, qos);
return QP_RESULT_OK;
} else {
return QP_RESULT_NO_DATA;
}
}
cmn_qpResult
cmn_qosProviderGetPublisherQosType(
cmn_qosProvider _this,
c_type *type)
{
assert(_this);
assert(type);
*type = c_keep(_this->pubQosAttr.qosSampleType);
return *type ? QP_RESULT_OK : QP_RESULT_NO_DATA;
}
cmn_qpResult
cmn_qosProviderGetDataWriterQos(
cmn_qosProvider _this,
const c_char *id,
c_voidp qos)
{
c_object q;
assert(_this);
assert(_this->defaultProfile);
assert(qos);
if((q = cmn_qosTableLookup(_this->dwQosAttr.qosTable, _this->defaultProfile, id)) != NULL){
_this->dwQosAttr.copyOut(q, qos);
return QP_RESULT_OK;
} else {
return QP_RESULT_NO_DATA;
}
}
cmn_qpResult
cmn_qosProviderGetDataWriterQosType(
cmn_qosProvider _this,
c_type *type)
{
assert(_this);
assert(type);
*type = c_keep(_this->dwQosAttr.qosSampleType);
return *type ? QP_RESULT_OK : QP_RESULT_NO_DATA;
}
cmn_qpResult
cmn_qosProviderGetSubscriberQos(
cmn_qosProvider _this,
const c_char *id,
c_voidp qos)
{
c_object q;
assert(_this);
assert(_this->defaultProfile);
assert(qos);
if((q = cmn_qosTableLookup(_this->subQosAttr.qosTable, _this->defaultProfile, id)) != NULL){
_this->subQosAttr.copyOut(q, qos);
return QP_RESULT_OK;
} else {
return QP_RESULT_NO_DATA;
}
}
cmn_qpResult
cmn_qosProviderGetSubscriberQosType(
cmn_qosProvider _this,
c_type *type)
{
assert(_this);
assert(type);
*type = c_keep(_this->subQosAttr.qosSampleType);
return *type ? QP_RESULT_OK : QP_RESULT_NO_DATA;
}
cmn_qpResult
cmn_qosProviderGetDataReaderQos(
cmn_qosProvider _this,
const c_char *id,
c_voidp qos)
{
c_object q;
assert(_this);
assert(_this->defaultProfile);
assert(qos);
if((q = cmn_qosTableLookup(_this->drQosAttr.qosTable, _this->defaultProfile, id)) != NULL){
_this->drQosAttr.copyOut(q, qos);
return QP_RESULT_OK;
} else {
return QP_RESULT_NO_DATA;
}
}
cmn_qpResult
cmn_qosProviderGetDataReaderQosType(
cmn_qosProvider _this,
c_type *type)
{
assert(_this);
assert(type);
*type = c_keep(_this->drQosAttr.qosSampleType);
return *type ? QP_RESULT_OK : QP_RESULT_NO_DATA;
}
| {
"content_hash": "6c7c69f3981bcd178ead84c748b3a2bc",
"timestamp": "",
"source": "github",
"line_count": 1258,
"max_line_length": 174,
"avg_line_length": 31.44912559618442,
"alnum_prop": 0.5554432171473346,
"repo_name": "osrf/opensplice",
"id": "5c9224ac21b04b7acd19e6fb42190b0a1544ccfd",
"size": "40361",
"binary": false,
"copies": "2",
"ref": "refs/heads/osrf-6.9.0",
"path": "src/api/dcps/common/code/cmn_qosProvider.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "16400"
},
{
"name": "Batchfile",
"bytes": "192174"
},
{
"name": "C",
"bytes": "19618578"
},
{
"name": "C#",
"bytes": "2428591"
},
{
"name": "C++",
"bytes": "8036199"
},
{
"name": "CMake",
"bytes": "35186"
},
{
"name": "CSS",
"bytes": "41427"
},
{
"name": "HTML",
"bytes": "457045"
},
{
"name": "Java",
"bytes": "5184488"
},
{
"name": "JavaScript",
"bytes": "540355"
},
{
"name": "LLVM",
"bytes": "13059"
},
{
"name": "Lex",
"bytes": "51476"
},
{
"name": "Makefile",
"bytes": "513684"
},
{
"name": "Objective-C",
"bytes": "38424"
},
{
"name": "Perl",
"bytes": "164028"
},
{
"name": "Python",
"bytes": "915683"
},
{
"name": "Shell",
"bytes": "363583"
},
{
"name": "TeX",
"bytes": "8134"
},
{
"name": "Visual Basic",
"bytes": "290"
},
{
"name": "Yacc",
"bytes": "202848"
}
],
"symlink_target": ""
} |
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from '../../../prop_types';
import i18n from '../../../i18n';
import { autobind, mixin } from '../../../utils/decorators';
import InputBase from '../input_base';
import InputSelectOption from './input_select_option';
import {
CssClassMixin,
SelectComponentMixin,
InputSelectActionsListenerMixin,
MaterializeSelectMixin,
} from '../../../mixins';
@mixin(
CssClassMixin,
SelectComponentMixin,
InputSelectActionsListenerMixin,
MaterializeSelectMixin
)
export default class InputSelect extends InputBase {
static propTypes = {
includeBlank: PropTypes.bool,
blankText: PropTypes.localizedString,
};
static defaultProps = {
includeBlank: true,
themeClassKey: 'input.select',
blankText: 'select',
};
getInputFormNode() {
return ReactDOM.findDOMNode(this.refs.select);
}
selectedValue() {
const value = this.state.value;
return !this.props.multiple ? value[0] : value;
}
renderOptions() {
const selectOptions = [];
const options = this.state.options;
if (this.props.includeBlank) {
selectOptions.push(
<InputSelectOption
name={i18n.t(this.props.blankText)}
value=""
key="empty_option"
/>
);
}
for (let i = 0; i < options.length; i++) {
const optionProps = options[i];
selectOptions.push(<InputSelectOption {...optionProps} key={optionProps.name} />);
}
return selectOptions;
}
render() {
return (
<select
id={this.props.id}
name={this.props.name}
value={this.selectedValue()}
onChange={this.handleChange}
disabled={this.isDisabled() || this.props.readOnly}
className={this.className()}
ref="select"
>
{this.renderOptions()}
</select>
);
}
@autobind
handleChange(event) {
const selectElement = ReactDOM.findDOMNode(this.refs.select);
const newValue = this.ensureIsArray(selectElement.value);
this.props.onChange(event, newValue, this);
if (!event.isDefaultPrevented()) {
this.setState({
value: newValue,
}, this.triggerDependableChanged);
}
}
@autobind
handleReset() {
this.setStatePromise({ value: [] })
.then(() => this.triggerDependableChanged);
}
}
| {
"content_hash": "d4ade50eb641f7f340e4f02465579988",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 88,
"avg_line_length": 23.58,
"alnum_prop": 0.6365564037319763,
"repo_name": "rafaelfbs/realizejs",
"id": "d7abc98b9dc022416a77dcc13bfb50809547cc4b",
"size": "2358",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/components/input/select/input_select.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12821"
},
{
"name": "JavaScript",
"bytes": "358052"
}
],
"symlink_target": ""
} |
package zero
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
"strconv"
)
// Int is a nullable int64.
// JSON marshals to zero if null.
// Considered null to SQL if zero.
type Int struct {
sql.NullInt64
}
// NewInt creates a new Int
func NewInt(i int64, valid bool) Int {
return Int{
NullInt64: sql.NullInt64{
Int64: i,
Valid: valid,
},
}
}
// IntFrom creates a new Int that will be null if zero.
func IntFrom(i int64) Int {
return NewInt(i, i != 0)
}
// IntFromPtr creates a new Int that be null if i is nil.
func IntFromPtr(i *int64) Int {
if i == nil {
return NewInt(0, false)
}
n := NewInt(*i, true)
return n
}
// UnmarshalJSON implements json.Unmarshaler.
// It supports number and null input.
// 0 will be considered a null Int.
// It also supports unmarshalling a sql.NullInt64.
func (i *Int) UnmarshalJSON(data []byte) error {
var err error
var v interface{}
if err = json.Unmarshal(data, &v); err != nil {
return err
}
switch v.(type) {
case float64:
// Unmarshal again, directly to int64, to avoid intermediate float64
err = json.Unmarshal(data, &i.Int64)
case map[string]interface{}:
err = json.Unmarshal(data, &i.NullInt64)
case nil:
i.Valid = false
return nil
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type zero.Int", reflect.TypeOf(v).Name())
}
i.Valid = (err == nil) && (i.Int64 != 0)
return err
}
// UnmarshalText implements encoding.TextUnmarshaler.
// It will unmarshal to a null Int if the input is a blank, zero, or not an integer.
// It will return an error if the input is not an integer, blank, or "null".
func (i *Int) UnmarshalText(text []byte) error {
str := string(text)
if str == "" || str == "null" {
i.Valid = false
return nil
}
var err error
i.Int64, err = strconv.ParseInt(string(text), 10, 64)
i.Valid = (err == nil) && (i.Int64 != 0)
return err
}
// MarshalJSON implements json.Marshaler.
// It will encode 0 if this Int is null.
func (i Int) MarshalJSON() ([]byte, error) {
n := i.Int64
if !i.Valid {
n = 0
}
return []byte(strconv.FormatInt(n, 10)), nil
}
// MarshalText implements encoding.TextMarshaler.
// It will encode a zero if this Int is null.
func (i Int) MarshalText() ([]byte, error) {
n := i.Int64
if !i.Valid {
n = 0
}
return []byte(strconv.FormatInt(n, 10)), nil
}
// SetValid changes this Int's value and also sets it to be non-null.
func (i *Int) SetValid(n int64) {
i.Int64 = n
i.Valid = true
}
// Ptr returns a pointer to this Int's value, or a nil pointer if this Int is null.
func (i Int) Ptr() *int64 {
if !i.Valid {
return nil
}
return &i.Int64
}
// IsZero returns true for null or zero Ints, for future omitempty support (Go 1.4?)
func (i Int) IsZero() bool {
return !i.Valid || i.Int64 == 0
}
| {
"content_hash": "4c1338f37778c653842030c1ea9bbc34",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 104,
"avg_line_length": 23.175,
"alnum_prop": 0.6652283351312478,
"repo_name": "jgsqware/clair",
"id": "3645c41faa904a04953473ffb9cb3f2f70cbd737",
"size": "2781",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/github.com/guregu/null/zero/int.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "427829"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template tag</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../intrusive/reference.html#header.boost.intrusive.options_hpp" title="Header <boost/intrusive/options.hpp>">
<link rel="prev" href="void_pointer.html" title="Struct template void_pointer">
<link rel="next" href="link_mode.html" title="Struct template link_mode">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="void_pointer.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.options_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="link_mode.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.intrusive.tag"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template tag</span></h2>
<p>boost::intrusive::tag</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../intrusive/reference.html#header.boost.intrusive.options_hpp" title="Header <boost/intrusive/options.hpp>">boost/intrusive/options.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Tag<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="tag.html" title="Struct template tag">tag</a> <span class="special">{</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp421282400"></a><h2>Description</h2>
<p>This option setter specifies the type of the tag of a base hook. A type cannot have two base hooks of the same type, so a tag can be used to differentiate two base hooks with otherwise same type </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005 Olaf Krzikalla<br>Copyright © 2006-2015 Ion Gaztanaga<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="void_pointer.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.options_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="link_mode.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "cfd22940a1de8dd054b37d76d905d311",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 456,
"avg_line_length": 75.41071428571429,
"alnum_prop": 0.6672981292919725,
"repo_name": "keichan100yen/ode-ext",
"id": "f39739ebb96e8680186d33af8911a9765537d708",
"size": "4223",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "boost/doc/html/boost/intrusive/tag.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "309067"
},
{
"name": "Batchfile",
"bytes": "37875"
},
{
"name": "C",
"bytes": "2967570"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "189322982"
},
{
"name": "CMake",
"bytes": "119251"
},
{
"name": "CSS",
"bytes": "456744"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "6246"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groff",
"bytes": "5189"
},
{
"name": "HTML",
"bytes": "181460055"
},
{
"name": "IDL",
"bytes": "28"
},
{
"name": "JavaScript",
"bytes": "419776"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1088024"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "11406"
},
{
"name": "Objective-C++",
"bytes": "630"
},
{
"name": "PHP",
"bytes": "68641"
},
{
"name": "Perl",
"bytes": "36491"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "1612978"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "Shell",
"bytes": "354720"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "XSLT",
"bytes": "553585"
},
{
"name": "Yacc",
"bytes": "19623"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="4dp"
/>
<stroke
android:width="1dp"
android:color="@color/color_red_e26254"
/>
<solid
android:color="@color/color_gray_fff0ee"
/>
</shape> | {
"content_hash": "cf59b791a53a436685949ef20d965adf",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 65,
"avg_line_length": 23.3125,
"alnum_prop": 0.5710455764075067,
"repo_name": "malaonline/Android",
"id": "63936f55a110ef375c80d5db2ee3d985f913c0c9",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/drawable/shape_goto_comment_pressed.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "118"
},
{
"name": "Java",
"bytes": "1634323"
},
{
"name": "Shell",
"bytes": "357"
}
],
"symlink_target": ""
} |
<?php
namespace florbalMohelnice\Components;
use Nette\Application\UI\Control,
florbalMohelnice\Models\UserModel,
Grido\Grid,
Grido\Components\Actions\Action,
Grido\Components\Filters\Filter,
Grido\Components\Columns\Column,
Grido\Components\Columns\Date;
/**
* Description of ProfilePermitControl
*
* @author Michal Fučík <michal.fuca.fucik@gmail.com>
* @package florbalMohelnice
*/
final class ProfilePermitControl extends Control {
/** @var data to display */
private $data;
/** @var user model */
private $userModel;
/** @var template file */
private $templateFile;
public function getUserModel() {
if (!isset($this->userModel)) throw new \Nette\InvalidStateException('User model has to be set');
return $this->userModel;
}
public function setUserModel(UserModel $um) {
$this->userModel = $um;
}
public function getTemplateFile() {
if (!isset($this->templateFile)) $this->templateFile = __DIR__.'/default.latte';
return $this->templateFile;
}
public function setTemplateFile($template) {
if (!file_exists($template)) throw new \Nette\InvalidArgumentException('Template file doesn\'t exist');
$this->templateFile = $template;
}
public function render() {
$this->template->setFile($this->getTemplateFile());
$this->template->render();
}
public function createComponentPermitGrid($name) {
$filterRenderType = Filter::RENDER_INNER;
$grid = new Grid($this, $name);
$grid->setModel($this->getUserModel()->webProfilesForCheckFluent());
$grid->setDefaultPerPage(30);
$grid->setPrimaryKey('kid');
$grid->addColumn('kid', 'KID')
->setSortable()
->setFilter()
->setSuggestion();
$grid->addColumn('surname', 'Příjmení')
->setSortable()
->setFilter()
->setSuggestion();
$grid->addColumn('name', 'Jméno')
->setSortable()
->setFilter()
->setSuggestion();
$grid->addAction('show', 'Zobrazit', Action::TYPE_HREF , 'editWebProfile');
$grid->setOperations(array('permit'=>'Schválit'), callback($this, 'editWebProfileOperationsHandler'));
$grid->setFilterRenderType($filterRenderType);
$grid->setExporting();
}
public function editWebProfileOperationsHandler($operation, $id) {
switch ($operation) {
case 'permit':
foreach ($id as $i)
$this->presenter->permitProfile($i);
break;
}
}
}
| {
"content_hash": "529e37e28a05ecac5862a583ad2dbffb",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 105,
"avg_line_length": 25.456521739130434,
"alnum_prop": 0.6865926558497011,
"repo_name": "fuca/fbcmohelnice",
"id": "0a7a97bf2d4deba345352289840eb7a983556f0b",
"size": "2349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/components/DEPRECATED ProfilePermitControl/ProfilePermitControl.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50842"
},
{
"name": "JavaScript",
"bytes": "617883"
},
{
"name": "PHP",
"bytes": "2095571"
},
{
"name": "Perl",
"bytes": "1005"
},
{
"name": "Ruby",
"bytes": "347"
},
{
"name": "Shell",
"bytes": "141"
}
],
"symlink_target": ""
} |
@implementation NSLayoutConstraint (TestUtils)
- (BOOL)isEqualToNSLayoutConstraint:(NSLayoutConstraint *)layoutConstraint
{
if (!layoutConstraint) {
return NO;
}
BOOL hasEqualPriority = (self.priority == layoutConstraint.priority);
BOOL hasEqualFirstItem = (self.firstItem == layoutConstraint.firstItem);
BOOL hasEqualFirstAttribute = (self.firstAttribute == layoutConstraint.firstAttribute);
BOOL hasEqualRelation = (self.relation == layoutConstraint.relation);
BOOL hasEqualSecondItem = (self.secondItem == layoutConstraint.secondItem);
BOOL hasEqualSecondAttribute = (self.secondAttribute == layoutConstraint.secondAttribute);
BOOL hasEqualMultiplier = (self.multiplier == layoutConstraint.multiplier);
BOOL hasEqualConstant = (self.constant == layoutConstraint.constant);
BOOL hasEqualShouldBeArchived = (self.shouldBeArchived == layoutConstraint.shouldBeArchived);
return hasEqualPriority && hasEqualFirstItem && hasEqualFirstAttribute && hasEqualRelation &&
hasEqualSecondItem && hasEqualSecondAttribute && hasEqualMultiplier && hasEqualConstant &&
hasEqualShouldBeArchived;
}
- (BOOL)isEqual:(id)object
{
if (self == object) {
return YES;
}
if (![object isKindOfClass:[NSLayoutConstraint class]]) {
return NO;
}
return [self isEqualToNSLayoutConstraint:(NSLayoutConstraint *)object];
}
- (NSUInteger)hash
{
return (int)self.priority ^ [self.firstItem hash] ^ self.firstAttribute ^ self.relation ^ [self.secondItem hash] ^
self.secondAttribute ^ (int)self.multiplier ^ (int)self.constant ^ self.shouldBeArchived;
}
@end
| {
"content_hash": "0b68663786eea15e9c295203e2d8058a",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 118,
"avg_line_length": 38.83720930232558,
"alnum_prop": 0.7287425149700599,
"repo_name": "rbaumbach/DropboxSimpleOAuth",
"id": "0f6f0f83c75b51bdbcfda83ba34390686b9cf38a",
"size": "1712",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Specs/NSLayoutConstraint+TestUtils.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1194"
},
{
"name": "Objective-C",
"bytes": "68322"
},
{
"name": "Ruby",
"bytes": "7975"
},
{
"name": "Shell",
"bytes": "149"
},
{
"name": "Swift",
"bytes": "7062"
}
],
"symlink_target": ""
} |
module AppleNews
module Component
class Photo < Base
include ScalableImage
role "photo"
end
end
end
| {
"content_hash": "4b903a6abe3e2758f3db83ffdb3fd311",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 27,
"avg_line_length": 15.5,
"alnum_prop": 0.6612903225806451,
"repo_name": "hodinkee/apple-news-rb",
"id": "da4ef0ae9223e2a30c21a6ad70df31fda75e19ec",
"size": "124",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/apple-news/components/photo.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "55883"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
var fs = require('fs');
var util = require('util');
var Q = require('q');
var gcloud = require('gcloud');
var BaseStorage = require('./BaseStorage');
util.inherits(GCloudStorage, BaseStorage);
/**
* GCloud Storage class
* @param {Object} options
* @constructor
*/
function GCloudStorage(options) {
BaseStorage.apply(this, arguments);
this.setKeyFilename(options.keyFilename);
this.setProjectId(options.projectId);
}
/**
* Upload file to GCloud Storage
* @param {Object} options Object with `bucket`, `key` and `source` properties
* @returns {promise}
*/
GCloudStorage.prototype.upload = function (options) {
var defer = Q.defer();
var bucket = this._getProject().storage().bucket(options.bucket);
var file = bucket.file(options.key);
fs.createReadStream(options.body)
.pipe(file.createWriteStream())
.on('error', function (error) {
defer.reject(error);
})
.on('end', function () {
defer.resolve();
});
return defer.promise;
};
/**
* Download file from GCloud Storage
* @param {Object} options Object with `bucket` and `key` properties
* @returns {promise}
*/
GCloudStorage.prototype.get = function (options) {
var defer = Q.defer();
var bucket = this._getProject().storage().bucket(options.bucket);
var file = bucket.file(options.key);
var buffer = '';
file.createReadStream()
.on('data', function (data) {
buffer += data;
})
.on('end', function () {
defer.resolve(new Buffer(buffer));
})
.on('error', function (error) {
defer.reject(error);
});
return defer.promise;
};
/**
* Remove file from GCloud Storage
* @param {Object} options Options with `bucket` and `key` properties
* @returns {promise}
*/
GCloudStorage.prototype.remove = function (options) {
var defer = Q.defer();
var bucket = this._getProject().storage().bucket(options.bucket);
var file = bucket.file(options.key);
file.delete(function (error) {
if (error) {
defer.reject(error);
} else {
defer.resolve();
}
});
return defer.promise;
};
/**
* Get gcloud project
* @returns {*}
* @private
*/
GCloudStorage.prototype._getProject = function () {
return this._project;
};
/**
* Set gcloud project
* @param project
* @returns {GCloudStorage}
* @private
*/
GCloudStorage.prototype._setProject = function (project) {
this._project = project;
return this;
};
/**
* Update project parameters after some changes
* @returns {GCloudStorage}
* @private
*/
GCloudStorage.prototype._updateProjectCredentials = function () {
this._setProject(gcloud({
keyFilename: this.getKeyFilename(),
projectId: this.getProjectId()
}));
return this;
};
/**
* Get project id from current google instance
* @returns {String}
*/
GCloudStorage.prototype.getProjectId = function () {
return this.projectId;
};
/**
* Set project id
* @param {String} id Google Cloud Project ID
* @returns {GCloudStorage}
*/
GCloudStorage.prototype.setProjectId = function (id) {
this.projectId = id;
this._updateProjectCredentials();
return this;
};
/**
* Get key filename
* @returns {String} Returns keyFilename from current instance
*/
GCloudStorage.prototype.getKeyFilename = function () {
return this.keyFilename;
};
/**
* Set key filename
* @param {String} key keyFilename for google cloud storage
* @returns {GCloudStorage}
*/
GCloudStorage.prototype.setKeyFilename = function (key) {
this.keyFilename = key;
this._updateProjectCredentials();
return this;
};
module.exports = GCloudStorage;
| {
"content_hash": "f31e0d26168cb60cebf59c7850af0083",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 78,
"avg_line_length": 22.043478260869566,
"alnum_prop": 0.6700479008171316,
"repo_name": "jmtt89/templateSailREST",
"id": "42edc49e4373bff93d96962abc5c0834d6a7c643",
"size": "3549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/services/storage/GCloudStorage.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "63417"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Tue Dec 02 08:47:49 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Class Hierarchy</title>
<meta name="date" content="2014-12-02">
<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="Class Hierarchy";
}
//-->
</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="be/quodlibet/jcoSon/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.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">
<h1 class="title">Hierarchy For All Packages</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="be/quodlibet/jcoSon/package-tree.html">be.quodlibet.jcoSon</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">be.quodlibet.jcoSon.<a href="be/quodlibet/jcoSon/jcoSon.html" title="class in be.quodlibet.jcoSon"><span class="strong">jcoSon</span></a></li>
</ul>
</li>
</ul>
</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="be/quodlibet/jcoSon/package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</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?overview-tree.html" target="_top">Frames</a></li>
<li><a href="overview-tree.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>
| {
"content_hash": "52569a39313d4e437de9d835e8197e7e",
"timestamp": "",
"source": "github",
"line_count": 127,
"max_line_length": 160,
"avg_line_length": 30.015748031496063,
"alnum_prop": 0.6382476390346274,
"repo_name": "dhorions/jcoSon",
"id": "ee77fad7c863a2dcb96bde3dc75e4fcda11b23fa",
"size": "3812",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/javadoc/overview-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "Java",
"bytes": "13214"
}
],
"symlink_target": ""
} |
#ifndef __TEST_TUPLE_HPP__
#define __TEST_TUPLE_HPP__
#include "cassandra.h"
#include "objects/object_base.hpp"
#include "objects/iterator.hpp"
#include "objects/statement.hpp"
#include <gtest/gtest.h>
namespace test { namespace driver {
/**
* Tuple object
*
* //TODO: Needs proper implementation
*/
class Tuple : public Object<CassTuple, cass_tuple_free> {
public:
class Exception : public test::Exception {
public:
Exception(const std::string& message)
: test::Exception(message) {}
};
/**
* Create an empty tuple object
*
* @param size Number of elements in the tuple
*/
Tuple(size_t size)
: Object<CassTuple, cass_tuple_free>(cass_tuple_new(size))
, size_(size)
, is_null_(true) {}
/**
* Create the tuple from a particular column
*
* @param column Column to retrieve tuple from
*/
Tuple(const CassValue* column)
: size_(0)
, is_null_(true) {
initialize(column);
}
/**
* Determine if the tuple is NULL (or unassigned)
*
* @return True if tuple is NULL; false otherwise
*/
bool is_null() { return is_null_; }
/**
* Get the next value
*
* @return The next value; NULL if iterator is NULL or has reached the end of
* the iterator
*/
const CassValue* next() {
if (cass_iterator_next(iterator_.get())) {
return cass_iterator_get_value(iterator_.get());
}
return NULL;
}
/**
* Set the value in the tuple
*
* @param value Parameterized value to set to the tuple
* @param index Index to place the value in the tuple
* @throws Exception If tuple is not able to have values added to it (e.g.
* The tuple was generated from server result)
*/
template <typename T>
void set(T value, size_t index) {
value.set(*this, index);
is_null_ = false;
}
/**
* Get the size of the tuple
*
* @return The number of elements in the tuple
*/
size_t size() { return size_; }
/**
* Get the current value from the tuple iterator (retrieved from server)
*
* @return Current value in the tuple
* @throws Exception If iterator is not valid
*/
template <typename T>
T value() {
if (iterator_) {
return T(cass_iterator_get_value(iterator_.get()));
}
throw Exception("Invalid Tuple: Values not retrieved from server");
}
/**
* Gets all the values as a single type (retrieved from server)
*
* @return The tuple as a vector of a single type
*/
template <typename T>
std::vector<T> values() {
std::vector<T> result;
const CassValue* value;
while ((value = next()) != NULL) {
result.push_back(T(value));
}
return result;
}
/**
* Bind the tuple to a statement at the given index
*
* @param statement The statement to bind the value to
* @param index The index/position where the value will be bound in the
* statement
*/
void statement_bind(Statement statement, size_t index) {
ASSERT_EQ(CASS_OK, cass_statement_bind_tuple(statement.get(), index, get()));
}
protected:
/**
* Iterator driver wrapped object
*/
Iterator iterator_;
/**
* Number of element in the tuple
*/
size_t size_;
/**
* Flag to determine if a tuple is empty (null)
*/
bool is_null_;
/**
* Initialize the iterator from the CassValue
*
* @param value CassValue to initialize iterator from
*/
void initialize(const CassValue* value) {
// Ensure the value is a tuple
ASSERT_TRUE(value != NULL) << "Invalid CassValue: Value should not be null";
ASSERT_EQ(CASS_VALUE_TYPE_TUPLE, cass_value_type(value));
// Initialize the iterator
size_ = cass_value_item_count(value);
iterator_ = cass_iterator_from_tuple(value);
// Determine if the tuple is empty (null)
const CassValue* check_value = cass_iterator_get_value(iterator_.get());
if (check_value) {
is_null_ = false;
}
}
};
}} // namespace test::driver
#endif // __TEST_TUPLE_HPP__
| {
"content_hash": "4907de53762564581418a9ab006f1fea",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 81,
"avg_line_length": 23.75147928994083,
"alnum_prop": 0.625560538116592,
"repo_name": "datastax/cpp-driver",
"id": "313927bafed0c9d2edd9d82826f85ed427af1025",
"size": "4589",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/src/integration/objects/tuple.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "372863"
},
{
"name": "C++",
"bytes": "3403723"
},
{
"name": "CMake",
"bytes": "105857"
},
{
"name": "Makefile",
"bytes": "1192"
},
{
"name": "PowerShell",
"bytes": "40084"
},
{
"name": "Ragel",
"bytes": "1870"
},
{
"name": "Ruby",
"bytes": "690"
},
{
"name": "Shell",
"bytes": "11836"
}
],
"symlink_target": ""
} |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp10.DocumentationRules
{
using StyleCop.Analyzers.Test.CSharp9.DocumentationRules;
public class SA1615CSharp10UnitTests : SA1615CSharp9UnitTests
{
}
}
| {
"content_hash": "1e388a13da30ed1852e4816305c8bfc8",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 91,
"avg_line_length": 33.81818181818182,
"alnum_prop": 0.7795698924731183,
"repo_name": "DotNetAnalyzers/StyleCopAnalyzers",
"id": "073c8848d41041b414d92e051c15db476c79e481",
"size": "374",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp10/DocumentationRules/SA1615CSharp10UnitTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "7601877"
},
{
"name": "PowerShell",
"bytes": "46372"
}
],
"symlink_target": ""
} |
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "2common.h"
#include "file_type.h"
#include "file_type_bios.h"
#include "futility.h"
#include "futility_options.h"
#include "host_common.h"
#include "host_common21.h"
#include "host_key21.h"
#include "kernel_blob.h"
#include "util_misc.h"
#include "vb1_helper.h"
#define DEFAULT_KEYSETDIR "/usr/share/vboot/devkeys"
/* Options */
struct sign_option_s sign_option = {
.keysetdir = DEFAULT_KEYSETDIR,
.version = 1,
.arch = ARCH_UNSPECIFIED,
.kloadaddr = CROS_32BIT_ENTRY_ADDR,
.padding = 65536,
.type = FILE_TYPE_UNKNOWN,
.hash_alg = VB2_HASH_SHA256, /* default */
.ro_size = 0xffffffff,
.rw_size = 0xffffffff,
.ro_offset = 0xffffffff,
.rw_offset = 0xffffffff,
.sig_size = 1024,
};
/* Helper to complain about invalid args. Returns num errors discovered */
static int no_opt_if(int expr, const char *optname)
{
if (expr) {
fprintf(stderr, "Missing --%s option\n", optname);
return 1;
}
return 0;
}
/* This wraps/signs a public key, producing a keyblock. */
int ft_sign_pubkey(const char *name, void *data)
{
struct vb2_packed_key *data_key;
uint32_t data_len;
struct vb2_keyblock *block;
int rv = 1;
int fd = -1;
if (futil_open_and_map_file(name, &fd, FILE_MODE_SIGN(sign_option),
(uint8_t **)&data_key, &data_len))
return 1;
if (vb2_packed_key_looks_ok(data_key, data_len)) {
fprintf(stderr, "Public key looks bad.\n");
goto done;
}
if (sign_option.pem_signpriv) {
if (sign_option.pem_external) {
/* External signing uses the PEM file directly. */
block = vb2_create_keyblock_external(
data_key,
sign_option.pem_signpriv,
sign_option.pem_algo,
sign_option.flags,
sign_option.pem_external);
} else {
sign_option.signprivate = vb2_read_private_key_pem(
sign_option.pem_signpriv,
sign_option.pem_algo);
if (!sign_option.signprivate) {
fprintf(stderr,
"Unable to read PEM signing key: %s\n",
strerror(errno));
goto done;
}
block = vb2_create_keyblock(data_key,
sign_option.signprivate,
sign_option.flags);
}
} else {
/* Not PEM. Should already have a signing key. */
block = vb2_create_keyblock(data_key, sign_option.signprivate,
sign_option.flags);
}
/* Write it out */
rv = WriteSomeParts(sign_option.outfile, block, block->keyblock_size,
NULL, 0);
done:
futil_unmap_and_close_file(fd, FILE_MODE_SIGN(sign_option),
(uint8_t *)data_key, data_len);
return rv;
}
int ft_sign_raw_kernel(const char *name, void *data)
{
uint8_t *vmlinuz_data = NULL, *kblob_data = NULL, *vblock_data = NULL;
uint32_t vmlinuz_size, kblob_size, vblock_size;
int rv = 1;
int fd = -1;
if (futil_open_and_map_file(name, &fd, FILE_MODE_SIGN(sign_option),
&vmlinuz_data, &vmlinuz_size))
return 1;
kblob_data = CreateKernelBlob(
vmlinuz_data, vmlinuz_size,
sign_option.arch, sign_option.kloadaddr,
sign_option.config_data, sign_option.config_size,
sign_option.bootloader_data, sign_option.bootloader_size,
&kblob_size);
if (!kblob_data) {
fprintf(stderr, "Unable to create kernel blob\n");
goto done;
}
VB2_DEBUG("kblob_size = %#x\n", kblob_size);
vblock_data = SignKernelBlob(kblob_data, kblob_size,
sign_option.padding,
sign_option.version,
sign_option.kloadaddr,
sign_option.keyblock,
sign_option.signprivate,
sign_option.flags, &vblock_size);
if (!vblock_data) {
fprintf(stderr, "Unable to sign kernel blob\n");
goto done;
}
VB2_DEBUG("vblock_size = %#x\n", vblock_size);
/* We should be creating a completely new output file.
* If not, something's wrong. */
if (!sign_option.create_new_outfile)
FATAL("create_new_outfile should be selected\n");
if (sign_option.vblockonly)
rv = WriteSomeParts(sign_option.outfile,
vblock_data, vblock_size,
NULL, 0);
else
rv = WriteSomeParts(sign_option.outfile,
vblock_data, vblock_size,
kblob_data, kblob_size);
done:
futil_unmap_and_close_file(fd, FILE_MODE_SIGN(sign_option),
vmlinuz_data, vmlinuz_size);
free(vblock_data);
free(kblob_data);
return rv;
}
int ft_sign_kern_preamble(const char *name, void *data)
{
uint8_t *kpart_data = NULL, *kblob_data = NULL, *vblock_data = NULL;
uint32_t kpart_size, kblob_size, vblock_size;
struct vb2_keyblock *keyblock = NULL;
struct vb2_kernel_preamble *preamble = NULL;
int rv = 1;
int fd = -1;
if (futil_open_and_map_file(name, &fd, FILE_MODE_SIGN(sign_option),
&kpart_data, &kpart_size))
return 1;
/* Note: This just sets some static pointers. It doesn't malloc. */
kblob_data = unpack_kernel_partition(kpart_data, kpart_size,
sign_option.padding,
&keyblock, &preamble, &kblob_size);
if (!kblob_data) {
fprintf(stderr, "Unable to unpack kernel partition\n");
goto done;
}
/*
* We don't let --kloadaddr change when resigning, because the original
* vbutil_kernel program didn't do it right. Since obviously no one
* ever noticed, we'll maintain bug-compatibility by just not allowing
* it here either. To enable it, we'd need to update the zeropage
* table's cmd_line_ptr as well as the preamble.
*/
sign_option.kloadaddr = preamble->body_load_address;
/* Replace the config if asked */
if (sign_option.config_data &&
0 != UpdateKernelBlobConfig(kblob_data, kblob_size,
sign_option.config_data,
sign_option.config_size)) {
fprintf(stderr, "Unable to update config\n");
goto done;
}
/* Preserve the version unless a new one is given */
if (!sign_option.version_specified)
sign_option.version = preamble->kernel_version;
/* Preserve the flags if not specified */
uint32_t kernel_flags = vb2_kernel_get_flags(preamble);
if (sign_option.flags_specified == 0)
sign_option.flags = kernel_flags;
/* Replace the keyblock if asked */
if (sign_option.keyblock)
keyblock = sign_option.keyblock;
/* Compute the new signature */
vblock_data = SignKernelBlob(kblob_data, kblob_size,
sign_option.padding,
sign_option.version,
sign_option.kloadaddr,
keyblock,
sign_option.signprivate,
sign_option.flags,
&vblock_size);
if (!vblock_data) {
fprintf(stderr, "Unable to sign kernel blob\n");
goto done;
}
VB2_DEBUG("vblock_size = %#x\n", vblock_size);
if (sign_option.create_new_outfile) {
/* Write out what we've been asked for */
if (sign_option.vblockonly)
rv = WriteSomeParts(sign_option.outfile,
vblock_data, vblock_size,
NULL, 0);
else
rv = WriteSomeParts(sign_option.outfile,
vblock_data, vblock_size,
kblob_data, kblob_size);
} else {
/* If we're modifying an existing file, it's mmap'ed so that
* all our modifications to the buffer will get flushed to
* disk when we close it. */
memcpy(kpart_data, vblock_data, vblock_size);
rv = 0;
}
done:
futil_unmap_and_close_file(fd, FILE_MODE_SIGN(sign_option), kpart_data,
kpart_size);
free(vblock_data);
return rv;
}
int ft_sign_raw_firmware(const char *name, void *data)
{
struct vb2_signature *body_sig = NULL;
struct vb2_fw_preamble *preamble = NULL;
uint8_t *buf;
uint32_t len;
int rv = 1;
int fd = -1;
if (futil_open_and_map_file(name, &fd, FILE_MODE_SIGN(sign_option),
&buf, &len))
return 1;
body_sig = vb2_calculate_signature(buf, len, sign_option.signprivate);
if (!body_sig) {
fprintf(stderr, "Error calculating body signature\n");
goto done;
}
preamble = vb2_create_fw_preamble(
sign_option.version,
(struct vb2_packed_key *)sign_option.kernel_subkey,
body_sig,
sign_option.signprivate,
sign_option.flags);
if (!preamble) {
fprintf(stderr, "Error creating firmware preamble.\n");
goto done;
}
rv = WriteSomeParts(sign_option.outfile,
sign_option.keyblock,
sign_option.keyblock->keyblock_size,
preamble, preamble->preamble_size);
done:
futil_unmap_and_close_file(fd, FILE_MODE_SIGN(sign_option), buf, len);
free(preamble);
free(body_sig);
return rv;
}
static int load_keyset(void)
{
char *buf = NULL;
int errorcnt = 0;
const char *s = NULL;
const char *b = NULL;
const char *k = NULL;
const char *format;
struct stat sb;
if (!sign_option.keysetdir)
FATAL("Keyset should never be NULL. Aborting\n");
/* Failure means this is not a directory */
if (stat(sign_option.keysetdir, &sb) == -1 ||
(sb.st_mode & S_IFMT) != S_IFDIR)
format = "%s%s.%s";
else
format = "%s/%s.%s";
switch (sign_option.type) {
case FILE_TYPE_BIOS_IMAGE:
case FILE_TYPE_RAW_FIRMWARE:
s = "firmware_data_key";
b = "firmware";
k = "kernel_subkey";
break;
case FILE_TYPE_RAW_KERNEL:
s = "kernel_data_key";
b = "kernel";
break;
case FILE_TYPE_KERN_PREAMBLE:
s = "kernel_data_key";
break;
default:
return 0;
}
if (s && !sign_option.signprivate) {
if (asprintf(&buf, format, sign_option.keysetdir, s,
"vbprivk") <= 0)
FATAL("Failed to allocate string\n");
INFO("Loading private data key from default keyset: %s\n", buf);
sign_option.signprivate = vb2_read_private_key(buf);
if (!sign_option.signprivate) {
ERROR("Error reading %s\n", buf);
errorcnt++;
}
free(buf);
}
if (b && !sign_option.keyblock) {
if (asprintf(&buf, format, sign_option.keysetdir, b,
"keyblock") <= 0)
FATAL("Failed to allocate string\n");
INFO("Loading keyblock from default keyset: %s\n", buf);
sign_option.keyblock = vb2_read_keyblock(buf);
if (!sign_option.keyblock) {
ERROR("Error reading %s\n", buf);
errorcnt++;
}
free(buf);
}
if (k && !sign_option.kernel_subkey) {
if (asprintf(&buf, format, sign_option.keysetdir, k,
"vbpubk") <= 0)
FATAL("Failed to allocate string\n");
INFO("Loading kernel subkey from default keyset: %s\n", buf);
sign_option.kernel_subkey = vb2_read_packed_key(buf);
if (!sign_option.kernel_subkey) {
ERROR("Error reading %s\n", buf);
errorcnt++;
}
free(buf);
}
return errorcnt;
}
static const char usage_pubkey[] = "\n"
"To sign a public key / create a new keyblock:\n"
"\n"
"Required PARAMS:\n"
" [--datapubkey] INFILE The public key to wrap\n"
" [--outfile] OUTFILE The resulting keyblock\n"
"\n"
"Optional PARAMS:\n"
" A private signing key, specified as either\n"
" -s|--signprivate FILE.vbprivk Signing key in .vbprivk format\n"
" Or\n"
" --pem_signpriv FILE.pem Signing key in PEM format...\n"
" --pem_algo NUM AND the algorithm to use (0 - %d)\n"
"\n"
" If a signing key is not given, the keyblock will not be signed."
"\n\n"
"And these, too:\n\n"
" -f|--flags NUM Flags specifying use conditions\n"
" --pem_external PROGRAM"
" External program to compute the signature\n"
" (requires a PEM signing key)\n"
"\n";
static void print_help_pubkey(int argc, char *argv[])
{
printf(usage_pubkey, VB2_ALG_COUNT - 1);
}
static const char usage_fw_main[] = "\n"
"To sign a raw firmware blob (FW_MAIN_A/B):\n"
"\n"
"Required PARAMS:\n"
" -v|--version NUM The firmware version number\n"
" [--fv] INFILE"
" The raw firmware blob (FW_MAIN_A/B)\n"
" [--outfile] OUTFILE Output VBLOCK_A/B\n"
"\n"
"Optional PARAMS:\n"
" -s|--signprivate FILE.vbprivk The private firmware data key\n"
" -b|--keyblock FILE.keyblock The keyblock containing the\n"
" public firmware data key\n"
" -k|--kernelkey FILE.vbpubk The public kernel subkey\n"
" -f|--flags NUM The preamble flags value"
" (default is 0)\n"
" -K|--keyset PATH Prefix of private firmware data"
" key,\n"
" keyblock and public kernel"
" subkey.\n"
" Prefix must be valid path with\n"
" optional file name prefix.\n"
" Used as defaults for -s, -b and"
" -k,\n"
" if not passed expliticly\n"
" (default is '%s')\n"
"\n";
static void print_help_raw_firmware(int argc, char *argv[])
{
printf(usage_fw_main, DEFAULT_KEYSETDIR);
}
static const char usage_bios[] = "\n"
"To sign a complete firmware image (bios.bin):\n"
"\n"
"Required PARAMS:\n"
" [--infile] INFILE Input firmware image (modified\n"
" in place if no OUTFILE given)\n"
"\n"
"Optional PARAMS:\n"
" -s|--signprivate FILE.vbprivk The private firmware data key\n"
" -b|--keyblock FILE.keyblock The keyblock containing the\n"
" public firmware data key\n"
" -k|--kernelkey FILE.vbpubk The public kernel subkey\n"
" -v|--version NUM The firmware version number"
" (default %d)\n"
" -f|--flags NUM The preamble flags value"
" (default is\n"
" unchanged, or 0 if unknown)\n"
" -d|--loemdir DIR Local OEM output vblock directory\n"
" -l|--loemid STRING Local OEM vblock suffix\n"
" -K|--keyset PATH Prefix of private firmware data"
" key,\n"
" keyblock and public kernel"
" subkey.\n"
" Prefix must be valid path with\n"
" optional file name prefix.\n"
" Used as defaults for -s, -b and"
" -k,\n"
" if not passed expliticly\n"
" (default is '%s')\n"
" [--outfile] OUTFILE Output firmware image\n"
"\n";
static void print_help_bios_image(int argc, char *argv[])
{
printf(usage_bios, sign_option.version, DEFAULT_KEYSETDIR);
}
static const char usage_new_kpart[] = "\n"
"To create a new kernel partition image (/dev/sda2, /dev/mmcblk0p2):\n"
"\n"
"Required PARAMS:\n"
" -v|--version NUM The kernel version number\n"
" --bootloader FILE Bootloader stub\n"
" --config FILE The kernel commandline file\n"
" --arch ARCH The CPU architecture (one of\n"
" x86|amd64, arm|aarch64, mips)\n"
" [--vmlinuz] INFILE Linux kernel bzImage file\n"
" [--outfile] OUTFILE Output kernel partition or vblock\n"
"\n"
"Optional PARAMS:\n"
" -s|--signprivate FILE.vbprivk"
" The private key to sign the kernel blob\n"
" -b|--keyblock FILE.keyblock Keyblock containing the public\n"
" key to verify the kernel blob\n"
" --kloadaddr NUM"
" RAM address to load the kernel body\n"
" (default %#x)\n"
" --pad NUM The vblock padding size in bytes\n"
" (default %#x)\n"
" --vblockonly Emit just the vblock (requires a\n"
" distinct outfile)\n"
" -f|--flags NUM The preamble flags value\n"
" -K|--keyset DIR Path to directory containing"
" private\n"
" kernel data key, and keyblock\n"
" -K|--keyset PATH Prefix of private kernel data key\n"
" and keyblock.\n"
" Prefix must be valid path with\n"
" optional file name prefix.\n"
" Used as defaults for -s and -b,\n"
" if not passed expliticly\n"
" (default is '%s')\n"
"\n";
static void print_help_raw_kernel(int argc, char *argv[])
{
printf(usage_new_kpart, sign_option.kloadaddr, sign_option.padding,
DEFAULT_KEYSETDIR);
}
static const char usage_old_kpart[] = "\n"
"To resign an existing kernel partition (/dev/sda2, /dev/mmcblk0p2):\n"
"\n"
"Required PARAMS:\n"
" [--infile] INFILE Input kernel partition (modified\n"
" in place if no OUTFILE given)\n"
"\n"
"Optional PARAMS:\n"
" -s|--signprivate FILE.vbprivk"
" The private key to sign the kernel blob\n"
" -b|--keyblock FILE.keyblock Keyblock containing the public\n"
" key to verify the kernel blob\n"
" -v|--version NUM The kernel version number\n"
" --config FILE The kernel commandline file\n"
" --pad NUM The vblock padding size in bytes\n"
" (default %#x)\n"
" [--outfile] OUTFILE Output kernel partition or vblock\n"
" --vblockonly Emit just the vblock (requires a\n"
" distinct OUTFILE)\n"
" -f|--flags NUM The preamble flags value\n"
" -K|--keyset PATH Prefix of private kernel data"
" key.\n"
" Prefix must be valid path with\n"
" optional file name prefix.\n"
" Used as default for -s,\n"
" if not passed expliticly\n"
" (default is '%s')\n"
"\n";
static void print_help_kern_preamble(int argc, char *argv[])
{
printf(usage_old_kpart, sign_option.padding, DEFAULT_KEYSETDIR);
}
static void print_help_usbpd1(int argc, char *argv[])
{
enum vb2_hash_algorithm algo;
printf("\n"
"Usage: " MYNAME " %s --type %s [options] INFILE [OUTFILE]\n"
"\n"
"This signs a %s.\n"
"\n"
"The INFILE is assumed to consist of equal-sized RO and RW"
" sections,\n"
"with the public key at the end of of the RO section and the"
" signature\n"
"at the end of the RW section (both in an opaque binary"
" format).\n"
"Signing the image will update both binary blobs, so both"
" public and\n"
"private keys are required.\n"
"\n"
"The signing key is specified with:\n"
"\n"
" --pem "
"FILE Signing keypair in PEM format\n"
"\n"
" --hash_alg "
"NUM Hash algorithm to use:\n",
argv[0],
futil_file_type_name(FILE_TYPE_USBPD1),
futil_file_type_desc(FILE_TYPE_USBPD1));
for (algo = 0; algo < VB2_HASH_ALG_COUNT; algo++) {
const char *name = vb2_get_hash_algorithm_name(algo);
if (strcmp(name, VB2_INVALID_ALG_NAME) != 0)
printf(" %d / %s%s\n",
algo, name,
algo == VB2_HASH_SHA256 ? " (default)" : "");
}
printf("\n"
"The size and offset assumptions can be overridden. "
"All numbers are in bytes.\n"
"Specify a size of 0 to ignore that section.\n"
"\n"
" --ro_size NUM"
" Size of the RO section (default half)\n"
" --rw_size NUM"
" Size of the RW section (default half)\n"
" --ro_offset NUM"
" Start of the RO section (default 0)\n"
" --rw_offset NUM"
" Start of the RW section (default half)\n"
"\n");
}
static void print_help_rwsig(int argc, char *argv[])
{
printf("\n"
"Usage: " MYNAME " %s --type %s [options] INFILE [OUTFILE]\n"
"\n"
"This signs a %s.\n"
"\n"
"Data only mode\n"
"This mode requires OUTFILE.\n"
"The INFILE is a binary blob of arbitrary size. It is signed using the\n"
"private key and the vb21_signature blob emitted.\n"
"\n"
"Data + Signature mode\n"
"If no OUTFILE is specified, the INFILE should contain an existing\n"
"vb21_signature blob near its end. The data_size from that signature is\n"
"used to re-sign a portion of the INFILE, and the old signature blob is\n"
"replaced.\n"
"\n"
"Key + Data + Signature mode\n"
"This mode also takes no output file.\n"
"If INFILE contains an FMAP, RW and signatures offsets are read from\n"
"FMAP. These regions must be named EC_RW and SIG_RW respectively.\n"
"If a public key is found in the region named KEY_RO, it will be replaced\n"
"in the RO image. This mode also produces EC_RW.bin which is a EC_RW\n"
"region image (same as the input file for 'Data + Signature mode').\n"
"\n"
"Options:\n"
"\n"
" --prikey FILE.vbprik2 Private key in vb2 format. Required\n"
" if INFILE is a binary blob. If not\n"
" provided, previous signature is copied\n"
" and a public key won't be replaced.\n"
" --version NUM Public key version if we are replacing\n"
" the key in INFILE (default: 1)\n"
" --sig_size NUM Offset from the end of INFILE where the\n"
" signature blob should be located, if\n"
" the file does not contain an FMAP.\n"
" (default 1024 bytes)\n"
" --data_size NUM Number of bytes of INFILE to sign\n"
"\n",
argv[0],
futil_file_type_name(FILE_TYPE_RWSIG),
futil_file_type_desc(FILE_TYPE_RWSIG));
}
static void (*help_type[NUM_FILE_TYPES])(int argc, char *argv[]) = {
[FILE_TYPE_PUBKEY] = &print_help_pubkey,
[FILE_TYPE_RAW_FIRMWARE] = &print_help_raw_firmware,
[FILE_TYPE_BIOS_IMAGE] = &print_help_bios_image,
[FILE_TYPE_RAW_KERNEL] = &print_help_raw_kernel,
[FILE_TYPE_KERN_PREAMBLE] = &print_help_kern_preamble,
[FILE_TYPE_USBPD1] = &print_help_usbpd1,
[FILE_TYPE_RWSIG] = &print_help_rwsig,
};
static const char usage_default[] = "\n"
"Usage: " MYNAME " %s [PARAMS] INFILE [OUTFILE]\n"
"\n"
"The following signing operations are supported:\n"
"\n"
" INFILE OUTFILE\n"
" public key (.vbpubk) keyblock\n"
" raw firmware blob (FW_MAIN_A/B) firmware preamble (VBLOCK_A/B)\n"
" full firmware image (bios.bin) same, or signed in-place\n"
" raw linux kernel (vmlinuz) kernel partition image\n"
" kernel partition (/dev/sda2) same, or signed in-place\n"
" usbpd1 firmware image same, or signed in-place\n"
" RW device image same, or signed in-place\n"
"\n"
"For more information, use \"" MYNAME " help %s TYPE\", where\n"
"TYPE is one of:\n\n";
static void print_help_default(int argc, char *argv[])
{
enum futil_file_type type;
printf(usage_default, argv[0], argv[0]);
for (type = 0; type < NUM_FILE_TYPES; type++)
if (help_type[type])
printf(" %s", futil_file_type_name(type));
printf("\n\n");
}
static void print_help(int argc, char *argv[])
{
enum futil_file_type type = FILE_TYPE_UNKNOWN;
if (argc > 1)
futil_str_to_file_type(argv[1], &type);
if (help_type[type])
help_type[type](argc, argv);
else
print_help_default(argc, argv);
}
enum no_short_opts {
OPT_FV = 1000,
OPT_INFILE,
OPT_OUTFILE,
OPT_BOOTLOADER,
OPT_CONFIG,
OPT_ARCH,
OPT_KLOADADDR,
OPT_PADDING,
OPT_PEM_SIGNPRIV,
OPT_PEM_ALGO,
OPT_PEM_EXTERNAL,
OPT_TYPE,
OPT_HASH_ALG,
OPT_RO_SIZE,
OPT_RW_SIZE,
OPT_RO_OFFSET,
OPT_RW_OFFSET,
OPT_DATA_SIZE,
OPT_SIG_SIZE,
OPT_PRIKEY,
OPT_HELP,
};
static const struct option long_opts[] = {
/* name hasarg *flag val */
{"signprivate", 1, NULL, 's'},
{"keyblock", 1, NULL, 'b'},
{"kernelkey", 1, NULL, 'k'},
{"version", 1, NULL, 'v'},
{"flags", 1, NULL, 'f'},
{"loemdir", 1, NULL, 'd'},
{"loemid", 1, NULL, 'l'},
{"keyset", 1, NULL, 'K'},
{"fv", 1, NULL, OPT_FV},
{"infile", 1, NULL, OPT_INFILE},
{"datapubkey", 1, NULL, OPT_INFILE}, /* alias */
{"vmlinuz", 1, NULL, OPT_INFILE}, /* alias */
{"outfile", 1, NULL, OPT_OUTFILE},
{"bootloader", 1, NULL, OPT_BOOTLOADER},
{"config", 1, NULL, OPT_CONFIG},
{"arch", 1, NULL, OPT_ARCH},
{"kloadaddr", 1, NULL, OPT_KLOADADDR},
{"pad", 1, NULL, OPT_PADDING},
{"pem_signpriv", 1, NULL, OPT_PEM_SIGNPRIV},
{"pem", 1, NULL, OPT_PEM_SIGNPRIV}, /* alias */
{"pem_algo", 1, NULL, OPT_PEM_ALGO},
{"pem_external", 1, NULL, OPT_PEM_EXTERNAL},
{"type", 1, NULL, OPT_TYPE},
{"vblockonly", 0, &sign_option.vblockonly, 1},
{"hash_alg", 1, NULL, OPT_HASH_ALG},
{"ro_size", 1, NULL, OPT_RO_SIZE},
{"rw_size", 1, NULL, OPT_RW_SIZE},
{"ro_offset", 1, NULL, OPT_RO_OFFSET},
{"rw_offset", 1, NULL, OPT_RW_OFFSET},
{"data_size", 1, NULL, OPT_DATA_SIZE},
{"sig_size", 1, NULL, OPT_SIG_SIZE},
{"prikey", 1, NULL, OPT_PRIKEY},
{"privkey", 1, NULL, OPT_PRIKEY}, /* alias */
{"help", 0, NULL, OPT_HELP},
{NULL, 0, NULL, 0},
};
static const char *short_opts = ":s:b:k:v:f:d:l:K:";
/* Return zero on success */
static int parse_number_opt(const char *arg, const char *name, uint32_t *dest)
{
char *e;
uint32_t val = strtoul(arg, &e, 0);
if (!*arg || (e && *e)) {
fprintf(stderr, "Invalid --%s \"%s\"\n", name, arg);
return 1;
}
*dest = val;
return 0;
}
static int do_sign(int argc, char *argv[])
{
char *infile = 0;
int i;
int errorcnt = 0;
char *e = 0;
int helpind = 0;
int longindex;
opterr = 0; /* quiet, you */
while ((i = getopt_long(argc, argv, short_opts, long_opts,
&longindex)) != -1) {
switch (i) {
case 's':
sign_option.signprivate = vb2_read_private_key(optarg);
if (!sign_option.signprivate) {
fprintf(stderr, "Error reading %s\n", optarg);
errorcnt++;
}
break;
case 'b':
sign_option.keyblock = vb2_read_keyblock(optarg);
if (!sign_option.keyblock) {
fprintf(stderr, "Error reading %s\n", optarg);
errorcnt++;
}
break;
case 'k':
sign_option.kernel_subkey = vb2_read_packed_key(optarg);
if (!sign_option.kernel_subkey) {
fprintf(stderr, "Error reading %s\n", optarg);
errorcnt++;
}
break;
case 'v':
sign_option.version_specified = 1;
sign_option.version = strtoul(optarg, &e, 0);
if (!*optarg || (e && *e)) {
fprintf(stderr,
"Invalid --version \"%s\"\n", optarg);
errorcnt++;
}
break;
case 'f':
sign_option.flags_specified = 1;
errorcnt += parse_number_opt(optarg, "flags",
&sign_option.flags);
break;
case 'd':
sign_option.loemdir = optarg;
break;
case 'l':
sign_option.loemid = optarg;
break;
case 'K':
sign_option.keysetdir = optarg;
break;
case OPT_FV:
sign_option.fv_specified = 1;
VBOOT_FALLTHROUGH;
case OPT_INFILE:
sign_option.inout_file_count++;
infile = optarg;
break;
case OPT_OUTFILE:
sign_option.inout_file_count++;
sign_option.outfile = optarg;
break;
case OPT_BOOTLOADER:
sign_option.bootloader_data = ReadFile(
optarg, &sign_option.bootloader_size);
if (!sign_option.bootloader_data) {
fprintf(stderr,
"Error reading bootloader file: %s\n",
strerror(errno));
errorcnt++;
}
VB2_DEBUG("bootloader file size=0x%" PRIx64 "\n",
sign_option.bootloader_size);
break;
case OPT_CONFIG:
sign_option.config_data = ReadConfigFile(
optarg, &sign_option.config_size);
if (!sign_option.config_data) {
fprintf(stderr,
"Error reading config file: %s\n",
strerror(errno));
errorcnt++;
}
break;
case OPT_ARCH:
/* check the first 3 characters to also match x86_64 */
if ((!strncasecmp(optarg, "x86", 3)) ||
(!strcasecmp(optarg, "amd64")))
sign_option.arch = ARCH_X86;
else if ((!strcasecmp(optarg, "arm")) ||
(!strcasecmp(optarg, "aarch64")))
sign_option.arch = ARCH_ARM;
else if (!strcasecmp(optarg, "mips"))
sign_option.arch = ARCH_MIPS;
else {
fprintf(stderr,
"Unknown architecture: \"%s\"\n",
optarg);
errorcnt++;
}
break;
case OPT_KLOADADDR:
errorcnt += parse_number_opt(optarg, "kloadaddr",
&sign_option.kloadaddr);
break;
case OPT_PADDING:
errorcnt += parse_number_opt(optarg, "padding",
&sign_option.padding);
break;
case OPT_RO_SIZE:
errorcnt += parse_number_opt(optarg, "ro_size",
&sign_option.ro_size);
break;
case OPT_RW_SIZE:
errorcnt += parse_number_opt(optarg, "rw_size",
&sign_option.rw_size);
break;
case OPT_RO_OFFSET:
errorcnt += parse_number_opt(optarg, "ro_offset",
&sign_option.ro_offset);
break;
case OPT_RW_OFFSET:
errorcnt += parse_number_opt(optarg, "rw_offset",
&sign_option.rw_offset);
break;
case OPT_DATA_SIZE:
errorcnt += parse_number_opt(optarg, "data_size",
&sign_option.data_size);
break;
case OPT_SIG_SIZE:
errorcnt += parse_number_opt(optarg, "sig_size",
&sign_option.sig_size);
break;
case OPT_PEM_SIGNPRIV:
sign_option.pem_signpriv = optarg;
break;
case OPT_PEM_ALGO:
sign_option.pem_algo_specified = 1;
sign_option.pem_algo = strtoul(optarg, &e, 0);
if (!*optarg || (e && *e) ||
(sign_option.pem_algo >= VB2_ALG_COUNT)) {
fprintf(stderr,
"Invalid --pem_algo \"%s\"\n", optarg);
errorcnt++;
}
break;
case OPT_HASH_ALG:
if (!vb2_lookup_hash_alg(optarg,
&sign_option.hash_alg)) {
fprintf(stderr,
"invalid hash_alg \"%s\"\n", optarg);
errorcnt++;
}
break;
case OPT_PEM_EXTERNAL:
sign_option.pem_external = optarg;
break;
case OPT_TYPE:
if (!futil_str_to_file_type(optarg,
&sign_option.type)) {
if (!strcasecmp("help", optarg))
print_file_types_and_exit(errorcnt);
fprintf(stderr,
"Invalid --type \"%s\"\n", optarg);
errorcnt++;
}
break;
case OPT_PRIKEY:
if (vb21_private_key_read(&sign_option.prikey,
optarg)) {
fprintf(stderr, "Error reading %s\n", optarg);
errorcnt++;
}
break;
case OPT_HELP:
helpind = optind - 1;
break;
case '?':
if (optopt)
fprintf(stderr, "Unrecognized option: -%c\n",
optopt);
else
fprintf(stderr, "Unrecognized option: %s\n",
argv[optind - 1]);
errorcnt++;
break;
case ':':
fprintf(stderr, "Missing argument to -%c\n", optopt);
errorcnt++;
break;
case 0: /* handled option */
break;
default:
FATAL("Unrecognized getopt output: %d\n", i);
}
}
if (helpind) {
/* Skip all the options we've already parsed */
optind--;
argv[optind] = argv[0];
argc -= optind;
argv += optind;
print_help(argc, argv);
return !!errorcnt;
}
/* If we don't have an input file already, we need one */
if (!infile) {
if (argc - optind <= 0) {
errorcnt++;
fprintf(stderr, "ERROR: missing input filename\n");
goto done;
} else {
sign_option.inout_file_count++;
infile = argv[optind++];
}
}
/* Look for an output file if we don't have one, just in case. */
if (!sign_option.outfile && argc - optind > 0) {
sign_option.inout_file_count++;
sign_option.outfile = argv[optind++];
}
/* What are we looking at? */
if (sign_option.type == FILE_TYPE_UNKNOWN &&
futil_file_type(infile, &sign_option.type)) {
errorcnt++;
goto done;
}
/* We may be able to infer the type based on the other args */
if (sign_option.type == FILE_TYPE_UNKNOWN) {
if (sign_option.bootloader_data || sign_option.config_data
|| sign_option.arch != ARCH_UNSPECIFIED)
sign_option.type = FILE_TYPE_RAW_KERNEL;
else if (sign_option.kernel_subkey || sign_option.fv_specified)
sign_option.type = FILE_TYPE_RAW_FIRMWARE;
}
/* Load keys and keyblocks from keyset path, if they were not provided
earlier. */
errorcnt += load_keyset();
VB2_DEBUG("type=%s\n", futil_file_type_name(sign_option.type));
/* Check the arguments for the type of thing we want to sign */
switch (sign_option.type) {
case FILE_TYPE_PUBKEY:
sign_option.create_new_outfile = 1;
if (sign_option.signprivate && sign_option.pem_signpriv) {
fprintf(stderr,
"Only one of --signprivate and --pem_signpriv"
" can be specified\n");
errorcnt++;
}
if ((sign_option.signprivate &&
sign_option.pem_algo_specified) ||
(sign_option.pem_signpriv &&
!sign_option.pem_algo_specified)) {
fprintf(stderr, "--pem_algo must be used with"
" --pem_signpriv\n");
errorcnt++;
}
if (sign_option.pem_external && !sign_option.pem_signpriv) {
fprintf(stderr, "--pem_external must be used with"
" --pem_signpriv\n");
errorcnt++;
}
/* We'll wait to read the PEM file, since the external signer
* may want to read it instead. */
break;
case FILE_TYPE_BIOS_IMAGE:
errorcnt += no_opt_if(!sign_option.signprivate, "signprivate");
errorcnt += no_opt_if(!sign_option.keyblock, "keyblock");
errorcnt += no_opt_if(!sign_option.kernel_subkey, "kernelkey");
break;
case FILE_TYPE_KERN_PREAMBLE:
errorcnt += no_opt_if(!sign_option.signprivate, "signprivate");
if (sign_option.vblockonly || sign_option.inout_file_count > 1)
sign_option.create_new_outfile = 1;
break;
case FILE_TYPE_RAW_FIRMWARE:
sign_option.create_new_outfile = 1;
errorcnt += no_opt_if(!sign_option.signprivate, "signprivate");
errorcnt += no_opt_if(!sign_option.keyblock, "keyblock");
errorcnt += no_opt_if(!sign_option.kernel_subkey, "kernelkey");
errorcnt += no_opt_if(!sign_option.version_specified,
"version");
break;
case FILE_TYPE_RAW_KERNEL:
sign_option.create_new_outfile = 1;
errorcnt += no_opt_if(!sign_option.signprivate, "signprivate");
errorcnt += no_opt_if(!sign_option.keyblock, "keyblock");
errorcnt += no_opt_if(!sign_option.version_specified,
"version");
errorcnt += no_opt_if(!sign_option.bootloader_data,
"bootloader");
errorcnt += no_opt_if(!sign_option.config_data, "config");
errorcnt += no_opt_if(sign_option.arch == ARCH_UNSPECIFIED,
"arch");
break;
case FILE_TYPE_USBPD1:
errorcnt += no_opt_if(!sign_option.pem_signpriv, "pem");
errorcnt += no_opt_if(sign_option.hash_alg == VB2_HASH_INVALID,
"hash_alg");
break;
case FILE_TYPE_RWSIG:
if (sign_option.inout_file_count > 1)
/* Signing raw data. No signature pre-exists. */
errorcnt += no_opt_if(!sign_option.prikey, "prikey");
break;
default:
/* Anything else we don't care */
break;
}
VB2_DEBUG("infile=%s\n", infile);
VB2_DEBUG("sign_option.inout_file_count=%d\n",
sign_option.inout_file_count);
VB2_DEBUG("sign_option.create_new_outfile=%d\n",
sign_option.create_new_outfile);
/* Make sure we have an output file if one is needed */
if (!sign_option.outfile) {
if (sign_option.create_new_outfile) {
errorcnt++;
fprintf(stderr, "Missing output filename\n");
goto done;
} else {
sign_option.outfile = infile;
}
}
VB2_DEBUG("sign_option.outfile=%s\n", sign_option.outfile);
if (argc - optind > 0) {
errorcnt++;
fprintf(stderr, "ERROR: too many arguments left over\n");
}
if (errorcnt)
goto done;
if (!sign_option.create_new_outfile) {
/* We'll read-modify-write the output file */
if (sign_option.inout_file_count > 1)
futil_copy_file_or_die(infile, sign_option.outfile);
infile = sign_option.outfile;
}
errorcnt += futil_file_type_sign(sign_option.type, infile);
done:
free(sign_option.signprivate);
free(sign_option.keyblock);
free(sign_option.kernel_subkey);
if (sign_option.prikey)
vb2_private_key_free(sign_option.prikey);
if (errorcnt)
fprintf(stderr, "Use --help for usage instructions\n");
return !!errorcnt;
}
DECLARE_FUTIL_COMMAND(sign, do_sign, VBOOT_VERSION_ALL,
"Sign / resign various binary components");
| {
"content_hash": "40ffa381600d218925152434c217eb3c",
"timestamp": "",
"source": "github",
"line_count": 1158,
"max_line_length": 85,
"avg_line_length": 31.389464594127805,
"alnum_prop": 0.5915706071693857,
"repo_name": "coreboot/vboot",
"id": "383d39d727c8183ae0fb27e9148935ca11f65f26",
"size": "36497",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "futility/cmd_sign.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2110653"
},
{
"name": "C++",
"bytes": "3766"
},
{
"name": "Makefile",
"bytes": "47824"
},
{
"name": "Python",
"bytes": "2603"
},
{
"name": "Rust",
"bytes": "2291"
},
{
"name": "Shell",
"bytes": "486575"
},
{
"name": "Standard ML",
"bytes": "2304"
}
],
"symlink_target": ""
} |
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('fantasy', 'Your task description goes here.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f) {
// Concat specified files.
var src = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
| {
"content_hash": "d28f9af58c11ed4e08cd652c32043abe",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 85,
"avg_line_length": 28.863636363636363,
"alnum_prop": 0.6070866141732284,
"repo_name": "joneshf/grunt-fantasy",
"id": "262b94bfa63ced4fde35746fe91215c79fc6bbe9",
"size": "1405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tasks/fantasy.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4389"
}
],
"symlink_target": ""
} |
package com.metroveu.metroveu.fragments;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.metroveu.metroveu.R;
import com.metroveu.metroveu.adapters.GenericAdapter;
import com.metroveu.metroveu.data.MetroDbHelper;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by Florencia Tarditti on 12/11/15.
*/
public class RouteFragment extends Fragment {
ArrayList<String> routeParades;
private FragmentTransaction ft;
ArrayList<String> paradesData;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.route_fragment, container, false);
Bundle routeBundle = getArguments();
final String originalName = routeBundle.getString("original_name");
Cursor routeInfo = new MetroDbHelper(getActivity().getApplicationContext()).getReadableDatabase().
rawQuery("select * from ruta where ruta_nom =?", new String[] {originalName});
ArrayList<String> routeData = new ArrayList<>();
if(routeInfo != null && routeInfo.moveToFirst()) {
do {
String parades = routeInfo.getString(routeInfo.getColumnIndex("ruta_parades"));
parades = parades.substring(1, parades.length() - 1);
parades = parades.replaceAll(",\\s+",",");
routeParades = new ArrayList<String>(Arrays.asList(parades.split(",")));
} while (routeInfo.moveToNext());
routeInfo.close();
}
GenericAdapter adapter = new GenericAdapter(getActivity().getBaseContext(), routeParades);
ListView routesListView = (ListView) rootView.findViewById(R.id.routeListView);
routesListView.setAdapter(adapter);
routesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String[] paradaInfo = routeParades.get(position).split("-");
Cursor liniaInfo = new MetroDbHelper(getActivity().getApplicationContext()).getReadableDatabase().
rawQuery("select * from linia where linia_nom = ?", new String[]{paradaInfo[0]});
String colorLinia = "#FFF";
if (liniaInfo != null && liniaInfo.moveToFirst()) {
colorLinia = liniaInfo.getString(liniaInfo.getColumnIndex("linia_color"));
liniaInfo.close();
}
Cursor parades = new MetroDbHelper(getActivity().getApplicationContext()).getReadableDatabase().
rawQuery("select * from pertany where pertany_linia = ? order by pertany_ordre", new String[] {paradaInfo[0]});
paradesData = new ArrayList<>();
if (parades != null && parades.moveToFirst()){
do {
paradesData.add(parades.getString(parades.getColumnIndex("pertany_parada")));
} while(parades.moveToNext());
parades.close();
}
final String finalColorLinia = colorLinia;
ParadaFragment paradaFragment = new ParadaFragment();
Bundle paradaBundle = new Bundle();
paradaBundle.putStringArrayList("parades_data", paradesData);
paradaBundle.putString("parada_nom", paradaInfo[1]);
paradaBundle.putString("linia_nom", paradaInfo[0]);
paradaBundle.putString("linia_color", finalColorLinia);
paradaBundle.putBoolean("rutaStarted", false);
paradaBundle.putStringArrayList("ruta", new ArrayList<String>());
paradaFragment.setArguments(paradaBundle);
ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, paradaFragment);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
}
| {
"content_hash": "2d39267bac71b85890e5a3e8e15ff93a",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 135,
"avg_line_length": 44.06060606060606,
"alnum_prop": 0.6274644658413572,
"repo_name": "joanvila/MetroVeu",
"id": "1b9fe532043ed97f0d42f2b6f2fcecc3d1831b05",
"size": "4362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/metroveu/metroveu/fragments/RouteFragment.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "136734"
}
],
"symlink_target": ""
} |
import copy
import mock
from webob import exc
from neutron.openstack.common import uuidutils
from neutron.tests.unit import test_api_v2
from neutron.tests.unit import test_api_v2_extension
from midonet.neutron.extensions import vtep
_uuid = uuidutils.generate_uuid
_get_path = test_api_v2._get_path
class VtepExtensionTestCase(test_api_v2_extension.ExtensionTestCase):
"""Test the endpoints for the vtep extension."""
fmt = "json"
def setUp(self):
super(VtepExtensionTestCase, self).setUp()
plural_mappings = {'vtep': 'vteps',
'vtep_port': 'vtep_ports',
'binding': 'bindings',
'vxlan_port': 'vxlan_ports'}
self._setUpExtension(
'midonet.neutron.extensions.vtep.VtepPluginBase',
None, vtep.RESOURCE_ATTRIBUTE_MAP,
vtep.Vtep, '', plural_mappings=plural_mappings)
def test_vxlan_binding_show(self):
port_id = _uuid()
mgmt_ip = "1.1.1.1"
vlan_id = 5
port_name = "steve"
reqstr = "%s_%s" % (port_name, vlan_id)
return_value = {'mgmt_ip': mgmt_ip,
'port_name': port_name,
'vlan_id': vlan_id,
'network_id': _uuid()}
instance = self.plugin.return_value
instance.get_vtep_vxlan.return_value = return_value
res = self.api.get(_get_path(
'vteps/%s/vxlans/%s' % (port_id, reqstr),
fmt=self.fmt))
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('vxlan', res)
def test_vxlan_binding_list(self):
mgmt_ip = "1.1.1.1"
vlan_id = 5
port_name = "steve"
return_value = [{'mgmt_ip': mgmt_ip,
'port_name': port_name,
'vlan_id': vlan_id,
'network_id': _uuid()}]
instance = self.plugin.return_value
instance.get_vtep_vxlans.return_value = return_value
res = self.api.get(_get_path('vteps/%s/vxlans' % mgmt_ip,
fmt=self.fmt))
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('vxlans', res)
self.assertEqual(1, len(res['vxlans']))
def test_vtep_binding_show(self):
mgmt_ip = "1.1.1.1"
vlan_id = 5
port_name = "steve"
reqstr = "%s_%s" % (port_name, vlan_id)
return_value = {'mgmt_ip': mgmt_ip,
'port_name': port_name,
'vlan_id': vlan_id,
'network_id': _uuid()}
instance = self.plugin.return_value
instance.get_vtep_binding.return_value = return_value
res = self.api.get(_get_path(
'vteps/%s/bindings/%s' % (mgmt_ip, reqstr),
fmt=self.fmt))
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('binding', res)
def test_vtep_binding_list(self):
mgmt_ip = "1.1.1.1"
vlan_id = 5
port_name = "steve"
return_value = [{'mgmt_ip': mgmt_ip,
'port_name': port_name,
'vlan_id': vlan_id,
'network_id': _uuid()}]
instance = self.plugin.return_value
instance.get_vtep_bindings.return_value = return_value
res = self.api.get(_get_path('vteps/%s/bindings' % mgmt_ip,
fmt=self.fmt))
self.assertEqual(exc.HTTPOk.code, res.status_int)
res = self.deserialize(res)
self.assertIn('bindings', res)
self.assertEqual(1, len(res['bindings']))
def test_vtep_list(self):
return_value = [{'management_ip': "1.1.1.1",
'name': 'dummy_vtep',
'tunnel_zone_id': _uuid()}]
instance = self.plugin.return_value
instance.get_vteps.return_value = return_value
res = self.api.get(_get_path('vteps', fmt=self.fmt))
self.assertEqual(exc.HTTPOk.code, res.status_int)
instance.get_vteps.assert_called_once_with(
mock.ANY, fields=mock.ANY, filters=mock.ANY)
res = self.deserialize(res)
self.assertIn('vteps', res)
self.assertEqual(1, len(res['vteps']))
def test_vtep_show(self):
vtep_ip = "1.1.1.1"
return_value = {'management_ip': vtep_ip,
'name': 'dummy_vtep',
'tunnel_zone_id': _uuid()}
instance = self.plugin.return_value
instance.get_vtep.return_value = return_value
res = self.api.get(_get_path('vteps/%s' % vtep_ip, fmt=self.fmt))
self.assertEqual(exc.HTTPOk.code, res.status_int)
instance.get_vtep.assert_called_once_with(
mock.ANY, vtep_ip, fields=mock.ANY)
res = self.deserialize(res)
self.assertIn('vtep', res)
def test_vtep_create(self):
vtep_ip = "1.1.1.1"
data = {'vtep': {'management_ip': vtep_ip,
'management_port': 4,
'description': "bank holiday",
'tenant_id': _uuid(),
'name': 'dummy_vtep',
'connection_state': "DISCONNECTED",
'tunnel_ip_addrs': None,
'tunnel_zone_id': _uuid()}}
return_value = copy.deepcopy(data['vtep'])
instance = self.plugin.return_value
instance.create_vtep.return_value = return_value
res = self.api.post(_get_path('vteps', fmt=self.fmt),
self.serialize(data),
content_type='application/%s' % self.fmt)
instance.create_vtep.assert_called_once_with(mock.ANY, vtep=mock.ANY)
self.assertEqual(exc.HTTPCreated.code, res.status_int)
res = self.deserialize(res)
self.assertIn('vtep', res)
self.assertIn(vtep_ip, res['vtep']['management_ip'])
class VtepExtensionTestCaseXml(VtepExtensionTestCase):
fmt = "xml"
| {
"content_hash": "e717addd0233baf3e76be8b377e47f61",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 77,
"avg_line_length": 34.23463687150838,
"alnum_prop": 0.5390013054830287,
"repo_name": "midokura/python-neutron-plugin-midonet",
"id": "a8ea882c684071405dd83cc1d03e1a713fce303f",
"size": "6713",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "midonet/neutron/tests/unit/test_extension_vtep.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "254357"
},
{
"name": "Shell",
"bytes": "9711"
}
],
"symlink_target": ""
} |
Windows Phone helpers
====================
Installation
------------
WPDevelopmentLibs is available through [nuget](https://www.nuget.org)
```sh
PM> Install-Package WPDevelopmentLibs
```
Converters
----------
- BoolToVisibility
- CurrencyAmount
- TimestampToDate
Helpers
-------
- WPDevelopmentLibs.Converters.DateHelpers
- UnixTimeStampToDateTime
- DateTimeToUnitTimeStamp
- WPDevelopmentLibs.Helpers.SettingsHelper
- GetApplicationSetting
- AddApplicationSettings
- RemoveApplicationSetting
- WPDevelopment.Net.OSimpleConnector
- WPDevelopmentLibs.UI.DataTemplateSelector
- WPDevelopment.classes.OFileWork
- WPDevelopmentLibs.Session
The MIT License (MIT)
---------------------
Copyright (c) 2016 Sergey Zinchenko, [DataLayer.ru](http://datalayer.ru/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | {
"content_hash": "b367a00c76ac3c49ba5f15cd5c9f6e11",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 79,
"avg_line_length": 33.10909090909091,
"alnum_prop": 0.7655134541460736,
"repo_name": "SergioMadness/windows-phone-helpers",
"id": "1f8d9be484a451e0685ae9d6806c4e70a3a14319",
"size": "1821",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "17178"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX ValueNum XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "valuenum.h"
#include "ssaconfig.h"
VNFunc GetVNFuncForOper(genTreeOps oper, bool isUnsigned)
{
if (!isUnsigned || (oper == GT_EQ) || (oper == GT_NE))
{
return VNFunc(oper);
}
switch (oper)
{
case GT_LT:
return VNF_LT_UN;
case GT_LE:
return VNF_LE_UN;
case GT_GE:
return VNF_GE_UN;
case GT_GT:
return VNF_GT_UN;
case GT_ADD:
return VNF_ADD_UN;
case GT_SUB:
return VNF_SUB_UN;
case GT_MUL:
return VNF_MUL_UN;
case GT_DIV:
return VNF_DIV_UN;
case GT_MOD:
return VNF_MOD_UN;
case GT_NOP:
case GT_COMMA:
return VNFunc(oper);
default:
unreached();
}
}
ValueNumStore::ValueNumStore(Compiler* comp, IAllocator* alloc)
: m_pComp(comp)
, m_alloc(alloc)
,
#ifdef DEBUG
m_numMapSels(0)
,
#endif
m_nextChunkBase(0)
, m_fixedPointMapSels(alloc, 8)
, m_chunks(alloc, 8)
, m_intCnsMap(nullptr)
, m_longCnsMap(nullptr)
, m_handleMap(nullptr)
, m_floatCnsMap(nullptr)
, m_doubleCnsMap(nullptr)
, m_byrefCnsMap(nullptr)
, m_VNFunc0Map(nullptr)
, m_VNFunc1Map(nullptr)
, m_VNFunc2Map(nullptr)
, m_VNFunc3Map(nullptr)
, m_VNFunc4Map(nullptr)
{
// We have no current allocation chunks.
for (unsigned i = 0; i < TYP_COUNT; i++)
{
for (unsigned j = CEA_None; j <= CEA_Count + MAX_LOOP_NUM; j++)
{
m_curAllocChunk[i][j] = NoChunk;
}
}
for (unsigned i = 0; i < SmallIntConstNum; i++)
{
m_VNsForSmallIntConsts[i] = NoVN;
}
// We will reserve chunk 0 to hold some special constants, like the constant NULL, the "exception" value, and the
// "zero map."
Chunk* specialConstChunk = new (m_alloc) Chunk(m_alloc, &m_nextChunkBase, TYP_REF, CEA_Const, MAX_LOOP_NUM);
specialConstChunk->m_numUsed +=
SRC_NumSpecialRefConsts; // Implicitly allocate 0 ==> NULL, and 1 ==> Exception, 2 ==> ZeroMap.
ChunkNum cn = m_chunks.Push(specialConstChunk);
assert(cn == 0);
m_mapSelectBudget = JitConfig.JitVNMapSelBudget();
}
// static.
template <typename T>
T ValueNumStore::EvalOp(VNFunc vnf, T v0)
{
genTreeOps oper = genTreeOps(vnf);
// Here we handle those unary ops that are the same for integral and floating-point types.
switch (oper)
{
case GT_NEG:
return -v0;
default:
// Must be int-specific
return EvalOpIntegral(vnf, v0);
}
}
template <typename T>
T ValueNumStore::EvalOpIntegral(VNFunc vnf, T v0)
{
genTreeOps oper = genTreeOps(vnf);
// Here we handle unary ops that are the same for all integral types.
switch (oper)
{
case GT_NOT:
return ~v0;
default:
unreached();
}
}
// static
template <typename T>
T ValueNumStore::EvalOp(VNFunc vnf, T v0, T v1, ValueNum* pExcSet)
{
if (vnf < VNF_Boundary)
{
genTreeOps oper = genTreeOps(vnf);
// Here we handle those that are the same for integral and floating-point types.
switch (oper)
{
case GT_ADD:
return v0 + v1;
case GT_SUB:
return v0 - v1;
case GT_MUL:
return v0 * v1;
case GT_DIV:
if (IsIntZero(v1))
{
*pExcSet = VNExcSetSingleton(VNForFunc(TYP_REF, VNF_DivideByZeroExc));
return (T)0;
}
if (IsOverflowIntDiv(v0, v1))
{
*pExcSet = VNExcSetSingleton(VNForFunc(TYP_REF, VNF_ArithmeticExc));
return (T)0;
}
else
{
return v0 / v1;
}
default:
// Must be int-specific
return EvalOpIntegral(vnf, v0, v1, pExcSet);
}
}
else // must be a VNF_ function
{
typedef typename jitstd::make_unsigned<T>::type UT;
switch (vnf)
{
case VNF_GT_UN:
return T(UT(v0) > UT(v1));
case VNF_GE_UN:
return T(UT(v0) >= UT(v1));
case VNF_LT_UN:
return T(UT(v0) < UT(v1));
case VNF_LE_UN:
return T(UT(v0) <= UT(v1));
case VNF_ADD_UN:
return T(UT(v0) + UT(v1));
case VNF_SUB_UN:
return T(UT(v0) - UT(v1));
case VNF_MUL_UN:
return T(UT(v0) * UT(v1));
case VNF_DIV_UN:
if (IsIntZero(v1))
{
*pExcSet = VNExcSetSingleton(VNForFunc(TYP_REF, VNF_DivideByZeroExc));
return (T)0;
}
else
{
return T(UT(v0) / UT(v1));
}
default:
// Must be int-specific
return EvalOpIntegral(vnf, v0, v1, pExcSet);
}
}
}
// Specialize for double for floating operations, that doesn't involve unsigned.
template <>
double ValueNumStore::EvalOp<double>(VNFunc vnf, double v0, double v1, ValueNum* pExcSet)
{
genTreeOps oper = genTreeOps(vnf);
// Here we handle those that are the same for floating-point types.
switch (oper)
{
case GT_ADD:
return v0 + v1;
case GT_SUB:
return v0 - v1;
case GT_MUL:
return v0 * v1;
case GT_DIV:
return v0 / v1;
case GT_MOD:
return fmod(v0, v1);
default:
unreached();
}
}
// Specialize for float for floating operations, that doesn't involve unsigned.
template <>
float ValueNumStore::EvalOp<float>(VNFunc vnf, float v0, float v1, ValueNum* pExcSet)
{
genTreeOps oper = genTreeOps(vnf);
// Here we handle those that are the same for floating-point types.
switch (oper)
{
case GT_ADD:
return v0 + v1;
case GT_SUB:
return v0 - v1;
case GT_MUL:
return v0 * v1;
case GT_DIV:
return v0 / v1;
case GT_MOD:
return fmodf(v0, v1);
default:
unreached();
}
}
template <typename T>
int ValueNumStore::EvalComparison(VNFunc vnf, T v0, T v1)
{
if (vnf < VNF_Boundary)
{
genTreeOps oper = genTreeOps(vnf);
// Here we handle those that are the same for floating-point types.
switch (oper)
{
case GT_EQ:
return v0 == v1;
case GT_NE:
return v0 != v1;
case GT_GT:
return v0 > v1;
case GT_GE:
return v0 >= v1;
case GT_LT:
return v0 < v1;
case GT_LE:
return v0 <= v1;
default:
unreached();
}
}
else // must be a VNF_ function
{
switch (vnf)
{
case VNF_GT_UN:
return unsigned(v0) > unsigned(v1);
case VNF_GE_UN:
return unsigned(v0) >= unsigned(v1);
case VNF_LT_UN:
return unsigned(v0) < unsigned(v1);
case VNF_LE_UN:
return unsigned(v0) <= unsigned(v1);
default:
unreached();
}
}
}
/* static */
template <typename T>
int ValueNumStore::EvalOrderedComparisonFloat(VNFunc vnf, T v0, T v1)
{
// !! NOTE !!
//
// All comparisons below are ordered comparisons.
//
// We should guard this function from unordered comparisons
// identified by the GTF_RELOP_NAN_UN flag. Either the flag
// should be bubbled (similar to GTF_UNSIGNED for ints)
// to this point or we should bail much earlier if any of
// the operands are NaN.
//
genTreeOps oper = genTreeOps(vnf);
// Here we handle those that are the same for floating-point types.
switch (oper)
{
case GT_EQ:
return v0 == v1;
case GT_NE:
return v0 != v1;
case GT_GT:
return v0 > v1;
case GT_GE:
return v0 >= v1;
case GT_LT:
return v0 < v1;
case GT_LE:
return v0 <= v1;
default:
unreached();
}
}
template <>
int ValueNumStore::EvalComparison<double>(VNFunc vnf, double v0, double v1)
{
return EvalOrderedComparisonFloat(vnf, v0, v1);
}
template <>
int ValueNumStore::EvalComparison<float>(VNFunc vnf, float v0, float v1)
{
return EvalOrderedComparisonFloat(vnf, v0, v1);
}
template <typename T>
T ValueNumStore::EvalOpIntegral(VNFunc vnf, T v0, T v1, ValueNum* pExcSet)
{
genTreeOps oper = genTreeOps(vnf);
switch (oper)
{
case GT_EQ:
return v0 == v1;
case GT_NE:
return v0 != v1;
case GT_GT:
return v0 > v1;
case GT_GE:
return v0 >= v1;
case GT_LT:
return v0 < v1;
case GT_LE:
return v0 <= v1;
case GT_OR:
return v0 | v1;
case GT_XOR:
return v0 ^ v1;
case GT_AND:
return v0 & v1;
case GT_LSH:
return v0 << v1;
case GT_RSH:
return v0 >> v1;
case GT_RSZ:
if (sizeof(T) == 8)
{
return UINT64(v0) >> v1;
}
else
{
return UINT32(v0) >> v1;
}
case GT_ROL:
if (sizeof(T) == 8)
{
return (v0 << v1) | (UINT64(v0) >> (64 - v1));
}
else
{
return (v0 << v1) | (UINT32(v0) >> (32 - v1));
}
case GT_ROR:
if (sizeof(T) == 8)
{
return (v0 << (64 - v1)) | (UINT64(v0) >> v1);
}
else
{
return (v0 << (32 - v1)) | (UINT32(v0) >> v1);
}
case GT_DIV:
case GT_MOD:
if (v1 == 0)
{
*pExcSet = VNExcSetSingleton(VNForFunc(TYP_REF, VNF_DivideByZeroExc));
}
else if (IsOverflowIntDiv(v0, v1))
{
*pExcSet = VNExcSetSingleton(VNForFunc(TYP_REF, VNF_ArithmeticExc));
return 0;
}
else // We are not dividing by Zero, so we can calculate the exact result.
{
// Perform the appropriate operation.
if (oper == GT_DIV)
{
return v0 / v1;
}
else // Must be GT_MOD
{
return v0 % v1;
}
}
case GT_UDIV:
case GT_UMOD:
if (v1 == 0)
{
*pExcSet = VNExcSetSingleton(VNForFunc(TYP_REF, VNF_DivideByZeroExc));
return 0;
}
else // We are not dividing by Zero, so we can calculate the exact result.
{
typedef typename jitstd::make_unsigned<T>::type UT;
// We need for force the source operands for the divide or mod operation
// to be considered unsigned.
//
if (oper == GT_UDIV)
{
// This is return unsigned(v0) / unsigned(v1) for both sizes of integers
return T(UT(v0) / UT(v1));
}
else // Must be GT_UMOD
{
// This is return unsigned(v0) % unsigned(v1) for both sizes of integers
return T(UT(v0) % UT(v1));
}
}
default:
unreached(); // NYI?
}
}
ValueNum ValueNumStore::VNExcSetSingleton(ValueNum x)
{
ValueNum res = VNForFunc(TYP_REF, VNF_ExcSetCons, x, VNForEmptyExcSet());
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" " STR_VN "%x = singleton exc set", res);
vnDump(m_pComp, x);
printf("\n");
}
#endif
return res;
}
ValueNumPair ValueNumStore::VNPExcSetSingleton(ValueNumPair xp)
{
return ValueNumPair(VNExcSetSingleton(xp.GetLiberal()), VNExcSetSingleton(xp.GetConservative()));
}
ValueNum ValueNumStore::VNExcSetUnion(ValueNum xs0, ValueNum xs1 DEBUGARG(bool topLevel))
{
if (xs0 == VNForEmptyExcSet())
{
return xs1;
}
else if (xs1 == VNForEmptyExcSet())
{
return xs0;
}
else
{
VNFuncApp funcXs0;
bool b0 = GetVNFunc(xs0, &funcXs0);
assert(b0 && funcXs0.m_func == VNF_ExcSetCons); // Precondition: xs0 is an exception set.
VNFuncApp funcXs1;
bool b1 = GetVNFunc(xs1, &funcXs1);
assert(b1 && funcXs1.m_func == VNF_ExcSetCons); // Precondition: xs1 is an exception set.
ValueNum res = NoVN;
if (funcXs0.m_args[0] < funcXs1.m_args[0])
{
res = VNForFunc(TYP_REF, VNF_ExcSetCons, funcXs0.m_args[0],
VNExcSetUnion(funcXs0.m_args[1], xs1 DEBUGARG(false)));
}
else if (funcXs0.m_args[0] == funcXs1.m_args[0])
{
// Equal elements; only add one to the result.
res = VNExcSetUnion(funcXs0.m_args[1], xs1);
}
else
{
assert(funcXs0.m_args[0] > funcXs1.m_args[0]);
res = VNForFunc(TYP_REF, VNF_ExcSetCons, funcXs1.m_args[0],
VNExcSetUnion(xs0, funcXs1.m_args[1] DEBUGARG(false)));
}
return res;
}
}
ValueNumPair ValueNumStore::VNPExcSetUnion(ValueNumPair xs0vnp, ValueNumPair xs1vnp)
{
return ValueNumPair(VNExcSetUnion(xs0vnp.GetLiberal(), xs1vnp.GetLiberal()),
VNExcSetUnion(xs0vnp.GetConservative(), xs1vnp.GetConservative()));
}
void ValueNumStore::VNUnpackExc(ValueNum vnWx, ValueNum* pvn, ValueNum* pvnx)
{
assert(vnWx != NoVN);
VNFuncApp funcApp;
if (GetVNFunc(vnWx, &funcApp) && funcApp.m_func == VNF_ValWithExc)
{
*pvn = funcApp.m_args[0];
*pvnx = funcApp.m_args[1];
}
else
{
*pvn = vnWx;
}
}
void ValueNumStore::VNPUnpackExc(ValueNumPair vnWx, ValueNumPair* pvn, ValueNumPair* pvnx)
{
VNUnpackExc(vnWx.GetLiberal(), pvn->GetLiberalAddr(), pvnx->GetLiberalAddr());
VNUnpackExc(vnWx.GetConservative(), pvn->GetConservativeAddr(), pvnx->GetConservativeAddr());
}
ValueNum ValueNumStore::VNNormVal(ValueNum vn)
{
VNFuncApp funcApp;
if (GetVNFunc(vn, &funcApp) && funcApp.m_func == VNF_ValWithExc)
{
return funcApp.m_args[0];
}
else
{
return vn;
}
}
ValueNumPair ValueNumStore::VNPNormVal(ValueNumPair vnp)
{
return ValueNumPair(VNNormVal(vnp.GetLiberal()), VNNormVal(vnp.GetConservative()));
}
ValueNum ValueNumStore::VNExcVal(ValueNum vn)
{
VNFuncApp funcApp;
if (GetVNFunc(vn, &funcApp) && funcApp.m_func == VNF_ValWithExc)
{
return funcApp.m_args[1];
}
else
{
return VNForEmptyExcSet();
}
}
ValueNumPair ValueNumStore::VNPExcVal(ValueNumPair vnp)
{
return ValueNumPair(VNExcVal(vnp.GetLiberal()), VNExcVal(vnp.GetConservative()));
}
// If vn "excSet" is not "VNForEmptyExcSet()", return "VNF_ValWithExc(vn, excSet)". Otherwise,
// just return "vn".
ValueNum ValueNumStore::VNWithExc(ValueNum vn, ValueNum excSet)
{
if (excSet == VNForEmptyExcSet())
{
return vn;
}
else
{
ValueNum vnNorm;
ValueNum vnX = VNForEmptyExcSet();
VNUnpackExc(vn, &vnNorm, &vnX);
return VNForFunc(TypeOfVN(vnNorm), VNF_ValWithExc, vnNorm, VNExcSetUnion(vnX, excSet));
}
}
ValueNumPair ValueNumStore::VNPWithExc(ValueNumPair vnp, ValueNumPair excSetVNP)
{
return ValueNumPair(VNWithExc(vnp.GetLiberal(), excSetVNP.GetLiberal()),
VNWithExc(vnp.GetConservative(), excSetVNP.GetConservative()));
}
bool ValueNumStore::IsKnownNonNull(ValueNum vn)
{
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
return GetVNFunc(vn, &funcAttr) && (s_vnfOpAttribs[funcAttr.m_func] & VNFOA_KnownNonNull) != 0;
}
bool ValueNumStore::IsSharedStatic(ValueNum vn)
{
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
return GetVNFunc(vn, &funcAttr) && (s_vnfOpAttribs[funcAttr.m_func] & VNFOA_SharedStatic) != 0;
}
ValueNumStore::Chunk::Chunk(
IAllocator* alloc, ValueNum* pNextBaseVN, var_types typ, ChunkExtraAttribs attribs, BasicBlock::loopNumber loopNum)
: m_defs(nullptr), m_numUsed(0), m_baseVN(*pNextBaseVN), m_typ(typ), m_attribs(attribs), m_loopNum(loopNum)
{
// Allocate "m_defs" here, according to the typ/attribs pair.
switch (attribs)
{
case CEA_None:
case CEA_NotAField:
break; // Nothing to do.
case CEA_Const:
switch (typ)
{
case TYP_INT:
m_defs = new (alloc) Alloc<TYP_INT>::Type[ChunkSize];
break;
case TYP_FLOAT:
m_defs = new (alloc) Alloc<TYP_FLOAT>::Type[ChunkSize];
break;
case TYP_LONG:
m_defs = new (alloc) Alloc<TYP_LONG>::Type[ChunkSize];
break;
case TYP_DOUBLE:
m_defs = new (alloc) Alloc<TYP_DOUBLE>::Type[ChunkSize];
break;
case TYP_BYREF:
m_defs = new (alloc) Alloc<TYP_BYREF>::Type[ChunkSize];
break;
case TYP_REF:
// We allocate space for a single REF constant, NULL, so we can access these values uniformly.
// Since this value is always the same, we represent it as a static.
m_defs = &s_specialRefConsts[0];
break; // Nothing to do.
default:
assert(false); // Should not reach here.
}
break;
case CEA_Handle:
m_defs = new (alloc) VNHandle[ChunkSize];
break;
case CEA_Func0:
m_defs = new (alloc) VNFunc[ChunkSize];
break;
case CEA_Func1:
m_defs = new (alloc) VNDefFunc1Arg[ChunkSize];
break;
case CEA_Func2:
m_defs = new (alloc) VNDefFunc2Arg[ChunkSize];
break;
case CEA_Func3:
m_defs = new (alloc) VNDefFunc3Arg[ChunkSize];
break;
case CEA_Func4:
m_defs = new (alloc) VNDefFunc4Arg[ChunkSize];
break;
default:
unreached();
}
*pNextBaseVN += ChunkSize;
}
ValueNumStore::Chunk* ValueNumStore::GetAllocChunk(var_types typ,
ChunkExtraAttribs attribs,
BasicBlock::loopNumber loopNum)
{
Chunk* res;
unsigned index;
if (loopNum == MAX_LOOP_NUM)
{
// Loop nest is unknown/irrelevant for this VN.
index = attribs;
}
else
{
// Loop nest is interesting. Since we know this is only true for unique VNs, we know attribs will
// be CEA_None and can just index based on loop number.
noway_assert(attribs == CEA_None);
// Map NOT_IN_LOOP -> MAX_LOOP_NUM to make the index range contiguous [0..MAX_LOOP_NUM]
index = CEA_Count + (loopNum == BasicBlock::NOT_IN_LOOP ? MAX_LOOP_NUM : loopNum);
}
ChunkNum cn = m_curAllocChunk[typ][index];
if (cn != NoChunk)
{
res = m_chunks.Get(cn);
if (res->m_numUsed < ChunkSize)
{
return res;
}
}
// Otherwise, must allocate a new one.
res = new (m_alloc) Chunk(m_alloc, &m_nextChunkBase, typ, attribs, loopNum);
cn = m_chunks.Push(res);
m_curAllocChunk[typ][index] = cn;
return res;
}
ValueNum ValueNumStore::VNForIntCon(INT32 cnsVal)
{
if (IsSmallIntConst(cnsVal))
{
unsigned ind = cnsVal - SmallIntConstMin;
ValueNum vn = m_VNsForSmallIntConsts[ind];
if (vn != NoVN)
{
return vn;
}
vn = GetVNForIntCon(cnsVal);
m_VNsForSmallIntConsts[ind] = vn;
return vn;
}
else
{
return GetVNForIntCon(cnsVal);
}
}
ValueNum ValueNumStore::VNForLongCon(INT64 cnsVal)
{
ValueNum res;
if (GetLongCnsMap()->Lookup(cnsVal, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(TYP_LONG, CEA_Const);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<INT64*>(c->m_defs)[offsetWithinChunk] = cnsVal;
GetLongCnsMap()->Set(cnsVal, res);
return res;
}
}
ValueNum ValueNumStore::VNForFloatCon(float cnsVal)
{
ValueNum res;
if (GetFloatCnsMap()->Lookup(cnsVal, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(TYP_FLOAT, CEA_Const);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<float*>(c->m_defs)[offsetWithinChunk] = cnsVal;
GetFloatCnsMap()->Set(cnsVal, res);
return res;
}
}
ValueNum ValueNumStore::VNForDoubleCon(double cnsVal)
{
ValueNum res;
if (GetDoubleCnsMap()->Lookup(cnsVal, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(TYP_DOUBLE, CEA_Const);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<double*>(c->m_defs)[offsetWithinChunk] = cnsVal;
GetDoubleCnsMap()->Set(cnsVal, res);
return res;
}
}
ValueNum ValueNumStore::VNForByrefCon(INT64 cnsVal)
{
ValueNum res;
if (GetByrefCnsMap()->Lookup(cnsVal, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(TYP_BYREF, CEA_Const);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<INT64*>(c->m_defs)[offsetWithinChunk] = cnsVal;
GetByrefCnsMap()->Set(cnsVal, res);
return res;
}
}
ValueNum ValueNumStore::VNForCastOper(var_types castToType, bool srcIsUnsigned /*=false*/)
{
assert(castToType != TYP_STRUCT);
INT32 cnsVal = INT32(castToType) << INT32(VCA_BitCount);
assert((cnsVal & INT32(VCA_ReservedBits)) == 0);
if (srcIsUnsigned)
{
// We record the srcIsUnsigned by or-ing a 0x01
cnsVal |= INT32(VCA_UnsignedSrc);
}
ValueNum result = VNForIntCon(cnsVal);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" VNForCastOper(%s%s) is " STR_VN "%x\n", varTypeName(castToType),
srcIsUnsigned ? ", unsignedSrc" : "", result);
}
#endif
return result;
}
ValueNum ValueNumStore::VNForHandle(ssize_t cnsVal, unsigned handleFlags)
{
assert((handleFlags & ~GTF_ICON_HDL_MASK) == 0);
ValueNum res;
VNHandle handle;
VNHandle::Initialize(&handle, cnsVal, handleFlags);
if (GetHandleMap()->Lookup(handle, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(TYP_I_IMPL, CEA_Handle);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNHandle*>(c->m_defs)[offsetWithinChunk] = handle;
GetHandleMap()->Set(handle, res);
return res;
}
}
// Returns the value number for zero of the given "typ".
// It has an unreached() for a "typ" that has no zero value, such as TYP_VOID.
ValueNum ValueNumStore::VNZeroForType(var_types typ)
{
switch (typ)
{
case TYP_BOOL:
case TYP_BYTE:
case TYP_UBYTE:
case TYP_CHAR:
case TYP_SHORT:
case TYP_USHORT:
case TYP_INT:
case TYP_UINT:
return VNForIntCon(0);
case TYP_LONG:
case TYP_ULONG:
return VNForLongCon(0);
case TYP_FLOAT:
#if FEATURE_X87_DOUBLES
return VNForDoubleCon(0.0);
#else
return VNForFloatCon(0.0f);
#endif
case TYP_DOUBLE:
return VNForDoubleCon(0.0);
case TYP_REF:
case TYP_ARRAY:
return VNForNull();
case TYP_BYREF:
return VNForByrefCon(0);
case TYP_STRUCT:
#ifdef FEATURE_SIMD
// TODO-CQ: Improve value numbering for SIMD types.
case TYP_SIMD8:
case TYP_SIMD12:
case TYP_SIMD16:
case TYP_SIMD32:
#endif // FEATURE_SIMD
return VNForZeroMap(); // Recursion!
// These should be unreached.
default:
unreached(); // Should handle all types.
}
}
// Returns the value number for one of the given "typ".
// It returns NoVN for a "typ" that has no one value, such as TYP_REF.
ValueNum ValueNumStore::VNOneForType(var_types typ)
{
switch (typ)
{
case TYP_BOOL:
case TYP_BYTE:
case TYP_UBYTE:
case TYP_CHAR:
case TYP_SHORT:
case TYP_USHORT:
case TYP_INT:
case TYP_UINT:
return VNForIntCon(1);
case TYP_LONG:
case TYP_ULONG:
return VNForLongCon(1);
case TYP_FLOAT:
return VNForFloatCon(1.0f);
case TYP_DOUBLE:
return VNForDoubleCon(1.0);
default:
return NoVN;
}
}
class Object* ValueNumStore::s_specialRefConsts[] = {nullptr, nullptr, nullptr};
// Nullary operators (i.e., symbolic constants).
ValueNum ValueNumStore::VNForFunc(var_types typ, VNFunc func)
{
assert(VNFuncArity(func) == 0);
assert(func != VNF_NotAField);
ValueNum res;
if (GetVNFunc0Map()->Lookup(func, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(typ, CEA_Func0);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNFunc*>(c->m_defs)[offsetWithinChunk] = func;
GetVNFunc0Map()->Set(func, res);
return res;
}
}
ValueNum ValueNumStore::VNForFunc(var_types typ, VNFunc func, ValueNum arg0VN)
{
assert(arg0VN == VNNormVal(arg0VN)); // Arguments don't carry exceptions.
ValueNum res;
VNDefFunc1Arg fstruct(func, arg0VN);
// Do constant-folding.
if (CanEvalForConstantArgs(func) && IsVNConstant(arg0VN))
{
return EvalFuncForConstantArgs(typ, func, arg0VN);
}
if (GetVNFunc1Map()->Lookup(fstruct, &res))
{
return res;
}
else
{
// Otherwise, create a new VN for this application.
Chunk* c = GetAllocChunk(typ, CEA_Func1);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNDefFunc1Arg*>(c->m_defs)[offsetWithinChunk] = fstruct;
GetVNFunc1Map()->Set(fstruct, res);
return res;
}
}
// Windows x86 and Windows ARM/ARM64 may not define _isnanf() but they do define _isnan().
// We will redirect the macros to these other functions if the macro is not defined for the
// platform. This has the side effect of a possible implicit upcasting for arguments passed.
#if (defined(_TARGET_X86_) || defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)) && !defined(FEATURE_PAL)
#if !defined(_isnanf)
#define _isnanf _isnan
#endif
#endif
ValueNum ValueNumStore::VNForFunc(var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN)
{
assert(arg0VN != NoVN && arg1VN != NoVN);
assert(arg0VN == VNNormVal(arg0VN)); // Arguments carry no exceptions.
assert(arg1VN == VNNormVal(arg1VN)); // Arguments carry no exceptions.
assert(VNFuncArity(func) == 2);
assert(func != VNF_MapSelect); // Precondition: use the special function VNForMapSelect defined for that.
ValueNum res;
// Do constant-folding.
if (CanEvalForConstantArgs(func) && IsVNConstant(arg0VN) && IsVNConstant(arg1VN))
{
bool canFold = true; // Normally we will be able to fold this 'func'
// Special case for VNF_Cast of constant handles
// Don't allow eval/fold of a GT_CAST(non-I_IMPL, Handle)
//
if ((func == VNF_Cast) && (typ != TYP_I_IMPL) && IsVNHandle(arg0VN))
{
canFold = false;
}
// It is possible for us to have mismatched types (see Bug 750863)
// We don't try to fold a binary operation when one of the constant operands
// is a floating-point constant and the other is not.
//
var_types arg0VNtyp = TypeOfVN(arg0VN);
bool arg0IsFloating = varTypeIsFloating(arg0VNtyp);
var_types arg1VNtyp = TypeOfVN(arg1VN);
bool arg1IsFloating = varTypeIsFloating(arg1VNtyp);
if (arg0IsFloating != arg1IsFloating)
{
canFold = false;
}
// NaNs are unordered wrt to other floats. While an ordered
// comparison would return false, an unordered comparison
// will return true if any operands are a NaN. We only perform
// ordered NaN comparison in EvalComparison.
if ((arg0IsFloating && (((arg0VNtyp == TYP_FLOAT) && _isnanf(GetConstantSingle(arg0VN))) ||
((arg0VNtyp == TYP_DOUBLE) && _isnan(GetConstantDouble(arg0VN))))) ||
(arg1IsFloating && (((arg1VNtyp == TYP_FLOAT) && _isnanf(GetConstantSingle(arg1VN))) ||
((arg0VNtyp == TYP_DOUBLE) && _isnan(GetConstantDouble(arg1VN))))))
{
canFold = false;
}
if (canFold)
{
return EvalFuncForConstantArgs(typ, func, arg0VN, arg1VN);
}
}
// We canonicalize commutative operations.
// (Perhaps should eventually handle associative/commutative [AC] ops -- but that gets complicated...)
if (VNFuncIsCommutative(func))
{
// Order arg0 arg1 by numerical VN value.
if (arg0VN > arg1VN)
{
jitstd::swap(arg0VN, arg1VN);
}
}
VNDefFunc2Arg fstruct(func, arg0VN, arg1VN);
if (GetVNFunc2Map()->Lookup(fstruct, &res))
{
return res;
}
else
{
// We have ways of evaluating some binary functions.
if (func < VNF_Boundary)
{
if (typ != TYP_BYREF) // We don't want/need to optimize a zero byref
{
ValueNum resultVN = NoVN;
ValueNum ZeroVN, OneVN; // We may need to create one of these in the switch below.
switch (genTreeOps(func))
{
case GT_ADD:
// This identity does not apply for floating point (when x == -0.0)
if (!varTypeIsFloating(typ))
{
// (x + 0) == (0 + x) => x
ZeroVN = VNZeroForType(typ);
if (arg0VN == ZeroVN)
{
resultVN = arg1VN;
}
else if (arg1VN == ZeroVN)
{
resultVN = arg0VN;
}
}
break;
case GT_SUB:
// (x - 0) => x
ZeroVN = VNZeroForType(typ);
if (arg1VN == ZeroVN)
{
resultVN = arg0VN;
}
break;
case GT_MUL:
// (x * 1) == (1 * x) => x
OneVN = VNOneForType(typ);
if (OneVN != NoVN)
{
if (arg0VN == OneVN)
{
resultVN = arg1VN;
}
else if (arg1VN == OneVN)
{
resultVN = arg0VN;
}
}
if (!varTypeIsFloating(typ))
{
// (x * 0) == (0 * x) => 0 (unless x is NaN, which we must assume a fp value may be)
ZeroVN = VNZeroForType(typ);
if (arg0VN == ZeroVN)
{
resultVN = ZeroVN;
}
else if (arg1VN == ZeroVN)
{
resultVN = ZeroVN;
}
}
break;
case GT_DIV:
case GT_UDIV:
// (x / 1) => x
OneVN = VNOneForType(typ);
if (OneVN != NoVN)
{
if (arg1VN == OneVN)
{
resultVN = arg0VN;
}
}
break;
case GT_OR:
case GT_XOR:
// (x | 0) == (0 | x) => x
// (x ^ 0) == (0 ^ x) => x
ZeroVN = VNZeroForType(typ);
if (arg0VN == ZeroVN)
{
resultVN = arg1VN;
}
else if (arg1VN == ZeroVN)
{
resultVN = arg0VN;
}
break;
case GT_AND:
// (x & 0) == (0 & x) => 0
ZeroVN = VNZeroForType(typ);
if (arg0VN == ZeroVN)
{
resultVN = ZeroVN;
}
else if (arg1VN == ZeroVN)
{
resultVN = ZeroVN;
}
break;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
case GT_ROL:
case GT_ROR:
// (x << 0) => x
// (x >> 0) => x
// (x rol 0) => x
// (x ror 0) => x
ZeroVN = VNZeroForType(typ);
if (arg1VN == ZeroVN)
{
resultVN = arg0VN;
}
break;
case GT_EQ:
// (x == x) => true (unless x is NaN)
if (!varTypeIsFloating(TypeOfVN(arg0VN)) && (arg0VN != NoVN) && (arg0VN == arg1VN))
{
resultVN = VNOneForType(typ);
}
if ((arg0VN == VNForNull() && IsKnownNonNull(arg1VN)) ||
(arg1VN == VNForNull() && IsKnownNonNull(arg0VN)))
{
resultVN = VNZeroForType(typ);
}
break;
case GT_NE:
// (x != x) => false (unless x is NaN)
if (!varTypeIsFloating(TypeOfVN(arg0VN)) && (arg0VN != NoVN) && (arg0VN == arg1VN))
{
resultVN = VNZeroForType(typ);
}
if ((arg0VN == VNForNull() && IsKnownNonNull(arg1VN)) ||
(arg1VN == VNForNull() && IsKnownNonNull(arg0VN)))
{
resultVN = VNOneForType(typ);
}
break;
default:
break;
}
if ((resultVN != NoVN) && (TypeOfVN(resultVN) == typ))
{
return resultVN;
}
}
}
else // must be a VNF_ function
{
if (func == VNF_CastClass)
{
// In terms of values, a castclass always returns its second argument, the object being cast.
// The IL operation may also throw an exception
return VNWithExc(arg1VN, VNExcSetSingleton(VNForFunc(TYP_REF, VNF_InvalidCastExc, arg1VN, arg0VN)));
}
}
// Otherwise, assign a new VN for the function application.
Chunk* c = GetAllocChunk(typ, CEA_Func2);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNDefFunc2Arg*>(c->m_defs)[offsetWithinChunk] = fstruct;
GetVNFunc2Map()->Set(fstruct, res);
return res;
}
}
//------------------------------------------------------------------------------
// VNForMapStore : Evaluate VNF_MapStore with the given arguments.
//
//
// Arguments:
// typ - Value type
// arg0VN - Map value number
// arg1VN - Index value number
// arg2VN - New value for map[index]
//
// Return Value:
// Value number for the result of the evaluation.
ValueNum ValueNumStore::VNForMapStore(var_types typ, ValueNum arg0VN, ValueNum arg1VN, ValueNum arg2VN)
{
ValueNum result = VNForFunc(typ, VNF_MapStore, arg0VN, arg1VN, arg2VN);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" VNForMapStore(" STR_VN "%x, " STR_VN "%x, " STR_VN "%x):%s returns ", arg0VN, arg1VN, arg2VN,
varTypeName(typ));
m_pComp->vnPrint(result, 1);
printf("\n");
}
#endif
return result;
}
//------------------------------------------------------------------------------
// VNForMapSelect : Evaluate VNF_MapSelect with the given arguments.
//
//
// Arguments:
// vnk - Value number kind
// typ - Value type
// arg0VN - Map value number
// arg1VN - Index value number
//
// Return Value:
// Value number for the result of the evaluation.
//
// Notes:
// This requires a "ValueNumKind" because it will attempt, given "select(phi(m1, ..., mk), ind)", to evaluate
// "select(m1, ind)", ..., "select(mk, ind)" to see if they agree. It needs to know which kind of value number
// (liberal/conservative) to read from the SSA def referenced in the phi argument.
ValueNum ValueNumStore::VNForMapSelect(ValueNumKind vnk, var_types typ, ValueNum arg0VN, ValueNum arg1VN)
{
unsigned budget = m_mapSelectBudget;
bool usedRecursiveVN = false;
ValueNum result = VNForMapSelectWork(vnk, typ, arg0VN, arg1VN, &budget, &usedRecursiveVN);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" VNForMapSelect(" STR_VN "%x, " STR_VN "%x):%s returns ", arg0VN, arg1VN, varTypeName(typ));
m_pComp->vnPrint(result, 1);
printf("\n");
}
#endif
return result;
}
//------------------------------------------------------------------------------
// VNForMapSelectWork : A method that does the work for VNForMapSelect and may call itself recursively.
//
//
// Arguments:
// vnk - Value number kind
// typ - Value type
// arg0VN - Zeroth argument
// arg1VN - First argument
// pBudget - Remaining budget for the outer evaluation
// pUsedRecursiveVN - Out-parameter that is set to true iff RecursiveVN was returned from this method
// or from a method called during one of recursive invocations.
//
// Return Value:
// Value number for the result of the evaluation.
//
// Notes:
// This requires a "ValueNumKind" because it will attempt, given "select(phi(m1, ..., mk), ind)", to evaluate
// "select(m1, ind)", ..., "select(mk, ind)" to see if they agree. It needs to know which kind of value number
// (liberal/conservative) to read from the SSA def referenced in the phi argument.
ValueNum ValueNumStore::VNForMapSelectWork(
ValueNumKind vnk, var_types typ, ValueNum arg0VN, ValueNum arg1VN, unsigned* pBudget, bool* pUsedRecursiveVN)
{
TailCall:
// This label allows us to directly implement a tail call by setting up the arguments, and doing a goto to here.
assert(arg0VN != NoVN && arg1VN != NoVN);
assert(arg0VN == VNNormVal(arg0VN)); // Arguments carry no exceptions.
assert(arg1VN == VNNormVal(arg1VN)); // Arguments carry no exceptions.
*pUsedRecursiveVN = false;
#ifdef DEBUG
// Provide a mechanism for writing tests that ensure we don't call this ridiculously often.
m_numMapSels++;
#if 1
// This printing is sometimes useful in debugging.
// if ((m_numMapSels % 1000) == 0) printf("%d VNF_MapSelect applications.\n", m_numMapSels);
#endif
unsigned selLim = JitConfig.JitVNMapSelLimit();
assert(selLim == 0 || m_numMapSels < selLim);
#endif
ValueNum res;
VNDefFunc2Arg fstruct(VNF_MapSelect, arg0VN, arg1VN);
if (GetVNFunc2Map()->Lookup(fstruct, &res))
{
return res;
}
else
{
// Give up if we've run out of budget.
if (--(*pBudget) == 0)
{
// We have to use 'nullptr' for the basic block here, because subsequent expressions
// in different blocks may find this result in the VNFunc2Map -- other expressions in
// the IR may "evaluate" to this same VNForExpr, so it is not "unique" in the sense
// that permits the BasicBlock attribution.
res = VNForExpr(nullptr, typ);
GetVNFunc2Map()->Set(fstruct, res);
return res;
}
// If it's recursive, stop the recursion.
if (SelectIsBeingEvaluatedRecursively(arg0VN, arg1VN))
{
*pUsedRecursiveVN = true;
return RecursiveVN;
}
if (arg0VN == VNForZeroMap())
{
return VNZeroForType(typ);
}
else if (IsVNFunc(arg0VN))
{
VNFuncApp funcApp;
GetVNFunc(arg0VN, &funcApp);
if (funcApp.m_func == VNF_MapStore)
{
// select(store(m, i, v), i) == v
if (funcApp.m_args[1] == arg1VN)
{
#if FEATURE_VN_TRACE_APPLY_SELECTORS
JITDUMP(" AX1: select([" STR_VN "%x]store(" STR_VN "%x, " STR_VN "%x, " STR_VN "%x), " STR_VN
"%x) ==> " STR_VN "%x.\n",
funcApp.m_args[0], arg0VN, funcApp.m_args[1], funcApp.m_args[2], arg1VN, funcApp.m_args[2]);
#endif
return funcApp.m_args[2];
}
// i # j ==> select(store(m, i, v), j) == select(m, j)
// Currently the only source of distinctions is when both indices are constants.
else if (IsVNConstant(arg1VN) && IsVNConstant(funcApp.m_args[1]))
{
assert(funcApp.m_args[1] != arg1VN); // we already checked this above.
#if FEATURE_VN_TRACE_APPLY_SELECTORS
JITDUMP(" AX2: " STR_VN "%x != " STR_VN "%x ==> select([" STR_VN "%x]store(" STR_VN
"%x, " STR_VN "%x, " STR_VN "%x), " STR_VN "%x) ==> select(" STR_VN "%x, " STR_VN "%x).\n",
arg1VN, funcApp.m_args[1], arg0VN, funcApp.m_args[0], funcApp.m_args[1], funcApp.m_args[2],
arg1VN, funcApp.m_args[0], arg1VN);
#endif
// This is the equivalent of the recursive tail call:
// return VNForMapSelect(vnk, typ, funcApp.m_args[0], arg1VN);
// Make sure we capture any exceptions from the "i" and "v" of the store...
arg0VN = funcApp.m_args[0];
goto TailCall;
}
}
else if (funcApp.m_func == VNF_PhiDef || funcApp.m_func == VNF_PhiMemoryDef)
{
unsigned lclNum = BAD_VAR_NUM;
bool isMemory = false;
VNFuncApp phiFuncApp;
bool defArgIsFunc = false;
if (funcApp.m_func == VNF_PhiDef)
{
lclNum = unsigned(funcApp.m_args[0]);
defArgIsFunc = GetVNFunc(funcApp.m_args[2], &phiFuncApp);
}
else
{
assert(funcApp.m_func == VNF_PhiMemoryDef);
isMemory = true;
defArgIsFunc = GetVNFunc(funcApp.m_args[1], &phiFuncApp);
}
if (defArgIsFunc && phiFuncApp.m_func == VNF_Phi)
{
// select(phi(m1, m2), x): if select(m1, x) == select(m2, x), return that, else new fresh.
// Get the first argument of the phi.
// We need to be careful about breaking infinite recursion. Record the outer select.
m_fixedPointMapSels.Push(VNDefFunc2Arg(VNF_MapSelect, arg0VN, arg1VN));
assert(IsVNConstant(phiFuncApp.m_args[0]));
unsigned phiArgSsaNum = ConstantValue<unsigned>(phiFuncApp.m_args[0]);
ValueNum phiArgVN;
if (isMemory)
{
phiArgVN = m_pComp->GetMemoryPerSsaData(phiArgSsaNum)->m_vnPair.Get(vnk);
}
else
{
phiArgVN = m_pComp->lvaTable[lclNum].GetPerSsaData(phiArgSsaNum)->m_vnPair.Get(vnk);
}
if (phiArgVN != ValueNumStore::NoVN)
{
bool allSame = true;
ValueNum argRest = phiFuncApp.m_args[1];
ValueNum sameSelResult =
VNForMapSelectWork(vnk, typ, phiArgVN, arg1VN, pBudget, pUsedRecursiveVN);
while (allSame && argRest != ValueNumStore::NoVN)
{
ValueNum cur = argRest;
VNFuncApp phiArgFuncApp;
if (GetVNFunc(argRest, &phiArgFuncApp) && phiArgFuncApp.m_func == VNF_Phi)
{
cur = phiArgFuncApp.m_args[0];
argRest = phiArgFuncApp.m_args[1];
}
else
{
argRest = ValueNumStore::NoVN; // Cause the loop to terminate.
}
assert(IsVNConstant(cur));
phiArgSsaNum = ConstantValue<unsigned>(cur);
if (isMemory)
{
phiArgVN = m_pComp->GetMemoryPerSsaData(phiArgSsaNum)->m_vnPair.Get(vnk);
}
else
{
phiArgVN = m_pComp->lvaTable[lclNum].GetPerSsaData(phiArgSsaNum)->m_vnPair.Get(vnk);
}
if (phiArgVN == ValueNumStore::NoVN)
{
allSame = false;
}
else
{
bool usedRecursiveVN = false;
ValueNum curResult =
VNForMapSelectWork(vnk, typ, phiArgVN, arg1VN, pBudget, &usedRecursiveVN);
*pUsedRecursiveVN |= usedRecursiveVN;
if (sameSelResult == ValueNumStore::RecursiveVN)
{
sameSelResult = curResult;
}
if (curResult != ValueNumStore::RecursiveVN && curResult != sameSelResult)
{
allSame = false;
}
}
}
if (allSame && sameSelResult != ValueNumStore::RecursiveVN)
{
// Make sure we're popping what we pushed.
assert(FixedPointMapSelsTopHasValue(arg0VN, arg1VN));
m_fixedPointMapSels.Pop();
// To avoid exponential searches, we make sure that this result is memo-ized.
// The result is always valid for memoization if we didn't rely on RecursiveVN to get it.
// If RecursiveVN was used, we are processing a loop and we can't memo-ize this intermediate
// result if, e.g., this block is in a multi-entry loop.
if (!*pUsedRecursiveVN)
{
GetVNFunc2Map()->Set(fstruct, sameSelResult);
}
return sameSelResult;
}
// Otherwise, fall through to creating the select(phi(m1, m2), x) function application.
}
// Make sure we're popping what we pushed.
assert(FixedPointMapSelsTopHasValue(arg0VN, arg1VN));
m_fixedPointMapSels.Pop();
}
}
}
// Otherwise, assign a new VN for the function application.
Chunk* c = GetAllocChunk(typ, CEA_Func2);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNDefFunc2Arg*>(c->m_defs)[offsetWithinChunk] = fstruct;
GetVNFunc2Map()->Set(fstruct, res);
return res;
}
}
ValueNum ValueNumStore::EvalFuncForConstantArgs(var_types typ, VNFunc func, ValueNum arg0VN)
{
assert(CanEvalForConstantArgs(func));
assert(IsVNConstant(arg0VN));
switch (TypeOfVN(arg0VN))
{
case TYP_INT:
{
int resVal = EvalOp(func, ConstantValue<int>(arg0VN));
// Unary op on a handle results in a handle.
return IsVNHandle(arg0VN) ? VNForHandle(ssize_t(resVal), GetHandleFlags(arg0VN)) : VNForIntCon(resVal);
}
case TYP_LONG:
{
INT64 resVal = EvalOp(func, ConstantValue<INT64>(arg0VN));
// Unary op on a handle results in a handle.
return IsVNHandle(arg0VN) ? VNForHandle(ssize_t(resVal), GetHandleFlags(arg0VN)) : VNForLongCon(resVal);
}
case TYP_FLOAT:
return VNForFloatCon(EvalOp(func, ConstantValue<float>(arg0VN)));
case TYP_DOUBLE:
return VNForDoubleCon(EvalOp(func, ConstantValue<double>(arg0VN)));
case TYP_REF:
// If arg0 has a possible exception, it wouldn't have been constant.
assert(!VNHasExc(arg0VN));
// Otherwise...
assert(arg0VN == VNForNull()); // Only other REF constant.
assert(func == VNFunc(GT_ARR_LENGTH)); // Only function we can apply to a REF constant!
return VNWithExc(VNForVoid(), VNExcSetSingleton(VNForFunc(TYP_REF, VNF_NullPtrExc, VNForNull())));
default:
unreached();
}
}
bool ValueNumStore::SelectIsBeingEvaluatedRecursively(ValueNum map, ValueNum ind)
{
for (unsigned i = 0; i < m_fixedPointMapSels.Size(); i++)
{
VNDefFunc2Arg& elem = m_fixedPointMapSels.GetRef(i);
assert(elem.m_func == VNF_MapSelect);
if (elem.m_arg0 == map && elem.m_arg1 == ind)
{
return true;
}
}
return false;
}
#ifdef DEBUG
bool ValueNumStore::FixedPointMapSelsTopHasValue(ValueNum map, ValueNum index)
{
if (m_fixedPointMapSels.Size() == 0)
{
return false;
}
VNDefFunc2Arg& top = m_fixedPointMapSels.TopRef();
return top.m_func == VNF_MapSelect && top.m_arg0 == map && top.m_arg1 == index;
}
#endif
// Given an integer constant value number return its value as an int.
//
int ValueNumStore::GetConstantInt32(ValueNum argVN)
{
assert(IsVNConstant(argVN));
var_types argVNtyp = TypeOfVN(argVN);
int result = 0;
switch (argVNtyp)
{
case TYP_INT:
result = ConstantValue<int>(argVN);
break;
#ifndef _TARGET_64BIT_
case TYP_REF:
case TYP_BYREF:
result = (int)ConstantValue<size_t>(argVN);
break;
#endif
default:
unreached();
}
return result;
}
// Given an integer constant value number return its value as an INT64.
//
INT64 ValueNumStore::GetConstantInt64(ValueNum argVN)
{
assert(IsVNConstant(argVN));
var_types argVNtyp = TypeOfVN(argVN);
INT64 result = 0;
switch (argVNtyp)
{
case TYP_INT:
result = (INT64)ConstantValue<int>(argVN);
break;
case TYP_LONG:
result = ConstantValue<INT64>(argVN);
break;
case TYP_REF:
case TYP_BYREF:
result = (INT64)ConstantValue<size_t>(argVN);
break;
default:
unreached();
}
return result;
}
// Given a double constant value number return its value as a double.
//
double ValueNumStore::GetConstantDouble(ValueNum argVN)
{
assert(IsVNConstant(argVN));
assert(TypeOfVN(argVN) == TYP_DOUBLE);
return ConstantValue<double>(argVN);
}
// Given a float constant value number return its value as a float.
//
float ValueNumStore::GetConstantSingle(ValueNum argVN)
{
assert(IsVNConstant(argVN));
assert(TypeOfVN(argVN) == TYP_FLOAT);
return ConstantValue<float>(argVN);
}
// Compute the proper value number when the VNFunc has all constant arguments
// This essentially performs constant folding at value numbering time
//
ValueNum ValueNumStore::EvalFuncForConstantArgs(var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN)
{
assert(CanEvalForConstantArgs(func));
assert(IsVNConstant(arg0VN) && IsVNConstant(arg1VN));
assert(!VNHasExc(arg0VN) && !VNHasExc(arg1VN)); // Otherwise, would not be constant.
// if our func is the VNF_Cast operation we handle it first
if (func == VNF_Cast)
{
return EvalCastForConstantArgs(typ, func, arg0VN, arg1VN);
}
if (typ == TYP_BYREF)
{
// We don't want to fold expressions that produce TYP_BYREF
return false;
}
var_types arg0VNtyp = TypeOfVN(arg0VN);
var_types arg1VNtyp = TypeOfVN(arg1VN);
// When both arguments are floating point types
// We defer to the EvalFuncForConstantFPArgs()
if (varTypeIsFloating(arg0VNtyp) && varTypeIsFloating(arg1VNtyp))
{
return EvalFuncForConstantFPArgs(typ, func, arg0VN, arg1VN);
}
// after this we shouldn't have to deal with floating point types for arg0VN or arg1VN
assert(!varTypeIsFloating(arg0VNtyp));
assert(!varTypeIsFloating(arg1VNtyp));
// Stack-normalize the result type.
if (varTypeIsSmall(typ))
{
typ = TYP_INT;
}
ValueNum result; // left uninitialized, we are required to initialize it on all paths below.
ValueNum excSet = VNForEmptyExcSet();
// Are both args of the same type?
if (arg0VNtyp == arg1VNtyp)
{
if (arg0VNtyp == TYP_INT)
{
int arg0Val = ConstantValue<int>(arg0VN);
int arg1Val = ConstantValue<int>(arg1VN);
assert(typ == TYP_INT);
int resultVal = EvalOp(func, arg0Val, arg1Val, &excSet);
// Bin op on a handle results in a handle.
ValueNum handleVN = IsVNHandle(arg0VN) ? arg0VN : IsVNHandle(arg1VN) ? arg1VN : NoVN;
ValueNum resultVN = (handleVN != NoVN)
? VNForHandle(ssize_t(resultVal), GetHandleFlags(handleVN)) // Use VN for Handle
: VNForIntCon(resultVal);
result = VNWithExc(resultVN, excSet);
}
else if (arg0VNtyp == TYP_LONG)
{
INT64 arg0Val = ConstantValue<INT64>(arg0VN);
INT64 arg1Val = ConstantValue<INT64>(arg1VN);
if (VNFuncIsComparison(func))
{
assert(typ == TYP_INT);
result = VNForIntCon(EvalComparison(func, arg0Val, arg1Val));
}
else
{
assert(typ == TYP_LONG);
INT64 resultVal = EvalOp(func, arg0Val, arg1Val, &excSet);
ValueNum handleVN = IsVNHandle(arg0VN) ? arg0VN : IsVNHandle(arg1VN) ? arg1VN : NoVN;
ValueNum resultVN = (handleVN != NoVN)
? VNForHandle(ssize_t(resultVal), GetHandleFlags(handleVN)) // Use VN for Handle
: VNForLongCon(resultVal);
result = VNWithExc(resultVN, excSet);
}
}
else // both args are TYP_REF or both args are TYP_BYREF
{
INT64 arg0Val = ConstantValue<size_t>(arg0VN); // We represent ref/byref constants as size_t's.
INT64 arg1Val = ConstantValue<size_t>(arg1VN); // Also we consider null to be zero.
if (VNFuncIsComparison(func))
{
assert(typ == TYP_INT);
result = VNForIntCon(EvalComparison(func, arg0Val, arg1Val));
}
else if (typ == TYP_INT) // We could see GT_OR of a constant ByRef and Null
{
int resultVal = (int)EvalOp(func, arg0Val, arg1Val, &excSet);
result = VNWithExc(VNForIntCon(resultVal), excSet);
}
else // We could see GT_OR of a constant ByRef and Null
{
assert((typ == TYP_BYREF) || (typ == TYP_LONG));
INT64 resultVal = EvalOp(func, arg0Val, arg1Val, &excSet);
result = VNWithExc(VNForByrefCon(resultVal), excSet);
}
}
}
else // We have args of different types
{
// We represent ref/byref constants as size_t's.
// Also we consider null to be zero.
//
INT64 arg0Val = GetConstantInt64(arg0VN);
INT64 arg1Val = GetConstantInt64(arg1VN);
if (VNFuncIsComparison(func))
{
assert(typ == TYP_INT);
result = VNForIntCon(EvalComparison(func, arg0Val, arg1Val));
}
else if (typ == TYP_INT) // We could see GT_OR of an int and constant ByRef or Null
{
int resultVal = (int)EvalOp(func, arg0Val, arg1Val, &excSet);
result = VNWithExc(VNForIntCon(resultVal), excSet);
}
else
{
assert(typ != TYP_INT);
ValueNum resultValx = VNForEmptyExcSet();
INT64 resultVal = EvalOp(func, arg0Val, arg1Val, &resultValx);
// check for the Exception case
if (resultValx != VNForEmptyExcSet())
{
result = VNWithExc(VNForVoid(), resultValx);
}
else
{
switch (typ)
{
case TYP_BYREF:
result = VNForByrefCon(resultVal);
break;
case TYP_LONG:
result = VNForLongCon(resultVal);
break;
case TYP_REF:
assert(resultVal == 0); // Only valid REF constant
result = VNForNull();
break;
default:
unreached();
}
}
}
}
return result;
}
// Compute the proper value number when the VNFunc has all constant floating-point arguments
// This essentially must perform constant folding at value numbering time
//
ValueNum ValueNumStore::EvalFuncForConstantFPArgs(var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN)
{
assert(CanEvalForConstantArgs(func));
assert(IsVNConstant(arg0VN) && IsVNConstant(arg1VN));
// We expect both argument types to be floating-point types
var_types arg0VNtyp = TypeOfVN(arg0VN);
var_types arg1VNtyp = TypeOfVN(arg1VN);
assert(varTypeIsFloating(arg0VNtyp));
assert(varTypeIsFloating(arg1VNtyp));
// We also expect both arguments to be of the same floating-point type
assert(arg0VNtyp == arg1VNtyp);
ValueNum result; // left uninitialized, we are required to initialize it on all paths below.
if (VNFuncIsComparison(func))
{
assert(genActualType(typ) == TYP_INT);
if (arg0VNtyp == TYP_FLOAT)
{
result = VNForIntCon(EvalComparison(func, GetConstantSingle(arg0VN), GetConstantSingle(arg1VN)));
}
else
{
assert(arg0VNtyp == TYP_DOUBLE);
result = VNForIntCon(EvalComparison(func, GetConstantDouble(arg0VN), GetConstantDouble(arg1VN)));
}
}
else
{
// We expect the return type to be the same as the argument type
assert(varTypeIsFloating(typ));
assert(arg0VNtyp == typ);
ValueNum exception = VNForEmptyExcSet();
if (typ == TYP_FLOAT)
{
float floatResultVal = EvalOp(func, GetConstantSingle(arg0VN), GetConstantSingle(arg1VN), &exception);
assert(exception == VNForEmptyExcSet()); // Floating point ops don't throw.
result = VNForFloatCon(floatResultVal);
}
else
{
assert(typ == TYP_DOUBLE);
double doubleResultVal = EvalOp(func, GetConstantDouble(arg0VN), GetConstantDouble(arg1VN), &exception);
assert(exception == VNForEmptyExcSet()); // Floating point ops don't throw.
result = VNForDoubleCon(doubleResultVal);
}
}
return result;
}
// Compute the proper value number for a VNF_Cast with constant arguments
// This essentially must perform constant folding at value numbering time
//
ValueNum ValueNumStore::EvalCastForConstantArgs(var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN)
{
assert(func == VNF_Cast);
assert(IsVNConstant(arg0VN) && IsVNConstant(arg1VN));
// Stack-normalize the result type.
if (varTypeIsSmall(typ))
{
typ = TYP_INT;
}
var_types arg0VNtyp = TypeOfVN(arg0VN);
var_types arg1VNtyp = TypeOfVN(arg1VN);
// arg1VN is really the gtCastType that we are casting to
assert(arg1VNtyp == TYP_INT);
int arg1Val = ConstantValue<int>(arg1VN);
assert(arg1Val >= 0);
if (IsVNHandle(arg0VN))
{
// We don't allow handles to be cast to random var_types.
assert(typ == TYP_I_IMPL);
}
// We previously encoded the castToType operation using vnForCastOper()
//
bool srcIsUnsigned = ((arg1Val & INT32(VCA_UnsignedSrc)) != 0);
var_types castToType = var_types(arg1Val >> INT32(VCA_BitCount));
var_types castFromType = arg0VNtyp;
switch (castFromType) // GT_CAST source type
{
#ifndef _TARGET_64BIT_
case TYP_REF:
case TYP_BYREF:
#endif
case TYP_INT:
{
int arg0Val = GetConstantInt32(arg0VN);
switch (castToType)
{
case TYP_BYTE:
assert(typ == TYP_INT);
return VNForIntCon(INT8(arg0Val));
case TYP_BOOL:
case TYP_UBYTE:
assert(typ == TYP_INT);
return VNForIntCon(UINT8(arg0Val));
case TYP_SHORT:
assert(typ == TYP_INT);
return VNForIntCon(INT16(arg0Val));
case TYP_CHAR:
case TYP_USHORT:
assert(typ == TYP_INT);
return VNForIntCon(UINT16(arg0Val));
case TYP_INT:
case TYP_UINT:
assert(typ == TYP_INT);
return arg0VN;
case TYP_LONG:
case TYP_ULONG:
assert(!IsVNHandle(arg0VN));
#ifdef _TARGET_64BIT_
if (typ == TYP_LONG)
{
if (srcIsUnsigned)
{
return VNForLongCon(INT64(unsigned(arg0Val)));
}
else
{
return VNForLongCon(INT64(arg0Val));
}
}
else
{
assert(typ == TYP_BYREF);
if (srcIsUnsigned)
{
return VNForByrefCon(INT64(unsigned(arg0Val)));
}
else
{
return VNForByrefCon(INT64(arg0Val));
}
}
#else // TARGET_32BIT
if (srcIsUnsigned)
return VNForLongCon(INT64(unsigned(arg0Val)));
else
return VNForLongCon(INT64(arg0Val));
#endif
case TYP_BYREF:
assert(typ == TYP_BYREF);
return VNForByrefCon((INT64)arg0Val);
case TYP_FLOAT:
assert(typ == TYP_FLOAT);
if (srcIsUnsigned)
{
return VNForFloatCon(float(unsigned(arg0Val)));
}
else
{
return VNForFloatCon(float(arg0Val));
}
case TYP_DOUBLE:
assert(typ == TYP_DOUBLE);
if (srcIsUnsigned)
{
return VNForDoubleCon(double(unsigned(arg0Val)));
}
else
{
return VNForDoubleCon(double(arg0Val));
}
default:
unreached();
}
break;
}
{
#ifdef _TARGET_64BIT_
case TYP_REF:
case TYP_BYREF:
#endif
case TYP_LONG:
INT64 arg0Val = GetConstantInt64(arg0VN);
switch (castToType)
{
case TYP_BYTE:
assert(typ == TYP_INT);
return VNForIntCon(INT8(arg0Val));
case TYP_BOOL:
case TYP_UBYTE:
assert(typ == TYP_INT);
return VNForIntCon(UINT8(arg0Val));
case TYP_SHORT:
assert(typ == TYP_INT);
return VNForIntCon(INT16(arg0Val));
case TYP_CHAR:
case TYP_USHORT:
assert(typ == TYP_INT);
return VNForIntCon(UINT16(arg0Val));
case TYP_INT:
assert(typ == TYP_INT);
return VNForIntCon(INT32(arg0Val));
case TYP_UINT:
assert(typ == TYP_INT);
return VNForIntCon(UINT32(arg0Val));
case TYP_LONG:
case TYP_ULONG:
assert(typ == TYP_LONG);
return arg0VN;
case TYP_BYREF:
assert(typ == TYP_BYREF);
return VNForByrefCon((INT64)arg0Val);
case TYP_FLOAT:
assert(typ == TYP_FLOAT);
if (srcIsUnsigned)
{
return VNForFloatCon(FloatingPointUtils::convertUInt64ToFloat(UINT64(arg0Val)));
}
else
{
return VNForFloatCon(float(arg0Val));
}
case TYP_DOUBLE:
assert(typ == TYP_DOUBLE);
if (srcIsUnsigned)
{
return VNForDoubleCon(FloatingPointUtils::convertUInt64ToDouble(UINT64(arg0Val)));
}
else
{
return VNForDoubleCon(double(arg0Val));
}
default:
unreached();
}
}
case TYP_FLOAT:
{
float arg0Val = GetConstantSingle(arg0VN);
switch (castToType)
{
case TYP_BYTE:
assert(typ == TYP_INT);
return VNForIntCon(INT8(arg0Val));
case TYP_BOOL:
case TYP_UBYTE:
assert(typ == TYP_INT);
return VNForIntCon(UINT8(arg0Val));
case TYP_SHORT:
assert(typ == TYP_INT);
return VNForIntCon(INT16(arg0Val));
case TYP_CHAR:
case TYP_USHORT:
assert(typ == TYP_INT);
return VNForIntCon(UINT16(arg0Val));
case TYP_INT:
assert(typ == TYP_INT);
return VNForIntCon(INT32(arg0Val));
case TYP_UINT:
assert(typ == TYP_INT);
return VNForIntCon(UINT32(arg0Val));
case TYP_LONG:
assert(typ == TYP_LONG);
return VNForLongCon(INT64(arg0Val));
case TYP_ULONG:
assert(typ == TYP_LONG);
return VNForLongCon(UINT64(arg0Val));
case TYP_FLOAT:
assert(typ == TYP_FLOAT);
return VNForFloatCon(arg0Val);
case TYP_DOUBLE:
assert(typ == TYP_DOUBLE);
return VNForDoubleCon(double(arg0Val));
default:
unreached();
}
}
case TYP_DOUBLE:
{
double arg0Val = GetConstantDouble(arg0VN);
switch (castToType)
{
case TYP_BYTE:
assert(typ == TYP_INT);
return VNForIntCon(INT8(arg0Val));
case TYP_BOOL:
case TYP_UBYTE:
assert(typ == TYP_INT);
return VNForIntCon(UINT8(arg0Val));
case TYP_SHORT:
assert(typ == TYP_INT);
return VNForIntCon(INT16(arg0Val));
case TYP_CHAR:
case TYP_USHORT:
assert(typ == TYP_INT);
return VNForIntCon(UINT16(arg0Val));
case TYP_INT:
assert(typ == TYP_INT);
return VNForIntCon(INT32(arg0Val));
case TYP_UINT:
assert(typ == TYP_INT);
return VNForIntCon(UINT32(arg0Val));
case TYP_LONG:
assert(typ == TYP_LONG);
return VNForLongCon(INT64(arg0Val));
case TYP_ULONG:
assert(typ == TYP_LONG);
return VNForLongCon(UINT64(arg0Val));
case TYP_FLOAT:
assert(typ == TYP_FLOAT);
return VNForFloatCon(float(arg0Val));
case TYP_DOUBLE:
assert(typ == TYP_DOUBLE);
return VNForDoubleCon(arg0Val);
default:
unreached();
}
}
default:
unreached();
}
}
bool ValueNumStore::CanEvalForConstantArgs(VNFunc vnf)
{
if (vnf < VNF_Boundary)
{
// We'll refine this as we get counterexamples. But to
// a first approximation, VNFuncs that are genTreeOps should
// be things we can evaluate.
genTreeOps oper = genTreeOps(vnf);
// Some exceptions...
switch (oper)
{
case GT_MKREFANY: // We can't evaluate these.
case GT_RETFILT:
case GT_LIST:
case GT_FIELD_LIST:
case GT_ARR_LENGTH:
return false;
case GT_MULHI:
assert(false && "Unexpected GT_MULHI node encountered before lowering");
return false;
default:
return true;
}
}
else
{
// some VNF_ that we can evaluate
switch (vnf)
{
case VNF_Cast: // We can evaluate these.
return true;
case VNF_ObjGetType:
return false;
default:
return false;
}
}
}
unsigned ValueNumStore::VNFuncArity(VNFunc vnf)
{
// Read the bit field out of the table...
return (s_vnfOpAttribs[vnf] & VNFOA_ArityMask) >> VNFOA_ArityShift;
}
template <>
bool ValueNumStore::IsOverflowIntDiv(int v0, int v1)
{
return (v1 == -1) && (v0 == INT32_MIN);
}
template <>
bool ValueNumStore::IsOverflowIntDiv(INT64 v0, INT64 v1)
{
return (v1 == -1) && (v0 == INT64_MIN);
}
template <typename T>
bool ValueNumStore::IsOverflowIntDiv(T v0, T v1)
{
return false;
}
template <>
bool ValueNumStore::IsIntZero(int v)
{
return v == 0;
}
template <>
bool ValueNumStore::IsIntZero(unsigned v)
{
return v == 0;
}
template <>
bool ValueNumStore::IsIntZero(INT64 v)
{
return v == 0;
}
template <>
bool ValueNumStore::IsIntZero(UINT64 v)
{
return v == 0;
}
template <typename T>
bool ValueNumStore::IsIntZero(T v)
{
return false;
}
template <>
float ValueNumStore::EvalOpIntegral<float>(VNFunc vnf, float v0)
{
assert(!"EvalOpIntegral<float>");
return 0.0f;
}
template <>
double ValueNumStore::EvalOpIntegral<double>(VNFunc vnf, double v0)
{
assert(!"EvalOpIntegral<double>");
return 0.0;
}
template <>
float ValueNumStore::EvalOpIntegral<float>(VNFunc vnf, float v0, float v1, ValueNum* pExcSet)
{
genTreeOps oper = genTreeOps(vnf);
switch (oper)
{
case GT_MOD:
return fmodf(v0, v1);
default:
// For any other values of 'oper', we will assert and return 0.0f
break;
}
assert(!"EvalOpIntegral<float> with pExcSet");
return 0.0f;
}
template <>
double ValueNumStore::EvalOpIntegral<double>(VNFunc vnf, double v0, double v1, ValueNum* pExcSet)
{
genTreeOps oper = genTreeOps(vnf);
switch (oper)
{
case GT_MOD:
return fmod(v0, v1);
default:
// For any other value of 'oper', we will assert and return 0.0
break;
}
assert(!"EvalOpIntegral<double> with pExcSet");
return 0.0;
}
ValueNum ValueNumStore::VNForFunc(var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN, ValueNum arg2VN)
{
assert(arg0VN != NoVN);
assert(arg1VN != NoVN);
assert(arg2VN != NoVN);
assert(VNFuncArity(func) == 3);
// Function arguments carry no exceptions.
CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef DEBUG
if (func != VNF_PhiDef)
{
// For a phi definition first and second argument are "plain" local/ssa numbers.
// (I don't know if having such non-VN arguments to a VN function is a good idea -- if we wanted to declare
// ValueNum to be "short" it would be a problem, for example. But we'll leave it for now, with these explicit
// exceptions.)
assert(arg0VN == VNNormVal(arg0VN));
assert(arg1VN == VNNormVal(arg1VN));
}
assert(arg2VN == VNNormVal(arg2VN));
#endif
assert(VNFuncArity(func) == 3);
ValueNum res;
VNDefFunc3Arg fstruct(func, arg0VN, arg1VN, arg2VN);
if (GetVNFunc3Map()->Lookup(fstruct, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(typ, CEA_Func3);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNDefFunc3Arg*>(c->m_defs)[offsetWithinChunk] = fstruct;
GetVNFunc3Map()->Set(fstruct, res);
return res;
}
}
ValueNum ValueNumStore::VNForFunc(
var_types typ, VNFunc func, ValueNum arg0VN, ValueNum arg1VN, ValueNum arg2VN, ValueNum arg3VN)
{
assert(arg0VN != NoVN && arg1VN != NoVN && arg2VN != NoVN && arg3VN != NoVN);
// Function arguments carry no exceptions.
assert(arg0VN == VNNormVal(arg0VN));
assert(arg1VN == VNNormVal(arg1VN));
assert(arg2VN == VNNormVal(arg2VN));
assert(arg3VN == VNNormVal(arg3VN));
assert(VNFuncArity(func) == 4);
ValueNum res;
VNDefFunc4Arg fstruct(func, arg0VN, arg1VN, arg2VN, arg3VN);
if (GetVNFunc4Map()->Lookup(fstruct, &res))
{
return res;
}
else
{
Chunk* c = GetAllocChunk(typ, CEA_Func4);
unsigned offsetWithinChunk = c->AllocVN();
res = c->m_baseVN + offsetWithinChunk;
reinterpret_cast<VNDefFunc4Arg*>(c->m_defs)[offsetWithinChunk] = fstruct;
GetVNFunc4Map()->Set(fstruct, res);
return res;
}
}
//------------------------------------------------------------------------
// VNForExpr: Opaque value number that is equivalent to itself but unique
// from all other value numbers.
//
// Arguments:
// block - BasicBlock where the expression that produces this value occurs.
// May be nullptr to force conservative "could be anywhere" interpretation.
// typ - Type of the expression in the IR
//
// Return Value:
// A new value number distinct from any previously generated, that compares as equal
// to itself, but not any other value number, and is annotated with the given
// type and block.
ValueNum ValueNumStore::VNForExpr(BasicBlock* block, var_types typ)
{
BasicBlock::loopNumber loopNum;
if (block == nullptr)
{
loopNum = MAX_LOOP_NUM;
}
else
{
loopNum = block->bbNatLoopNum;
}
// We always allocate a new, unique VN in this call.
// The 'typ' is used to partition the allocation of VNs into different chunks.
Chunk* c = GetAllocChunk(typ, CEA_None, loopNum);
unsigned offsetWithinChunk = c->AllocVN();
ValueNum result = c->m_baseVN + offsetWithinChunk;
return result;
}
ValueNum ValueNumStore::VNApplySelectors(ValueNumKind vnk,
ValueNum map,
FieldSeqNode* fieldSeq,
size_t* wbFinalStructSize)
{
if (fieldSeq == nullptr)
{
return map;
}
else
{
assert(fieldSeq != FieldSeqStore::NotAField());
// Skip any "FirstElem" pseudo-fields or any "ConstantIndex" pseudo-fields
if (fieldSeq->IsPseudoField())
{
return VNApplySelectors(vnk, map, fieldSeq->m_next, wbFinalStructSize);
}
// Otherwise, is a real field handle.
CORINFO_FIELD_HANDLE fldHnd = fieldSeq->m_fieldHnd;
CORINFO_CLASS_HANDLE structHnd = NO_CLASS_HANDLE;
ValueNum fldHndVN = VNForHandle(ssize_t(fldHnd), GTF_ICON_FIELD_HDL);
noway_assert(fldHnd != nullptr);
CorInfoType fieldCit = m_pComp->info.compCompHnd->getFieldType(fldHnd, &structHnd);
var_types fieldType = JITtype2varType(fieldCit);
size_t structSize = 0;
if (varTypeIsStruct(fieldType))
{
structSize = m_pComp->info.compCompHnd->getClassSize(structHnd);
// We do not normalize the type field accesses during importation unless they
// are used in a call, return or assignment.
if ((fieldType == TYP_STRUCT) && (structSize <= m_pComp->largestEnregisterableStructSize()))
{
fieldType = m_pComp->impNormStructType(structHnd);
}
}
if (wbFinalStructSize != nullptr)
{
*wbFinalStructSize = structSize;
}
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" VNApplySelectors:\n");
const char* modName;
const char* fldName = m_pComp->eeGetFieldName(fldHnd, &modName);
printf(" VNForHandle(Fseq[%s]) is " STR_VN "%x, fieldType is %s", fldName, fldHndVN,
varTypeName(fieldType));
if (varTypeIsStruct(fieldType))
{
printf(", size = %d", structSize);
}
printf("\n");
}
#endif
if (fieldSeq->m_next != nullptr)
{
ValueNum newMap = VNForMapSelect(vnk, fieldType, map, fldHndVN);
return VNApplySelectors(vnk, newMap, fieldSeq->m_next, wbFinalStructSize);
}
else // end of fieldSeq
{
return VNForMapSelect(vnk, fieldType, map, fldHndVN);
}
}
}
ValueNum ValueNumStore::VNApplySelectorsTypeCheck(ValueNum elem, var_types indType, size_t elemStructSize)
{
var_types elemTyp = TypeOfVN(elem);
// Check if the elemTyp is matching/compatible
if (indType != elemTyp)
{
bool isConstant = IsVNConstant(elem);
if (isConstant && (elemTyp == genActualType(indType)))
{
// (i.e. We recorded a constant of TYP_INT for a TYP_BYTE field)
}
else
{
// We are trying to read from an 'elem' of type 'elemType' using 'indType' read
size_t elemTypSize = (elemTyp == TYP_STRUCT) ? elemStructSize : genTypeSize(elemTyp);
size_t indTypeSize = genTypeSize(indType);
if ((indType == TYP_REF) && (varTypeIsStruct(elemTyp)))
{
// indType is TYP_REF and elemTyp is TYP_STRUCT
//
// We have a pointer to a static that is a Boxed Struct
//
return elem;
}
else if (indTypeSize > elemTypSize)
{
// Reading beyong the end of 'elem'
// return a new unique value number
elem = VNForExpr(nullptr, indType);
JITDUMP(" *** Mismatched types in VNApplySelectorsTypeCheck (reading beyond the end)\n");
}
else if (varTypeIsStruct(indType))
{
// indType is TYP_STRUCT
// return a new unique value number
elem = VNForExpr(nullptr, indType);
JITDUMP(" *** Mismatched types in VNApplySelectorsTypeCheck (indType is TYP_STRUCT)\n");
}
else
{
// We are trying to read an 'elem' of type 'elemType' using 'indType' read
// insert a cast of elem to 'indType'
elem = VNForCast(elem, indType, elemTyp);
}
}
}
return elem;
}
ValueNum ValueNumStore::VNApplySelectorsAssignTypeCoerce(ValueNum elem, var_types indType, BasicBlock* block)
{
var_types elemTyp = TypeOfVN(elem);
// Check if the elemTyp is matching/compatible
if (indType != elemTyp)
{
bool isConstant = IsVNConstant(elem);
if (isConstant && (elemTyp == genActualType(indType)))
{
// (i.e. We recorded a constant of TYP_INT for a TYP_BYTE field)
}
else
{
// We are trying to write an 'elem' of type 'elemType' using 'indType' store
if (varTypeIsStruct(indType))
{
// return a new unique value number
elem = VNForExpr(block, indType);
JITDUMP(" *** Mismatched types in VNApplySelectorsAssignTypeCoerce (indType is TYP_STRUCT)\n");
}
else
{
// We are trying to write an 'elem' of type 'elemType' using 'indType' store
// insert a cast of elem to 'indType'
elem = VNForCast(elem, indType, elemTyp);
}
}
}
return elem;
}
//------------------------------------------------------------------------
// VNApplySelectorsAssign: Compute the value number corresponding to "map" but with
// the element at "fieldSeq" updated to have type "elem"; this is the new memory
// value for an assignment of value "elem" into the memory at location "fieldSeq"
// that occurs in block "block" and has type "indType" (so long as the selectors
// into that memory occupy disjoint locations, which is true for GcHeap).
//
// Arguments:
// vnk - Identifies whether to recurse to Conservative or Liberal value numbers
// when recursing through phis
// map - Value number for the field map before the assignment
// elem - Value number for the value being stored (to the given field)
// indType - Type of the indirection storing the value to the field
// block - Block where the assignment occurs
//
// Return Value:
// The value number corresponding to memory after the assignment.
ValueNum ValueNumStore::VNApplySelectorsAssign(
ValueNumKind vnk, ValueNum map, FieldSeqNode* fieldSeq, ValueNum elem, var_types indType, BasicBlock* block)
{
if (fieldSeq == nullptr)
{
return VNApplySelectorsAssignTypeCoerce(elem, indType, block);
}
else
{
assert(fieldSeq != FieldSeqStore::NotAField());
// Skip any "FirstElem" pseudo-fields or any "ConstantIndex" pseudo-fields
// These will occur, at least, in struct static expressions, for method table offsets.
if (fieldSeq->IsPseudoField())
{
return VNApplySelectorsAssign(vnk, map, fieldSeq->m_next, elem, indType, block);
}
// Otherwise, fldHnd is a real field handle.
CORINFO_FIELD_HANDLE fldHnd = fieldSeq->m_fieldHnd;
CORINFO_CLASS_HANDLE structType = nullptr;
noway_assert(fldHnd != nullptr);
CorInfoType fieldCit = m_pComp->info.compCompHnd->getFieldType(fldHnd, &structType);
var_types fieldType = JITtype2varType(fieldCit);
ValueNum fieldHndVN = VNForHandle(ssize_t(fldHnd), GTF_ICON_FIELD_HDL);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" fieldHnd " STR_VN "%x is ", fieldHndVN);
vnDump(m_pComp, fieldHndVN);
printf("\n");
ValueNum seqNextVN = VNForFieldSeq(fieldSeq->m_next);
ValueNum fieldSeqVN = VNForFunc(TYP_REF, VNF_FieldSeq, fieldHndVN, seqNextVN);
printf(" fieldSeq " STR_VN "%x is ", fieldSeqVN);
vnDump(m_pComp, fieldSeqVN);
printf("\n");
}
#endif
ValueNum elemAfter;
if (fieldSeq->m_next)
{
ValueNum fseqMap = VNForMapSelect(vnk, fieldType, map, fieldHndVN);
elemAfter = VNApplySelectorsAssign(vnk, fseqMap, fieldSeq->m_next, elem, indType, block);
}
else
{
elemAfter = VNApplySelectorsAssignTypeCoerce(elem, indType, block);
}
ValueNum newMap = VNForMapStore(fieldType, map, fieldHndVN, elemAfter);
return newMap;
}
}
ValueNumPair ValueNumStore::VNPairApplySelectors(ValueNumPair map, FieldSeqNode* fieldSeq, var_types indType)
{
size_t structSize = 0;
ValueNum liberalVN = VNApplySelectors(VNK_Liberal, map.GetLiberal(), fieldSeq, &structSize);
liberalVN = VNApplySelectorsTypeCheck(liberalVN, indType, structSize);
structSize = 0;
ValueNum conservVN = VNApplySelectors(VNK_Conservative, map.GetConservative(), fieldSeq, &structSize);
conservVN = VNApplySelectorsTypeCheck(conservVN, indType, structSize);
return ValueNumPair(liberalVN, conservVN);
}
bool ValueNumStore::IsVNNotAField(ValueNum vn)
{
return m_chunks.GetNoExpand(GetChunkNum(vn))->m_attribs == CEA_NotAField;
}
ValueNum ValueNumStore::VNForFieldSeq(FieldSeqNode* fieldSeq)
{
if (fieldSeq == nullptr)
{
return VNForNull();
}
else if (fieldSeq == FieldSeqStore::NotAField())
{
// We always allocate a new, unique VN in this call.
Chunk* c = GetAllocChunk(TYP_REF, CEA_NotAField);
unsigned offsetWithinChunk = c->AllocVN();
ValueNum result = c->m_baseVN + offsetWithinChunk;
return result;
}
else
{
ssize_t fieldHndVal = ssize_t(fieldSeq->m_fieldHnd);
ValueNum fieldHndVN = VNForHandle(fieldHndVal, GTF_ICON_FIELD_HDL);
ValueNum seqNextVN = VNForFieldSeq(fieldSeq->m_next);
ValueNum fieldSeqVN = VNForFunc(TYP_REF, VNF_FieldSeq, fieldHndVN, seqNextVN);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" fieldHnd " STR_VN "%x is ", fieldHndVN);
vnDump(m_pComp, fieldHndVN);
printf("\n");
printf(" fieldSeq " STR_VN "%x is ", fieldSeqVN);
vnDump(m_pComp, fieldSeqVN);
printf("\n");
}
#endif
return fieldSeqVN;
}
}
FieldSeqNode* ValueNumStore::FieldSeqVNToFieldSeq(ValueNum vn)
{
if (vn == VNForNull())
{
return nullptr;
}
assert(IsVNFunc(vn));
VNFuncApp funcApp;
GetVNFunc(vn, &funcApp);
if (funcApp.m_func == VNF_NotAField)
{
return FieldSeqStore::NotAField();
}
assert(funcApp.m_func == VNF_FieldSeq);
const ssize_t fieldHndVal = ConstantValue<ssize_t>(funcApp.m_args[0]);
FieldSeqNode* head =
m_pComp->GetFieldSeqStore()->CreateSingleton(reinterpret_cast<CORINFO_FIELD_HANDLE>(fieldHndVal));
FieldSeqNode* tail = FieldSeqVNToFieldSeq(funcApp.m_args[1]);
return m_pComp->GetFieldSeqStore()->Append(head, tail);
}
ValueNum ValueNumStore::FieldSeqVNAppend(ValueNum fsVN1, ValueNum fsVN2)
{
if (fsVN1 == VNForNull())
{
return fsVN2;
}
assert(IsVNFunc(fsVN1));
VNFuncApp funcApp1;
GetVNFunc(fsVN1, &funcApp1);
if ((funcApp1.m_func == VNF_NotAField) || IsVNNotAField(fsVN2))
{
return VNForFieldSeq(FieldSeqStore::NotAField());
}
assert(funcApp1.m_func == VNF_FieldSeq);
ValueNum tailRes = FieldSeqVNAppend(funcApp1.m_args[1], fsVN2);
ValueNum fieldSeqVN = VNForFunc(TYP_REF, VNF_FieldSeq, funcApp1.m_args[0], tailRes);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" fieldSeq " STR_VN "%x is ", fieldSeqVN);
vnDump(m_pComp, fieldSeqVN);
printf("\n");
}
#endif
return fieldSeqVN;
}
ValueNum ValueNumStore::ExtendPtrVN(GenTreePtr opA, GenTreePtr opB)
{
if (opB->OperGet() == GT_CNS_INT)
{
FieldSeqNode* fldSeq = opB->gtIntCon.gtFieldSeq;
if (fldSeq != nullptr)
{
return ExtendPtrVN(opA, opB->gtIntCon.gtFieldSeq);
}
}
return NoVN;
}
ValueNum ValueNumStore::ExtendPtrVN(GenTreePtr opA, FieldSeqNode* fldSeq)
{
assert(fldSeq != nullptr);
ValueNum res = NoVN;
ValueNum opAvnWx = opA->gtVNPair.GetLiberal();
assert(VNIsValid(opAvnWx));
ValueNum opAvn;
ValueNum opAvnx = VNForEmptyExcSet();
VNUnpackExc(opAvnWx, &opAvn, &opAvnx);
assert(VNIsValid(opAvn) && VNIsValid(opAvnx));
VNFuncApp funcApp;
if (!GetVNFunc(opAvn, &funcApp))
{
return res;
}
if (funcApp.m_func == VNF_PtrToLoc)
{
#ifdef DEBUG
// For PtrToLoc, lib == cons.
VNFuncApp consFuncApp;
assert(GetVNFunc(VNNormVal(opA->GetVN(VNK_Conservative)), &consFuncApp) && consFuncApp.Equals(funcApp));
#endif
ValueNum fldSeqVN = VNForFieldSeq(fldSeq);
res = VNForFunc(TYP_BYREF, VNF_PtrToLoc, funcApp.m_args[0], FieldSeqVNAppend(funcApp.m_args[1], fldSeqVN));
}
else if (funcApp.m_func == VNF_PtrToStatic)
{
ValueNum fldSeqVN = VNForFieldSeq(fldSeq);
res = VNForFunc(TYP_BYREF, VNF_PtrToStatic, FieldSeqVNAppend(funcApp.m_args[0], fldSeqVN));
}
else if (funcApp.m_func == VNF_PtrToArrElem)
{
ValueNum fldSeqVN = VNForFieldSeq(fldSeq);
res = VNForFunc(TYP_BYREF, VNF_PtrToArrElem, funcApp.m_args[0], funcApp.m_args[1], funcApp.m_args[2],
FieldSeqVNAppend(funcApp.m_args[3], fldSeqVN));
}
if (res != NoVN)
{
res = VNWithExc(res, opAvnx);
}
return res;
}
ValueNum Compiler::fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
ValueNum arrVN,
ValueNum inxVN,
FieldSeqNode* fldSeq,
ValueNum rhsVN,
var_types indType)
{
bool invalidateArray = false;
ValueNum elemTypeEqVN = vnStore->VNForHandle(ssize_t(elemTypeEq), GTF_ICON_CLASS_HDL);
var_types arrElemType = DecodeElemType(elemTypeEq);
ValueNum hAtArrType = vnStore->VNForMapSelect(VNK_Liberal, TYP_REF, fgCurMemoryVN[GcHeap], elemTypeEqVN);
ValueNum hAtArrTypeAtArr = vnStore->VNForMapSelect(VNK_Liberal, TYP_REF, hAtArrType, arrVN);
ValueNum hAtArrTypeAtArrAtInx = vnStore->VNForMapSelect(VNK_Liberal, arrElemType, hAtArrTypeAtArr, inxVN);
ValueNum newValAtInx = ValueNumStore::NoVN;
ValueNum newValAtArr = ValueNumStore::NoVN;
ValueNum newValAtArrType = ValueNumStore::NoVN;
if (fldSeq == FieldSeqStore::NotAField())
{
// This doesn't represent a proper array access
JITDUMP(" *** NotAField sequence encountered in fgValueNumberArrIndexAssign\n");
// Store a new unique value for newValAtArrType
newValAtArrType = vnStore->VNForExpr(compCurBB, TYP_REF);
invalidateArray = true;
}
else
{
// Note that this does the right thing if "fldSeq" is null -- returns last "rhs" argument.
// This is the value that should be stored at "arr[inx]".
newValAtInx =
vnStore->VNApplySelectorsAssign(VNK_Liberal, hAtArrTypeAtArrAtInx, fldSeq, rhsVN, indType, compCurBB);
var_types arrElemFldType = arrElemType; // Uses arrElemType unless we has a non-null fldSeq
if (vnStore->IsVNFunc(newValAtInx))
{
VNFuncApp funcApp;
vnStore->GetVNFunc(newValAtInx, &funcApp);
if (funcApp.m_func == VNF_MapStore)
{
arrElemFldType = vnStore->TypeOfVN(newValAtInx);
}
}
if (indType != arrElemFldType)
{
// Mismatched types: Store between different types (indType into array of arrElemFldType)
//
JITDUMP(" *** Mismatched types in fgValueNumberArrIndexAssign\n");
// Store a new unique value for newValAtArrType
newValAtArrType = vnStore->VNForExpr(compCurBB, TYP_REF);
invalidateArray = true;
}
}
if (!invalidateArray)
{
newValAtArr = vnStore->VNForMapStore(indType, hAtArrTypeAtArr, inxVN, newValAtInx);
newValAtArrType = vnStore->VNForMapStore(TYP_REF, hAtArrType, arrVN, newValAtArr);
}
#ifdef DEBUG
if (verbose)
{
printf(" hAtArrType " STR_VN "%x is MapSelect(curGcHeap(" STR_VN "%x), ", hAtArrType, fgCurMemoryVN[GcHeap]);
if (arrElemType == TYP_STRUCT)
{
printf("%s[]).\n", eeGetClassName(elemTypeEq));
}
else
{
printf("%s[]).\n", varTypeName(arrElemType));
}
printf(" hAtArrTypeAtArr " STR_VN "%x is MapSelect(hAtArrType(" STR_VN "%x), arr=" STR_VN "%x)\n",
hAtArrTypeAtArr, hAtArrType, arrVN);
printf(" hAtArrTypeAtArrAtInx " STR_VN "%x is MapSelect(hAtArrTypeAtArr(" STR_VN "%x), inx=" STR_VN "%x):%s\n",
hAtArrTypeAtArrAtInx, hAtArrTypeAtArr, inxVN, varTypeName(arrElemType));
if (!invalidateArray)
{
printf(" newValAtInd " STR_VN "%x is ", newValAtInx);
vnStore->vnDump(this, newValAtInx);
printf("\n");
printf(" newValAtArr " STR_VN "%x is ", newValAtArr);
vnStore->vnDump(this, newValAtArr);
printf("\n");
}
printf(" newValAtArrType " STR_VN "%x is ", newValAtArrType);
vnStore->vnDump(this, newValAtArrType);
printf("\n");
printf(" fgCurMemoryVN assigned:\n");
}
#endif // DEBUG
return vnStore->VNForMapStore(TYP_REF, fgCurMemoryVN[GcHeap], elemTypeEqVN, newValAtArrType);
}
ValueNum Compiler::fgValueNumberArrIndexVal(GenTreePtr tree, VNFuncApp* pFuncApp, ValueNum addrXvn)
{
assert(vnStore->IsVNHandle(pFuncApp->m_args[0]));
CORINFO_CLASS_HANDLE arrElemTypeEQ = CORINFO_CLASS_HANDLE(vnStore->ConstantValue<ssize_t>(pFuncApp->m_args[0]));
ValueNum arrVN = pFuncApp->m_args[1];
ValueNum inxVN = pFuncApp->m_args[2];
FieldSeqNode* fldSeq = vnStore->FieldSeqVNToFieldSeq(pFuncApp->m_args[3]);
return fgValueNumberArrIndexVal(tree, arrElemTypeEQ, arrVN, inxVN, addrXvn, fldSeq);
}
ValueNum Compiler::fgValueNumberArrIndexVal(GenTreePtr tree,
CORINFO_CLASS_HANDLE elemTypeEq,
ValueNum arrVN,
ValueNum inxVN,
ValueNum excVN,
FieldSeqNode* fldSeq)
{
assert(tree == nullptr || tree->OperIsIndir());
// The VN inputs are required to be non-exceptional values.
assert(arrVN == vnStore->VNNormVal(arrVN));
assert(inxVN == vnStore->VNNormVal(inxVN));
var_types elemTyp = DecodeElemType(elemTypeEq);
var_types indType = (tree == nullptr) ? elemTyp : tree->TypeGet();
ValueNum selectedElem;
if (fldSeq == FieldSeqStore::NotAField())
{
// This doesn't represent a proper array access
JITDUMP(" *** NotAField sequence encountered in fgValueNumberArrIndexVal\n");
// a new unique value number
selectedElem = vnStore->VNForExpr(compCurBB, elemTyp);
#ifdef DEBUG
if (verbose)
{
printf(" IND of PtrToArrElem is unique VN " STR_VN "%x.\n", selectedElem);
}
#endif // DEBUG
if (tree != nullptr)
{
tree->gtVNPair.SetBoth(selectedElem);
}
}
else
{
ValueNum elemTypeEqVN = vnStore->VNForHandle(ssize_t(elemTypeEq), GTF_ICON_CLASS_HDL);
ValueNum hAtArrType = vnStore->VNForMapSelect(VNK_Liberal, TYP_REF, fgCurMemoryVN[GcHeap], elemTypeEqVN);
ValueNum hAtArrTypeAtArr = vnStore->VNForMapSelect(VNK_Liberal, TYP_REF, hAtArrType, arrVN);
ValueNum wholeElem = vnStore->VNForMapSelect(VNK_Liberal, elemTyp, hAtArrTypeAtArr, inxVN);
#ifdef DEBUG
if (verbose)
{
printf(" hAtArrType " STR_VN "%x is MapSelect(curGcHeap(" STR_VN "%x), ", hAtArrType,
fgCurMemoryVN[GcHeap]);
if (elemTyp == TYP_STRUCT)
{
printf("%s[]).\n", eeGetClassName(elemTypeEq));
}
else
{
printf("%s[]).\n", varTypeName(elemTyp));
}
printf(" hAtArrTypeAtArr " STR_VN "%x is MapSelect(hAtArrType(" STR_VN "%x), arr=" STR_VN "%x).\n",
hAtArrTypeAtArr, hAtArrType, arrVN);
printf(" wholeElem " STR_VN "%x is MapSelect(hAtArrTypeAtArr(" STR_VN "%x), ind=" STR_VN "%x).\n",
wholeElem, hAtArrTypeAtArr, inxVN);
}
#endif // DEBUG
selectedElem = wholeElem;
size_t elemStructSize = 0;
if (fldSeq)
{
selectedElem = vnStore->VNApplySelectors(VNK_Liberal, wholeElem, fldSeq, &elemStructSize);
elemTyp = vnStore->TypeOfVN(selectedElem);
}
selectedElem = vnStore->VNApplySelectorsTypeCheck(selectedElem, indType, elemStructSize);
selectedElem = vnStore->VNWithExc(selectedElem, excVN);
#ifdef DEBUG
if (verbose && (selectedElem != wholeElem))
{
printf(" selectedElem is " STR_VN "%x after applying selectors.\n", selectedElem);
}
#endif // DEBUG
if (tree != nullptr)
{
tree->gtVNPair.SetLiberal(selectedElem);
// TODO-CQ: what to do here about exceptions? We don't have the array and ind conservative
// values, so we don't have their exceptions. Maybe we should.
tree->gtVNPair.SetConservative(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
}
}
return selectedElem;
}
ValueNum Compiler::fgValueNumberByrefExposedLoad(var_types type, ValueNum pointerVN)
{
ValueNum memoryVN = fgCurMemoryVN[ByrefExposed];
// The memoization for VNFunc applications does not factor in the result type, so
// VNF_ByrefExposedLoad takes the loaded type as an explicit parameter.
ValueNum typeVN = vnStore->VNForIntCon(type);
ValueNum loadVN = vnStore->VNForFunc(type, VNF_ByrefExposedLoad, typeVN, vnStore->VNNormVal(pointerVN), memoryVN);
return loadVN;
}
var_types ValueNumStore::TypeOfVN(ValueNum vn)
{
if (vn == NoVN)
{
return TYP_UNDEF;
}
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
return c->m_typ;
}
//------------------------------------------------------------------------
// LoopOfVN: If the given value number is an opaque one associated with a particular
// expression in the IR, give the loop number where the expression occurs; otherwise,
// returns MAX_LOOP_NUM.
//
// Arguments:
// vn - Value number to query
//
// Return Value:
// The correspondingblock's bbNatLoopNum, which may be BasicBlock::NOT_IN_LOOP.
// Returns MAX_LOOP_NUM if this VN is not an opaque value number associated with
// a particular expression/location in the IR.
BasicBlock::loopNumber ValueNumStore::LoopOfVN(ValueNum vn)
{
if (vn == NoVN)
{
return MAX_LOOP_NUM;
}
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
return c->m_loopNum;
}
bool ValueNumStore::IsVNConstant(ValueNum vn)
{
if (vn == NoVN)
{
return false;
}
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
if (c->m_attribs == CEA_Const)
{
return vn != VNForVoid(); // Void is not a "real" constant -- in the sense that it represents no value.
}
else
{
return c->m_attribs == CEA_Handle;
}
}
bool ValueNumStore::IsVNInt32Constant(ValueNum vn)
{
if (!IsVNConstant(vn))
{
return false;
}
return TypeOfVN(vn) == TYP_INT;
}
unsigned ValueNumStore::GetHandleFlags(ValueNum vn)
{
assert(IsVNHandle(vn));
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
unsigned offset = ChunkOffset(vn);
VNHandle* handle = &reinterpret_cast<VNHandle*>(c->m_defs)[offset];
return handle->m_flags;
}
bool ValueNumStore::IsVNHandle(ValueNum vn)
{
if (vn == NoVN)
{
return false;
}
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
return c->m_attribs == CEA_Handle;
}
bool ValueNumStore::IsVNConstantBound(ValueNum vn)
{
// Do we have "var < 100"?
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
if (!GetVNFunc(vn, &funcAttr))
{
return false;
}
if (funcAttr.m_func != (VNFunc)GT_LE && funcAttr.m_func != (VNFunc)GT_GE && funcAttr.m_func != (VNFunc)GT_LT &&
funcAttr.m_func != (VNFunc)GT_GT)
{
return false;
}
return IsVNInt32Constant(funcAttr.m_args[0]) != IsVNInt32Constant(funcAttr.m_args[1]);
}
void ValueNumStore::GetConstantBoundInfo(ValueNum vn, ConstantBoundInfo* info)
{
assert(IsVNConstantBound(vn));
assert(info);
// Do we have var < 100?
VNFuncApp funcAttr;
GetVNFunc(vn, &funcAttr);
bool isOp1Const = IsVNInt32Constant(funcAttr.m_args[1]);
if (isOp1Const)
{
info->cmpOper = funcAttr.m_func;
info->cmpOpVN = funcAttr.m_args[0];
info->constVal = GetConstantInt32(funcAttr.m_args[1]);
}
else
{
info->cmpOper = GenTree::SwapRelop((genTreeOps)funcAttr.m_func);
info->cmpOpVN = funcAttr.m_args[1];
info->constVal = GetConstantInt32(funcAttr.m_args[0]);
}
}
bool ValueNumStore::IsVNArrLenBound(ValueNum vn)
{
// Do we have "var < a.len"?
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
if (!GetVNFunc(vn, &funcAttr))
{
return false;
}
if (funcAttr.m_func != (VNFunc)GT_LE && funcAttr.m_func != (VNFunc)GT_GE && funcAttr.m_func != (VNFunc)GT_LT &&
funcAttr.m_func != (VNFunc)GT_GT)
{
return false;
}
if (!IsVNArrLen(funcAttr.m_args[0]) && !IsVNArrLen(funcAttr.m_args[1]))
{
return false;
}
return true;
}
void ValueNumStore::GetArrLenBoundInfo(ValueNum vn, ArrLenArithBoundInfo* info)
{
assert(IsVNArrLenBound(vn));
// Do we have var < a.len?
VNFuncApp funcAttr;
GetVNFunc(vn, &funcAttr);
bool isOp1ArrLen = IsVNArrLen(funcAttr.m_args[1]);
if (isOp1ArrLen)
{
info->cmpOper = funcAttr.m_func;
info->cmpOp = funcAttr.m_args[0];
info->vnArray = GetArrForLenVn(funcAttr.m_args[1]);
}
else
{
info->cmpOper = GenTree::SwapRelop((genTreeOps)funcAttr.m_func);
info->cmpOp = funcAttr.m_args[1];
info->vnArray = GetArrForLenVn(funcAttr.m_args[0]);
}
}
bool ValueNumStore::IsVNArrLenArith(ValueNum vn)
{
// Do we have "a.len +or- var"
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
return GetVNFunc(vn, &funcAttr) && // vn is a func.
(funcAttr.m_func == (VNFunc)GT_ADD || funcAttr.m_func == (VNFunc)GT_SUB) && // the func is +/-
(IsVNArrLen(funcAttr.m_args[0]) || IsVNArrLen(funcAttr.m_args[1])); // either op1 or op2 is a.len
}
void ValueNumStore::GetArrLenArithInfo(ValueNum vn, ArrLenArithBoundInfo* info)
{
// Do we have a.len +/- var?
assert(IsVNArrLenArith(vn));
VNFuncApp funcArith;
GetVNFunc(vn, &funcArith);
bool isOp1ArrLen = IsVNArrLen(funcArith.m_args[1]);
if (isOp1ArrLen)
{
info->arrOper = funcArith.m_func;
info->arrOp = funcArith.m_args[0];
info->vnArray = GetArrForLenVn(funcArith.m_args[1]);
}
else
{
info->arrOper = funcArith.m_func;
info->arrOp = funcArith.m_args[1];
info->vnArray = GetArrForLenVn(funcArith.m_args[0]);
}
}
bool ValueNumStore::IsVNArrLenArithBound(ValueNum vn)
{
// Do we have: "var < a.len - var"
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
if (!GetVNFunc(vn, &funcAttr))
{
return false;
}
// Suitable comparator.
if (funcAttr.m_func != (VNFunc)GT_LE && funcAttr.m_func != (VNFunc)GT_GE && funcAttr.m_func != (VNFunc)GT_LT &&
funcAttr.m_func != (VNFunc)GT_GT)
{
return false;
}
// Either the op0 or op1 is arr len arithmetic.
if (!IsVNArrLenArith(funcAttr.m_args[0]) && !IsVNArrLenArith(funcAttr.m_args[1]))
{
return false;
}
return true;
}
void ValueNumStore::GetArrLenArithBoundInfo(ValueNum vn, ArrLenArithBoundInfo* info)
{
assert(IsVNArrLenArithBound(vn));
VNFuncApp funcAttr;
GetVNFunc(vn, &funcAttr);
// Check whether op0 or op1 ia arr len arithmetic.
bool isOp1ArrLenArith = IsVNArrLenArith(funcAttr.m_args[1]);
if (isOp1ArrLenArith)
{
info->cmpOper = funcAttr.m_func;
info->cmpOp = funcAttr.m_args[0];
GetArrLenArithInfo(funcAttr.m_args[1], info);
}
else
{
info->cmpOper = GenTree::SwapRelop((genTreeOps)funcAttr.m_func);
info->cmpOp = funcAttr.m_args[1];
GetArrLenArithInfo(funcAttr.m_args[0], info);
}
}
ValueNum ValueNumStore::GetArrForLenVn(ValueNum vn)
{
if (vn == NoVN)
{
return NoVN;
}
VNFuncApp funcAttr;
if (GetVNFunc(vn, &funcAttr) && funcAttr.m_func == (VNFunc)GT_ARR_LENGTH)
{
return funcAttr.m_args[0];
}
return NoVN;
}
bool ValueNumStore::IsVNNewArr(ValueNum vn, VNFuncApp* funcApp)
{
if (vn == NoVN)
{
return false;
}
bool result = false;
if (GetVNFunc(vn, funcApp))
{
result = (funcApp->m_func == VNF_JitNewArr) || (funcApp->m_func == VNF_JitReadyToRunNewArr);
}
return result;
}
int ValueNumStore::GetNewArrSize(ValueNum vn)
{
VNFuncApp funcApp;
if (IsVNNewArr(vn, &funcApp))
{
ValueNum arg1VN = funcApp.m_args[1];
if (IsVNConstant(arg1VN) && TypeOfVN(arg1VN) == TYP_INT)
{
return ConstantValue<int>(arg1VN);
}
}
return 0;
}
bool ValueNumStore::IsVNArrLen(ValueNum vn)
{
if (vn == NoVN)
{
return false;
}
VNFuncApp funcAttr;
return (GetVNFunc(vn, &funcAttr) && funcAttr.m_func == (VNFunc)GT_ARR_LENGTH);
}
ValueNum ValueNumStore::EvalMathFuncUnary(var_types typ, CorInfoIntrinsics gtMathFN, ValueNum arg0VN)
{
assert(arg0VN == VNNormVal(arg0VN));
// If the math intrinsic is not implemented by target-specific instructions, such as implemented
// by user calls, then don't do constant folding on it. This minimizes precision loss.
if (IsVNConstant(arg0VN) && Compiler::IsTargetIntrinsic(gtMathFN))
{
assert(varTypeIsFloating(TypeOfVN(arg0VN)));
if (typ == TYP_DOUBLE)
{
// Both operand and its result must be of the same floating point type.
assert(typ == TypeOfVN(arg0VN));
double arg0Val = GetConstantDouble(arg0VN);
double res = 0.0;
switch (gtMathFN)
{
case CORINFO_INTRINSIC_Sin:
res = sin(arg0Val);
break;
case CORINFO_INTRINSIC_Cos:
res = cos(arg0Val);
break;
case CORINFO_INTRINSIC_Sqrt:
res = sqrt(arg0Val);
break;
case CORINFO_INTRINSIC_Abs:
res = fabs(arg0Val);
break;
case CORINFO_INTRINSIC_Round:
res = FloatingPointUtils::round(arg0Val);
break;
default:
unreached(); // the above are the only math intrinsics at the time of this writing.
}
return VNForDoubleCon(res);
}
else if (typ == TYP_FLOAT)
{
// Both operand and its result must be of the same floating point type.
assert(typ == TypeOfVN(arg0VN));
float arg0Val = GetConstantSingle(arg0VN);
float res = 0.0f;
switch (gtMathFN)
{
case CORINFO_INTRINSIC_Sin:
res = sinf(arg0Val);
break;
case CORINFO_INTRINSIC_Cos:
res = cosf(arg0Val);
break;
case CORINFO_INTRINSIC_Sqrt:
res = sqrtf(arg0Val);
break;
case CORINFO_INTRINSIC_Abs:
res = fabsf(arg0Val);
break;
case CORINFO_INTRINSIC_Round:
res = FloatingPointUtils::round(arg0Val);
break;
default:
unreached(); // the above are the only math intrinsics at the time of this writing.
}
return VNForFloatCon(res);
}
else
{
// CORINFO_INTRINSIC_Round is currently the only intrinsic that takes floating-point arguments
// and that returns a non floating-point result.
assert(typ == TYP_INT);
assert(gtMathFN == CORINFO_INTRINSIC_Round);
int res = 0;
switch (TypeOfVN(arg0VN))
{
case TYP_DOUBLE:
{
double arg0Val = GetConstantDouble(arg0VN);
res = int(FloatingPointUtils::round(arg0Val));
break;
}
case TYP_FLOAT:
{
float arg0Val = GetConstantSingle(arg0VN);
res = int(FloatingPointUtils::round(arg0Val));
break;
}
default:
unreached();
}
return VNForIntCon(res);
}
}
else
{
assert(typ == TYP_DOUBLE || typ == TYP_FLOAT || (typ == TYP_INT && gtMathFN == CORINFO_INTRINSIC_Round));
VNFunc vnf = VNF_Boundary;
switch (gtMathFN)
{
case CORINFO_INTRINSIC_Sin:
vnf = VNF_Sin;
break;
case CORINFO_INTRINSIC_Cos:
vnf = VNF_Cos;
break;
case CORINFO_INTRINSIC_Sqrt:
vnf = VNF_Sqrt;
break;
case CORINFO_INTRINSIC_Abs:
vnf = VNF_Abs;
break;
case CORINFO_INTRINSIC_Round:
if (typ == TYP_DOUBLE)
{
vnf = VNF_RoundDouble;
}
else if (typ == TYP_FLOAT)
{
vnf = VNF_RoundFloat;
}
else if (typ == TYP_INT)
{
vnf = VNF_RoundInt;
}
else
{
noway_assert(!"Invalid INTRINSIC_Round");
}
break;
case CORINFO_INTRINSIC_Cosh:
vnf = VNF_Cosh;
break;
case CORINFO_INTRINSIC_Sinh:
vnf = VNF_Sinh;
break;
case CORINFO_INTRINSIC_Tan:
vnf = VNF_Tan;
break;
case CORINFO_INTRINSIC_Tanh:
vnf = VNF_Tanh;
break;
case CORINFO_INTRINSIC_Asin:
vnf = VNF_Asin;
break;
case CORINFO_INTRINSIC_Acos:
vnf = VNF_Acos;
break;
case CORINFO_INTRINSIC_Atan:
vnf = VNF_Atan;
break;
case CORINFO_INTRINSIC_Log10:
vnf = VNF_Log10;
break;
case CORINFO_INTRINSIC_Exp:
vnf = VNF_Exp;
break;
case CORINFO_INTRINSIC_Ceiling:
vnf = VNF_Ceiling;
break;
case CORINFO_INTRINSIC_Floor:
vnf = VNF_Floor;
break;
default:
unreached(); // the above are the only math intrinsics at the time of this writing.
}
return VNForFunc(typ, vnf, arg0VN);
}
}
ValueNum ValueNumStore::EvalMathFuncBinary(var_types typ, CorInfoIntrinsics gtMathFN, ValueNum arg0VN, ValueNum arg1VN)
{
assert(varTypeIsFloating(typ));
assert(arg0VN == VNNormVal(arg0VN));
assert(arg1VN == VNNormVal(arg1VN));
VNFunc vnf = VNF_Boundary;
// Currently, none of the binary math intrinsic are implemented by target-specific instructions.
// To minimize precision loss, do not do constant folding on them.
switch (gtMathFN)
{
case CORINFO_INTRINSIC_Atan2:
vnf = VNF_Atan2;
break;
case CORINFO_INTRINSIC_Pow:
vnf = VNF_Pow;
break;
default:
unreached(); // the above are the only binary math intrinsics at the time of this writing.
}
return VNForFunc(typ, vnf, arg0VN, arg1VN);
}
bool ValueNumStore::IsVNFunc(ValueNum vn)
{
if (vn == NoVN)
{
return false;
}
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
switch (c->m_attribs)
{
case CEA_NotAField:
case CEA_Func0:
case CEA_Func1:
case CEA_Func2:
case CEA_Func3:
case CEA_Func4:
return true;
default:
return false;
}
}
bool ValueNumStore::GetVNFunc(ValueNum vn, VNFuncApp* funcApp)
{
if (vn == NoVN)
{
return false;
}
Chunk* c = m_chunks.GetNoExpand(GetChunkNum(vn));
unsigned offset = ChunkOffset(vn);
assert(offset < c->m_numUsed);
switch (c->m_attribs)
{
case CEA_Func4:
{
VNDefFunc4Arg* farg4 = &reinterpret_cast<VNDefFunc4Arg*>(c->m_defs)[offset];
funcApp->m_func = farg4->m_func;
funcApp->m_arity = 4;
funcApp->m_args[0] = farg4->m_arg0;
funcApp->m_args[1] = farg4->m_arg1;
funcApp->m_args[2] = farg4->m_arg2;
funcApp->m_args[3] = farg4->m_arg3;
return true;
}
case CEA_Func3:
{
VNDefFunc3Arg* farg3 = &reinterpret_cast<VNDefFunc3Arg*>(c->m_defs)[offset];
funcApp->m_func = farg3->m_func;
funcApp->m_arity = 3;
funcApp->m_args[0] = farg3->m_arg0;
funcApp->m_args[1] = farg3->m_arg1;
funcApp->m_args[2] = farg3->m_arg2;
return true;
}
case CEA_Func2:
{
VNDefFunc2Arg* farg2 = &reinterpret_cast<VNDefFunc2Arg*>(c->m_defs)[offset];
funcApp->m_func = farg2->m_func;
funcApp->m_arity = 2;
funcApp->m_args[0] = farg2->m_arg0;
funcApp->m_args[1] = farg2->m_arg1;
return true;
}
case CEA_Func1:
{
VNDefFunc1Arg* farg1 = &reinterpret_cast<VNDefFunc1Arg*>(c->m_defs)[offset];
funcApp->m_func = farg1->m_func;
funcApp->m_arity = 1;
funcApp->m_args[0] = farg1->m_arg0;
return true;
}
case CEA_Func0:
{
VNDefFunc0Arg* farg0 = &reinterpret_cast<VNDefFunc0Arg*>(c->m_defs)[offset];
funcApp->m_func = farg0->m_func;
funcApp->m_arity = 0;
return true;
}
case CEA_NotAField:
{
funcApp->m_func = VNF_NotAField;
funcApp->m_arity = 0;
return true;
}
default:
return false;
}
}
ValueNum ValueNumStore::VNForRefInAddr(ValueNum vn)
{
var_types vnType = TypeOfVN(vn);
if (vnType == TYP_REF)
{
return vn;
}
// Otherwise...
assert(vnType == TYP_BYREF);
VNFuncApp funcApp;
if (GetVNFunc(vn, &funcApp))
{
assert(funcApp.m_arity == 2 && (funcApp.m_func == VNFunc(GT_ADD) || funcApp.m_func == VNFunc(GT_SUB)));
var_types vnArg0Type = TypeOfVN(funcApp.m_args[0]);
if (vnArg0Type == TYP_REF || vnArg0Type == TYP_BYREF)
{
return VNForRefInAddr(funcApp.m_args[0]);
}
else
{
assert(funcApp.m_func == VNFunc(GT_ADD) &&
(TypeOfVN(funcApp.m_args[1]) == TYP_REF || TypeOfVN(funcApp.m_args[1]) == TYP_BYREF));
return VNForRefInAddr(funcApp.m_args[1]);
}
}
else
{
assert(IsVNConstant(vn));
return vn;
}
}
bool ValueNumStore::VNIsValid(ValueNum vn)
{
ChunkNum cn = GetChunkNum(vn);
if (cn >= m_chunks.Size())
{
return false;
}
// Otherwise...
Chunk* c = m_chunks.GetNoExpand(cn);
return ChunkOffset(vn) < c->m_numUsed;
}
#ifdef DEBUG
void ValueNumStore::vnDump(Compiler* comp, ValueNum vn, bool isPtr)
{
printf(" {");
if (vn == NoVN)
{
printf("NoVN");
}
else if (IsVNHandle(vn))
{
ssize_t val = ConstantValue<ssize_t>(vn);
printf("Hnd const: 0x%p", dspPtr(val));
}
else if (IsVNConstant(vn))
{
var_types vnt = TypeOfVN(vn);
switch (vnt)
{
case TYP_BOOL:
case TYP_BYTE:
case TYP_UBYTE:
case TYP_CHAR:
case TYP_SHORT:
case TYP_USHORT:
case TYP_INT:
case TYP_UINT:
{
int val = ConstantValue<int>(vn);
if (isPtr)
{
printf("PtrCns[%p]", dspPtr(val));
}
else
{
printf("IntCns");
if ((val > -1000) && (val < 1000))
{
printf(" %ld", val);
}
else
{
printf(" 0x%X", val);
}
}
}
break;
case TYP_LONG:
case TYP_ULONG:
{
INT64 val = ConstantValue<INT64>(vn);
if (isPtr)
{
printf("LngPtrCns: 0x%p", dspPtr(val));
}
else
{
printf("LngCns: ");
if ((val > -1000) && (val < 1000))
{
printf(" %ld", val);
}
else if ((val & 0xFFFFFFFF00000000LL) == 0)
{
printf(" 0x%X", val);
}
else
{
printf(" 0x%llx", val);
}
}
}
break;
case TYP_FLOAT:
printf("FltCns[%f]", ConstantValue<float>(vn));
break;
case TYP_DOUBLE:
printf("DblCns[%f]", ConstantValue<double>(vn));
break;
case TYP_REF:
case TYP_ARRAY:
if (vn == VNForNull())
{
printf("null");
}
else if (vn == VNForVoid())
{
printf("void");
}
else
{
assert(vn == VNForZeroMap());
printf("zeroMap");
}
break;
case TYP_BYREF:
printf("byrefVal");
break;
case TYP_STRUCT:
#ifdef FEATURE_SIMD
case TYP_SIMD8:
case TYP_SIMD12:
case TYP_SIMD16:
case TYP_SIMD32:
#endif // FEATURE_SIMD
printf("structVal");
break;
// These should be unreached.
default:
unreached();
}
}
else if (IsVNArrLenBound(vn))
{
ArrLenArithBoundInfo info;
GetArrLenBoundInfo(vn, &info);
info.dump(this);
}
else if (IsVNArrLenArithBound(vn))
{
ArrLenArithBoundInfo info;
GetArrLenArithBoundInfo(vn, &info);
info.dump(this);
}
else if (IsVNFunc(vn))
{
VNFuncApp funcApp;
GetVNFunc(vn, &funcApp);
// A few special cases...
switch (funcApp.m_func)
{
case VNF_FieldSeq:
vnDumpFieldSeq(comp, &funcApp, true);
break;
case VNF_MapSelect:
vnDumpMapSelect(comp, &funcApp);
break;
case VNF_MapStore:
vnDumpMapStore(comp, &funcApp);
break;
default:
printf("%s(", VNFuncName(funcApp.m_func));
for (unsigned i = 0; i < funcApp.m_arity; i++)
{
if (i > 0)
{
printf(", ");
}
printf(STR_VN "%x", funcApp.m_args[i]);
#if FEATURE_VN_DUMP_FUNC_ARGS
printf("=");
vnDump(comp, funcApp.m_args[i]);
#endif
}
printf(")");
}
}
else
{
// Otherwise, just a VN with no structure; print just the VN.
printf("%x", vn);
}
printf("}");
}
void ValueNumStore::vnDumpFieldSeq(Compiler* comp, VNFuncApp* fieldSeq, bool isHead)
{
assert(fieldSeq->m_func == VNF_FieldSeq); // Precondition.
// First arg is the field handle VN.
assert(IsVNConstant(fieldSeq->m_args[0]) && TypeOfVN(fieldSeq->m_args[0]) == TYP_I_IMPL);
ssize_t fieldHndVal = ConstantValue<ssize_t>(fieldSeq->m_args[0]);
bool hasTail = (fieldSeq->m_args[1] != VNForNull());
if (isHead && hasTail)
{
printf("(");
}
CORINFO_FIELD_HANDLE fldHnd = CORINFO_FIELD_HANDLE(fieldHndVal);
if (fldHnd == FieldSeqStore::FirstElemPseudoField)
{
printf("#FirstElem");
}
else if (fldHnd == FieldSeqStore::ConstantIndexPseudoField)
{
printf("#ConstantIndex");
}
else
{
const char* modName;
const char* fldName = m_pComp->eeGetFieldName(fldHnd, &modName);
printf("%s", fldName);
}
if (hasTail)
{
printf(", ");
assert(IsVNFunc(fieldSeq->m_args[1]));
VNFuncApp tail;
GetVNFunc(fieldSeq->m_args[1], &tail);
vnDumpFieldSeq(comp, &tail, false);
}
if (isHead && hasTail)
{
printf(")");
}
}
void ValueNumStore::vnDumpMapSelect(Compiler* comp, VNFuncApp* mapSelect)
{
assert(mapSelect->m_func == VNF_MapSelect); // Precondition.
ValueNum mapVN = mapSelect->m_args[0]; // First arg is the map id
ValueNum indexVN = mapSelect->m_args[1]; // Second arg is the index
comp->vnPrint(mapVN, 0);
printf("[");
comp->vnPrint(indexVN, 0);
printf("]");
}
void ValueNumStore::vnDumpMapStore(Compiler* comp, VNFuncApp* mapStore)
{
assert(mapStore->m_func == VNF_MapStore); // Precondition.
ValueNum mapVN = mapStore->m_args[0]; // First arg is the map id
ValueNum indexVN = mapStore->m_args[1]; // Second arg is the index
ValueNum newValVN = mapStore->m_args[2]; // Third arg is the new value
comp->vnPrint(mapVN, 0);
printf("[");
comp->vnPrint(indexVN, 0);
printf(" := ");
comp->vnPrint(newValVN, 0);
printf("]");
}
#endif // DEBUG
// Static fields, methods.
static UINT8 vnfOpAttribs[VNF_COUNT];
static genTreeOps genTreeOpsIllegalAsVNFunc[] = {GT_IND, // When we do heap memory.
GT_NULLCHECK, GT_QMARK, GT_COLON, GT_LOCKADD, GT_XADD, GT_XCHG,
GT_CMPXCHG, GT_LCLHEAP, GT_BOX,
// These need special semantics:
GT_COMMA, // == second argument (but with exception(s) from first).
GT_ADDR, GT_ARR_BOUNDS_CHECK,
GT_OBJ, // May reference heap memory.
GT_BLK, // May reference heap memory.
GT_INIT_VAL, // Not strictly a pass-through.
// These control-flow operations need no values.
GT_JTRUE, GT_RETURN, GT_SWITCH, GT_RETFILT, GT_CKFINITE};
UINT8* ValueNumStore::s_vnfOpAttribs = nullptr;
void ValueNumStore::InitValueNumStoreStatics()
{
// Make sure we've gotten constants right...
assert(unsigned(VNFOA_Arity) == (1 << VNFOA_ArityShift));
assert(unsigned(VNFOA_AfterArity) == (unsigned(VNFOA_Arity) << VNFOA_ArityBits));
s_vnfOpAttribs = &vnfOpAttribs[0];
for (unsigned i = 0; i < GT_COUNT; i++)
{
genTreeOps gtOper = static_cast<genTreeOps>(i);
unsigned arity = 0;
if (GenTree::OperIsUnary(gtOper))
{
arity = 1;
}
else if (GenTree::OperIsBinary(gtOper))
{
arity = 2;
}
// Since GT_ARR_BOUNDS_CHECK is not currently GTK_BINOP
else if (gtOper == GT_ARR_BOUNDS_CHECK)
{
arity = 2;
}
vnfOpAttribs[i] |= (arity << VNFOA_ArityShift);
if (GenTree::OperIsCommutative(gtOper))
{
vnfOpAttribs[i] |= VNFOA_Commutative;
}
}
// I so wish this wasn't the best way to do this...
int vnfNum = VNF_Boundary + 1; // The macro definition below will update this after using it.
#define ValueNumFuncDef(vnf, arity, commute, knownNonNull, sharedStatic) \
if (commute) \
vnfOpAttribs[vnfNum] |= VNFOA_Commutative; \
if (knownNonNull) \
vnfOpAttribs[vnfNum] |= VNFOA_KnownNonNull; \
if (sharedStatic) \
vnfOpAttribs[vnfNum] |= VNFOA_SharedStatic; \
vnfOpAttribs[vnfNum] |= (arity << VNFOA_ArityShift); \
vnfNum++;
#include "valuenumfuncs.h"
#undef ValueNumFuncDef
unsigned n = sizeof(genTreeOpsIllegalAsVNFunc) / sizeof(genTreeOps);
for (unsigned i = 0; i < n; i++)
{
vnfOpAttribs[genTreeOpsIllegalAsVNFunc[i]] |= VNFOA_IllegalGenTreeOp;
}
}
#ifdef DEBUG
// Define the name array.
#define ValueNumFuncDef(vnf, arity, commute, knownNonNull, sharedStatic) #vnf,
const char* ValueNumStore::VNFuncNameArr[] = {
#include "valuenumfuncs.h"
#undef ValueNumFuncDef
};
// static
const char* ValueNumStore::VNFuncName(VNFunc vnf)
{
if (vnf < VNF_Boundary)
{
return GenTree::NodeName(genTreeOps(vnf));
}
else
{
return VNFuncNameArr[vnf - (VNF_Boundary + 1)];
}
}
static const char* s_reservedNameArr[] = {
"$VN.Recursive", // -2 RecursiveVN
"$VN.No", // -1 NoVN
"$VN.Null", // 0 VNForNull()
"$VN.ZeroMap", // 1 VNForZeroMap()
"$VN.ReadOnlyHeap", // 2 VNForROH()
"$VN.Void", // 3 VNForVoid()
"$VN.EmptyExcSet" // 4 VNForEmptyExcSet()
};
// Returns the string name of "vn" when it is a reserved value number, nullptr otherwise
// static
const char* ValueNumStore::reservedName(ValueNum vn)
{
int val = vn - ValueNumStore::RecursiveVN; // Add two, making 'RecursiveVN' equal to zero
int max = ValueNumStore::SRC_NumSpecialRefConsts - ValueNumStore::RecursiveVN;
if ((val >= 0) && (val < max))
{
return s_reservedNameArr[val];
}
return nullptr;
}
#endif // DEBUG
// Returns true if "vn" is a reserved value number
// static
bool ValueNumStore::isReservedVN(ValueNum vn)
{
int val = vn - ValueNumStore::RecursiveVN; // Adding two, making 'RecursiveVN' equal to zero
int max = ValueNumStore::SRC_NumSpecialRefConsts - ValueNumStore::RecursiveVN;
if ((val >= 0) && (val < max))
{
return true;
}
return false;
}
#ifdef DEBUG
void ValueNumStore::RunTests(Compiler* comp)
{
VNFunc VNF_Add = GenTreeOpToVNFunc(GT_ADD);
ValueNumStore* vns = new (comp->getAllocatorDebugOnly()) ValueNumStore(comp, comp->getAllocatorDebugOnly());
ValueNum vnNull = VNForNull();
assert(vnNull == VNForNull());
ValueNum vnFor1 = vns->VNForIntCon(1);
assert(vnFor1 == vns->VNForIntCon(1));
assert(vns->TypeOfVN(vnFor1) == TYP_INT);
assert(vns->IsVNConstant(vnFor1));
assert(vns->ConstantValue<int>(vnFor1) == 1);
ValueNum vnFor100 = vns->VNForIntCon(100);
assert(vnFor100 == vns->VNForIntCon(100));
assert(vnFor100 != vnFor1);
assert(vns->TypeOfVN(vnFor100) == TYP_INT);
assert(vns->IsVNConstant(vnFor100));
assert(vns->ConstantValue<int>(vnFor100) == 100);
ValueNum vnFor1F = vns->VNForFloatCon(1.0f);
assert(vnFor1F == vns->VNForFloatCon(1.0f));
assert(vnFor1F != vnFor1 && vnFor1F != vnFor100);
assert(vns->TypeOfVN(vnFor1F) == TYP_FLOAT);
assert(vns->IsVNConstant(vnFor1F));
assert(vns->ConstantValue<float>(vnFor1F) == 1.0f);
ValueNum vnFor1D = vns->VNForDoubleCon(1.0);
assert(vnFor1D == vns->VNForDoubleCon(1.0));
assert(vnFor1D != vnFor1F && vnFor1D != vnFor1 && vnFor1D != vnFor100);
assert(vns->TypeOfVN(vnFor1D) == TYP_DOUBLE);
assert(vns->IsVNConstant(vnFor1D));
assert(vns->ConstantValue<double>(vnFor1D) == 1.0);
ValueNum vnRandom1 = vns->VNForExpr(nullptr, TYP_INT);
ValueNum vnForFunc2a = vns->VNForFunc(TYP_INT, VNF_Add, vnFor1, vnRandom1);
assert(vnForFunc2a == vns->VNForFunc(TYP_INT, VNF_Add, vnFor1, vnRandom1));
assert(vnForFunc2a != vnFor1D && vnForFunc2a != vnFor1F && vnForFunc2a != vnFor1 && vnForFunc2a != vnRandom1);
assert(vns->TypeOfVN(vnForFunc2a) == TYP_INT);
assert(!vns->IsVNConstant(vnForFunc2a));
assert(vns->IsVNFunc(vnForFunc2a));
VNFuncApp fa2a;
bool b = vns->GetVNFunc(vnForFunc2a, &fa2a);
assert(b);
assert(fa2a.m_func == VNF_Add && fa2a.m_arity == 2 && fa2a.m_args[0] == vnFor1 && fa2a.m_args[1] == vnRandom1);
ValueNum vnForFunc2b = vns->VNForFunc(TYP_INT, VNF_Add, vnFor1, vnFor100);
assert(vnForFunc2b == vns->VNForFunc(TYP_INT, VNF_Add, vnFor1, vnFor100));
assert(vnForFunc2b != vnFor1D && vnForFunc2b != vnFor1F && vnForFunc2b != vnFor1 && vnForFunc2b != vnFor100);
assert(vns->TypeOfVN(vnForFunc2b) == TYP_INT);
assert(vns->IsVNConstant(vnForFunc2b));
assert(vns->ConstantValue<int>(vnForFunc2b) == 101);
// printf("Did ValueNumStore::RunTests.\n");
}
#endif // DEBUG
typedef ExpandArrayStack<BasicBlock*> BlockStack;
// This represents the "to do" state of the value number computation.
struct ValueNumberState
{
// These two stacks collectively represent the set of blocks that are candidates for
// processing, because at least one predecessor has been processed. Blocks on "m_toDoAllPredsDone"
// have had *all* predecessors processed, and thus are candidates for some extra optimizations.
// Blocks on "m_toDoNotAllPredsDone" have at least one predecessor that has not been processed.
// Blocks are initially on "m_toDoNotAllPredsDone" may be moved to "m_toDoAllPredsDone" when their last
// unprocessed predecessor is processed, thus maintaining the invariants.
BlockStack m_toDoAllPredsDone;
BlockStack m_toDoNotAllPredsDone;
Compiler* m_comp;
// TBD: This should really be a bitset...
// For now:
// first bit indicates completed,
// second bit indicates that it's been pushed on all-done stack,
// third bit indicates that it's been pushed on not-all-done stack.
BYTE* m_visited;
enum BlockVisitBits
{
BVB_complete = 0x1,
BVB_onAllDone = 0x2,
BVB_onNotAllDone = 0x4,
};
bool GetVisitBit(unsigned bbNum, BlockVisitBits bvb)
{
return (m_visited[bbNum] & bvb) != 0;
}
void SetVisitBit(unsigned bbNum, BlockVisitBits bvb)
{
m_visited[bbNum] |= bvb;
}
ValueNumberState(Compiler* comp)
: m_toDoAllPredsDone(comp->getAllocator(), /*minSize*/ 4)
, m_toDoNotAllPredsDone(comp->getAllocator(), /*minSize*/ 4)
, m_comp(comp)
, m_visited(new (comp, CMK_ValueNumber) BYTE[comp->fgBBNumMax + 1]())
{
}
BasicBlock* ChooseFromNotAllPredsDone()
{
assert(m_toDoAllPredsDone.Size() == 0);
// If we have no blocks with all preds done, then (ideally, if all cycles have been captured by loops)
// we must have at least one block within a loop. We want to do the loops first. Doing a loop entry block
// should break the cycle, making the rest of the body of the loop (unless there's a nested loop) doable by the
// all-preds-done rule. If several loop entry blocks are available, at least one should have all non-loop preds
// done -- we choose that.
for (unsigned i = 0; i < m_toDoNotAllPredsDone.Size(); i++)
{
BasicBlock* cand = m_toDoNotAllPredsDone.Get(i);
// Skip any already-completed blocks (a block may have all its preds finished, get added to the
// all-preds-done todo set, and get processed there). Do this by moving the last one down, to
// keep the array compact.
while (GetVisitBit(cand->bbNum, BVB_complete))
{
if (i + 1 < m_toDoNotAllPredsDone.Size())
{
cand = m_toDoNotAllPredsDone.Pop();
m_toDoNotAllPredsDone.Set(i, cand);
}
else
{
// "cand" is the last element; delete it.
(void)m_toDoNotAllPredsDone.Pop();
break;
}
}
// We may have run out of non-complete candidates above. If so, we're done.
if (i == m_toDoNotAllPredsDone.Size())
{
break;
}
// See if "cand" is a loop entry.
unsigned lnum;
if (m_comp->optBlockIsLoopEntry(cand, &lnum))
{
// "lnum" is the innermost loop of which "cand" is the entry; find the outermost.
unsigned lnumPar = m_comp->optLoopTable[lnum].lpParent;
while (lnumPar != BasicBlock::NOT_IN_LOOP)
{
if (m_comp->optLoopTable[lnumPar].lpEntry == cand)
{
lnum = lnumPar;
}
else
{
break;
}
lnumPar = m_comp->optLoopTable[lnumPar].lpParent;
}
bool allNonLoopPredsDone = true;
for (flowList* pred = m_comp->BlockPredsWithEH(cand); pred != nullptr; pred = pred->flNext)
{
BasicBlock* predBlock = pred->flBlock;
if (!m_comp->optLoopTable[lnum].lpContains(predBlock))
{
if (!GetVisitBit(predBlock->bbNum, BVB_complete))
{
allNonLoopPredsDone = false;
}
}
}
if (allNonLoopPredsDone)
{
return cand;
}
}
}
// If we didn't find a loop entry block with all non-loop preds done above, then return a random member (if
// there is one).
if (m_toDoNotAllPredsDone.Size() == 0)
{
return nullptr;
}
else
{
return m_toDoNotAllPredsDone.Pop();
}
}
// Debugging output that is too detailed for a normal JIT dump...
#define DEBUG_VN_VISIT 0
// Record that "blk" has been visited, and add any unvisited successors of "blk" to the appropriate todo set.
void FinishVisit(BasicBlock* blk)
{
#ifdef DEBUG_VN_VISIT
JITDUMP("finish(BB%02u).\n", blk->bbNum);
#endif // DEBUG_VN_VISIT
SetVisitBit(blk->bbNum, BVB_complete);
AllSuccessorIter succsEnd = blk->GetAllSuccs(m_comp).end();
for (AllSuccessorIter succs = blk->GetAllSuccs(m_comp).begin(); succs != succsEnd; ++succs)
{
BasicBlock* succ = (*succs);
#ifdef DEBUG_VN_VISIT
JITDUMP(" Succ(BB%02u).\n", succ->bbNum);
#endif // DEBUG_VN_VISIT
if (GetVisitBit(succ->bbNum, BVB_complete))
{
continue;
}
#ifdef DEBUG_VN_VISIT
JITDUMP(" Not yet completed.\n");
#endif // DEBUG_VN_VISIT
bool allPredsVisited = true;
for (flowList* pred = m_comp->BlockPredsWithEH(succ); pred != nullptr; pred = pred->flNext)
{
BasicBlock* predBlock = pred->flBlock;
if (!GetVisitBit(predBlock->bbNum, BVB_complete))
{
allPredsVisited = false;
break;
}
}
if (allPredsVisited)
{
#ifdef DEBUG_VN_VISIT
JITDUMP(" All preds complete, adding to allDone.\n");
#endif // DEBUG_VN_VISIT
assert(!GetVisitBit(succ->bbNum, BVB_onAllDone)); // Only last completion of last succ should add to
// this.
m_toDoAllPredsDone.Push(succ);
SetVisitBit(succ->bbNum, BVB_onAllDone);
}
else
{
#ifdef DEBUG_VN_VISIT
JITDUMP(" Not all preds complete Adding to notallDone, if necessary...\n");
#endif // DEBUG_VN_VISIT
if (!GetVisitBit(succ->bbNum, BVB_onNotAllDone))
{
#ifdef DEBUG_VN_VISIT
JITDUMP(" Was necessary.\n");
#endif // DEBUG_VN_VISIT
m_toDoNotAllPredsDone.Push(succ);
SetVisitBit(succ->bbNum, BVB_onNotAllDone);
}
}
}
}
bool ToDoExists()
{
return m_toDoAllPredsDone.Size() > 0 || m_toDoNotAllPredsDone.Size() > 0;
}
};
void Compiler::fgValueNumber()
{
#ifdef DEBUG
// This could be a JITDUMP, but some people find it convenient to set a breakpoint on the printf.
if (verbose)
{
printf("\n*************** In fgValueNumber()\n");
}
#endif
// If we skipped SSA, skip VN as well.
if (fgSsaPassesCompleted == 0)
{
return;
}
// Allocate the value number store.
assert(fgVNPassesCompleted > 0 || vnStore == nullptr);
if (fgVNPassesCompleted == 0)
{
CompAllocator* allocator = new (this, CMK_ValueNumber) CompAllocator(this, CMK_ValueNumber);
vnStore = new (this, CMK_ValueNumber) ValueNumStore(this, allocator);
}
else
{
ValueNumPair noVnp;
// Make sure the memory SSA names have no value numbers.
for (unsigned i = 0; i < lvMemoryNumSsaNames; i++)
{
lvMemoryPerSsaData.GetRef(i).m_vnPair = noVnp;
}
for (BasicBlock* blk = fgFirstBB; blk != nullptr; blk = blk->bbNext)
{
// Now iterate over the block's statements, and their trees.
for (GenTreePtr stmts = blk->FirstNonPhiDef(); stmts != nullptr; stmts = stmts->gtNext)
{
assert(stmts->IsStatement());
for (GenTreePtr tree = stmts->gtStmt.gtStmtList; tree; tree = tree->gtNext)
{
tree->gtVNPair.SetBoth(ValueNumStore::NoVN);
}
}
}
}
// Compute the side effects of loops.
optComputeLoopSideEffects();
// At the block level, we will use a modified worklist algorithm. We will have two
// "todo" sets of unvisited blocks. Blocks (other than the entry block) are put in a
// todo set only when some predecessor has been visited, so all blocks have at least one
// predecessor visited. The distinction between the two sets is whether *all* predecessors have
// already been visited. We visit such blocks preferentially if they exist, since phi definitions
// in such blocks will have all arguments defined, enabling a simplification in the case that all
// arguments to the phi have the same VN. If no such blocks exist, we pick a block with at least
// one unvisited predecessor. In this case, we assign a new VN for phi definitions.
// Start by giving incoming arguments value numbers.
// Also give must-init vars a zero of their type.
for (unsigned i = 0; i < lvaCount; i++)
{
LclVarDsc* varDsc = &lvaTable[i];
if (varDsc->lvIsParam)
{
// We assume that code equivalent to this variable initialization loop
// has been performed when doing SSA naming, so that all the variables we give
// initial VNs to here have been given initial SSA definitions there.
// SSA numbers always start from FIRST_SSA_NUM, and we give the value number to SSA name FIRST_SSA_NUM.
// We use the VNF_InitVal(i) from here so we know that this value is loop-invariant
// in all loops.
ValueNum initVal = vnStore->VNForFunc(varDsc->TypeGet(), VNF_InitVal, vnStore->VNForIntCon(i));
LclSsaVarDsc* ssaDef = varDsc->GetPerSsaData(SsaConfig::FIRST_SSA_NUM);
ssaDef->m_vnPair.SetBoth(initVal);
ssaDef->m_defLoc.m_blk = fgFirstBB;
}
else if (info.compInitMem || varDsc->lvMustInit ||
(varDsc->lvTracked && VarSetOps::IsMember(this, fgFirstBB->bbLiveIn, varDsc->lvVarIndex)))
{
// The last clause covers the use-before-def variables (the ones that are live-in to the the first block),
// these are variables that are read before being initialized (at least on some control flow paths)
// if they are not must-init, then they get VNF_InitVal(i), as with the param case.)
bool isZeroed = (info.compInitMem || varDsc->lvMustInit);
ValueNum initVal = ValueNumStore::NoVN; // We must assign a new value to initVal
var_types typ = varDsc->TypeGet();
switch (typ)
{
case TYP_LCLBLK: // The outgoing args area for arm and x64
case TYP_BLK: // A blob of memory
// TYP_BLK is used for the EHSlots LclVar on x86 (aka shadowSPslotsVar)
// and for the lvaInlinedPInvokeFrameVar on x64, arm and x86
// The stack associated with these LclVars are not zero initialized
// thus we set 'initVN' to a new, unique VN.
//
initVal = vnStore->VNForExpr(fgFirstBB);
break;
case TYP_BYREF:
if (isZeroed)
{
// LclVars of TYP_BYREF can be zero-inited.
initVal = vnStore->VNForByrefCon(0);
}
else
{
// Here we have uninitialized TYP_BYREF
initVal = vnStore->VNForFunc(typ, VNF_InitVal, vnStore->VNForIntCon(i));
}
break;
default:
if (isZeroed)
{
// By default we will zero init these LclVars
initVal = vnStore->VNZeroForType(typ);
}
else
{
initVal = vnStore->VNForFunc(typ, VNF_InitVal, vnStore->VNForIntCon(i));
}
break;
}
#ifdef _TARGET_X86_
bool isVarargParam = (i == lvaVarargsBaseOfStkArgs || i == lvaVarargsHandleArg);
if (isVarargParam)
initVal = vnStore->VNForExpr(fgFirstBB); // a new, unique VN.
#endif
assert(initVal != ValueNumStore::NoVN);
LclSsaVarDsc* ssaDef = varDsc->GetPerSsaData(SsaConfig::FIRST_SSA_NUM);
ssaDef->m_vnPair.SetBoth(initVal);
ssaDef->m_defLoc.m_blk = fgFirstBB;
}
}
// Give memory an initial value number (about which we know nothing).
ValueNum memoryInitVal = vnStore->VNForFunc(TYP_REF, VNF_InitVal, vnStore->VNForIntCon(-1)); // Use -1 for memory.
GetMemoryPerSsaData(SsaConfig::FIRST_SSA_NUM)->m_vnPair.SetBoth(memoryInitVal);
#ifdef DEBUG
if (verbose)
{
printf("Memory Initial Value in BB01 is: " STR_VN "%x\n", memoryInitVal);
}
#endif // DEBUG
ValueNumberState vs(this);
// Push the first block. This has no preds.
vs.m_toDoAllPredsDone.Push(fgFirstBB);
while (vs.ToDoExists())
{
while (vs.m_toDoAllPredsDone.Size() > 0)
{
BasicBlock* toDo = vs.m_toDoAllPredsDone.Pop();
fgValueNumberBlock(toDo);
// Record that we've visited "toDo", and add successors to the right sets.
vs.FinishVisit(toDo);
}
// OK, we've run out of blocks whose predecessors are done. Pick one whose predecessors are not all done,
// process that. This may make more "all-done" blocks, so we'll go around the outer loop again --
// note that this is an "if", not a "while" loop.
if (vs.m_toDoNotAllPredsDone.Size() > 0)
{
BasicBlock* toDo = vs.ChooseFromNotAllPredsDone();
if (toDo == nullptr)
{
continue; // We may have run out, because of completed blocks on the not-all-preds done list.
}
fgValueNumberBlock(toDo);
// Record that we've visited "toDo", and add successors to the right sest.
vs.FinishVisit(toDo);
}
}
#ifdef DEBUG
JitTestCheckVN();
#endif // DEBUG
fgVNPassesCompleted++;
}
void Compiler::fgValueNumberBlock(BasicBlock* blk)
{
compCurBB = blk;
#ifdef DEBUG
compCurStmtNum = blk->bbStmtNum - 1; // Set compCurStmtNum
#endif
unsigned outerLoopNum = BasicBlock::NOT_IN_LOOP;
// First: visit phi's. If "newVNForPhis", give them new VN's. If not,
// first check to see if all phi args have the same value.
GenTreePtr firstNonPhi = blk->FirstNonPhiDef();
for (GenTreePtr phiDefs = blk->bbTreeList; phiDefs != firstNonPhi; phiDefs = phiDefs->gtNext)
{
// TODO-Cleanup: It has been proposed that we should have an IsPhiDef predicate. We would use it
// in Block::FirstNonPhiDef as well.
GenTreePtr phiDef = phiDefs->gtStmt.gtStmtExpr;
assert(phiDef->OperGet() == GT_ASG);
GenTreeLclVarCommon* newSsaVar = phiDef->gtOp.gtOp1->AsLclVarCommon();
ValueNumPair phiAppVNP;
ValueNumPair sameVNPair;
GenTreePtr phiFunc = phiDef->gtOp.gtOp2;
// At this point a GT_PHI node should never have a nullptr for gtOp1
// and the gtOp1 should always be a GT_LIST node.
GenTreePtr phiOp1 = phiFunc->gtOp.gtOp1;
noway_assert(phiOp1 != nullptr);
noway_assert(phiOp1->OperGet() == GT_LIST);
GenTreeArgList* phiArgs = phiFunc->gtOp.gtOp1->AsArgList();
// A GT_PHI node should have more than one argument.
noway_assert(phiArgs->Rest() != nullptr);
GenTreeLclVarCommon* phiArg = phiArgs->Current()->AsLclVarCommon();
phiArgs = phiArgs->Rest();
phiAppVNP.SetBoth(vnStore->VNForIntCon(phiArg->gtSsaNum));
bool allSameLib = true;
bool allSameCons = true;
sameVNPair = lvaTable[phiArg->gtLclNum].GetPerSsaData(phiArg->gtSsaNum)->m_vnPair;
if (!sameVNPair.BothDefined())
{
allSameLib = false;
allSameCons = false;
}
while (phiArgs != nullptr)
{
phiArg = phiArgs->Current()->AsLclVarCommon();
// Set the VN of the phi arg.
phiArg->gtVNPair = lvaTable[phiArg->gtLclNum].GetPerSsaData(phiArg->gtSsaNum)->m_vnPair;
if (phiArg->gtVNPair.BothDefined())
{
if (phiArg->gtVNPair.GetLiberal() != sameVNPair.GetLiberal())
{
allSameLib = false;
}
if (phiArg->gtVNPair.GetConservative() != sameVNPair.GetConservative())
{
allSameCons = false;
}
}
else
{
allSameLib = false;
allSameCons = false;
}
ValueNumPair phiArgSsaVNP;
phiArgSsaVNP.SetBoth(vnStore->VNForIntCon(phiArg->gtSsaNum));
phiAppVNP = vnStore->VNPairForFunc(newSsaVar->TypeGet(), VNF_Phi, phiArgSsaVNP, phiAppVNP);
phiArgs = phiArgs->Rest();
}
ValueNumPair newVNPair;
if (allSameLib)
{
newVNPair.SetLiberal(sameVNPair.GetLiberal());
}
else
{
newVNPair.SetLiberal(phiAppVNP.GetLiberal());
}
if (allSameCons)
{
newVNPair.SetConservative(sameVNPair.GetConservative());
}
else
{
newVNPair.SetConservative(phiAppVNP.GetConservative());
}
LclSsaVarDsc* newSsaVarDsc = lvaTable[newSsaVar->gtLclNum].GetPerSsaData(newSsaVar->GetSsaNum());
// If all the args of the phi had the same value(s, liberal and conservative), then there wasn't really
// a reason to have the phi -- just pass on that value.
if (allSameLib && allSameCons)
{
newSsaVarDsc->m_vnPair = newVNPair;
#ifdef DEBUG
if (verbose)
{
printf("In SSA definition, incoming phi args all same, set VN of local %d/%d to ",
newSsaVar->GetLclNum(), newSsaVar->GetSsaNum());
vnpPrint(newVNPair, 1);
printf(".\n");
}
#endif // DEBUG
}
else
{
// They were not the same; we need to create a phi definition.
ValueNumPair lclNumVNP;
lclNumVNP.SetBoth(ValueNum(newSsaVar->GetLclNum()));
ValueNumPair ssaNumVNP;
ssaNumVNP.SetBoth(ValueNum(newSsaVar->GetSsaNum()));
ValueNumPair vnPhiDef =
vnStore->VNPairForFunc(newSsaVar->TypeGet(), VNF_PhiDef, lclNumVNP, ssaNumVNP, phiAppVNP);
newSsaVarDsc->m_vnPair = vnPhiDef;
#ifdef DEBUG
if (verbose)
{
printf("SSA definition: set VN of local %d/%d to ", newSsaVar->GetLclNum(), newSsaVar->GetSsaNum());
vnpPrint(vnPhiDef, 1);
printf(".\n");
}
#endif // DEBUG
}
}
// Now do the same for each MemoryKind.
for (MemoryKind memoryKind : allMemoryKinds())
{
// Is there a phi for this block?
if (blk->bbMemorySsaPhiFunc[memoryKind] == nullptr)
{
fgCurMemoryVN[memoryKind] = GetMemoryPerSsaData(blk->bbMemorySsaNumIn[memoryKind])->m_vnPair.GetLiberal();
assert(fgCurMemoryVN[memoryKind] != ValueNumStore::NoVN);
}
else
{
if ((memoryKind == ByrefExposed) && byrefStatesMatchGcHeapStates)
{
// The update for GcHeap will copy its result to ByrefExposed.
assert(memoryKind < GcHeap);
assert(blk->bbMemorySsaPhiFunc[memoryKind] == blk->bbMemorySsaPhiFunc[GcHeap]);
continue;
}
unsigned loopNum;
ValueNum newMemoryVN;
if (optBlockIsLoopEntry(blk, &loopNum))
{
newMemoryVN = fgMemoryVNForLoopSideEffects(memoryKind, blk, loopNum);
}
else
{
// Are all the VN's the same?
BasicBlock::MemoryPhiArg* phiArgs = blk->bbMemorySsaPhiFunc[memoryKind];
assert(phiArgs != BasicBlock::EmptyMemoryPhiDef);
// There should be > 1 args to a phi.
assert(phiArgs->m_nextArg != nullptr);
ValueNum phiAppVN = vnStore->VNForIntCon(phiArgs->GetSsaNum());
JITDUMP(" Building phi application: $%x = SSA# %d.\n", phiAppVN, phiArgs->GetSsaNum());
bool allSame = true;
ValueNum sameVN = GetMemoryPerSsaData(phiArgs->GetSsaNum())->m_vnPair.GetLiberal();
if (sameVN == ValueNumStore::NoVN)
{
allSame = false;
}
phiArgs = phiArgs->m_nextArg;
while (phiArgs != nullptr)
{
ValueNum phiArgVN = GetMemoryPerSsaData(phiArgs->GetSsaNum())->m_vnPair.GetLiberal();
if (phiArgVN == ValueNumStore::NoVN || phiArgVN != sameVN)
{
allSame = false;
}
#ifdef DEBUG
ValueNum oldPhiAppVN = phiAppVN;
#endif
unsigned phiArgSSANum = phiArgs->GetSsaNum();
ValueNum phiArgSSANumVN = vnStore->VNForIntCon(phiArgSSANum);
JITDUMP(" Building phi application: $%x = SSA# %d.\n", phiArgSSANumVN, phiArgSSANum);
phiAppVN = vnStore->VNForFunc(TYP_REF, VNF_Phi, phiArgSSANumVN, phiAppVN);
JITDUMP(" Building phi application: $%x = phi($%x, $%x).\n", phiAppVN, phiArgSSANumVN,
oldPhiAppVN);
phiArgs = phiArgs->m_nextArg;
}
if (allSame)
{
newMemoryVN = sameVN;
}
else
{
newMemoryVN =
vnStore->VNForFunc(TYP_REF, VNF_PhiMemoryDef, vnStore->VNForHandle(ssize_t(blk), 0), phiAppVN);
}
}
GetMemoryPerSsaData(blk->bbMemorySsaNumIn[memoryKind])->m_vnPair.SetLiberal(newMemoryVN);
fgCurMemoryVN[memoryKind] = newMemoryVN;
if ((memoryKind == GcHeap) && byrefStatesMatchGcHeapStates)
{
// Keep the CurMemoryVNs in sync
fgCurMemoryVN[ByrefExposed] = newMemoryVN;
}
}
#ifdef DEBUG
if (verbose)
{
printf("The SSA definition for %s (#%d) at start of BB%02u is ", memoryKindNames[memoryKind],
blk->bbMemorySsaNumIn[memoryKind], blk->bbNum);
vnPrint(fgCurMemoryVN[memoryKind], 1);
printf("\n");
}
#endif // DEBUG
}
// Now iterate over the remaining statements, and their trees.
for (GenTreePtr stmt = firstNonPhi; stmt != nullptr; stmt = stmt->gtNext)
{
assert(stmt->IsStatement());
#ifdef DEBUG
compCurStmtNum++;
if (verbose)
{
printf("\n***** BB%02u, stmt %d (before)\n", blk->bbNum, compCurStmtNum);
gtDispTree(stmt->gtStmt.gtStmtExpr);
printf("\n");
}
#endif
for (GenTreePtr tree = stmt->gtStmt.gtStmtList; tree; tree = tree->gtNext)
{
fgValueNumberTree(tree);
}
#ifdef DEBUG
if (verbose)
{
printf("\n***** BB%02u, stmt %d (after)\n", blk->bbNum, compCurStmtNum);
gtDispTree(stmt->gtStmt.gtStmtExpr);
printf("\n");
if (stmt->gtNext)
{
printf("---------\n");
}
}
#endif
}
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((memoryKind == GcHeap) && byrefStatesMatchGcHeapStates)
{
// The update to the shared SSA data will have already happened for ByrefExposed.
assert(memoryKind > ByrefExposed);
assert(blk->bbMemorySsaNumOut[memoryKind] == blk->bbMemorySsaNumOut[ByrefExposed]);
assert(GetMemoryPerSsaData(blk->bbMemorySsaNumOut[memoryKind])->m_vnPair.GetLiberal() ==
fgCurMemoryVN[memoryKind]);
continue;
}
if (blk->bbMemorySsaNumOut[memoryKind] != blk->bbMemorySsaNumIn[memoryKind])
{
GetMemoryPerSsaData(blk->bbMemorySsaNumOut[memoryKind])->m_vnPair.SetLiberal(fgCurMemoryVN[memoryKind]);
}
}
compCurBB = nullptr;
}
ValueNum Compiler::fgMemoryVNForLoopSideEffects(MemoryKind memoryKind,
BasicBlock* entryBlock,
unsigned innermostLoopNum)
{
// "loopNum" is the innermost loop for which "blk" is the entry; find the outermost one.
assert(innermostLoopNum != BasicBlock::NOT_IN_LOOP);
unsigned loopsInNest = innermostLoopNum;
unsigned loopNum = innermostLoopNum;
while (loopsInNest != BasicBlock::NOT_IN_LOOP)
{
if (optLoopTable[loopsInNest].lpEntry != entryBlock)
{
break;
}
loopNum = loopsInNest;
loopsInNest = optLoopTable[loopsInNest].lpParent;
}
#ifdef DEBUG
if (verbose)
{
printf("Computing %s state for block BB%02u, entry block for loops %d to %d:\n", memoryKindNames[memoryKind],
entryBlock->bbNum, innermostLoopNum, loopNum);
}
#endif // DEBUG
// If this loop has memory havoc effects, just use a new, unique VN.
if (optLoopTable[loopNum].lpLoopHasMemoryHavoc[memoryKind])
{
ValueNum res = vnStore->VNForExpr(entryBlock, TYP_REF);
#ifdef DEBUG
if (verbose)
{
printf(" Loop %d has memory havoc effect; heap state is new fresh $%x.\n", loopNum, res);
}
#endif // DEBUG
return res;
}
// Otherwise, find the predecessors of the entry block that are not in the loop.
// If there is only one such, use its memory value as the "base." If more than one,
// use a new unique VN.
BasicBlock* nonLoopPred = nullptr;
bool multipleNonLoopPreds = false;
for (flowList* pred = BlockPredsWithEH(entryBlock); pred != nullptr; pred = pred->flNext)
{
BasicBlock* predBlock = pred->flBlock;
if (!optLoopTable[loopNum].lpContains(predBlock))
{
if (nonLoopPred == nullptr)
{
nonLoopPred = predBlock;
}
else
{
#ifdef DEBUG
if (verbose)
{
printf(" Entry block has >1 non-loop preds: (at least) BB%02u and BB%02u.\n", nonLoopPred->bbNum,
predBlock->bbNum);
}
#endif // DEBUG
multipleNonLoopPreds = true;
break;
}
}
}
if (multipleNonLoopPreds)
{
ValueNum res = vnStore->VNForExpr(entryBlock, TYP_REF);
#ifdef DEBUG
if (verbose)
{
printf(" Therefore, memory state is new, fresh $%x.\n", res);
}
#endif // DEBUG
return res;
}
// Otherwise, there is a single non-loop pred.
assert(nonLoopPred != nullptr);
// What is its memory post-state?
ValueNum newMemoryVN = GetMemoryPerSsaData(nonLoopPred->bbMemorySsaNumOut[memoryKind])->m_vnPair.GetLiberal();
assert(newMemoryVN !=
ValueNumStore::NoVN); // We must have processed the single non-loop pred before reaching the loop entry.
#ifdef DEBUG
if (verbose)
{
printf(" Init %s state is $%x, with new, fresh VN at:\n", memoryKindNames[memoryKind], newMemoryVN);
}
#endif // DEBUG
// Modify "base" by setting all the modified fields/field maps/array maps to unknown values.
// These annotations apply specifically to the GcHeap, where we disambiguate across such stores.
if (memoryKind == GcHeap)
{
// First the fields/field maps.
Compiler::LoopDsc::FieldHandleSet* fieldsMod = optLoopTable[loopNum].lpFieldsModified;
if (fieldsMod != nullptr)
{
for (Compiler::LoopDsc::FieldHandleSet::KeyIterator ki = fieldsMod->Begin(); !ki.Equal(fieldsMod->End());
++ki)
{
CORINFO_FIELD_HANDLE fldHnd = ki.Get();
ValueNum fldHndVN = vnStore->VNForHandle(ssize_t(fldHnd), GTF_ICON_FIELD_HDL);
#ifdef DEBUG
if (verbose)
{
const char* modName;
const char* fldName = eeGetFieldName(fldHnd, &modName);
printf(" VNForHandle(Fseq[%s]) is " STR_VN "%x\n", fldName, fldHndVN);
printf(" fgCurMemoryVN assigned:\n");
}
#endif // DEBUG
newMemoryVN =
vnStore->VNForMapStore(TYP_REF, newMemoryVN, fldHndVN, vnStore->VNForExpr(entryBlock, TYP_REF));
}
}
// Now do the array maps.
Compiler::LoopDsc::ClassHandleSet* elemTypesMod = optLoopTable[loopNum].lpArrayElemTypesModified;
if (elemTypesMod != nullptr)
{
for (Compiler::LoopDsc::ClassHandleSet::KeyIterator ki = elemTypesMod->Begin();
!ki.Equal(elemTypesMod->End()); ++ki)
{
CORINFO_CLASS_HANDLE elemClsHnd = ki.Get();
#ifdef DEBUG
if (verbose)
{
var_types elemTyp = DecodeElemType(elemClsHnd);
if (varTypeIsStruct(elemTyp))
{
printf(" Array map %s[]\n", eeGetClassName(elemClsHnd));
}
else
{
printf(" Array map %s[]\n", varTypeName(elemTyp));
}
printf(" fgCurMemoryVN assigned:\n");
}
#endif // DEBUG
ValueNum elemTypeVN = vnStore->VNForHandle(ssize_t(elemClsHnd), GTF_ICON_CLASS_HDL);
ValueNum uniqueVN = vnStore->VNForExpr(entryBlock, TYP_REF);
newMemoryVN = vnStore->VNForMapStore(TYP_REF, newMemoryVN, elemTypeVN, uniqueVN);
}
}
}
else
{
// If there were any fields/elements modified, this should have been recorded as havoc
// for ByrefExposed.
assert(memoryKind == ByrefExposed);
assert((optLoopTable[loopNum].lpFieldsModified == nullptr) ||
optLoopTable[loopNum].lpLoopHasMemoryHavoc[memoryKind]);
assert((optLoopTable[loopNum].lpArrayElemTypesModified == nullptr) ||
optLoopTable[loopNum].lpLoopHasMemoryHavoc[memoryKind]);
}
#ifdef DEBUG
if (verbose)
{
printf(" Final %s state is $%x.\n", memoryKindNames[memoryKind], newMemoryVN);
}
#endif // DEBUG
return newMemoryVN;
}
void Compiler::fgMutateGcHeap(GenTreePtr tree DEBUGARG(const char* msg))
{
// Update the current memory VN, and if we're tracking the heap SSA # caused by this node, record it.
recordGcHeapStore(tree, vnStore->VNForExpr(compCurBB, TYP_REF) DEBUGARG(msg));
}
void Compiler::fgMutateAddressExposedLocal(GenTreePtr tree DEBUGARG(const char* msg))
{
// Update the current ByrefExposed VN, and if we're tracking the heap SSA # caused by this node, record it.
recordAddressExposedLocalStore(tree, vnStore->VNForExpr(compCurBB) DEBUGARG(msg));
}
void Compiler::recordGcHeapStore(GenTreePtr curTree, ValueNum gcHeapVN DEBUGARG(const char* msg))
{
// bbMemoryDef must include GcHeap for any block that mutates the GC Heap
// and GC Heap mutations are also ByrefExposed mutations
assert((compCurBB->bbMemoryDef & memoryKindSet(GcHeap, ByrefExposed)) == memoryKindSet(GcHeap, ByrefExposed));
fgCurMemoryVN[GcHeap] = gcHeapVN;
if (byrefStatesMatchGcHeapStates)
{
// Since GcHeap and ByrefExposed share SSA nodes, they need to share
// value numbers too.
fgCurMemoryVN[ByrefExposed] = gcHeapVN;
}
else
{
// GcHeap and ByrefExposed have different defnums and VNs. We conservatively
// assume that this GcHeap store may alias any byref load/store, so don't
// bother trying to record the map/select stuff, and instead just an opaque VN
// for ByrefExposed
fgCurMemoryVN[ByrefExposed] = vnStore->VNForExpr(compCurBB);
}
#ifdef DEBUG
if (verbose)
{
printf(" fgCurMemoryVN[GcHeap] assigned by %s at ", msg);
Compiler::printTreeID(curTree);
printf(" to VN: " STR_VN "%x.\n", gcHeapVN);
}
#endif // DEBUG
// If byrefStatesMatchGcHeapStates is true, then since GcHeap and ByrefExposed share
// their SSA map entries, the below will effectively update both.
fgValueNumberRecordMemorySsa(GcHeap, curTree);
}
void Compiler::recordAddressExposedLocalStore(GenTreePtr curTree, ValueNum memoryVN DEBUGARG(const char* msg))
{
// This should only happen if GcHeap and ByrefExposed are being tracked separately;
// otherwise we'd go through recordGcHeapStore.
assert(!byrefStatesMatchGcHeapStates);
// bbMemoryDef must include ByrefExposed for any block that mutates an address-exposed local
assert((compCurBB->bbMemoryDef & memoryKindSet(ByrefExposed)) != 0);
fgCurMemoryVN[ByrefExposed] = memoryVN;
#ifdef DEBUG
if (verbose)
{
printf(" fgCurMemoryVN[ByrefExposed] assigned by %s at ", msg);
Compiler::printTreeID(curTree);
printf(" to VN: " STR_VN "%x.\n", memoryVN);
}
#endif // DEBUG
fgValueNumberRecordMemorySsa(ByrefExposed, curTree);
}
void Compiler::fgValueNumberRecordMemorySsa(MemoryKind memoryKind, GenTreePtr tree)
{
unsigned ssaNum;
if (GetMemorySsaMap(memoryKind)->Lookup(tree, &ssaNum))
{
GetMemoryPerSsaData(ssaNum)->m_vnPair.SetLiberal(fgCurMemoryVN[memoryKind]);
#ifdef DEBUG
if (verbose)
{
printf("Node ");
Compiler::printTreeID(tree);
printf(" sets %s SSA # %d to VN $%x: ", memoryKindNames[memoryKind], ssaNum, fgCurMemoryVN[memoryKind]);
vnStore->vnDump(this, fgCurMemoryVN[memoryKind]);
printf("\n");
}
#endif // DEBUG
}
}
// The input 'tree' is a leaf node that is a constant
// Assign the proper value number to the tree
void Compiler::fgValueNumberTreeConst(GenTreePtr tree)
{
genTreeOps oper = tree->OperGet();
var_types typ = tree->TypeGet();
assert(GenTree::OperIsConst(oper));
switch (typ)
{
case TYP_LONG:
case TYP_ULONG:
case TYP_INT:
case TYP_UINT:
case TYP_CHAR:
case TYP_SHORT:
case TYP_BYTE:
case TYP_UBYTE:
case TYP_BOOL:
if (tree->IsCnsIntOrI() && tree->IsIconHandle())
{
tree->gtVNPair.SetBoth(
vnStore->VNForHandle(ssize_t(tree->gtIntConCommon.IconValue()), tree->GetIconHandleFlag()));
}
else if ((typ == TYP_LONG) || (typ == TYP_ULONG))
{
tree->gtVNPair.SetBoth(vnStore->VNForLongCon(INT64(tree->gtIntConCommon.LngValue())));
}
else
{
tree->gtVNPair.SetBoth(vnStore->VNForIntCon(int(tree->gtIntConCommon.IconValue())));
}
break;
case TYP_FLOAT:
tree->gtVNPair.SetBoth(vnStore->VNForFloatCon((float)tree->gtDblCon.gtDconVal));
break;
case TYP_DOUBLE:
tree->gtVNPair.SetBoth(vnStore->VNForDoubleCon(tree->gtDblCon.gtDconVal));
break;
case TYP_REF:
if (tree->gtIntConCommon.IconValue() == 0)
{
tree->gtVNPair.SetBoth(ValueNumStore::VNForNull());
}
else
{
assert(tree->gtFlags == GTF_ICON_STR_HDL); // Constant object can be only frozen string.
tree->gtVNPair.SetBoth(
vnStore->VNForHandle(ssize_t(tree->gtIntConCommon.IconValue()), tree->GetIconHandleFlag()));
}
break;
case TYP_BYREF:
if (tree->gtIntConCommon.IconValue() == 0)
{
tree->gtVNPair.SetBoth(ValueNumStore::VNForNull());
}
else
{
assert(tree->IsCnsIntOrI());
if (tree->IsIconHandle())
{
tree->gtVNPair.SetBoth(
vnStore->VNForHandle(ssize_t(tree->gtIntConCommon.IconValue()), tree->GetIconHandleFlag()));
}
else
{
tree->gtVNPair.SetBoth(vnStore->VNForByrefCon(tree->gtIntConCommon.IconValue()));
}
}
break;
default:
unreached();
}
}
//------------------------------------------------------------------------
// fgValueNumberBlockAssignment: Perform value numbering for block assignments.
//
// Arguments:
// tree - the block assignment to be value numbered.
// evalAsgLhsInd - true iff we should value number the LHS of the assignment.
//
// Return Value:
// None.
//
// Assumptions:
// 'tree' must be a block assignment (GT_INITBLK, GT_COPYBLK, GT_COPYOBJ).
void Compiler::fgValueNumberBlockAssignment(GenTreePtr tree, bool evalAsgLhsInd)
{
GenTree* lhs = tree->gtGetOp1();
GenTree* rhs = tree->gtGetOp2();
#ifdef DEBUG
// Sometimes we query the memory ssa map in an assertion, and need a dummy location for the ignored result.
unsigned memorySsaNum;
#endif
if (tree->OperIsInitBlkOp())
{
GenTreeLclVarCommon* lclVarTree;
bool isEntire;
if (tree->DefinesLocal(this, &lclVarTree, &isEntire))
{
assert(lclVarTree->gtFlags & GTF_VAR_DEF);
// Should not have been recorded as updating the GC heap.
assert(!GetMemorySsaMap(GcHeap)->Lookup(tree, &memorySsaNum));
unsigned lclNum = lclVarTree->GetLclNum();
// Ignore vars that we excluded from SSA (for example, because they're address-exposed). They don't have
// SSA names in which to store VN's on defs. We'll yield unique VN's when we read from them.
if (!fgExcludeFromSsa(lclNum))
{
// Should not have been recorded as updating ByrefExposed.
assert(!GetMemorySsaMap(ByrefExposed)->Lookup(tree, &memorySsaNum));
unsigned lclDefSsaNum = GetSsaNumForLocalVarDef(lclVarTree);
ValueNum initBlkVN = ValueNumStore::NoVN;
GenTreePtr initConst = rhs;
if (isEntire && initConst->OperGet() == GT_CNS_INT)
{
unsigned initVal = 0xFF & (unsigned)initConst->AsIntConCommon()->IconValue();
if (initVal == 0)
{
initBlkVN = vnStore->VNZeroForType(lclVarTree->TypeGet());
}
}
ValueNum lclVarVN = (initBlkVN != ValueNumStore::NoVN)
? initBlkVN
: vnStore->VNForExpr(compCurBB, var_types(lvaTable[lclNum].lvType));
lvaTable[lclNum].GetPerSsaData(lclDefSsaNum)->m_vnPair.SetBoth(lclVarVN);
#ifdef DEBUG
if (verbose)
{
printf("N%03u ", tree->gtSeqNum);
Compiler::printTreeID(tree);
printf(" ");
gtDispNodeName(tree);
printf(" V%02u/%d => ", lclNum, lclDefSsaNum);
vnPrint(lclVarVN, 1);
printf("\n");
}
#endif // DEBUG
}
else if (lvaVarAddrExposed(lclVarTree->gtLclNum))
{
fgMutateAddressExposedLocal(tree DEBUGARG("INITBLK - address-exposed local"));
}
}
else
{
// For now, arbitrary side effect on GcHeap/ByrefExposed.
// TODO-CQ: Why not be complete, and get this case right?
fgMutateGcHeap(tree DEBUGARG("INITBLK - non local"));
}
// Initblock's are of type void. Give them the void "value" -- they may occur in argument lists, which we
// want to be able to give VN's to.
tree->gtVNPair.SetBoth(ValueNumStore::VNForVoid());
}
else
{
assert(tree->OperIsCopyBlkOp());
// TODO-Cleanup: We should factor things so that we uniformly rely on "PtrTo" VN's, and
// the memory cases can be shared with assignments.
GenTreeLclVarCommon* lclVarTree = nullptr;
bool isEntire = false;
// Note that we don't care about exceptions here, since we're only using the values
// to perform an assignment (which happens after any exceptions are raised...)
if (tree->DefinesLocal(this, &lclVarTree, &isEntire))
{
// Should not have been recorded as updating the GC heap.
assert(!GetMemorySsaMap(GcHeap)->Lookup(tree, &memorySsaNum));
unsigned lhsLclNum = lclVarTree->GetLclNum();
FieldSeqNode* lhsFldSeq = nullptr;
// If it's excluded from SSA, don't need to do anything.
if (!fgExcludeFromSsa(lhsLclNum))
{
// Should not have been recorded as updating ByrefExposed.
assert(!GetMemorySsaMap(ByrefExposed)->Lookup(tree, &memorySsaNum));
unsigned lclDefSsaNum = GetSsaNumForLocalVarDef(lclVarTree);
if (lhs->IsLocalExpr(this, &lclVarTree, &lhsFldSeq) ||
(lhs->OperIsBlk() && (lhs->AsBlk()->gtBlkSize == lvaLclSize(lhsLclNum))))
{
noway_assert(lclVarTree->gtLclNum == lhsLclNum);
}
else
{
GenTree* lhsAddr;
if (lhs->OperIsBlk())
{
lhsAddr = lhs->AsBlk()->Addr();
}
else
{
assert(lhs->OperGet() == GT_IND);
lhsAddr = lhs->gtOp.gtOp1;
}
// For addr-of-local expressions, lib/cons shouldn't matter.
assert(lhsAddr->gtVNPair.BothEqual());
ValueNum lhsAddrVN = lhsAddr->GetVN(VNK_Liberal);
// Unpack the PtrToLoc value number of the address.
assert(vnStore->IsVNFunc(lhsAddrVN));
VNFuncApp lhsAddrFuncApp;
vnStore->GetVNFunc(lhsAddrVN, &lhsAddrFuncApp);
assert(lhsAddrFuncApp.m_func == VNF_PtrToLoc);
assert(vnStore->IsVNConstant(lhsAddrFuncApp.m_args[0]) &&
vnStore->ConstantValue<unsigned>(lhsAddrFuncApp.m_args[0]) == lhsLclNum);
lhsFldSeq = vnStore->FieldSeqVNToFieldSeq(lhsAddrFuncApp.m_args[1]);
}
// Now we need to get the proper RHS.
GenTreeLclVarCommon* rhsLclVarTree = nullptr;
LclVarDsc* rhsVarDsc = nullptr;
FieldSeqNode* rhsFldSeq = nullptr;
ValueNumPair rhsVNPair;
bool isNewUniq = false;
if (!rhs->OperIsIndir())
{
if (rhs->IsLocalExpr(this, &rhsLclVarTree, &rhsFldSeq))
{
unsigned rhsLclNum = rhsLclVarTree->GetLclNum();
rhsVarDsc = &lvaTable[rhsLclNum];
if (fgExcludeFromSsa(rhsLclNum) || rhsFldSeq == FieldSeqStore::NotAField())
{
rhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, rhsLclVarTree->TypeGet()));
isNewUniq = true;
}
else
{
rhsVNPair = lvaTable[rhsLclVarTree->GetLclNum()]
.GetPerSsaData(rhsLclVarTree->GetSsaNum())
->m_vnPair;
var_types indType = rhsLclVarTree->TypeGet();
rhsVNPair = vnStore->VNPairApplySelectors(rhsVNPair, rhsFldSeq, indType);
}
}
else
{
rhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, rhs->TypeGet()));
isNewUniq = true;
}
}
else
{
GenTreePtr srcAddr = rhs->AsIndir()->Addr();
VNFuncApp srcAddrFuncApp;
if (srcAddr->IsLocalAddrExpr(this, &rhsLclVarTree, &rhsFldSeq))
{
unsigned rhsLclNum = rhsLclVarTree->GetLclNum();
rhsVarDsc = &lvaTable[rhsLclNum];
if (fgExcludeFromSsa(rhsLclNum) || rhsFldSeq == FieldSeqStore::NotAField())
{
isNewUniq = true;
}
else
{
rhsVNPair = lvaTable[rhsLclVarTree->GetLclNum()]
.GetPerSsaData(rhsLclVarTree->GetSsaNum())
->m_vnPair;
var_types indType = rhsLclVarTree->TypeGet();
rhsVNPair = vnStore->VNPairApplySelectors(rhsVNPair, rhsFldSeq, indType);
}
}
else if (vnStore->GetVNFunc(vnStore->VNNormVal(srcAddr->gtVNPair.GetLiberal()), &srcAddrFuncApp))
{
if (srcAddrFuncApp.m_func == VNF_PtrToStatic)
{
var_types indType = lclVarTree->TypeGet();
ValueNum fieldSeqVN = srcAddrFuncApp.m_args[0];
FieldSeqNode* zeroOffsetFldSeq = nullptr;
if (GetZeroOffsetFieldMap()->Lookup(srcAddr, &zeroOffsetFldSeq))
{
fieldSeqVN =
vnStore->FieldSeqVNAppend(fieldSeqVN, vnStore->VNForFieldSeq(zeroOffsetFldSeq));
}
FieldSeqNode* fldSeqForStaticVar = vnStore->FieldSeqVNToFieldSeq(fieldSeqVN);
if (fldSeqForStaticVar != FieldSeqStore::NotAField())
{
// We model statics as indices into GcHeap (which is a subset of ByrefExposed).
ValueNum selectedStaticVar;
size_t structSize = 0;
selectedStaticVar = vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap],
fldSeqForStaticVar, &structSize);
selectedStaticVar =
vnStore->VNApplySelectorsTypeCheck(selectedStaticVar, indType, structSize);
rhsVNPair.SetLiberal(selectedStaticVar);
rhsVNPair.SetConservative(vnStore->VNForExpr(compCurBB, indType));
}
else
{
JITDUMP(" *** Missing field sequence info for Src/RHS of COPYBLK\n");
rhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, indType)); // a new unique value number
}
}
else if (srcAddrFuncApp.m_func == VNF_PtrToArrElem)
{
ValueNum elemLib =
fgValueNumberArrIndexVal(nullptr, &srcAddrFuncApp, vnStore->VNForEmptyExcSet());
rhsVNPair.SetLiberal(elemLib);
rhsVNPair.SetConservative(vnStore->VNForExpr(compCurBB, lclVarTree->TypeGet()));
}
else
{
isNewUniq = true;
}
}
else
{
isNewUniq = true;
}
}
if (lhsFldSeq == FieldSeqStore::NotAField())
{
// We don't have proper field sequence information for the lhs
//
JITDUMP(" *** Missing field sequence info for Dst/LHS of COPYBLK\n");
isNewUniq = true;
}
else if (lhsFldSeq != nullptr && isEntire)
{
// This can occur in for structs with one field, itself of a struct type.
// We won't promote these.
// TODO-Cleanup: decide what exactly to do about this.
// Always treat them as maps, making them use/def, or reconstitute the
// map view here?
isNewUniq = true;
}
else if (!isNewUniq)
{
ValueNumPair oldLhsVNPair = lvaTable[lhsLclNum].GetPerSsaData(lclVarTree->GetSsaNum())->m_vnPair;
rhsVNPair = vnStore->VNPairApplySelectorsAssign(oldLhsVNPair, lhsFldSeq, rhsVNPair,
lclVarTree->TypeGet(), compCurBB);
}
if (isNewUniq)
{
rhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lclVarTree->TypeGet()));
}
lvaTable[lhsLclNum].GetPerSsaData(lclDefSsaNum)->m_vnPair = vnStore->VNPNormVal(rhsVNPair);
#ifdef DEBUG
if (verbose)
{
printf("Tree ");
Compiler::printTreeID(tree);
printf(" assigned VN to local var V%02u/%d: ", lhsLclNum, lclDefSsaNum);
if (isNewUniq)
{
printf("new uniq ");
}
vnpPrint(rhsVNPair, 1);
printf("\n");
}
#endif // DEBUG
}
else if (lvaVarAddrExposed(lhsLclNum))
{
fgMutateAddressExposedLocal(tree DEBUGARG("COPYBLK - address-exposed local"));
}
}
else
{
// For now, arbitrary side effect on GcHeap/ByrefExposed.
// TODO-CQ: Why not be complete, and get this case right?
fgMutateGcHeap(tree DEBUGARG("COPYBLK - non local"));
}
// Copyblock's are of type void. Give them the void "value" -- they may occur in argument lists, which we want
// to be able to give VN's to.
tree->gtVNPair.SetBoth(ValueNumStore::VNForVoid());
}
}
void Compiler::fgValueNumberTree(GenTreePtr tree, bool evalAsgLhsInd)
{
genTreeOps oper = tree->OperGet();
#ifdef FEATURE_SIMD
// TODO-CQ: For now TYP_SIMD values are not handled by value numbering to be amenable for CSE'ing.
if (oper == GT_SIMD)
{
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, TYP_UNKNOWN));
return;
}
#endif
var_types typ = tree->TypeGet();
if (GenTree::OperIsConst(oper))
{
// If this is a struct assignment, with a constant rhs, it is an initBlk, and it is not
// really useful to value number the constant.
if (!varTypeIsStruct(tree))
{
fgValueNumberTreeConst(tree);
}
}
else if (GenTree::OperIsLeaf(oper))
{
switch (oper)
{
case GT_LCL_VAR:
case GT_REG_VAR:
{
GenTreeLclVarCommon* lcl = tree->AsLclVarCommon();
unsigned lclNum = lcl->gtLclNum;
if ((lcl->gtFlags & GTF_VAR_DEF) == 0 ||
(lcl->gtFlags & GTF_VAR_USEASG)) // If it is a "pure" def, will handled as part of the assignment.
{
LclVarDsc* varDsc = &lvaTable[lcl->gtLclNum];
if (varDsc->lvPromoted && varDsc->lvFieldCnt == 1)
{
// If the promoted var has only one field var, treat like a use of the field var.
lclNum = varDsc->lvFieldLclStart;
}
// Initialize to the undefined value, so we know whether we hit any of the cases here.
lcl->gtVNPair = ValueNumPair();
if (lcl->gtSsaNum == SsaConfig::RESERVED_SSA_NUM)
{
// Not an SSA variable.
if (lvaVarAddrExposed(lclNum))
{
// Address-exposed locals are part of ByrefExposed.
ValueNum addrVN = vnStore->VNForFunc(TYP_BYREF, VNF_PtrToLoc, vnStore->VNForIntCon(lclNum),
vnStore->VNForFieldSeq(nullptr));
ValueNum loadVN = fgValueNumberByrefExposedLoad(typ, addrVN);
lcl->gtVNPair.SetBoth(loadVN);
}
else
{
// Assign odd cases a new, unique, VN.
lcl->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lcl->TypeGet()));
}
}
else
{
var_types varType = varDsc->TypeGet();
ValueNumPair wholeLclVarVNP = varDsc->GetPerSsaData(lcl->gtSsaNum)->m_vnPair;
// Check for mismatched LclVar size
//
unsigned typSize = genTypeSize(genActualType(typ));
unsigned varSize = genTypeSize(genActualType(varType));
if (typSize == varSize)
{
lcl->gtVNPair = wholeLclVarVNP;
}
else // mismatched LclVar definition and LclVar use size
{
if (typSize < varSize)
{
// the indirection is reading less that the whole LclVar
// create a new VN that represent the partial value
//
ValueNumPair partialLclVarVNP = vnStore->VNPairForCast(wholeLclVarVNP, typ, varType);
lcl->gtVNPair = partialLclVarVNP;
}
else
{
assert(typSize > varSize);
// the indirection is reading beyond the end of the field
//
lcl->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, typ)); // return a new unique value
// number
}
}
}
// Temporary, to make progress.
// TODO-CQ: This should become an assert again...
if (lcl->gtVNPair.GetLiberal() == ValueNumStore::NoVN)
{
assert(lcl->gtVNPair.GetConservative() == ValueNumStore::NoVN);
// We don't want to fabricate arbitrary value numbers to things we can't reason about.
// So far, we know about two of these cases:
// Case 1) We have a local var who has never been defined but it's seen as a use.
// This is the case of storeIndir(addr(lclvar)) = expr. In this case since we only
// take the address of the variable, this doesn't mean it's a use nor we have to
// initialize it, so in this very rare case, we fabricate a value number.
// Case 2) Local variables that represent structs which are assigned using CpBlk.
GenTree* nextNode = lcl->gtNext;
assert((nextNode->gtOper == GT_ADDR && nextNode->gtOp.gtOp1 == lcl) ||
varTypeIsStruct(lcl->TypeGet()));
lcl->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lcl->TypeGet()));
}
assert(lcl->gtVNPair.BothDefined());
}
// TODO-Review: For the short term, we have a workaround for copyblk/initblk. Those that use
// addrSpillTemp will have a statement like "addrSpillTemp = addr(local)." If we previously decided
// that this block operation defines the local, we will have labeled the "local" node as a DEF
// (or USEDEF). This flag propogates to the "local" on the RHS. So we'll assume that this is correct,
// and treat it as a def (to a new, unique VN).
else if ((lcl->gtFlags & GTF_VAR_DEF) != 0)
{
LclVarDsc* varDsc = &lvaTable[lcl->gtLclNum];
if (lcl->gtSsaNum != SsaConfig::RESERVED_SSA_NUM)
{
lvaTable[lclNum]
.GetPerSsaData(lcl->gtSsaNum)
->m_vnPair.SetBoth(vnStore->VNForExpr(compCurBB, lcl->TypeGet()));
}
lcl->gtVNPair = ValueNumPair(); // Avoid confusion -- we don't set the VN of a lcl being defined.
}
}
break;
case GT_FTN_ADDR:
// Use the value of the function pointer (actually, a method handle.)
tree->gtVNPair.SetBoth(
vnStore->VNForHandle(ssize_t(tree->gtFptrVal.gtFptrMethod), GTF_ICON_METHOD_HDL));
break;
// This group passes through a value from a child node.
case GT_RET_EXPR:
tree->SetVNsFromNode(tree->gtRetExpr.gtInlineCandidate);
break;
case GT_LCL_FLD:
{
GenTreeLclFld* lclFld = tree->AsLclFld();
assert(fgExcludeFromSsa(lclFld->GetLclNum()) || lclFld->gtFieldSeq != nullptr);
// If this is a (full) def, then the variable will be labeled with the new SSA number,
// which will not have a value. We skip; it will be handled by one of the assignment-like
// forms (assignment, or initBlk or copyBlk).
if (((lclFld->gtFlags & GTF_VAR_DEF) == 0) || (lclFld->gtFlags & GTF_VAR_USEASG))
{
unsigned lclNum = lclFld->GetLclNum();
unsigned ssaNum = lclFld->GetSsaNum();
LclVarDsc* varDsc = &lvaTable[lclNum];
if (ssaNum == SsaConfig::UNINIT_SSA_NUM)
{
if (varDsc->GetPerSsaData(ssaNum)->m_vnPair.GetLiberal() == ValueNumStore::NoVN)
{
ValueNum vnForLcl = vnStore->VNForExpr(compCurBB, lclFld->TypeGet());
varDsc->GetPerSsaData(ssaNum)->m_vnPair = ValueNumPair(vnForLcl, vnForLcl);
}
}
var_types indType = tree->TypeGet();
if (lclFld->gtFieldSeq == FieldSeqStore::NotAField() || fgExcludeFromSsa(lclFld->GetLclNum()))
{
// This doesn't represent a proper field access or it's a struct
// with overlapping fields that is hard to reason about; return a new unique VN.
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, indType));
}
else
{
ValueNumPair lclVNPair = varDsc->GetPerSsaData(ssaNum)->m_vnPair;
tree->gtVNPair = vnStore->VNPairApplySelectors(lclVNPair, lclFld->gtFieldSeq, indType);
}
}
}
break;
// The ones below here all get a new unique VN -- but for various reasons, explained after each.
case GT_CATCH_ARG:
// We know nothing about the value of a caught expression.
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
break;
case GT_CLS_VAR:
// Skip GT_CLS_VAR nodes that are the LHS of an assignment. (We labeled these earlier.)
// We will "evaluate" this as part of the assignment. (Unless we're explicitly told by
// the caller to evaluate anyway -- perhaps the assignment is an "op=" assignment.)
//
if (((tree->gtFlags & GTF_CLS_VAR_ASG_LHS) == 0) || evalAsgLhsInd)
{
bool isVolatile = (tree->gtFlags & GTF_FLD_VOLATILE) != 0;
if (isVolatile)
{
// For Volatile indirection, first mutate GcHeap/ByrefExposed
fgMutateGcHeap(tree DEBUGARG("GTF_FLD_VOLATILE - read"));
}
// We just mutate GcHeap/ByrefExposed if isVolatile is true, and then do the read as normal.
//
// This allows:
// 1: read s;
// 2: volatile read s;
// 3: read s;
//
// We should never assume that the values read by 1 and 2 are the same (because the heap was mutated
// in between them)... but we *should* be able to prove that the values read in 2 and 3 are the
// same.
//
ValueNumPair clsVarVNPair;
// If the static field handle is for a struct type field, then the value of the static
// is a "ref" to the boxed struct -- treat it as the address of the static (we assume that a
// first element offset will be added to get to the actual struct...)
GenTreeClsVar* clsVar = tree->AsClsVar();
FieldSeqNode* fldSeq = clsVar->gtFieldSeq;
assert(fldSeq != nullptr); // We need to have one.
ValueNum selectedStaticVar = ValueNumStore::NoVN;
if (gtIsStaticFieldPtrToBoxedStruct(clsVar->TypeGet(), fldSeq->m_fieldHnd))
{
clsVarVNPair.SetBoth(
vnStore->VNForFunc(TYP_BYREF, VNF_PtrToStatic, vnStore->VNForFieldSeq(fldSeq)));
}
else
{
// This is a reference to heap memory.
// We model statics as indices into GcHeap (which is a subset of ByrefExposed).
FieldSeqNode* fldSeqForStaticVar =
GetFieldSeqStore()->CreateSingleton(tree->gtClsVar.gtClsVarHnd);
size_t structSize = 0;
selectedStaticVar = vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap],
fldSeqForStaticVar, &structSize);
selectedStaticVar =
vnStore->VNApplySelectorsTypeCheck(selectedStaticVar, tree->TypeGet(), structSize);
clsVarVNPair.SetLiberal(selectedStaticVar);
// The conservative interpretation always gets a new, unique VN.
clsVarVNPair.SetConservative(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
}
// The ValueNum returned must represent the full-sized IL-Stack value
// If we need to widen this value then we need to introduce a VNF_Cast here to represent
// the widened value. This is necessary since the CSE package can replace all occurances
// of a given ValueNum with a LclVar that is a full-sized IL-Stack value
//
if (varTypeIsSmall(tree->TypeGet()))
{
var_types castToType = tree->TypeGet();
clsVarVNPair = vnStore->VNPairForCast(clsVarVNPair, castToType, castToType);
}
tree->gtVNPair = clsVarVNPair;
}
break;
case GT_MEMORYBARRIER: // Leaf
// For MEMORYBARRIER add an arbitrary side effect on GcHeap/ByrefExposed.
fgMutateGcHeap(tree DEBUGARG("MEMORYBARRIER"));
break;
// These do not represent values.
case GT_NO_OP:
case GT_JMP: // Control flow
case GT_LABEL: // Control flow
#if !FEATURE_EH_FUNCLETS
case GT_END_LFIN: // Control flow
#endif
case GT_ARGPLACE:
// This node is a standin for an argument whose value will be computed later. (Perhaps it's
// a register argument, and we don't want to preclude use of the register in arg evaluation yet.)
// We give this a "fake" value number now; if the call in which it occurs cares about the
// value (e.g., it's a helper call whose result is a function of argument values) we'll reset
// this later, when the later args have been assigned VNs.
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
break;
case GT_PHI_ARG:
// This one is special because we should never process it in this method: it should
// always be taken care of, when needed, during pre-processing of a blocks phi definitions.
assert(false);
break;
default:
unreached();
}
}
else if (GenTree::OperIsSimple(oper))
{
#ifdef DEBUG
// Sometimes we query the memory ssa map in an assertion, and need a dummy location for the ignored result.
unsigned memorySsaNum;
#endif
if (GenTree::OperIsAssignment(oper) && !varTypeIsStruct(tree))
{
GenTreePtr lhs = tree->gtOp.gtOp1;
GenTreePtr rhs = tree->gtOp.gtOp2;
ValueNumPair rhsVNPair;
if (oper == GT_ASG)
{
rhsVNPair = rhs->gtVNPair;
}
else // Must be an "op="
{
// If the LHS is an IND, we didn't evaluate it when we visited it previously.
// But we didn't know that the parent was an op=. We do now, so go back and evaluate it.
// (We actually check if the effective val is the IND. We will have evaluated any non-last
// args of an LHS comma already -- including their memory effects.)
GenTreePtr lhsVal = lhs->gtEffectiveVal(/*commaOnly*/ true);
if (lhsVal->OperIsIndir() || (lhsVal->OperGet() == GT_CLS_VAR))
{
fgValueNumberTree(lhsVal, /*evalAsgLhsInd*/ true);
}
// Now we can make this assertion:
assert(lhsVal->gtVNPair.BothDefined());
genTreeOps op = GenTree::OpAsgToOper(oper);
if (GenTree::OperIsBinary(op))
{
ValueNumPair lhsNormVNP;
ValueNumPair lhsExcVNP;
lhsExcVNP.SetBoth(ValueNumStore::VNForEmptyExcSet());
vnStore->VNPUnpackExc(lhsVal->gtVNPair, &lhsNormVNP, &lhsExcVNP);
assert(rhs->gtVNPair.BothDefined());
ValueNumPair rhsNormVNP;
ValueNumPair rhsExcVNP;
rhsExcVNP.SetBoth(ValueNumStore::VNForEmptyExcSet());
vnStore->VNPUnpackExc(rhs->gtVNPair, &rhsNormVNP, &rhsExcVNP);
rhsVNPair = vnStore->VNPWithExc(vnStore->VNPairForFunc(tree->TypeGet(),
GetVNFuncForOper(op, (tree->gtFlags &
GTF_UNSIGNED) != 0),
lhsNormVNP, rhsNormVNP),
vnStore->VNPExcSetUnion(lhsExcVNP, rhsExcVNP));
}
else
{
// As of now, GT_CHS ==> GT_NEG is the only pattern fitting this.
assert(GenTree::OperIsUnary(op));
ValueNumPair lhsNormVNP;
ValueNumPair lhsExcVNP;
lhsExcVNP.SetBoth(ValueNumStore::VNForEmptyExcSet());
vnStore->VNPUnpackExc(lhsVal->gtVNPair, &lhsNormVNP, &lhsExcVNP);
rhsVNPair = vnStore->VNPWithExc(vnStore->VNPairForFunc(tree->TypeGet(),
GetVNFuncForOper(op, (tree->gtFlags &
GTF_UNSIGNED) != 0),
lhsNormVNP),
lhsExcVNP);
}
}
if (tree->TypeGet() != TYP_VOID)
{
// Assignment operators, as expressions, return the value of the RHS.
tree->gtVNPair = rhsVNPair;
}
// Now that we've labeled the assignment as a whole, we don't care about exceptions.
rhsVNPair = vnStore->VNPNormVal(rhsVNPair);
// If the types of the rhs and lhs are different then we
// may want to change the ValueNumber assigned to the lhs.
//
if (rhs->TypeGet() != lhs->TypeGet())
{
if (rhs->TypeGet() == TYP_REF)
{
// If we have an unsafe IL assignment of a TYP_REF to a non-ref (typically a TYP_BYREF)
// then don't propagate this ValueNumber to the lhs, instead create a new unique VN
//
rhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lhs->TypeGet()));
}
}
// We have to handle the case where the LHS is a comma. In that case, we don't evaluate the comma,
// so we give it VNForVoid, and we're really interested in the effective value.
GenTreePtr lhsCommaIter = lhs;
while (lhsCommaIter->OperGet() == GT_COMMA)
{
lhsCommaIter->gtVNPair.SetBoth(vnStore->VNForVoid());
lhsCommaIter = lhsCommaIter->gtOp.gtOp2;
}
lhs = lhs->gtEffectiveVal();
// Now, record the new VN for an assignment (performing the indicated "state update").
// It's safe to use gtEffectiveVal here, because the non-last elements of a comma list on the
// LHS will come before the assignment in evaluation order.
switch (lhs->OperGet())
{
case GT_LCL_VAR:
case GT_REG_VAR:
{
GenTreeLclVarCommon* lcl = lhs->AsLclVarCommon();
unsigned lclDefSsaNum = GetSsaNumForLocalVarDef(lcl);
// Should not have been recorded as updating the GC heap.
assert(!GetMemorySsaMap(GcHeap)->Lookup(tree, &memorySsaNum));
if (lclDefSsaNum != SsaConfig::RESERVED_SSA_NUM)
{
// Should not have been recorded as updating ByrefExposed mem.
assert(!GetMemorySsaMap(ByrefExposed)->Lookup(tree, &memorySsaNum));
assert(rhsVNPair.GetLiberal() != ValueNumStore::NoVN);
lhs->gtVNPair = rhsVNPair;
lvaTable[lcl->gtLclNum].GetPerSsaData(lclDefSsaNum)->m_vnPair = rhsVNPair;
#ifdef DEBUG
if (verbose)
{
printf("N%03u ", lhs->gtSeqNum);
Compiler::printTreeID(lhs);
printf(" ");
gtDispNodeName(lhs);
gtDispLeaf(lhs, nullptr);
printf(" => ");
vnpPrint(lhs->gtVNPair, 1);
printf("\n");
}
#endif // DEBUG
}
else if (lvaVarAddrExposed(lcl->gtLclNum))
{
// We could use MapStore here and MapSelect on reads of address-exposed locals
// (using the local nums as selectors) to get e.g. propagation of values
// through address-taken locals in regions of code with no calls or byref
// writes.
// For now, just use a new opaque VN.
ValueNum heapVN = vnStore->VNForExpr(compCurBB);
recordAddressExposedLocalStore(tree, heapVN DEBUGARG("local assign"));
}
#ifdef DEBUG
else
{
if (verbose)
{
JITDUMP("Tree ");
Compiler::printTreeID(tree);
printf(" assigns to non-address-taken local var V%02u; excluded from SSA, so value not "
"tracked.\n",
lcl->GetLclNum());
}
}
#endif // DEBUG
}
break;
case GT_LCL_FLD:
{
GenTreeLclFld* lclFld = lhs->AsLclFld();
unsigned lclDefSsaNum = GetSsaNumForLocalVarDef(lclFld);
// Should not have been recorded as updating the GC heap.
assert(!GetMemorySsaMap(GcHeap)->Lookup(tree, &memorySsaNum));
if (lclDefSsaNum != SsaConfig::RESERVED_SSA_NUM)
{
ValueNumPair newLhsVNPair;
// Is this a full definition?
if ((lclFld->gtFlags & GTF_VAR_USEASG) == 0)
{
assert(!lclFld->IsPartialLclFld(this));
assert(rhsVNPair.GetLiberal() != ValueNumStore::NoVN);
newLhsVNPair = rhsVNPair;
}
else
{
// We should never have a null field sequence here.
assert(lclFld->gtFieldSeq != nullptr);
if (lclFld->gtFieldSeq == FieldSeqStore::NotAField())
{
// We don't know what field this represents. Assign a new VN to the whole variable
// (since we may be writing to an unknown portion of it.)
newLhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lvaGetActualType(lclFld->gtLclNum)));
}
else
{
// We do know the field sequence.
// The "lclFld" node will be labeled with the SSA number of its "use" identity
// (we looked in a side table above for its "def" identity). Look up that value.
ValueNumPair oldLhsVNPair =
lvaTable[lclFld->GetLclNum()].GetPerSsaData(lclFld->GetSsaNum())->m_vnPair;
newLhsVNPair = vnStore->VNPairApplySelectorsAssign(oldLhsVNPair, lclFld->gtFieldSeq,
rhsVNPair, // Pre-value.
lclFld->TypeGet(), compCurBB);
}
}
lvaTable[lclFld->GetLclNum()].GetPerSsaData(lclDefSsaNum)->m_vnPair = newLhsVNPair;
lhs->gtVNPair = newLhsVNPair;
#ifdef DEBUG
if (verbose)
{
if (lhs->gtVNPair.GetLiberal() != ValueNumStore::NoVN)
{
printf("N%03u ", lhs->gtSeqNum);
Compiler::printTreeID(lhs);
printf(" ");
gtDispNodeName(lhs);
gtDispLeaf(lhs, nullptr);
printf(" => ");
vnpPrint(lhs->gtVNPair, 1);
printf("\n");
}
}
#endif // DEBUG
}
else if (lvaVarAddrExposed(lclFld->gtLclNum))
{
// This side-effects ByrefExposed. Just use a new opaque VN.
// As with GT_LCL_VAR, we could probably use MapStore here and MapSelect at corresponding
// loads, but to do so would have to identify the subset of address-exposed locals
// whose fields can be disambiguated.
ValueNum heapVN = vnStore->VNForExpr(compCurBB);
recordAddressExposedLocalStore(tree, heapVN DEBUGARG("local field assign"));
}
}
break;
case GT_PHI_ARG:
assert(false); // Phi arg cannot be LHS.
case GT_BLK:
case GT_OBJ:
case GT_IND:
{
bool isVolatile = (lhs->gtFlags & GTF_IND_VOLATILE) != 0;
if (isVolatile)
{
// For Volatile store indirection, first mutate GcHeap/ByrefExposed
fgMutateGcHeap(lhs DEBUGARG("GTF_IND_VOLATILE - store"));
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lhs->TypeGet()));
}
GenTreePtr arg = lhs->gtOp.gtOp1;
// Indicates whether the argument of the IND is the address of a local.
bool wasLocal = false;
lhs->gtVNPair = rhsVNPair;
VNFuncApp funcApp;
ValueNum argVN = arg->gtVNPair.GetLiberal();
bool argIsVNFunc = vnStore->GetVNFunc(vnStore->VNNormVal(argVN), &funcApp);
// Is this an assignment to a (field of, perhaps) a local?
// If it is a PtrToLoc, lib and cons VNs will be the same.
if (argIsVNFunc)
{
IndirectAssignmentAnnotation* pIndirAnnot =
nullptr; // This will be used if "tree" is an "indirect assignment",
// explained below.
if (funcApp.m_func == VNF_PtrToLoc)
{
assert(arg->gtVNPair.BothEqual()); // If it's a PtrToLoc, lib/cons shouldn't differ.
assert(vnStore->IsVNConstant(funcApp.m_args[0]));
unsigned lclNum = vnStore->ConstantValue<unsigned>(funcApp.m_args[0]);
wasLocal = true;
if (!fgExcludeFromSsa(lclNum))
{
FieldSeqNode* fieldSeq = vnStore->FieldSeqVNToFieldSeq(funcApp.m_args[1]);
// Either "arg" is the address of (part of) a local itself, or the assignment is an
// "indirect assignment", where an outer comma expression assigned the address of a
// local to a temp, and that temp is our lhs, and we recorded this in a table when we
// made the indirect assignment...or else we have a "rogue" PtrToLoc, one that should
// have made the local in question address-exposed. Assert on that.
GenTreeLclVarCommon* lclVarTree = nullptr;
bool isEntire = false;
unsigned lclDefSsaNum = SsaConfig::RESERVED_SSA_NUM;
ValueNumPair newLhsVNPair;
if (arg->DefinesLocalAddr(this, genTypeSize(lhs->TypeGet()), &lclVarTree, &isEntire))
{
// The local #'s should agree.
assert(lclNum == lclVarTree->GetLclNum());
if (fieldSeq == FieldSeqStore::NotAField())
{
// We don't know where we're storing, so give the local a new, unique VN.
// Do this by considering it an "entire" assignment, with an unknown RHS.
isEntire = true;
rhsVNPair.SetBoth(vnStore->VNForExpr(compCurBB, lclVarTree->TypeGet()));
}
if (isEntire)
{
newLhsVNPair = rhsVNPair;
lclDefSsaNum = lclVarTree->GetSsaNum();
}
else
{
// Don't use the lclVarTree's VN: if it's a local field, it will
// already be dereferenced by it's field sequence.
ValueNumPair oldLhsVNPair = lvaTable[lclVarTree->GetLclNum()]
.GetPerSsaData(lclVarTree->GetSsaNum())
->m_vnPair;
lclDefSsaNum = GetSsaNumForLocalVarDef(lclVarTree);
newLhsVNPair =
vnStore->VNPairApplySelectorsAssign(oldLhsVNPair, fieldSeq, rhsVNPair,
lhs->TypeGet(), compCurBB);
}
lvaTable[lclNum].GetPerSsaData(lclDefSsaNum)->m_vnPair = newLhsVNPair;
}
else if (m_indirAssignMap != nullptr && GetIndirAssignMap()->Lookup(tree, &pIndirAnnot))
{
// The local #'s should agree.
assert(lclNum == pIndirAnnot->m_lclNum);
assert(pIndirAnnot->m_defSsaNum != SsaConfig::RESERVED_SSA_NUM);
lclDefSsaNum = pIndirAnnot->m_defSsaNum;
// Does this assignment write the entire width of the local?
if (genTypeSize(lhs->TypeGet()) == genTypeSize(var_types(lvaTable[lclNum].lvType)))
{
assert(pIndirAnnot->m_useSsaNum == SsaConfig::RESERVED_SSA_NUM);
assert(pIndirAnnot->m_isEntire);
newLhsVNPair = rhsVNPair;
}
else
{
assert(pIndirAnnot->m_useSsaNum != SsaConfig::RESERVED_SSA_NUM);
assert(!pIndirAnnot->m_isEntire);
assert(pIndirAnnot->m_fieldSeq == fieldSeq);
ValueNumPair oldLhsVNPair =
lvaTable[lclNum].GetPerSsaData(pIndirAnnot->m_useSsaNum)->m_vnPair;
newLhsVNPair =
vnStore->VNPairApplySelectorsAssign(oldLhsVNPair, fieldSeq, rhsVNPair,
lhs->TypeGet(), compCurBB);
}
lvaTable[lclNum].GetPerSsaData(lclDefSsaNum)->m_vnPair = newLhsVNPair;
}
else
{
unreached(); // "Rogue" PtrToLoc, as discussed above.
}
#ifdef DEBUG
if (verbose)
{
printf("Tree ");
Compiler::printTreeID(tree);
printf(" assigned VN to local var V%02u/%d: VN ", lclNum, lclDefSsaNum);
vnpPrint(newLhsVNPair, 1);
printf("\n");
}
#endif // DEBUG
}
else if (lvaVarAddrExposed(lclNum))
{
// Need to record the effect on ByrefExposed.
// We could use MapStore here and MapSelect on reads of address-exposed locals
// (using the local nums as selectors) to get e.g. propagation of values
// through address-taken locals in regions of code with no calls or byref
// writes.
// For now, just use a new opaque VN.
ValueNum heapVN = vnStore->VNForExpr(compCurBB);
recordAddressExposedLocalStore(tree, heapVN DEBUGARG("PtrToLoc indir"));
}
}
}
// Was the argument of the GT_IND the address of a local, handled above?
if (!wasLocal)
{
GenTreePtr obj = nullptr;
GenTreePtr staticOffset = nullptr;
FieldSeqNode* fldSeq = nullptr;
// Is the LHS an array index expression?
if (argIsVNFunc && funcApp.m_func == VNF_PtrToArrElem)
{
CORINFO_CLASS_HANDLE elemTypeEq =
CORINFO_CLASS_HANDLE(vnStore->ConstantValue<ssize_t>(funcApp.m_args[0]));
ValueNum arrVN = funcApp.m_args[1];
ValueNum inxVN = funcApp.m_args[2];
FieldSeqNode* fldSeq = vnStore->FieldSeqVNToFieldSeq(funcApp.m_args[3]);
// Does the child of the GT_IND 'arg' have an associated zero-offset field sequence?
FieldSeqNode* addrFieldSeq = nullptr;
if (GetZeroOffsetFieldMap()->Lookup(arg, &addrFieldSeq))
{
fldSeq = GetFieldSeqStore()->Append(addrFieldSeq, fldSeq);
}
#ifdef DEBUG
if (verbose)
{
printf("Tree ");
Compiler::printTreeID(tree);
printf(" assigns to an array element:\n");
}
#endif // DEBUG
ValueNum heapVN = fgValueNumberArrIndexAssign(elemTypeEq, arrVN, inxVN, fldSeq,
rhsVNPair.GetLiberal(), lhs->TypeGet());
recordGcHeapStore(tree, heapVN DEBUGARG("Array element assignment"));
}
// It may be that we haven't parsed it yet. Try.
else if (lhs->gtFlags & GTF_IND_ARR_INDEX)
{
ArrayInfo arrInfo;
bool b = GetArrayInfoMap()->Lookup(lhs, &arrInfo);
assert(b);
ValueNum arrVN = ValueNumStore::NoVN;
ValueNum inxVN = ValueNumStore::NoVN;
FieldSeqNode* fldSeq = nullptr;
// Try to parse it.
GenTreePtr arr = nullptr;
arg->ParseArrayAddress(this, &arrInfo, &arr, &inxVN, &fldSeq);
if (arr == nullptr)
{
fgMutateGcHeap(tree DEBUGARG("assignment to unparseable array expression"));
return;
}
// Otherwise, parsing succeeded.
// Need to form H[arrType][arr][ind][fldSeq] = rhsVNPair.GetLiberal()
// Get the element type equivalence class representative.
CORINFO_CLASS_HANDLE elemTypeEq =
EncodeElemType(arrInfo.m_elemType, arrInfo.m_elemStructType);
arrVN = arr->gtVNPair.GetLiberal();
FieldSeqNode* zeroOffsetFldSeq = nullptr;
if (GetZeroOffsetFieldMap()->Lookup(arg, &zeroOffsetFldSeq))
{
fldSeq = GetFieldSeqStore()->Append(fldSeq, zeroOffsetFldSeq);
}
ValueNum heapVN = fgValueNumberArrIndexAssign(elemTypeEq, arrVN, inxVN, fldSeq,
rhsVNPair.GetLiberal(), lhs->TypeGet());
recordGcHeapStore(tree, heapVN DEBUGARG("assignment to unparseable array expression"));
}
else if (arg->IsFieldAddr(this, &obj, &staticOffset, &fldSeq))
{
if (fldSeq == FieldSeqStore::NotAField())
{
fgMutateGcHeap(tree DEBUGARG("NotAField"));
}
else
{
assert(fldSeq != nullptr);
#ifdef DEBUG
CORINFO_CLASS_HANDLE fldCls = info.compCompHnd->getFieldClass(fldSeq->m_fieldHnd);
if (obj != nullptr)
{
// Make sure that the class containing it is not a value class (as we are expecting
// an instance field)
assert((info.compCompHnd->getClassAttribs(fldCls) & CORINFO_FLG_VALUECLASS) == 0);
assert(staticOffset == nullptr);
}
#endif // DEBUG
// Get the first (instance or static) field from field seq. GcHeap[field] will yield
// the "field map".
if (fldSeq->IsFirstElemFieldSeq())
{
fldSeq = fldSeq->m_next;
assert(fldSeq != nullptr);
}
// Get a field sequence for just the first field in the sequence
//
FieldSeqNode* firstFieldOnly = GetFieldSeqStore()->CreateSingleton(fldSeq->m_fieldHnd);
// The final field in the sequence will need to match the 'indType'
var_types indType = lhs->TypeGet();
ValueNum fldMapVN =
vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap], firstFieldOnly);
// The type of the field is "struct" if there are more fields in the sequence,
// otherwise it is the type returned from VNApplySelectors above.
var_types firstFieldType = vnStore->TypeOfVN(fldMapVN);
ValueNum storeVal =
rhsVNPair.GetLiberal(); // The value number from the rhs of the assignment
ValueNum newFldMapVN = ValueNumStore::NoVN;
// when (obj != nullptr) we have an instance field, otherwise a static field
// when (staticOffset != nullptr) it represents a offset into a static or the call to
// Shared Static Base
if ((obj != nullptr) || (staticOffset != nullptr))
{
ValueNum valAtAddr = fldMapVN;
ValueNum normVal = ValueNumStore::NoVN;
if (obj != nullptr)
{
// construct the ValueNumber for 'fldMap at obj'
normVal = vnStore->VNNormVal(obj->GetVN(VNK_Liberal));
valAtAddr =
vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, normVal);
}
else // (staticOffset != nullptr)
{
// construct the ValueNumber for 'fldMap at staticOffset'
normVal = vnStore->VNNormVal(staticOffset->GetVN(VNK_Liberal));
valAtAddr =
vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, normVal);
}
// Now get rid of any remaining struct field dereferences. (if they exist)
if (fldSeq->m_next)
{
storeVal =
vnStore->VNApplySelectorsAssign(VNK_Liberal, valAtAddr, fldSeq->m_next,
storeVal, indType, compCurBB);
}
// From which we can construct the new ValueNumber for 'fldMap at normVal'
newFldMapVN = vnStore->VNForMapStore(vnStore->TypeOfVN(fldMapVN), fldMapVN, normVal,
storeVal);
}
else
{
// plain static field
// Now get rid of any remaining struct field dereferences. (if they exist)
if (fldSeq->m_next)
{
storeVal =
vnStore->VNApplySelectorsAssign(VNK_Liberal, fldMapVN, fldSeq->m_next,
storeVal, indType, compCurBB);
}
newFldMapVN = vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap],
fldSeq, storeVal, indType, compCurBB);
}
// It is not strictly necessary to set the lhs value number,
// but the dumps read better with it set to the 'storeVal' that we just computed
lhs->gtVNPair.SetBoth(storeVal);
#ifdef DEBUG
if (verbose)
{
printf(" fgCurMemoryVN assigned:\n");
}
#endif // DEBUG
// bbMemoryDef must include GcHeap for any block that mutates the GC heap
assert((compCurBB->bbMemoryDef & memoryKindSet(GcHeap)) != 0);
// Update the field map for firstField in GcHeap to this new value.
ValueNum heapVN =
vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap], firstFieldOnly,
newFldMapVN, indType, compCurBB);
recordGcHeapStore(tree, heapVN DEBUGARG("StoreField"));
}
}
else
{
GenTreeLclVarCommon* lclVarTree = nullptr;
bool isLocal = tree->DefinesLocal(this, &lclVarTree);
if (isLocal && lvaVarAddrExposed(lclVarTree->gtLclNum))
{
// Store to address-exposed local; need to record the effect on ByrefExposed.
// We could use MapStore here and MapSelect on reads of address-exposed locals
// (using the local nums as selectors) to get e.g. propagation of values
// through address-taken locals in regions of code with no calls or byref
// writes.
// For now, just use a new opaque VN.
ValueNum memoryVN = vnStore->VNForExpr(compCurBB);
recordAddressExposedLocalStore(tree, memoryVN DEBUGARG("PtrToLoc indir"));
}
else if (!isLocal)
{
// If it doesn't define a local, then it might update GcHeap/ByrefExposed.
// For the new ByrefExposed VN, we could use an operator here like
// VNF_ByrefExposedStore that carries the VNs of the pointer and RHS, then
// at byref loads if the current ByrefExposed VN happens to be
// VNF_ByrefExposedStore with the same pointer VN, we could propagate the
// VN from the RHS to the VN for the load. This would e.g. allow tracking
// values through assignments to out params. For now, just model this
// as an opaque GcHeap/ByrefExposed mutation.
fgMutateGcHeap(tree DEBUGARG("assign-of-IND"));
}
}
}
// We don't actually evaluate an IND on the LHS, so give it the Void value.
tree->gtVNPair.SetBoth(vnStore->VNForVoid());
}
break;
case GT_CLS_VAR:
{
bool isVolatile = (lhs->gtFlags & GTF_FLD_VOLATILE) != 0;
if (isVolatile)
{
// For Volatile store indirection, first mutate GcHeap/ByrefExposed
fgMutateGcHeap(lhs DEBUGARG("GTF_CLS_VAR - store")); // always change fgCurMemoryVN
}
// We model statics as indices into GcHeap (which is a subset of ByrefExposed).
FieldSeqNode* fldSeqForStaticVar = GetFieldSeqStore()->CreateSingleton(lhs->gtClsVar.gtClsVarHnd);
assert(fldSeqForStaticVar != FieldSeqStore::NotAField());
ValueNum storeVal = rhsVNPair.GetLiberal(); // The value number from the rhs of the assignment
storeVal = vnStore->VNApplySelectorsAssign(VNK_Liberal, fgCurMemoryVN[GcHeap], fldSeqForStaticVar,
storeVal, lhs->TypeGet(), compCurBB);
// It is not strictly necessary to set the lhs value number,
// but the dumps read better with it set to the 'storeVal' that we just computed
lhs->gtVNPair.SetBoth(storeVal);
#ifdef DEBUG
if (verbose)
{
printf(" fgCurMemoryVN assigned:\n");
}
#endif // DEBUG
// bbMemoryDef must include GcHeap for any block that mutates the GC heap
assert((compCurBB->bbMemoryDef & memoryKindSet(GcHeap)) != 0);
// Update the field map for the fgCurMemoryVN and SSA for the tree
recordGcHeapStore(tree, storeVal DEBUGARG("Static Field store"));
}
break;
default:
assert(!"Unknown node for lhs of assignment!");
// For Unknown stores, mutate GcHeap/ByrefExposed
fgMutateGcHeap(lhs DEBUGARG("Unkwown Assignment - store")); // always change fgCurMemoryVN
break;
}
}
// Other kinds of assignment: initblk and copyblk.
else if (oper == GT_ASG && varTypeIsStruct(tree))
{
fgValueNumberBlockAssignment(tree, evalAsgLhsInd);
}
else if (oper == GT_ADDR)
{
// We have special representations for byrefs to lvalues.
GenTreePtr arg = tree->gtOp.gtOp1;
if (arg->OperIsLocal())
{
FieldSeqNode* fieldSeq = nullptr;
ValueNum newVN = ValueNumStore::NoVN;
if (fgExcludeFromSsa(arg->gtLclVarCommon.GetLclNum()))
{
newVN = vnStore->VNForExpr(compCurBB, TYP_BYREF);
}
else if (arg->OperGet() == GT_LCL_FLD)
{
fieldSeq = arg->AsLclFld()->gtFieldSeq;
if (fieldSeq == nullptr)
{
// Local field with unknown field seq -- not a precise pointer.
newVN = vnStore->VNForExpr(compCurBB, TYP_BYREF);
}
}
if (newVN == ValueNumStore::NoVN)
{
assert(arg->gtLclVarCommon.GetSsaNum() != ValueNumStore::NoVN);
newVN = vnStore->VNForFunc(TYP_BYREF, VNF_PtrToLoc,
vnStore->VNForIntCon(arg->gtLclVarCommon.GetLclNum()),
vnStore->VNForFieldSeq(fieldSeq));
}
tree->gtVNPair.SetBoth(newVN);
}
else if ((arg->gtOper == GT_IND) || arg->OperIsBlk())
{
// Usually the ADDR and IND just cancel out...
// except when this GT_ADDR has a valid zero-offset field sequence
//
FieldSeqNode* zeroOffsetFieldSeq = nullptr;
if (GetZeroOffsetFieldMap()->Lookup(tree, &zeroOffsetFieldSeq) &&
(zeroOffsetFieldSeq != FieldSeqStore::NotAField()))
{
ValueNum addrExtended = vnStore->ExtendPtrVN(arg->gtOp.gtOp1, zeroOffsetFieldSeq);
if (addrExtended != ValueNumStore::NoVN)
{
tree->gtVNPair.SetBoth(addrExtended); // We don't care about lib/cons differences for addresses.
}
else
{
// ExtendPtrVN returned a failure result
// So give this address a new unique value
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, TYP_BYREF));
}
}
else
{
// They just cancel, so fetch the ValueNumber from the op1 of the GT_IND node.
//
GenTree* addr = arg->AsIndir()->Addr();
tree->gtVNPair = addr->gtVNPair;
// For the CSE phase mark the address as GTF_DONT_CSE
// because it will end up with the same value number as tree (the GT_ADDR).
addr->gtFlags |= GTF_DONT_CSE;
}
}
else
{
// May be more cases to do here! But we'll punt for now.
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, TYP_BYREF));
}
}
else if ((oper == GT_IND) || GenTree::OperIsBlk(oper))
{
// So far, we handle cases in which the address is a ptr-to-local, or if it's
// a pointer to an object field or array alement. Other cases become uses of
// the current ByrefExposed value and the pointer value, so that at least we
// can recognize redundant loads with no stores between them.
GenTreePtr addr = tree->AsIndir()->Addr();
GenTreeLclVarCommon* lclVarTree = nullptr;
FieldSeqNode* fldSeq1 = nullptr;
FieldSeqNode* fldSeq2 = nullptr;
GenTreePtr obj = nullptr;
GenTreePtr staticOffset = nullptr;
bool isVolatile = (tree->gtFlags & GTF_IND_VOLATILE) != 0;
// See if the addr has any exceptional part.
ValueNumPair addrNvnp;
ValueNumPair addrXvnp = ValueNumPair(ValueNumStore::VNForEmptyExcSet(), ValueNumStore::VNForEmptyExcSet());
vnStore->VNPUnpackExc(addr->gtVNPair, &addrNvnp, &addrXvnp);
// Is the dereference immutable? If so, model it as referencing the read-only heap.
if (tree->gtFlags & GTF_IND_INVARIANT)
{
assert(!isVolatile); // We don't expect both volatile and invariant
tree->gtVNPair =
ValueNumPair(vnStore->VNForMapSelect(VNK_Liberal, TYP_REF, ValueNumStore::VNForROH(),
addrNvnp.GetLiberal()),
vnStore->VNForMapSelect(VNK_Conservative, TYP_REF, ValueNumStore::VNForROH(),
addrNvnp.GetConservative()));
tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp);
}
else if (isVolatile)
{
// For Volatile indirection, mutate GcHeap/ByrefExposed
fgMutateGcHeap(tree DEBUGARG("GTF_IND_VOLATILE - read"));
// The value read by the GT_IND can immediately change
ValueNum newUniq = vnStore->VNForExpr(compCurBB, tree->TypeGet());
tree->gtVNPair = vnStore->VNPWithExc(ValueNumPair(newUniq, newUniq), addrXvnp);
}
// We always want to evaluate the LHS when the GT_IND node is marked with GTF_IND_ARR_INDEX
// as this will relabel the GT_IND child correctly using the VNF_PtrToArrElem
else if ((tree->gtFlags & GTF_IND_ARR_INDEX) != 0)
{
ArrayInfo arrInfo;
bool b = GetArrayInfoMap()->Lookup(tree, &arrInfo);
assert(b);
ValueNum inxVN = ValueNumStore::NoVN;
FieldSeqNode* fldSeq = nullptr;
// GenTreePtr addr = tree->gtOp.gtOp1;
ValueNum addrVN = addrNvnp.GetLiberal();
// Try to parse it.
GenTreePtr arr = nullptr;
addr->ParseArrayAddress(this, &arrInfo, &arr, &inxVN, &fldSeq);
if (arr == nullptr)
{
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
return;
}
assert(fldSeq != FieldSeqStore::NotAField());
// Otherwise...
// Need to form H[arrType][arr][ind][fldSeq]
// Get the array element type equivalence class rep.
CORINFO_CLASS_HANDLE elemTypeEq = EncodeElemType(arrInfo.m_elemType, arrInfo.m_elemStructType);
ValueNum elemTypeEqVN = vnStore->VNForHandle(ssize_t(elemTypeEq), GTF_ICON_CLASS_HDL);
// We take the "VNNormVal"s here, because if either has exceptional outcomes, they will be captured
// as part of the value of the composite "addr" operation...
ValueNum arrVN = vnStore->VNNormVal(arr->gtVNPair.GetLiberal());
inxVN = vnStore->VNNormVal(inxVN);
// Additionally, relabel the address with a PtrToArrElem value number.
ValueNum fldSeqVN = vnStore->VNForFieldSeq(fldSeq);
ValueNum elemAddr =
vnStore->VNForFunc(TYP_BYREF, VNF_PtrToArrElem, elemTypeEqVN, arrVN, inxVN, fldSeqVN);
// The aggregate "addr" VN should have had all the exceptions bubble up...
elemAddr = vnStore->VNWithExc(elemAddr, addrXvnp.GetLiberal());
addr->gtVNPair.SetBoth(elemAddr);
#ifdef DEBUG
if (verbose)
{
printf(" Relabeled IND_ARR_INDEX address node ");
Compiler::printTreeID(addr);
printf(" with l:" STR_VN "%x: ", elemAddr);
vnStore->vnDump(this, elemAddr);
printf("\n");
if (vnStore->VNNormVal(elemAddr) != elemAddr)
{
printf(" [" STR_VN "%x is: ", vnStore->VNNormVal(elemAddr));
vnStore->vnDump(this, vnStore->VNNormVal(elemAddr));
printf("]\n");
}
}
#endif // DEBUG
// We now need to retrieve the value number for the array element value
// and give this value number to the GT_IND node 'tree'
// We do this whenever we have an rvalue, or for the LHS when we have an "op=",
// but we don't do it for a normal LHS assignment into an array element.
//
if (evalAsgLhsInd || ((tree->gtFlags & GTF_IND_ASG_LHS) == 0))
{
fgValueNumberArrIndexVal(tree, elemTypeEq, arrVN, inxVN, addrXvnp.GetLiberal(), fldSeq);
}
}
else if (tree->gtFlags & GTF_IND_ARR_LEN)
{
// It's an array length. The argument is the sum of an array ref with some integer values...
ValueNum arrRefLib = vnStore->VNForRefInAddr(tree->gtOp.gtOp1->gtVNPair.GetLiberal());
ValueNum arrRefCons = vnStore->VNForRefInAddr(tree->gtOp.gtOp1->gtVNPair.GetConservative());
assert(vnStore->TypeOfVN(arrRefLib) == TYP_REF || vnStore->TypeOfVN(arrRefLib) == TYP_BYREF);
if (vnStore->IsVNConstant(arrRefLib))
{
// (or in weird cases, a REF or BYREF constant, in which case the result is an exception).
tree->gtVNPair.SetLiberal(
vnStore->VNWithExc(ValueNumStore::VNForVoid(),
vnStore->VNExcSetSingleton(
vnStore->VNForFunc(TYP_REF, VNF_NullPtrExc, arrRefLib))));
}
else
{
tree->gtVNPair.SetLiberal(vnStore->VNForFunc(TYP_INT, VNFunc(GT_ARR_LENGTH), arrRefLib));
}
assert(vnStore->TypeOfVN(arrRefCons) == TYP_REF || vnStore->TypeOfVN(arrRefCons) == TYP_BYREF);
if (vnStore->IsVNConstant(arrRefCons))
{
// (or in weird cases, a REF or BYREF constant, in which case the result is an exception).
tree->gtVNPair.SetConservative(
vnStore->VNWithExc(ValueNumStore::VNForVoid(),
vnStore->VNExcSetSingleton(
vnStore->VNForFunc(TYP_REF, VNF_NullPtrExc, arrRefCons))));
}
else
{
tree->gtVNPair.SetConservative(vnStore->VNForFunc(TYP_INT, VNFunc(GT_ARR_LENGTH), arrRefCons));
}
}
// In general we skip GT_IND nodes on that are the LHS of an assignment. (We labeled these earlier.)
// We will "evaluate" this as part of the assignment. (Unless we're explicitly told by
// the caller to evaluate anyway -- perhaps the assignment is an "op=" assignment.)
else if (((tree->gtFlags & GTF_IND_ASG_LHS) == 0) || evalAsgLhsInd)
{
FieldSeqNode* localFldSeq = nullptr;
VNFuncApp funcApp;
// Is it a local or a heap address?
if (addr->IsLocalAddrExpr(this, &lclVarTree, &localFldSeq) &&
!fgExcludeFromSsa(lclVarTree->GetLclNum()))
{
unsigned lclNum = lclVarTree->GetLclNum();
unsigned ssaNum = lclVarTree->GetSsaNum();
LclVarDsc* varDsc = &lvaTable[lclNum];
if ((localFldSeq == FieldSeqStore::NotAField()) || (localFldSeq == nullptr))
{
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
}
else
{
var_types indType = tree->TypeGet();
ValueNumPair lclVNPair = varDsc->GetPerSsaData(ssaNum)->m_vnPair;
tree->gtVNPair = vnStore->VNPairApplySelectors(lclVNPair, localFldSeq, indType);
;
}
tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp);
}
else if (vnStore->GetVNFunc(addrNvnp.GetLiberal(), &funcApp) && funcApp.m_func == VNF_PtrToStatic)
{
var_types indType = tree->TypeGet();
ValueNum fieldSeqVN = funcApp.m_args[0];
FieldSeqNode* fldSeqForStaticVar = vnStore->FieldSeqVNToFieldSeq(fieldSeqVN);
if (fldSeqForStaticVar != FieldSeqStore::NotAField())
{
ValueNum selectedStaticVar;
// We model statics as indices into the GcHeap (which is a subset of ByrefExposed).
size_t structSize = 0;
selectedStaticVar = vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap],
fldSeqForStaticVar, &structSize);
selectedStaticVar = vnStore->VNApplySelectorsTypeCheck(selectedStaticVar, indType, structSize);
tree->gtVNPair.SetLiberal(selectedStaticVar);
tree->gtVNPair.SetConservative(vnStore->VNForExpr(compCurBB, indType));
}
else
{
JITDUMP(" *** Missing field sequence info for VNF_PtrToStatic value GT_IND\n");
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, indType)); // a new unique value number
}
tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp);
}
else if (vnStore->GetVNFunc(addrNvnp.GetLiberal(), &funcApp) && (funcApp.m_func == VNF_PtrToArrElem))
{
fgValueNumberArrIndexVal(tree, &funcApp, addrXvnp.GetLiberal());
}
else if (addr->IsFieldAddr(this, &obj, &staticOffset, &fldSeq2))
{
if (fldSeq2 == FieldSeqStore::NotAField())
{
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
}
else if (fldSeq2 != nullptr)
{
// Get the first (instance or static) field from field seq. GcHeap[field] will yield the "field
// map".
CLANG_FORMAT_COMMENT_ANCHOR;
#ifdef DEBUG
CORINFO_CLASS_HANDLE fldCls = info.compCompHnd->getFieldClass(fldSeq2->m_fieldHnd);
if (obj != nullptr)
{
// Make sure that the class containing it is not a value class (as we are expecting an
// instance field)
assert((info.compCompHnd->getClassAttribs(fldCls) & CORINFO_FLG_VALUECLASS) == 0);
assert(staticOffset == nullptr);
}
#endif // DEBUG
// Get a field sequence for just the first field in the sequence
//
FieldSeqNode* firstFieldOnly = GetFieldSeqStore()->CreateSingleton(fldSeq2->m_fieldHnd);
size_t structSize = 0;
ValueNum fldMapVN =
vnStore->VNApplySelectors(VNK_Liberal, fgCurMemoryVN[GcHeap], firstFieldOnly, &structSize);
// The final field in the sequence will need to match the 'indType'
var_types indType = tree->TypeGet();
// The type of the field is "struct" if there are more fields in the sequence,
// otherwise it is the type returned from VNApplySelectors above.
var_types firstFieldType = vnStore->TypeOfVN(fldMapVN);
ValueNum valAtAddr = fldMapVN;
if (obj != nullptr)
{
// construct the ValueNumber for 'fldMap at obj'
ValueNum objNormVal = vnStore->VNNormVal(obj->GetVN(VNK_Liberal));
valAtAddr = vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, objNormVal);
}
else if (staticOffset != nullptr)
{
// construct the ValueNumber for 'fldMap at staticOffset'
ValueNum offsetNormVal = vnStore->VNNormVal(staticOffset->GetVN(VNK_Liberal));
valAtAddr = vnStore->VNForMapSelect(VNK_Liberal, firstFieldType, fldMapVN, offsetNormVal);
}
// Now get rid of any remaining struct field dereferences.
if (fldSeq2->m_next)
{
valAtAddr = vnStore->VNApplySelectors(VNK_Liberal, valAtAddr, fldSeq2->m_next, &structSize);
}
valAtAddr = vnStore->VNApplySelectorsTypeCheck(valAtAddr, indType, structSize);
tree->gtVNPair.SetLiberal(valAtAddr);
// The conservative value is a new, unique VN.
tree->gtVNPair.SetConservative(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp);
}
else
{
// Occasionally we do an explicit null test on a REF, so we just dereference it with no
// field sequence. The result is probably unused.
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp);
}
}
else // We don't know where the address points, so it is an ByrefExposed load.
{
ValueNum addrVN = addr->gtVNPair.GetLiberal();
ValueNum loadVN = fgValueNumberByrefExposedLoad(typ, addrVN);
tree->gtVNPair.SetLiberal(loadVN);
tree->gtVNPair.SetConservative(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
tree->gtVNPair = vnStore->VNPWithExc(tree->gtVNPair, addrXvnp);
}
}
}
else if (tree->OperGet() == GT_CAST)
{
fgValueNumberCastTree(tree);
}
else if (tree->OperGet() == GT_INTRINSIC)
{
fgValueNumberIntrinsic(tree);
}
else if (ValueNumStore::VNFuncIsLegal(GetVNFuncForOper(oper, (tree->gtFlags & GTF_UNSIGNED) != 0)))
{
if (GenTree::OperIsUnary(oper))
{
if (tree->gtOp.gtOp1 != nullptr)
{
if (tree->OperGet() == GT_NOP)
{
// Pass through arg vn.
tree->gtVNPair = tree->gtOp.gtOp1->gtVNPair;
}
else
{
ValueNumPair op1VNP;
ValueNumPair op1VNPx = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(tree->gtOp.gtOp1->gtVNPair, &op1VNP, &op1VNPx);
tree->gtVNPair =
vnStore->VNPWithExc(vnStore->VNPairForFunc(tree->TypeGet(),
GetVNFuncForOper(oper, (tree->gtFlags &
GTF_UNSIGNED) != 0),
op1VNP),
op1VNPx);
}
}
else // Is actually nullary.
{
// Mostly we'll leave these without a value number, assuming we'll detect these as VN failures
// if they actually need to have values. With the exception of NOPs, which can sometimes have
// meaning.
if (tree->OperGet() == GT_NOP)
{
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
}
}
}
else
{
assert(!GenTree::OperIsAssignment(oper)); // We handled assignments earlier.
assert(GenTree::OperIsBinary(oper));
// Standard binary operator.
ValueNumPair op2VNPair;
if (tree->gtOp.gtOp2 == nullptr)
{
op2VNPair.SetBoth(ValueNumStore::VNForNull());
}
else
{
op2VNPair = tree->gtOp.gtOp2->gtVNPair;
}
// A few special case: if we add a field offset constant to a PtrToXXX, we get back a new PtrToXXX.
ValueNum newVN = ValueNumStore::NoVN;
ValueNumPair op1vnp;
ValueNumPair op1Xvnp = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(tree->gtOp.gtOp1->gtVNPair, &op1vnp, &op1Xvnp);
ValueNumPair op2vnp;
ValueNumPair op2Xvnp = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(op2VNPair, &op2vnp, &op2Xvnp);
ValueNumPair excSet = vnStore->VNPExcSetUnion(op1Xvnp, op2Xvnp);
if (oper == GT_ADD)
{
newVN = vnStore->ExtendPtrVN(tree->gtOp.gtOp1, tree->gtOp.gtOp2);
if (newVN == ValueNumStore::NoVN)
{
newVN = vnStore->ExtendPtrVN(tree->gtOp.gtOp2, tree->gtOp.gtOp1);
}
}
if (newVN != ValueNumStore::NoVN)
{
newVN = vnStore->VNWithExc(newVN, excSet.GetLiberal());
// We don't care about differences between liberal and conservative for pointer values.
tree->gtVNPair.SetBoth(newVN);
}
else
{
ValueNumPair normalRes =
vnStore->VNPairForFunc(tree->TypeGet(),
GetVNFuncForOper(oper, (tree->gtFlags & GTF_UNSIGNED) != 0), op1vnp,
op2vnp);
// Overflow-checking operations add an overflow exception
if (tree->gtOverflowEx())
{
ValueNum overflowExcSet =
vnStore->VNExcSetSingleton(vnStore->VNForFunc(TYP_REF, VNF_OverflowExc));
excSet = vnStore->VNPExcSetUnion(excSet, ValueNumPair(overflowExcSet, overflowExcSet));
}
tree->gtVNPair = vnStore->VNPWithExc(normalRes, excSet);
}
}
}
else // ValueNumStore::VNFuncIsLegal returns false
{
// Some of the genTreeOps that aren't legal VNFuncs so they get special handling.
switch (oper)
{
case GT_COMMA:
{
ValueNumPair op1vnp;
ValueNumPair op1Xvnp = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(tree->gtOp.gtOp1->gtVNPair, &op1vnp, &op1Xvnp);
ValueNumPair op2vnp;
ValueNumPair op2Xvnp = ValueNumStore::VNPForEmptyExcSet();
GenTree* op2 = tree->gtGetOp2();
if (op2->OperIsIndir() && ((op2->gtFlags & GTF_IND_ASG_LHS) != 0))
{
// If op2 represents the lhs of an assignment then we give a VNForVoid for the lhs
op2vnp = ValueNumPair(ValueNumStore::VNForVoid(), ValueNumStore::VNForVoid());
}
else if ((op2->OperGet() == GT_CLS_VAR) && (op2->gtFlags & GTF_CLS_VAR_ASG_LHS))
{
// If op2 represents the lhs of an assignment then we give a VNForVoid for the lhs
op2vnp = ValueNumPair(ValueNumStore::VNForVoid(), ValueNumStore::VNForVoid());
}
else
{
vnStore->VNPUnpackExc(op2->gtVNPair, &op2vnp, &op2Xvnp);
}
tree->gtVNPair = vnStore->VNPWithExc(op2vnp, vnStore->VNPExcSetUnion(op1Xvnp, op2Xvnp));
}
break;
case GT_NULLCHECK:
// Explicit null check.
tree->gtVNPair =
vnStore->VNPWithExc(ValueNumPair(ValueNumStore::VNForVoid(), ValueNumStore::VNForVoid()),
vnStore->VNPExcSetSingleton(
vnStore->VNPairForFunc(TYP_REF, VNF_NullPtrExc,
tree->gtOp.gtOp1->gtVNPair)));
break;
case GT_LOCKADD: // Binop
case GT_XADD: // Binop
case GT_XCHG: // Binop
// For CMPXCHG and other intrinsics add an arbitrary side effect on GcHeap/ByrefExposed.
fgMutateGcHeap(tree DEBUGARG("Interlocked intrinsic"));
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
break;
case GT_JTRUE:
case GT_LIST:
// These nodes never need to have a ValueNumber
tree->gtVNPair.SetBoth(ValueNumStore::NoVN);
break;
default:
// The default action is to give the node a new, unique VN.
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
break;
}
}
}
else
{
assert(GenTree::OperIsSpecial(oper));
// TBD: We must handle these individually. For now:
switch (oper)
{
case GT_CALL:
fgValueNumberCall(tree->AsCall());
break;
case GT_ARR_BOUNDS_CHECK:
#ifdef FEATURE_SIMD
case GT_SIMD_CHK:
#endif // FEATURE_SIMD
{
// A bounds check node has no value, but may throw exceptions.
ValueNumPair excSet = vnStore->VNPExcSetSingleton(
vnStore->VNPairForFunc(TYP_REF, VNF_IndexOutOfRangeExc,
vnStore->VNPNormVal(tree->AsBoundsChk()->gtIndex->gtVNPair),
vnStore->VNPNormVal(tree->AsBoundsChk()->gtArrLen->gtVNPair)));
excSet = vnStore->VNPExcSetUnion(excSet, vnStore->VNPExcVal(tree->AsBoundsChk()->gtIndex->gtVNPair));
excSet = vnStore->VNPExcSetUnion(excSet, vnStore->VNPExcVal(tree->AsBoundsChk()->gtArrLen->gtVNPair));
tree->gtVNPair = vnStore->VNPWithExc(vnStore->VNPForVoid(), excSet);
}
break;
case GT_CMPXCHG: // Specialop
// For CMPXCHG and other intrinsics add an arbitrary side effect on GcHeap/ByrefExposed.
fgMutateGcHeap(tree DEBUGARG("Interlocked intrinsic"));
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
break;
default:
tree->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, tree->TypeGet()));
}
}
#ifdef DEBUG
if (verbose)
{
if (tree->gtVNPair.GetLiberal() != ValueNumStore::NoVN)
{
printf("N%03u ", tree->gtSeqNum);
printTreeID(tree);
printf(" ");
gtDispNodeName(tree);
if (tree->OperIsLeaf() || tree->OperIsLocalStore()) // local stores used to be leaves
{
gtDispLeaf(tree, nullptr);
}
printf(" => ");
vnpPrint(tree->gtVNPair, 1);
printf("\n");
}
}
#endif // DEBUG
}
void Compiler::fgValueNumberIntrinsic(GenTreePtr tree)
{
assert(tree->OperGet() == GT_INTRINSIC);
GenTreeIntrinsic* intrinsic = tree->AsIntrinsic();
ValueNumPair arg0VNP, arg1VNP;
ValueNumPair arg0VNPx = ValueNumStore::VNPForEmptyExcSet();
ValueNumPair arg1VNPx = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(intrinsic->gtOp.gtOp1->gtVNPair, &arg0VNP, &arg0VNPx);
if (intrinsic->gtOp.gtOp2 != nullptr)
{
vnStore->VNPUnpackExc(intrinsic->gtOp.gtOp2->gtVNPair, &arg1VNP, &arg1VNPx);
}
switch (intrinsic->gtIntrinsicId)
{
case CORINFO_INTRINSIC_Sin:
case CORINFO_INTRINSIC_Sqrt:
case CORINFO_INTRINSIC_Abs:
case CORINFO_INTRINSIC_Cos:
case CORINFO_INTRINSIC_Round:
case CORINFO_INTRINSIC_Cosh:
case CORINFO_INTRINSIC_Sinh:
case CORINFO_INTRINSIC_Tan:
case CORINFO_INTRINSIC_Tanh:
case CORINFO_INTRINSIC_Asin:
case CORINFO_INTRINSIC_Acos:
case CORINFO_INTRINSIC_Atan:
case CORINFO_INTRINSIC_Atan2:
case CORINFO_INTRINSIC_Log10:
case CORINFO_INTRINSIC_Pow:
case CORINFO_INTRINSIC_Exp:
case CORINFO_INTRINSIC_Ceiling:
case CORINFO_INTRINSIC_Floor:
// GT_INTRINSIC is a currently a subtype of binary operators. But most of
// the math intrinsics are actually unary operations.
if (intrinsic->gtOp.gtOp2 == nullptr)
{
intrinsic->gtVNPair =
vnStore->VNPWithExc(vnStore->EvalMathFuncUnary(tree->TypeGet(), intrinsic->gtIntrinsicId, arg0VNP),
arg0VNPx);
}
else
{
ValueNumPair newVNP =
vnStore->EvalMathFuncBinary(tree->TypeGet(), intrinsic->gtIntrinsicId, arg0VNP, arg1VNP);
ValueNumPair excSet = vnStore->VNPExcSetUnion(arg0VNPx, arg1VNPx);
intrinsic->gtVNPair = vnStore->VNPWithExc(newVNP, excSet);
}
break;
case CORINFO_INTRINSIC_Object_GetType:
intrinsic->gtVNPair =
vnStore->VNPWithExc(vnStore->VNPairForFunc(intrinsic->TypeGet(), VNF_ObjGetType, arg0VNP), arg0VNPx);
break;
default:
unreached();
}
}
void Compiler::fgValueNumberCastTree(GenTreePtr tree)
{
assert(tree->OperGet() == GT_CAST);
ValueNumPair srcVNPair = tree->gtOp.gtOp1->gtVNPair;
var_types castToType = tree->CastToType();
var_types castFromType = tree->CastFromType();
bool srcIsUnsigned = ((tree->gtFlags & GTF_UNSIGNED) != 0);
bool hasOverflowCheck = tree->gtOverflowEx();
assert(genActualType(castToType) == genActualType(tree->TypeGet())); // Insure that the resultType is correct
tree->gtVNPair = vnStore->VNPairForCast(srcVNPair, castToType, castFromType, srcIsUnsigned, hasOverflowCheck);
}
// Compute the normal ValueNumber for a cast operation with no exceptions
ValueNum ValueNumStore::VNForCast(ValueNum srcVN,
var_types castToType,
var_types castFromType,
bool srcIsUnsigned /* = false */)
{
// The resulting type after performingthe cast is always widened to a supported IL stack size
var_types resultType = genActualType(castToType);
// When we're considering actual value returned by a non-checking cast whether or not the source is
// unsigned does *not* matter for non-widening casts. That is, if we cast an int or a uint to short,
// we just extract the first two bytes from the source bit pattern, not worrying about the interpretation.
// The same is true in casting between signed/unsigned types of the same width. Only when we're doing
// a widening cast do we care about whether the source was unsigned,so we know whether to sign or zero extend it.
//
bool srcIsUnsignedNorm = srcIsUnsigned;
if (genTypeSize(castToType) <= genTypeSize(castFromType))
{
srcIsUnsignedNorm = false;
}
ValueNum castTypeVN = VNForCastOper(castToType, srcIsUnsigned);
ValueNum resultVN = VNForFunc(resultType, VNF_Cast, srcVN, castTypeVN);
#ifdef DEBUG
if (m_pComp->verbose)
{
printf(" VNForCast(" STR_VN "%x, " STR_VN "%x) returns ", srcVN, castTypeVN);
m_pComp->vnPrint(resultVN, 1);
printf("\n");
}
#endif
return resultVN;
}
// Compute the ValueNumberPair for a cast operation
ValueNumPair ValueNumStore::VNPairForCast(ValueNumPair srcVNPair,
var_types castToType,
var_types castFromType,
bool srcIsUnsigned, /* = false */
bool hasOverflowCheck) /* = false */
{
// The resulting type after performingthe cast is always widened to a supported IL stack size
var_types resultType = genActualType(castToType);
ValueNumPair castArgVNP;
ValueNumPair castArgxVNP = ValueNumStore::VNPForEmptyExcSet();
VNPUnpackExc(srcVNPair, &castArgVNP, &castArgxVNP);
// When we're considering actual value returned by a non-checking cast (or a checking cast that succeeds),
// whether or not the source is unsigned does *not* matter for non-widening casts.
// That is, if we cast an int or a uint to short, we just extract the first two bytes from the source
// bit pattern, not worrying about the interpretation. The same is true in casting between signed/unsigned
// types of the same width. Only when we're doing a widening cast do we care about whether the source
// was unsigned, so we know whether to sign or zero extend it.
//
// Important: Casts to floating point cannot be optimized in this fashion. (bug 946768)
//
bool srcIsUnsignedNorm = srcIsUnsigned;
if (genTypeSize(castToType) <= genTypeSize(castFromType) && !varTypeIsFloating(castToType))
{
srcIsUnsignedNorm = false;
}
ValueNum castTypeVN = VNForCastOper(castToType, srcIsUnsignedNorm);
ValueNumPair castTypeVNPair(castTypeVN, castTypeVN);
ValueNumPair castNormRes = VNPairForFunc(resultType, VNF_Cast, castArgVNP, castTypeVNPair);
ValueNumPair resultVNP = VNPWithExc(castNormRes, castArgxVNP);
// If we have a check for overflow, add the exception information.
if (hasOverflowCheck)
{
// For overflow checking, we always need to know whether the source is unsigned.
castTypeVNPair.SetBoth(VNForCastOper(castToType, srcIsUnsigned));
ValueNumPair excSet =
VNPExcSetSingleton(VNPairForFunc(TYP_REF, VNF_ConvOverflowExc, castArgVNP, castTypeVNPair));
excSet = VNPExcSetUnion(excSet, castArgxVNP);
resultVNP = VNPWithExc(castNormRes, excSet);
}
return resultVNP;
}
void Compiler::fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc)
{
unsigned nArgs = ValueNumStore::VNFuncArity(vnf);
assert(vnf != VNF_Boundary);
GenTreeArgList* args = call->gtCallArgs;
bool generateUniqueVN = false;
bool useEntryPointAddrAsArg0 = false;
switch (vnf)
{
case VNF_JitNew:
{
generateUniqueVN = true;
vnpExc = ValueNumStore::VNPForEmptyExcSet();
}
break;
case VNF_JitNewArr:
{
generateUniqueVN = true;
ValueNumPair vnp1 = vnStore->VNPNormVal(args->Rest()->Current()->gtVNPair);
// The New Array helper may throw an overflow exception
vnpExc = vnStore->VNPExcSetSingleton(vnStore->VNPairForFunc(TYP_REF, VNF_NewArrOverflowExc, vnp1));
}
break;
case VNF_BoxNullable:
{
// Generate unique VN so, VNForFunc generates a uniq value number for box nullable.
// Alternatively instead of using vnpUniq below in VNPairForFunc(...),
// we could use the value number of what the byref arg0 points to.
//
// But retrieving the value number of what the byref arg0 points to is quite a bit more work
// and doing so only very rarely allows for an additional optimization.
generateUniqueVN = true;
}
break;
case VNF_JitReadyToRunNew:
{
generateUniqueVN = true;
vnpExc = ValueNumStore::VNPForEmptyExcSet();
useEntryPointAddrAsArg0 = true;
}
break;
case VNF_JitReadyToRunNewArr:
{
generateUniqueVN = true;
ValueNumPair vnp1 = vnStore->VNPNormVal(args->Current()->gtVNPair);
// The New Array helper may throw an overflow exception
vnpExc = vnStore->VNPExcSetSingleton(vnStore->VNPairForFunc(TYP_REF, VNF_NewArrOverflowExc, vnp1));
useEntryPointAddrAsArg0 = true;
}
break;
case VNF_ReadyToRunStaticBase:
case VNF_ReadyToRunGenericStaticBase:
case VNF_ReadyToRunIsInstanceOf:
case VNF_ReadyToRunCastClass:
{
useEntryPointAddrAsArg0 = true;
}
break;
default:
{
assert(s_helperCallProperties.IsPure(eeGetHelperNum(call->gtCallMethHnd)));
}
break;
}
if (generateUniqueVN)
{
nArgs--;
}
ValueNumPair vnpUniq;
if (generateUniqueVN)
{
// Generate unique VN so, VNForFunc generates a unique value number.
vnpUniq.SetBoth(vnStore->VNForExpr(compCurBB, call->TypeGet()));
}
if (nArgs == 0)
{
if (generateUniqueVN)
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnpUniq);
}
else
{
call->gtVNPair.SetBoth(vnStore->VNForFunc(call->TypeGet(), vnf));
}
}
else
{
auto getCurrentArg = [call, &args, useEntryPointAddrAsArg0](int currentIndex) {
GenTreePtr arg = args->Current();
if ((arg->gtFlags & GTF_LATE_ARG) != 0)
{
// This arg is a setup node that moves the arg into position.
// Value-numbering will have visited the separate late arg that
// holds the actual value, and propagated/computed the value number
// for this arg there.
if (useEntryPointAddrAsArg0)
{
// The args in the fgArgInfo don't include the entry point, so
// index into them using one less than the requested index.
--currentIndex;
}
return call->fgArgInfo->GetLateArg(currentIndex);
}
return arg;
};
// Has at least one argument.
ValueNumPair vnp0;
ValueNumPair vnp0x = ValueNumStore::VNPForEmptyExcSet();
#ifdef FEATURE_READYTORUN_COMPILER
if (useEntryPointAddrAsArg0)
{
ValueNum callAddrVN = vnStore->VNForPtrSizeIntCon((ssize_t)call->gtCall.gtEntryPoint.addr);
vnp0 = ValueNumPair(callAddrVN, callAddrVN);
}
else
#endif
{
assert(!useEntryPointAddrAsArg0);
ValueNumPair vnp0wx = getCurrentArg(0)->gtVNPair;
vnStore->VNPUnpackExc(vnp0wx, &vnp0, &vnp0x);
// Also include in the argument exception sets
vnpExc = vnStore->VNPExcSetUnion(vnpExc, vnp0x);
args = args->Rest();
}
if (nArgs == 1)
{
if (generateUniqueVN)
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnp0, vnpUniq);
}
else
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnp0);
}
}
else
{
// Has at least two arguments.
ValueNumPair vnp1wx = getCurrentArg(1)->gtVNPair;
ValueNumPair vnp1;
ValueNumPair vnp1x = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(vnp1wx, &vnp1, &vnp1x);
vnpExc = vnStore->VNPExcSetUnion(vnpExc, vnp1x);
args = args->Rest();
if (nArgs == 2)
{
if (generateUniqueVN)
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnp0, vnp1, vnpUniq);
}
else
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnp0, vnp1);
}
}
else
{
ValueNumPair vnp2wx = getCurrentArg(2)->gtVNPair;
ValueNumPair vnp2;
ValueNumPair vnp2x = ValueNumStore::VNPForEmptyExcSet();
vnStore->VNPUnpackExc(vnp2wx, &vnp2, &vnp2x);
vnpExc = vnStore->VNPExcSetUnion(vnpExc, vnp2x);
args = args->Rest();
assert(nArgs == 3); // Our current maximum.
assert(args == nullptr);
if (generateUniqueVN)
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnp0, vnp1, vnp2, vnpUniq);
}
else
{
call->gtVNPair = vnStore->VNPairForFunc(call->TypeGet(), vnf, vnp0, vnp1, vnp2);
}
}
}
// Add the accumulated exceptions.
call->gtVNPair = vnStore->VNPWithExc(call->gtVNPair, vnpExc);
}
}
void Compiler::fgValueNumberCall(GenTreeCall* call)
{
// First: do value numbering of any argument placeholder nodes in the argument list
// (by transferring from the VN of the late arg that they are standing in for...)
unsigned i = 0;
GenTreeArgList* args = call->gtCallArgs;
bool updatedArgPlace = false;
while (args != nullptr)
{
GenTreePtr arg = args->Current();
if (arg->OperGet() == GT_ARGPLACE)
{
// Find the corresponding late arg.
GenTreePtr lateArg = call->fgArgInfo->GetLateArg(i);
assert(lateArg->gtVNPair.BothDefined());
arg->gtVNPair = lateArg->gtVNPair;
updatedArgPlace = true;
#ifdef DEBUG
if (verbose)
{
printf("VN of ARGPLACE tree ");
Compiler::printTreeID(arg);
printf(" updated to ");
vnpPrint(arg->gtVNPair, 1);
printf("\n");
}
#endif
}
i++;
args = args->Rest();
}
if (updatedArgPlace)
{
// Now we have to update the VN's of the argument list nodes, since that will be used in determining
// loop-invariance.
fgUpdateArgListVNs(call->gtCallArgs);
}
if (call->gtCallType == CT_HELPER)
{
bool modHeap = fgValueNumberHelperCall(call);
if (modHeap)
{
// For now, arbitrary side effect on GcHeap/ByrefExposed.
fgMutateGcHeap(call DEBUGARG("HELPER - modifies heap"));
}
}
else
{
if (call->TypeGet() == TYP_VOID)
{
call->gtVNPair.SetBoth(ValueNumStore::VNForVoid());
}
else
{
call->gtVNPair.SetBoth(vnStore->VNForExpr(compCurBB, call->TypeGet()));
}
// For now, arbitrary side effect on GcHeap/ByrefExposed.
fgMutateGcHeap(call DEBUGARG("CALL"));
}
}
void Compiler::fgUpdateArgListVNs(GenTreeArgList* args)
{
if (args == nullptr)
{
return;
}
// Otherwise...
fgUpdateArgListVNs(args->Rest());
fgValueNumberTree(args);
}
VNFunc Compiler::fgValueNumberHelperMethVNFunc(CorInfoHelpFunc helpFunc)
{
assert(s_helperCallProperties.IsPure(helpFunc) || s_helperCallProperties.IsAllocator(helpFunc));
VNFunc vnf = VNF_Boundary; // An illegal value...
switch (helpFunc)
{
// These translate to other function symbols:
case CORINFO_HELP_DIV:
vnf = VNFunc(GT_DIV);
break;
case CORINFO_HELP_MOD:
vnf = VNFunc(GT_MOD);
break;
case CORINFO_HELP_UDIV:
vnf = VNFunc(GT_UDIV);
break;
case CORINFO_HELP_UMOD:
vnf = VNFunc(GT_UMOD);
break;
case CORINFO_HELP_LLSH:
vnf = VNFunc(GT_LSH);
break;
case CORINFO_HELP_LRSH:
vnf = VNFunc(GT_RSH);
break;
case CORINFO_HELP_LRSZ:
vnf = VNFunc(GT_RSZ);
break;
case CORINFO_HELP_LMUL:
case CORINFO_HELP_LMUL_OVF:
vnf = VNFunc(GT_MUL);
break;
case CORINFO_HELP_ULMUL_OVF:
vnf = VNFunc(GT_MUL);
break; // Is this the right thing?
case CORINFO_HELP_LDIV:
vnf = VNFunc(GT_DIV);
break;
case CORINFO_HELP_LMOD:
vnf = VNFunc(GT_MOD);
break;
case CORINFO_HELP_ULDIV:
vnf = VNFunc(GT_UDIV);
break;
case CORINFO_HELP_ULMOD:
vnf = VNFunc(GT_UMOD);
break;
case CORINFO_HELP_LNG2DBL:
vnf = VNF_Lng2Dbl;
break;
case CORINFO_HELP_ULNG2DBL:
vnf = VNF_ULng2Dbl;
break;
case CORINFO_HELP_DBL2INT:
vnf = VNF_Dbl2Int;
break;
case CORINFO_HELP_DBL2INT_OVF:
vnf = VNF_Dbl2Int;
break;
case CORINFO_HELP_DBL2LNG:
vnf = VNF_Dbl2Lng;
break;
case CORINFO_HELP_DBL2LNG_OVF:
vnf = VNF_Dbl2Lng;
break;
case CORINFO_HELP_DBL2UINT:
vnf = VNF_Dbl2UInt;
break;
case CORINFO_HELP_DBL2UINT_OVF:
vnf = VNF_Dbl2UInt;
break;
case CORINFO_HELP_DBL2ULNG:
vnf = VNF_Dbl2ULng;
break;
case CORINFO_HELP_DBL2ULNG_OVF:
vnf = VNF_Dbl2ULng;
break;
case CORINFO_HELP_FLTREM:
vnf = VNFunc(GT_MOD);
break;
case CORINFO_HELP_DBLREM:
vnf = VNFunc(GT_MOD);
break;
case CORINFO_HELP_FLTROUND:
vnf = VNF_FltRound;
break; // Is this the right thing?
case CORINFO_HELP_DBLROUND:
vnf = VNF_DblRound;
break; // Is this the right thing?
// These allocation operations probably require some augmentation -- perhaps allocSiteId,
// something about array length...
case CORINFO_HELP_NEW_CROSSCONTEXT:
case CORINFO_HELP_NEWFAST:
case CORINFO_HELP_NEWSFAST:
case CORINFO_HELP_NEWSFAST_ALIGN8:
vnf = VNF_JitNew;
break;
case CORINFO_HELP_READYTORUN_NEW:
vnf = VNF_JitReadyToRunNew;
break;
case CORINFO_HELP_NEWARR_1_DIRECT:
case CORINFO_HELP_NEWARR_1_OBJ:
case CORINFO_HELP_NEWARR_1_VC:
case CORINFO_HELP_NEWARR_1_ALIGN8:
vnf = VNF_JitNewArr;
break;
case CORINFO_HELP_READYTORUN_NEWARR_1:
vnf = VNF_JitReadyToRunNewArr;
break;
case CORINFO_HELP_GETGENERICS_GCSTATIC_BASE:
vnf = VNF_GetgenericsGcstaticBase;
break;
case CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE:
vnf = VNF_GetgenericsNongcstaticBase;
break;
case CORINFO_HELP_GETSHARED_GCSTATIC_BASE:
vnf = VNF_GetsharedGcstaticBase;
break;
case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE:
vnf = VNF_GetsharedNongcstaticBase;
break;
case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR:
vnf = VNF_GetsharedGcstaticBaseNoctor;
break;
case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR:
vnf = VNF_GetsharedNongcstaticBaseNoctor;
break;
case CORINFO_HELP_READYTORUN_STATIC_BASE:
vnf = VNF_ReadyToRunStaticBase;
break;
#if COR_JIT_EE_VERSION > 460
case CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE:
vnf = VNF_ReadyToRunGenericStaticBase;
break;
#endif // COR_JIT_EE_VERSION > 460
case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS:
vnf = VNF_GetsharedGcstaticBaseDynamicclass;
break;
case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS:
vnf = VNF_GetsharedNongcstaticBaseDynamicclass;
break;
case CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS:
vnf = VNF_ClassinitSharedDynamicclass;
break;
case CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE:
vnf = VNF_GetgenericsGcthreadstaticBase;
break;
case CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE:
vnf = VNF_GetgenericsNongcthreadstaticBase;
break;
case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE:
vnf = VNF_GetsharedGcthreadstaticBase;
break;
case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE:
vnf = VNF_GetsharedNongcthreadstaticBase;
break;
case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR:
vnf = VNF_GetsharedGcthreadstaticBaseNoctor;
break;
case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR:
vnf = VNF_GetsharedNongcthreadstaticBaseNoctor;
break;
case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS:
vnf = VNF_GetsharedGcthreadstaticBaseDynamicclass;
break;
case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS:
vnf = VNF_GetsharedNongcthreadstaticBaseDynamicclass;
break;
case CORINFO_HELP_GETSTATICFIELDADDR_CONTEXT:
vnf = VNF_GetStaticAddrContext;
break;
case CORINFO_HELP_GETSTATICFIELDADDR_TLS:
vnf = VNF_GetStaticAddrTLS;
break;
case CORINFO_HELP_RUNTIMEHANDLE_METHOD:
case CORINFO_HELP_RUNTIMEHANDLE_METHOD_LOG:
vnf = VNF_RuntimeHandleMethod;
break;
case CORINFO_HELP_RUNTIMEHANDLE_CLASS:
case CORINFO_HELP_RUNTIMEHANDLE_CLASS_LOG:
vnf = VNF_RuntimeHandleClass;
break;
case CORINFO_HELP_STRCNS:
vnf = VNF_StrCns;
break;
case CORINFO_HELP_CHKCASTCLASS:
case CORINFO_HELP_CHKCASTCLASS_SPECIAL:
case CORINFO_HELP_CHKCASTARRAY:
case CORINFO_HELP_CHKCASTINTERFACE:
case CORINFO_HELP_CHKCASTANY:
vnf = VNF_CastClass;
break;
case CORINFO_HELP_READYTORUN_CHKCAST:
vnf = VNF_ReadyToRunCastClass;
break;
case CORINFO_HELP_ISINSTANCEOFCLASS:
case CORINFO_HELP_ISINSTANCEOFINTERFACE:
case CORINFO_HELP_ISINSTANCEOFARRAY:
case CORINFO_HELP_ISINSTANCEOFANY:
vnf = VNF_IsInstanceOf;
break;
case CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE:
vnf = VNF_TypeHandleToRuntimeType;
break;
case CORINFO_HELP_READYTORUN_ISINSTANCEOF:
vnf = VNF_ReadyToRunIsInstanceOf;
break;
case CORINFO_HELP_LDELEMA_REF:
vnf = VNF_LdElemA;
break;
case CORINFO_HELP_UNBOX:
vnf = VNF_Unbox;
break;
// A constant within any method.
case CORINFO_HELP_GETCURRENTMANAGEDTHREADID:
vnf = VNF_ManagedThreadId;
break;
case CORINFO_HELP_GETREFANY:
// TODO-CQ: This should really be interpreted as just a struct field reference, in terms of values.
vnf = VNF_GetRefanyVal;
break;
case CORINFO_HELP_GETCLASSFROMMETHODPARAM:
vnf = VNF_GetClassFromMethodParam;
break;
case CORINFO_HELP_GETSYNCFROMCLASSHANDLE:
vnf = VNF_GetSyncFromClassHandle;
break;
case CORINFO_HELP_LOOP_CLONE_CHOICE_ADDR:
vnf = VNF_LoopCloneChoiceAddr;
break;
case CORINFO_HELP_BOX_NULLABLE:
vnf = VNF_BoxNullable;
break;
default:
unreached();
}
assert(vnf != VNF_Boundary);
return vnf;
}
bool Compiler::fgValueNumberHelperCall(GenTreeCall* call)
{
CorInfoHelpFunc helpFunc = eeGetHelperNum(call->gtCallMethHnd);
bool pure = s_helperCallProperties.IsPure(helpFunc);
bool isAlloc = s_helperCallProperties.IsAllocator(helpFunc);
bool modHeap = s_helperCallProperties.MutatesHeap(helpFunc);
bool mayRunCctor = s_helperCallProperties.MayRunCctor(helpFunc);
bool noThrow = s_helperCallProperties.NoThrow(helpFunc);
ValueNumPair vnpExc = ValueNumStore::VNPForEmptyExcSet();
// If the JIT helper can throw an exception make sure that we fill in
// vnpExc with a Value Number that represents the exception(s) that can be thrown.
if (!noThrow)
{
// If the helper is known to only throw only one particular exception
// we can set vnpExc to that exception, otherwise we conservatively
// model the JIT helper as possibly throwing multiple different exceptions
//
switch (helpFunc)
{
case CORINFO_HELP_OVERFLOW:
// This helper always throws the VNF_OverflowExc exception
vnpExc = vnStore->VNPExcSetSingleton(vnStore->VNPairForFunc(TYP_REF, VNF_OverflowExc));
break;
default:
// Setup vnpExc with the information that multiple different exceptions
// could be generated by this helper
vnpExc = vnStore->VNPExcSetSingleton(vnStore->VNPairForFunc(TYP_REF, VNF_HelperMultipleExc));
}
}
ValueNumPair vnpNorm;
if (call->TypeGet() == TYP_VOID)
{
vnpNorm = ValueNumStore::VNPForVoid();
}
else
{
// TODO-CQ: this is a list of helpers we're going to treat as non-pure,
// because they raise complications. Eventually, we need to handle those complications...
bool needsFurtherWork = false;
switch (helpFunc)
{
case CORINFO_HELP_NEW_MDARR:
// This is a varargs helper. We need to represent the array shape in the VN world somehow.
needsFurtherWork = true;
break;
default:
break;
}
if (!needsFurtherWork && (pure || isAlloc))
{
VNFunc vnf = fgValueNumberHelperMethVNFunc(helpFunc);
if (mayRunCctor)
{
if ((call->gtFlags & GTF_CALL_HOISTABLE) == 0)
{
modHeap = true;
}
}
fgValueNumberHelperCallFunc(call, vnf, vnpExc);
return modHeap;
}
else
{
vnpNorm.SetBoth(vnStore->VNForExpr(compCurBB, call->TypeGet()));
}
}
call->gtVNPair = vnStore->VNPWithExc(vnpNorm, vnpExc);
return modHeap;
}
#ifdef DEBUG
// This method asserts that SSA name constraints specified are satisfied.
// Until we figure out otherwise, all VN's are assumed to be liberal.
// TODO-Cleanup: new JitTestLabels for lib vs cons vs both VN classes?
void Compiler::JitTestCheckVN()
{
typedef SimplerHashTable<ssize_t, SmallPrimitiveKeyFuncs<ssize_t>, ValueNum, JitSimplerHashBehavior> LabelToVNMap;
typedef SimplerHashTable<ValueNum, SmallPrimitiveKeyFuncs<ValueNum>, ssize_t, JitSimplerHashBehavior> VNToLabelMap;
// If we have no test data, early out.
if (m_nodeTestData == nullptr)
{
return;
}
NodeToTestDataMap* testData = GetNodeTestData();
// First we have to know which nodes in the tree are reachable.
typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, int, JitSimplerHashBehavior> NodeToIntMap;
NodeToIntMap* reachable = FindReachableNodesInNodeTestData();
LabelToVNMap* labelToVN = new (getAllocatorDebugOnly()) LabelToVNMap(getAllocatorDebugOnly());
VNToLabelMap* vnToLabel = new (getAllocatorDebugOnly()) VNToLabelMap(getAllocatorDebugOnly());
if (verbose)
{
printf("\nJit Testing: Value numbering.\n");
}
for (NodeToTestDataMap::KeyIterator ki = testData->Begin(); !ki.Equal(testData->End()); ++ki)
{
TestLabelAndNum tlAndN;
GenTreePtr node = ki.Get();
ValueNum nodeVN = node->GetVN(VNK_Liberal);
bool b = testData->Lookup(node, &tlAndN);
assert(b);
if (tlAndN.m_tl == TL_VN || tlAndN.m_tl == TL_VNNorm)
{
int dummy;
if (!reachable->Lookup(node, &dummy))
{
printf("Node ");
Compiler::printTreeID(node);
printf(" had a test constraint declared, but has become unreachable at the time the constraint is "
"tested.\n"
"(This is probably as a result of some optimization -- \n"
"you may need to modify the test case to defeat this opt.)\n");
assert(false);
}
if (verbose)
{
printf(" Node ");
Compiler::printTreeID(node);
printf(" -- VN class %d.\n", tlAndN.m_num);
}
if (tlAndN.m_tl == TL_VNNorm)
{
nodeVN = vnStore->VNNormVal(nodeVN);
}
ValueNum vn;
if (labelToVN->Lookup(tlAndN.m_num, &vn))
{
if (verbose)
{
printf(" Already in hash tables.\n");
}
// The mapping(s) must be one-to-one: if the label has a mapping, then the ssaNm must, as well.
ssize_t num2;
bool b = vnToLabel->Lookup(vn, &num2);
// And the mappings must be the same.
if (tlAndN.m_num != num2)
{
printf("Node: ");
Compiler::printTreeID(node);
printf(", with value number " STR_VN "%x, was declared in VN class %d,\n", nodeVN, tlAndN.m_num);
printf("but this value number " STR_VN
"%x has already been associated with a different SSA name class: %d.\n",
vn, num2);
assert(false);
}
// And the current node must be of the specified SSA family.
if (nodeVN != vn)
{
printf("Node: ");
Compiler::printTreeID(node);
printf(", " STR_VN "%x was declared in SSA name class %d,\n", nodeVN, tlAndN.m_num);
printf("but that name class was previously bound to a different value number: " STR_VN "%x.\n", vn);
assert(false);
}
}
else
{
ssize_t num;
// The mapping(s) must be one-to-one: if the label has no mapping, then the ssaNm may not, either.
if (vnToLabel->Lookup(nodeVN, &num))
{
printf("Node: ");
Compiler::printTreeID(node);
printf(", " STR_VN "%x was declared in value number class %d,\n", nodeVN, tlAndN.m_num);
printf(
"but this value number has already been associated with a different value number class: %d.\n",
num);
assert(false);
}
// Add to both mappings.
labelToVN->Set(tlAndN.m_num, nodeVN);
vnToLabel->Set(nodeVN, tlAndN.m_num);
if (verbose)
{
printf(" added to hash tables.\n");
}
}
}
}
}
void Compiler::vnpPrint(ValueNumPair vnp, unsigned level)
{
if (vnp.BothEqual())
{
vnPrint(vnp.GetLiberal(), level);
}
else
{
printf("<l:");
vnPrint(vnp.GetLiberal(), level);
printf(", c:");
vnPrint(vnp.GetConservative(), level);
printf(">");
}
}
void Compiler::vnPrint(ValueNum vn, unsigned level)
{
if (ValueNumStore::isReservedVN(vn))
{
printf(ValueNumStore::reservedName(vn));
}
else
{
printf(STR_VN "%x", vn);
if (level > 0)
{
vnStore->vnDump(this, vn);
}
}
}
#endif // DEBUG
// Methods of ValueNumPair.
ValueNumPair::ValueNumPair() : m_liberal(ValueNumStore::NoVN), m_conservative(ValueNumStore::NoVN)
{
}
bool ValueNumPair::BothDefined() const
{
return (m_liberal != ValueNumStore::NoVN) && (m_conservative != ValueNumStore::NoVN);
}
| {
"content_hash": "55407eee3374275f96d3e4e337b69639",
"timestamp": "",
"source": "github",
"line_count": 7916,
"max_line_length": 120,
"avg_line_length": 38.57806973218798,
"alnum_prop": 0.5119423414455243,
"repo_name": "sjsinju/coreclr",
"id": "3ab27e4c1bc0eb123ee1c91f05ea2567c221b460",
"size": "305384",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/jit/valuenum.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1005088"
},
{
"name": "Awk",
"bytes": "5861"
},
{
"name": "Batchfile",
"bytes": "110363"
},
{
"name": "C",
"bytes": "2900914"
},
{
"name": "C#",
"bytes": "134970711"
},
{
"name": "C++",
"bytes": "69031634"
},
{
"name": "CMake",
"bytes": "637309"
},
{
"name": "Groovy",
"bytes": "185276"
},
{
"name": "Makefile",
"bytes": "2736"
},
{
"name": "Objective-C",
"bytes": "656894"
},
{
"name": "PAWN",
"bytes": "903"
},
{
"name": "Perl",
"bytes": "24550"
},
{
"name": "PowerShell",
"bytes": "5539"
},
{
"name": "Python",
"bytes": "207778"
},
{
"name": "Roff",
"bytes": "529523"
},
{
"name": "Shell",
"bytes": "182104"
},
{
"name": "Smalltalk",
"bytes": "1354762"
},
{
"name": "SuperCollider",
"bytes": "4752"
},
{
"name": "Yacc",
"bytes": "157348"
}
],
"symlink_target": ""
} |
"""Functions and Classes used to build the QAOA circuit in cirq for 2-SAT.
Quantum Approximate Optimization Algorithm (QAOA) provides a recipe on how to
parametrized a trial wavefunction of the ground state which can be solved
variationally.
Original paper:
A Quantum Approximate Optimization Algorithm
https://arxiv.org/abs/1411.4028
Different from the standard QAOA algorithm, we will allocate chunks of time to
apply either Hamiltonian, and optimize over these decisions.
"""
import itertools
import math
from typing import List
import cirq
from bangbang_qaoa import circuit_lib
from bangbang_qaoa.two_sat import dnf_lib
def _get_sign(is_negative, other_is_negative = False):
"""Returns the sign to multiply by time.
Args:
is_negative: Boolean. If True, multiply by -1.
other_is_negative: Additional argument. If True, multiply by -1.
Default value False
Returns:
-1 or 1 integer. -1 if only one of is_negative values is True
"""
return (1 - 2 * is_negative) * (1 - 2 * other_is_negative)
def generate_clause_hamiltonian_exponential(clause, time
):
"""Generates the operators for this clause.
Applies e^(iZt) on each qubit, and e^(i ZZ t) on both. The sign of t gets
flipped if the variable is negated.
Args:
clause: dnf_lib.Clause, the clause that defines the local Hamiltonian
time: Float, how long to apply the Hamiltonian
Returns:
A list of operations corresponding to each of the gates being applied by
this clause.
"""
# Corrects for the fact that ZPowGate and ZZPowGate perform e^(-i*\pi*Z*t/2)
# up to global phase.
time = -2 * time / math.pi
return [
cirq.ZPowGate(
exponent=_get_sign(clause.is_negative1) * time,
global_shift=-0.5).on(cirq.LineQubit(clause.index1)),
cirq.ZPowGate(
exponent=_get_sign(clause.is_negative2) * time,
global_shift=-0.5).on(cirq.LineQubit(clause.index2)),
cirq.ZZPowGate(
exponent=_get_sign(clause.is_negative1, clause.is_negative2) * time,
global_shift=-0.5).on(cirq.LineQubit(clause.index1),
cirq.LineQubit(clause.index2))]
def generate_dnf_hamiltonian_exponential(dnf, time
):
"""Returns the list of all operators for the DNF.
Iterates over the list of operators produced by each clause and flattens.
Args:
dnf: dnf_lib.DNF, the dnf that defines the local Hamiltonian.
time: Float, how long to apply the Hamiltonian.
Returns:
List of all cirq operators for the Hamiltonian defined by the DNF.
"""
clause_operators_list = [
generate_clause_hamiltonian_exponential(clause, time)
for clause in dnf.clauses
]
return list(itertools.chain.from_iterable(clause_operators_list))
class BangBangProtocolCircuit(circuit_lib.BangBangProtocolCircuit):
"""Modified QAOA circuit generator for bang-bang protocols.
This circuit will divide the given time into a series of chunks that will
be allocated to one of the two Hamiltonians.
Attributes:
chunk_time: Positive float, amount of time allocated to each chunk.
dnf: dnf_lib.DNF, the 2-DNF we are trying to find the best solution to.
hamiltonian_diagonal: List of floats, the diagonal of the target
Hamiltonian, that determines the evaluations of each measurement.
simulator: cirq.Simulator, the simulator to run the circuit.
"""
def __init__(self, chunk_time, dnf):
"""Initializer.
This class creates QAOA circuit in cirq.
Args:
chunk_time: Positive float, amount of time allocated to each chunk.
dnf: dnf_lib.DNF, the 2-DNF we are trying to find the best solution to.
"""
super(BangBangProtocolCircuit, self).__init__(chunk_time, dnf.num_literals)
self.dnf = dnf
self.hamiltonian_diagonal = self.get_hamiltonian_diagonal()
def generate_constraint_hamiltonian_exponential(self, time):
"""Returns the time evolution of the Hamiltonian for the DNF.
Iterates over the list of operators produced by each clause and flattens.
Args:
time: Float, how long to apply the Hamiltonian.
Returns:
List of all cirq operators for the Hamiltonian defined by the DNF.
"""
return generate_dnf_hamiltonian_exponential(self.dnf, time)
def constraint_evaluation(self, measurement):
"""Returns the fraction of clauses were satisfied compared to optimal.
For any given 2-DNF, we want to maximize the probability of measuring
literal assignments that return large values.
Args:
measurement: List of 0s and 1s, corresponding to a binary value of a
measurement. Each 0 or 1 corresponds to a truth value of a literal
assignement, where 0 is False and 1 is True.
Returns:
Float in interval [0, 1], the number of clauses satisfied by this literal
assignment divided by the number of clauses satisfied by the optimal
assignment.
"""
return (self.dnf.get_num_clauses_satisfied(measurement) /
self.dnf.optimal_num_satisfied)
| {
"content_hash": "9cc60035ff126419c869df230a93b1ee",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 79,
"avg_line_length": 34.62162162162162,
"alnum_prop": 0.6963309914129586,
"repo_name": "google-research/google-research",
"id": "4ba72b93356d7403be7f5439de7a6b0bc0ff4eb8",
"size": "5732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bangbang_qaoa/two_sat/dnf_circuit_lib.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9817"
},
{
"name": "C++",
"bytes": "4166670"
},
{
"name": "CMake",
"bytes": "6412"
},
{
"name": "CSS",
"bytes": "27092"
},
{
"name": "Cuda",
"bytes": "1431"
},
{
"name": "Dockerfile",
"bytes": "7145"
},
{
"name": "Gnuplot",
"bytes": "11125"
},
{
"name": "HTML",
"bytes": "77599"
},
{
"name": "ImageJ Macro",
"bytes": "50488"
},
{
"name": "Java",
"bytes": "487585"
},
{
"name": "JavaScript",
"bytes": "896512"
},
{
"name": "Julia",
"bytes": "67986"
},
{
"name": "Jupyter Notebook",
"bytes": "71290299"
},
{
"name": "Lua",
"bytes": "29905"
},
{
"name": "MATLAB",
"bytes": "103813"
},
{
"name": "Makefile",
"bytes": "5636"
},
{
"name": "NASL",
"bytes": "63883"
},
{
"name": "Perl",
"bytes": "8590"
},
{
"name": "Python",
"bytes": "53790200"
},
{
"name": "R",
"bytes": "101058"
},
{
"name": "Roff",
"bytes": "1208"
},
{
"name": "Rust",
"bytes": "2389"
},
{
"name": "Shell",
"bytes": "730444"
},
{
"name": "Smarty",
"bytes": "5966"
},
{
"name": "Starlark",
"bytes": "245038"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="support-vector-drawable-23.4.0">
<CLASSES>
<root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-vector-drawable/23.4.0/jars/classes.jar!/" />
<root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/support-vector-drawable/23.4.0/res" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://D:/android-sdk_r24.3.4-windows/android-sdk-windows/extras/android/m2repository/com/android/support/support-vector-drawable/23.4.0/support-vector-drawable-23.4.0-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "15f8ac203405f4bb4e33b0fd9412d9b3",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 201,
"avg_line_length": 55.416666666666664,
"alnum_prop": 0.706766917293233,
"repo_name": "chengkun123/FallPhotoWall",
"id": "5952967d5b741ee9d8fb26c44fa5847b7b7d7ee8",
"size": "665",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/support_vector_drawable_23_4_0.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "106122"
}
],
"symlink_target": ""
} |
package org.drools.persistence.map;
import org.drools.persistence.info.SessionInfo;
import org.drools.persistence.info.WorkItemInfo;
public interface KnowledgeSessionStorage {
SessionInfo findSessionInfo(Long sessionId);
void saveOrUpdate(SessionInfo storedObject);
void lock(SessionInfo sessionInfo);
void saveOrUpdate(WorkItemInfo workItemInfo);
Long getNextWorkItemId();
WorkItemInfo findWorkItemInfo(Long id);
void remove(WorkItemInfo workItemInfo);
void lock(WorkItemInfo workItemInfo);
Long getNextStatefulKnowledgeSessionId();
}
| {
"content_hash": "32e3f4108997e8daa48ff24ad4089c81",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 49,
"avg_line_length": 21.214285714285715,
"alnum_prop": 0.7693602693602694,
"repo_name": "jiripetrlik/drools",
"id": "f4c0f9c541fc11df93f8fa207a7502de02f53f7d",
"size": "1171",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "drools-persistence-jpa/src/main/java/org/drools/persistence/map/KnowledgeSessionStorage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2554"
},
{
"name": "CSS",
"bytes": "1412"
},
{
"name": "GAP",
"bytes": "197229"
},
{
"name": "HTML",
"bytes": "10889"
},
{
"name": "Java",
"bytes": "27474110"
},
{
"name": "Protocol Buffer",
"bytes": "13819"
},
{
"name": "Python",
"bytes": "4555"
},
{
"name": "Ruby",
"bytes": "491"
},
{
"name": "Shell",
"bytes": "1120"
},
{
"name": "Standard ML",
"bytes": "82260"
},
{
"name": "XSLT",
"bytes": "24302"
}
],
"symlink_target": ""
} |
"""
Address book store interfaces
"""
from txdav.common.icommondatastore import ICommonTransaction, \
IShareableCollection, CommonStoreError
from txdav.idav import INotifier
from txdav.idav import IDataStoreObject
__all__ = [
# Classes
"GroupWithUnsharedAddressNotAllowedError",
"KindChangeNotAllowedError",
"IAddressBookTransaction",
"IAddressBookHome",
"IAddressBook",
"IAddressBookObject",
]
class GroupWithUnsharedAddressNotAllowedError(CommonStoreError):
"""
Sharee cannot add unshared group members.
"""
class KindChangeNotAllowedError(CommonStoreError):
"""
Cannot change group kind.
"""
class IAddressBookTransaction(ICommonTransaction):
"""
Transaction interface that addressbook stores must provide.
"""
def addressbookHomeWithUID(uid, create=False): #@NoSelf
"""
Retrieve the addressbook home for the principal with the given C{uid}.
If C{create} is C{True}, create the addressbook home if it doesn't
already exist.
@return: a L{Deferred} which fires with an L{IAddressBookHome} or
C{None} if no such addressbook home exists.
"""
#
# Interfaces
#
class IAddressBookHome(INotifier, IDataStoreObject):
"""
AddressBook home
An addressbook home belongs to a specific principal and contains the
addressbooks which that principal has direct access to. This
includes both addressbooks owned by the principal as well as
addressbooks that have been shared with and accepts by the principal.
"""
def uid(): #@NoSelf
"""
Retrieve the unique identifier for this addressbook home.
@return: a string.
"""
def addressbooks(): #@NoSelf
"""
Retrieve addressbooks contained in this addressbook home.
@return: an iterable of L{IAddressBook}s.
"""
def loadAddressbooks(): #@NoSelf
"""
Pre-load all addressbooks Depth:1.
@return: an iterable of L{IAddressBook}s.
"""
def addressbookWithName(name): #@NoSelf
"""
Retrieve the addressbook with the given C{name} contained in this
addressbook home.
@param name: a string.
@return: an L{IAddressBook} or C{None} if no such addressbook
exists.
"""
def createAddressBookWithName(name): #@NoSelf
"""
Create an addressbook with the given C{name} in this addressbook
home.
@param name: a string.
@raise AddressBookAlreadyExistsError: if an addressbook with the
given C{name} already exists.
"""
def removeAddressBookWithName(name): #@NoSelf
"""
Remove the addressbook with the given C{name} from this addressbook
home. If this addressbook home owns the addressbook, also remove
the addressbook from all addressbook homes.
@param name: a string.
@raise NoSuchAddressBookObjectError: if no such addressbook exists.
"""
class IAddressBook(INotifier, IShareableCollection, IDataStoreObject):
"""
AddressBook
An addressbook is a container for addressbook objects (contacts),
An addressbook belongs to a specific principal but may be
shared with other principals, granting them read-only or
read/write access.
"""
def rename(name): #@NoSelf
"""
Change the name of this addressbook.
"""
def ownerAddressBookHome(): #@NoSelf
"""
Retrieve the addressbook home for the owner of this addressbook.
AddressBooks may be shared from one (the owner's) addressbook home
to other (the sharee's) addressbook homes.
@return: an L{IAddressBookHome}.
"""
def addressbookObjects(): #@NoSelf
"""
Retrieve the addressbook objects contained in this addressbook.
@return: an iterable of L{IAddressBookObject}s.
"""
def addressbookObjectWithName(name): #@NoSelf
"""
Retrieve the addressbook object with the given C{name} contained
in this addressbook.
@param name: a string.
@return: a L{Deferred} that fires with an L{IAddressBookObject} or
C{None} if no such addressbook object exists.
"""
def addressbookObjectWithUID(uid): #@NoSelf
"""
Retrieve the addressbook object with the given C{uid} contained
in this addressbook.
@param uid: a string.
@return: an L{IAddressBookObject} or C{None} if no such addressbook
object exists.
"""
def createAddressBookObjectWithName(name, component): #@NoSelf
"""
Create an addressbook component with the given C{name} in this
addressbook from the given C{component}.
@param name: a string.
@param component: a C{VCARD} L{Component}
@raise AddressBookObjectNameAlreadyExistsError: if an addressbook
object with the given C{name} already exists.
@raise AddressBookObjectUIDAlreadyExistsError: if an addressbook
object with the same UID as the given C{component} already
exists.
@raise InvalidAddressBookComponentError: if the given
C{component} is not a valid C{VCARD} L{VComponent} for
an addressbook object.
"""
def syncToken(): #@NoSelf
"""
Retrieve the current sync token for this addressbook.
@return: a string containing a sync token.
"""
def addressbookObjectsSinceToken(token): #@NoSelf
"""
Retrieve all addressbook objects in this addressbook that have
changed since the given C{token} was last valid.
@param token: a sync token.
@return: a 3-tuple containing an iterable of
L{IAddressBookObject}s that have changed, an iterable of uids
that have been removed, and the current sync token.
"""
class IAddressBookObject(IDataStoreObject):
"""
AddressBook object
An addressbook object describes a contact (vCard).
"""
def addressbook(): #@NoSelf
"""
@return: The address book which this address book object is a part of.
@rtype: L{IAddressBook}
"""
def setComponent(component): #@NoSelf
"""
Rewrite this addressbook object to match the given C{component}.
C{component} must have the same UID and KIND as this addressbook object.
@param component: a C{VCARD} L{VComponent}.
@raise InvalidAddressBookComponentError: if the given
C{component} is not a valid C{VCARD} L{VComponent} for
an addressbook object.
"""
def component(): #@NoSelf
"""
Retrieve the addressbook component for this addressbook object.
@raise ConcurrentModification: if this L{IAddressBookObject} has been
deleted and committed by another transaction between its creation
and the first call to this method.
@return: a C{VCARD} L{VComponent}.
"""
def uid(): #@NoSelf
"""
Retrieve the UID for this addressbook object.
@return: a string containing a UID.
"""
| {
"content_hash": "b86fd9034fff9e1aeea0fbf2466f518f",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 80,
"avg_line_length": 28.96,
"alnum_prop": 0.6439226519337017,
"repo_name": "trevor/calendarserver",
"id": "07e731e2a0e70e8729a50ed8a113dc0703c16f19",
"size": "7962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "txdav/carddav/iaddressbookstore.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4214"
},
{
"name": "D",
"bytes": "13143"
},
{
"name": "JavaScript",
"bytes": "76566"
},
{
"name": "Python",
"bytes": "9260291"
},
{
"name": "Shell",
"bytes": "78964"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="date_time">d MMMM, EEEE</string>
<string name="language">en</string>
<string name="desc_date_format">d MMMM, EEEE</string>
<string name="desc_time">'hozirgi vaqt' + #hour12+' '+ifelse(#minute,#minute,'oclock')+', soat ilovasiga kirish uchun ikki marta bosing'</string>
<string name="weather_type_0">Tiniq</string>
<string name="weather_type_1">Bulutli</string>
<string name="weather_type_2">Tumanli</string>
<string name="weather_type_3">Tumanli</string>
<string name="weather_type_4">Qattiq yomg'ir</string>
<string name="weather_type_5">Jala</string>
<string name="weather_type_6">Juda kuchli yog'ingarchilik</string>
<string name="weather_type_7">Momaqaldiroq</string>
<string name="weather_type_8">Jala</string>
<string name="weather_type_9">Kuchli yog'ingarchilik</string>
<string name="weather_type_10">Yomg'ir</string>
<string name="weather_type_11">Mayda yomg'ir</string>
<string name="weather_type_12">Qorli yomg'ir</string>
<string name="weather_type_13">Qor bo'roni</string>
<string name="weather_type_14">Qorli jala</string>
<string name="weather_type_15">Kuchli qor</string>
<string name="weather_type_16">Qor</string>
<string name="weather_type_17">Yengil qor</string>
<string name="weather_type_18">Kuchli qum bo'roni</string>
<string name="weather_type_19">Qum bo'roni</string>
<string name="weather_type_20">Engil qum bo'roni</string>
<string name="weather_type_21">Qum bo'roni</string>
<string name="weather_type_22">Do'l</string>
<string name="weather_type_23">Chang</string>
<string name="weather_type_24">Tumanli</string>
</resources>
| {
"content_hash": "c487e795bfc4eed53552f0c6226c9c96",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 149,
"avg_line_length": 54.28125,
"alnum_prop": 0.6850892343120323,
"repo_name": "ingbrzy/Xiaomi.eu-MIUIv9-XML-Compare",
"id": "06791210652e791440843b4bac23d99155474608",
"size": "1737",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "mido/extras/weather_clock/content/strings/strings_uz_UZ.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Smali",
"bytes": "200738"
}
],
"symlink_target": ""
} |
java -Djava.security.egd=file:/dev/./urandom -jar /app/app.jar | {
"content_hash": "99405d07d4b2a66bebdae6025a9e62b5",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 62,
"avg_line_length": 62,
"alnum_prop": 0.7419354838709677,
"repo_name": "zjqbobo/master2",
"id": "41a0d44d1eb0e1ec5c01aab15c77bd294b9542c3",
"size": "62",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spring.cloud/discovery/target/classes/runboot.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "168940"
},
{
"name": "HTML",
"bytes": "20339"
},
{
"name": "Java",
"bytes": "111704"
},
{
"name": "JavaScript",
"bytes": "710287"
},
{
"name": "Shell",
"bytes": "765"
}
],
"symlink_target": ""
} |
import { Directive, ElementRef, Input, Output, EventEmitter,
Renderer, HostListener, AfterContentChecked, AfterViewChecked }from '@angular/core';
@Directive({ selector: '[focus]' })
export class FocusDirective implements AfterContentChecked, AfterViewChecked {
@Input("focus") focus: boolean = false;
ngAfterContentChecked(){
// if(this.focus){
// setTimeout(()=>{
// this.elementRef.nativeElement.focus();
// }, 300);
// }
}
ngAfterViewChecked(){
if(this.focus){
this.elementRef.nativeElement.focus();
}
}
constructor(private elementRef: ElementRef){
}
} | {
"content_hash": "9e45e62c4021e00cc54172804439b3dc",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 86,
"avg_line_length": 28,
"alnum_prop": 0.6145833333333334,
"repo_name": "nickppa/MyCompents",
"id": "831b53a1a9b612c7b317be1cf2bbad9ef053bc50",
"size": "672",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/Components/Shares/Focus/focus.directive.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39085"
},
{
"name": "HTML",
"bytes": "31157"
},
{
"name": "JavaScript",
"bytes": "65422"
},
{
"name": "TypeScript",
"bytes": "93988"
}
],
"symlink_target": ""
} |
/**
* Reverse a linked list from position m to n
* Do it in-place and in one-pass
*
* Eg:
* Given 1->2->3->4->5->NULL, m = 2 and n = 4
* Return 1->4->3->2->5->NULL
*
* Note:
* 1 <= m <= n <= length of the list
*
* Tags: Linkedlist
*/
class reverseLinkedList2 {
public static void main(String[] args) {
}
/**
* Move pointers to m
* Then insert next code to sublist's head till we reach n
* Reconnect sublist with original list after reversing
* We need 1 dummy head, head and tail for sublist,
* And cur for current node, preCur for dummy head of sublist
* 5 pointers in total
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m >= n || head == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for (int i = 1; i < m; i++) pre = pre.next; // m, n 1-based index
ListNode cur = pre.next;
for (int i = m; i < n; i++) { // insert next to head to reverse
ListNode temp = cur.next.next;
cur.next.next = pre.next;
pre.next = cur.next;
cur.next = temp;
} // pre.next - pos to be insert, pre never moved
return dummy.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}
| {
"content_hash": "ec416d23957a9ed281861cfd0973f1b6",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 73,
"avg_line_length": 27.11111111111111,
"alnum_prop": 0.5300546448087432,
"repo_name": "Wei620/LC150",
"id": "14dde6d078f9798ab71417354cbfe4cda8a47953",
"size": "1464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Medium/ReverseLinkedList2.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "474785"
},
{
"name": "SQLPL",
"bytes": "663"
}
],
"symlink_target": ""
} |
package hu.progtech.cd2t100.computation;
/**
* This kind of exception occurs when there was an attempt to register an
* {@code InstructionInfo} to a specified opcode, but the opcode
* has already been mapped to another info object.
*
* @see hu.progtech.cd2t100.formal.InstructionInfo
* @see hu.progtech.cd2t100.formal.InstructionLoader
*/
public class OpcodeAlreadyRegisteredException extends Exception {
/**
* Constructs a new {@code OpcodeAlreadyRegisteredException} with the
* specified message.
*
* @param message the message contained in this exception
*/
public OpcodeAlreadyRegisteredException(String message) {
super(message);
}
}
| {
"content_hash": "9c7a5593401e8b4d29aa1604605d7378",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 74,
"avg_line_length": 30.954545454545453,
"alnum_prop": 0.7430249632892805,
"repo_name": "battila7/cd2t-100",
"id": "f729c451a26eb46a03a62ee3c1b63bc42ab9aaf5",
"size": "681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cd2t-100-core/src/main/java/hu/progtech/cd2t100/computation/OpcodeAlreadyRegisteredException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "1758"
},
{
"name": "CSS",
"bytes": "1017"
},
{
"name": "Groovy",
"bytes": "18066"
},
{
"name": "Java",
"bytes": "304189"
},
{
"name": "Shell",
"bytes": "237"
}
],
"symlink_target": ""
} |
$:.unshift(File.expand_path(File.dirname(__FILE__)))
begin
require 'facets'
require 'facets/date'
rescue
require 'rubygems'
require 'facets'
require 'facets/date'
end
require 'date'
require 'core_ext/string'
require 'calendar_maker/view_helpers'
require 'calendar_maker/calendar'
| {
"content_hash": "43514375b6bddf3aa156f59fe3a6ac83",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 52,
"avg_line_length": 18.3125,
"alnum_prop": 0.7337883959044369,
"repo_name": "jaypee/calendar-maker",
"id": "5566dfbdbb2df8e0c01bfd0536dff53104da50ed",
"size": "293",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/calendar_maker.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
// This file is automatically generated.
package adila.db;
/*
* Fujitsu ARROWS A SoftBank 101F
*
* DEVICE: SBM101F
* MODEL: 101F
*/
final class sbm101f_101f {
public static final String DATA = "Fujitsu|ARROWS A SoftBank 101F|";
}
| {
"content_hash": "8f2e79272f8b3109459aa2cef1095a83",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 72,
"avg_line_length": 18.53846153846154,
"alnum_prop": 0.6970954356846473,
"repo_name": "karim/adila",
"id": "5b71376e9b5a9c1bd050e6fa932aca6f8ba9b302",
"size": "241",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/src/main/java/adila/db/sbm101f_101f.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2903103"
},
{
"name": "Prolog",
"bytes": "489"
},
{
"name": "Python",
"bytes": "3280"
}
],
"symlink_target": ""
} |
#pragma once
#include <cupy/complex/complex.h>
#include <cupy/complex/math_private.h>
namespace thrust {
namespace detail {
namespace complex {
using thrust::complex;
__host__ __device__ inline complex<float> cprojf(const complex<float>& z) {
if (!isinf(z.real()) && !isinf(z.imag())) {
return z;
} else {
// std::numeric_limits<T>::infinity() doesn't run on the GPU
return complex<float>(infinity<float>(), copysignf(0.0, z.imag()));
}
}
__host__ __device__ inline complex<double> cproj(const complex<double>& z) {
if (!isinf(z.real()) && !isinf(z.imag())) {
return z;
} else {
// numeric_limits<T>::infinity() doesn't run on the GPU
return complex<double>(infinity<double>(), copysign(0.0, z.imag()));
}
}
}
}
template <typename T>
__host__ __device__ inline thrust::complex<T> proj(const thrust::complex<T>& z) {
return detail::complex::cproj(z);
}
template <>
__host__ __device__ inline thrust::complex<double> proj(
const thrust::complex<double>& z) {
return detail::complex::cproj(z);
}
template <>
__host__ __device__ inline thrust::complex<float> proj(const thrust::complex<float>& z) {
return detail::complex::cprojf(z);
}
}
| {
"content_hash": "620588430debe7a45f4413acecfdda94",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 89,
"avg_line_length": 24.285714285714285,
"alnum_prop": 0.6436974789915967,
"repo_name": "cupy/cupy",
"id": "f5e2d33901a84b8fc69f65d4424d396880882a91",
"size": "1841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cupy/_core/include/cupy/complex/cproj.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "38"
},
{
"name": "C",
"bytes": "712019"
},
{
"name": "C++",
"bytes": "895316"
},
{
"name": "Cuda",
"bytes": "151799"
},
{
"name": "Cython",
"bytes": "1996454"
},
{
"name": "Dockerfile",
"bytes": "40251"
},
{
"name": "PowerShell",
"bytes": "7361"
},
{
"name": "Python",
"bytes": "4841354"
},
{
"name": "Shell",
"bytes": "24521"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<object name="participant">
<properties>
<property
name="id"
type="integer"
unsigned="1"
notnull="1"
autoincrement="true" />
<property
name="user_id"
type="integer"
unsigned="1"
notnull="1" />
<property
name="survey_publication_id"
type="integer"
unsigned="1"
notnull="1" />
<property
name="date"
type="integer"
unsigned="1"
notnull="1" />
<property
name="progress"
type="integer"
default='0' />
<property
name="status"
type="text"
length="50"
fixed="true"
notnull="1"
default="notstarted" />
<property
name="start_time"
type="integer"
unsigned="1"
notnull="1" />
<property
name="total_time"
type="integer"
unsigned="1"
notnull="1" />
<property
name="context_id"
type="integer"
unsigned="1"
notnull="1" />
<property
name="context_template_id"
type="integer"
unsigned="1"
notnull="1" />
<property
name="parent_id"
type="integer"
unsigned="1"
notnull="1" />
<property
name="context_name"
type="text"
length="150"
fixed="true"
notnull="1" />
</properties>
<index name="survey_publication_id">
<indexproperty name="survey_publication_id" />
</index>
<index name="user_id">
<indexproperty name="user_id" />
</index>
</object> | {
"content_hash": "a635c9cfa4fd3293d721069b39d9c45f",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 54,
"avg_line_length": 26.756756756756758,
"alnum_prop": 0.4075757575757576,
"repo_name": "cosnicsTHLU/cosnics",
"id": "231de3600c50847e9e76b47adea66c80c2e4db4f",
"size": "1980",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Chamilo/Application/Survey/Resources/Storage/participant.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "86189"
},
{
"name": "C#",
"bytes": "23363"
},
{
"name": "CSS",
"bytes": "1135928"
},
{
"name": "CoffeeScript",
"bytes": "17503"
},
{
"name": "Gherkin",
"bytes": "24033"
},
{
"name": "HTML",
"bytes": "542339"
},
{
"name": "JavaScript",
"bytes": "5296016"
},
{
"name": "Makefile",
"bytes": "3221"
},
{
"name": "PHP",
"bytes": "21903304"
},
{
"name": "Ruby",
"bytes": "618"
},
{
"name": "Shell",
"bytes": "6385"
},
{
"name": "Smarty",
"bytes": "15750"
},
{
"name": "XSLT",
"bytes": "44115"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Skiftet\Speakout\Models;
/**
*
*/
class Survey extends BaseModel
{
public function url(): string
{
return $this->client()->endpoint().'/surveys/'.urlencode((string)$this['id']);
}
}
| {
"content_hash": "33dcdd664e3461e4013ed1fa8ae32b34",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 86,
"avg_line_length": 16.466666666666665,
"alnum_prop": 0.6234817813765182,
"repo_name": "Skiftet/php-speakout-api",
"id": "619047789675c96095abb85f0901e25b0ba0fc4b",
"size": "247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Models/Survey.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "749"
},
{
"name": "PHP",
"bytes": "24236"
}
],
"symlink_target": ""
} |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Numbers\V2;
use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;
class RegulatoryComplianceInstance extends InstanceResource {
/**
* Initialize the RegulatoryComplianceInstance
*
* @param Version $version Version that contains the resource
* @param mixed[] $payload The response payload
*/
public function __construct(Version $version, array $payload) {
parent::__construct($version);
$this->solution = [];
}
/**
* Magic getter to access properties
*
* @param string $name Property to access
* @return mixed The requested property
* @throws TwilioException For unknown properties
*/
public function __get(string $name) {
if (\array_key_exists($name, $this->properties)) {
return $this->properties[$name];
}
if (\property_exists($this, '_' . $name)) {
$method = 'get' . \ucfirst($name);
return $this->$method();
}
throw new TwilioException('Unknown property: ' . $name);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString(): string {
return '[Twilio.Numbers.V2.RegulatoryComplianceInstance]';
}
} | {
"content_hash": "e941723ae8b54348277eb789b836aee3",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 67,
"avg_line_length": 25.482758620689655,
"alnum_prop": 0.5940460081190798,
"repo_name": "twilio/twilio-php",
"id": "d98bf456b3ea8d781e87060733c14f095d922080",
"size": "1478",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "src/Twilio/Rest/Numbers/V2/RegulatoryComplianceInstance.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "280"
},
{
"name": "Makefile",
"bytes": "2427"
},
{
"name": "PHP",
"bytes": "13273912"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mangopay.core;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Hector Espert hespert@peertopark.com
*/
public class ObjectToolTest {
public ObjectToolTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of nonNull method, of class ObjectTool.
*/
@Test
public void testNonNull() {
Object object = null;
assertFalse(ObjectTool.nonNull(object));
object = new Object();
assertTrue(ObjectTool.nonNull(object));
}
/**
* Test of isNull method, of class ObjectTool.
*/
@Test
public void testIsNull() {
Object object = null;
assertTrue(ObjectTool.isNull(object));
object = new Object();
assertFalse(ObjectTool.isNull(object));
}
}
| {
"content_hash": "7f047e2ec87cb329bd906e72925c0005",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 79,
"avg_line_length": 20.903225806451612,
"alnum_prop": 0.6234567901234568,
"repo_name": "Mangopay/mangopay2-java-sdk",
"id": "a8faed4e6968551c5ed6b9c313002d978f130e19",
"size": "1296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/mangopay/core/ObjectToolTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "773138"
},
{
"name": "Shell",
"bytes": "478"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace Axiom.Runtime.Builtins.Meta
{
// integer(Term)
public class IntegerPredicate : AbstractPredicate
{
public override int Arity()
{
return 1;
}
public override string Name()
{
return "integer";
}
public override void Execute(AbstractMachineState state)
{
AMProgram program = (AMProgram)state.Program;
AbstractTerm X0 = ((AbstractTerm)state["X0"]).Dereference();
if (X0.IsConstant)
{
string constantData = (string)X0.Data();
int v;
if (Int32.TryParse(constantData, out v))
{
program.Next();
}
else
{
state.Backtrack();
return;
}
}
else
{
state.Backtrack();
}
}
}
}
| {
"content_hash": "e0bc3a9118472b94a5f9f324306b1889",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 72,
"avg_line_length": 21.857142857142858,
"alnum_prop": 0.4407096171802054,
"repo_name": "ahodroj/prologdotnet",
"id": "bb38db26bd7c9d9546edc145632ded1f364d5c05",
"size": "1071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Prolog.AbstractMachine/Builtins/Meta/IntegerPredicate.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "572287"
},
{
"name": "Prolog",
"bytes": "1274"
}
],
"symlink_target": ""
} |
layout: post
date: '2015-06-26'
title: "Antonios Couture 9"
category: Antonios Couture
tags: [Antonios Couture]
---
### Antonios Couture 9
Just **$289.99**
###
<a href="https://www.readybrides.com/en/antonios-couture/17336-antonios-couture-9.html"><img src="//static.msromantic.com/38503/antonios-couture-9.jpg" alt="Antonios Couture 9" style="width:100%;" /></a>
<!-- break --><a href="https://www.readybrides.com/en/antonios-couture/17336-antonios-couture-9.html"><img src="//static.msromantic.com/38502/antonios-couture-9.jpg" alt="Antonios Couture 9" style="width:100%;" /></a>
Buy it: [https://www.readybrides.com/en/antonios-couture/17336-antonios-couture-9.html](https://www.readybrides.com/en/antonios-couture/17336-antonios-couture-9.html)
| {
"content_hash": "2501cd561e8e9cd13608a0548a0de7a8",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 217,
"avg_line_length": 53.714285714285715,
"alnum_prop": 0.7313829787234043,
"repo_name": "variousweddingdress/variousweddingdress.github.io",
"id": "dab9616449d4d1aad54b3b1fafc7b8151cc76055",
"size": "756",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2015-06-26-Antonios-Couture-9.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "83876"
},
{
"name": "HTML",
"bytes": "14755"
},
{
"name": "Ruby",
"bytes": "897"
}
],
"symlink_target": ""
} |
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.util;
/**
* This class describes an DNS'S SRV record.
*
* @author Sebastien Vincent
*/
public class SRVRecord
{
/**
* DNSJava SRVRecord.
*/
private org.xbill.DNS.SRVRecord record;
/**
* Constructor.
*
* @param record DNSJava SRVRecord
*/
public SRVRecord(org.xbill.DNS.SRVRecord record)
{
this.record = record;
}
/**
* Get port.
*
* @return port
*/
public int getPort()
{
return record.getPort();
}
/**
* Get target.
*
* @return target
*/
public String getTarget()
{
return record.getTarget().toString();
}
/**
* Get priority.
*
* @return priority
*/
public int getPriority()
{
return record.getPriority();
}
/**
* Get weight.
*
* @return weight
*/
public int getWeight()
{
return record.getWeight();
}
/**
* Get DNS TTL.
*
* @return DNS TTL
*/
public long getTTL()
{
return record.getTTL();
}
/**
* Get domain name.
*
* @return domain name
*/
public String getName()
{
return record.getName().toString();
}
/**
* Returns the toString of the org.xbill.DNS.SRVRecord that was passed to
* the constructor.
*
* @return the toString of the org.xbill.DNS.SRVRecord that was passed to
* the constructor.
*/
@Override
public String toString()
{
return record.toString();
}
}
| {
"content_hash": "3241e0ad5a2e51afb361c5a124180dda",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 77,
"avg_line_length": 17.038834951456312,
"alnum_prop": 0.5293447293447293,
"repo_name": "ibauersachs/jitsi",
"id": "7423653f47d899cd180f112cbcdc0fb48c1e199f",
"size": "1755",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/net/java/sip/communicator/util/SRVRecord.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "423671"
},
{
"name": "C++",
"bytes": "464408"
},
{
"name": "CSS",
"bytes": "7555"
},
{
"name": "Groff",
"bytes": "2384"
},
{
"name": "HTML",
"bytes": "5051"
},
{
"name": "Java",
"bytes": "21111446"
},
{
"name": "Makefile",
"bytes": "12348"
},
{
"name": "Mathematica",
"bytes": "21265"
},
{
"name": "Objective-C",
"bytes": "171020"
},
{
"name": "Shell",
"bytes": "13717"
},
{
"name": "Visual Basic",
"bytes": "11032"
},
{
"name": "XSLT",
"bytes": "1814"
}
],
"symlink_target": ""
} |
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_15/run_15_comparison}
\caption{Theoretical vortex profile fits to experimental data at $z/c$=6.97, $V_{free}$=23.21, station 2.}
\label{fig:run_15_comparison}
\end{figure}
| {
"content_hash": "84d7e9be181014646add3eb3e8ffa534",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 106,
"avg_line_length": 30,
"alnum_prop": 0.7375,
"repo_name": "Jwely/pivpr",
"id": "bd1ef16822fb18a26292589d90a731e8326102bd",
"size": "240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "texdocs/figs/run_15/run_15_comparison.tex",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "MATLAB",
"bytes": "137127"
},
{
"name": "Python",
"bytes": "183435"
},
{
"name": "TeX",
"bytes": "1267545"
}
],
"symlink_target": ""
} |
import { setPropertiesFromJSON } from '../../json-helper';
/**
* Generated class for shr.core.PlainText.
*/
class PlainText {
/**
* Get the value (aliases string).
* @returns {string} The string
*/
get value() {
return this._string;
}
/**
* Set the value (aliases string).
* @param {string} value - The string
*/
set value(value) {
this._string = value;
}
/**
* Get the string.
* @returns {string} The string
*/
get string() {
return this._string;
}
/**
* Set the string.
* @param {string} string - The string
*/
set string(string) {
this._string = string;
}
/**
* Get the Language.
* @returns {Language} The shr.base.Language
*/
get language() {
return this._language;
}
/**
* Set the Language.
* @param {Language} language - The shr.base.Language
*/
set language(language) {
this._language = language;
}
/**
* Deserializes JSON data to an instance of the PlainText class.
* The JSON must be valid against the PlainText JSON schema, although this is not validated by the function.
* @param {object} json - the JSON data to deserialize
* @returns {PlainText} An instance of PlainText populated with the JSON data
*/
static fromJSON(json={}) {
const inst = new PlainText();
setPropertiesFromJSON(inst, json);
return inst;
}
}
export default PlainText;
| {
"content_hash": "11ec75c5ca614dfeca56706249fbd298",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 110,
"avg_line_length": 20.705882352941178,
"alnum_prop": 0.6164772727272727,
"repo_name": "standardhealth/flux",
"id": "948d8683549ef7ea434e04e912f0324ed82ca57b",
"size": "1408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/model/shr/core/PlainText.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "64811"
},
{
"name": "HTML",
"bytes": "928"
},
{
"name": "JavaScript",
"bytes": "2806490"
}
],
"symlink_target": ""
} |
package org.apache.camel.dataformat.bindy;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.camel.CamelContext;
import org.apache.camel.dataformat.bindy.annotation.BindyConverter;
import org.apache.camel.dataformat.bindy.annotation.KeyValuePairField;
import org.apache.camel.dataformat.bindy.annotation.Link;
import org.apache.camel.dataformat.bindy.annotation.Message;
import org.apache.camel.dataformat.bindy.annotation.OneToMany;
import org.apache.camel.dataformat.bindy.annotation.Section;
import org.apache.camel.dataformat.bindy.util.ConverterUtils;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The BindyKeyValuePairFactory is the class who allows to bind data of type key
* value pair. Such format exist in financial messages FIX. This class allows to
* generate a model associated to message, bind data from a message to the
* POJOs, export data of POJOs to a message and format data into String, Date,
* Double, ... according to the format/pattern defined
*/
public class BindyKeyValuePairFactory extends BindyAbstractFactory implements BindyFactory {
private static final Logger LOG = LoggerFactory.getLogger(BindyKeyValuePairFactory.class);
private Map<Integer, KeyValuePairField> keyValuePairFields = new LinkedHashMap<>();
private Map<Integer, Field> annotatedFields = new LinkedHashMap<>();
private Map<String, Integer> sections = new HashMap<>();
private String keyValuePairSeparator;
private String pairSeparator;
private boolean messageOrdered;
public BindyKeyValuePairFactory(Class<?> type) throws Exception {
super(type);
// Initialize what is specific to Key Value Pair model
initKeyValuePairModel();
}
/**
* method uses to initialize the model representing the classes who will
* bind the data This process will scan for classes according to the package
* name provided, check the annotated classes and fields. Next, we retrieve
* the parameters required like : Pair Separator & key value pair separator
*
* @throws Exception
*/
public void initKeyValuePairModel() throws Exception {
// Find annotated KeyValuePairfields declared in the Model classes
initAnnotatedFields();
// Initialize key value pair parameter(s)
initMessageParameters();
}
@Override
public void initAnnotatedFields() {
for (Class<?> cl : models) {
List<Field> linkFields = new ArrayList<>();
for (Field field : cl.getDeclaredFields()) {
KeyValuePairField keyValuePairField = field.getAnnotation(KeyValuePairField.class);
if (keyValuePairField != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Key declared in the class : {}, key : {}, Field : {}", cl.getName(), keyValuePairField.tag(), keyValuePairField);
}
keyValuePairFields.put(keyValuePairField.tag(), keyValuePairField);
annotatedFields.put(keyValuePairField.tag(), field);
}
Link linkField = field.getAnnotation(Link.class);
if (linkField != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Class linked : {}, Field {}", cl.getName(), field);
}
linkFields.add(field);
}
}
if (!linkFields.isEmpty()) {
annotatedLinkFields.put(cl.getName(), linkFields);
}
}
}
@Override
public void bind(CamelContext camelContext, List<String> data, Map<String, Object> model, int line) throws Exception {
// Map to hold the model @OneToMany classes while binding
Map<String, List<Object>> lists = new HashMap<>();
bind(camelContext, data, model, line, lists);
}
public void bind(CamelContext camelContext, List<String> data, Map<String, Object> model, int line, Map<String, List<Object>> lists) throws Exception {
Map<Integer, List<String>> results = new HashMap<>();
LOG.debug("Key value pairs data : {}", data);
// Separate the key from its value
// e.g 8=FIX 4.1 --> key = 8 and Value = FIX 4.1
ObjectHelper.notNull(keyValuePairSeparator, "Key Value Pair not defined in the @Message annotation");
// Generate map of key value
// We use a Map of List as we can have the same key several times
// (relation one to many)
for (String s : data) {
// Get KeyValuePair
String[] keyValuePair = s.split(getKeyValuePairSeparator());
// Extract only if value is populated in key:value pair in incoming message.
if (keyValuePair.length > 1) {
// Extract Key
int key = Integer.parseInt(keyValuePair[0]);
// Extract key value
String value = keyValuePair[1];
LOG.debug("Key: {}, value: {}", key, value);
// Add value to the Map using key value as key
if (!results.containsKey(key)) {
List<String> list = new LinkedList<>();
list.add(value);
results.put(key, list);
} else {
List<String> list = results.get(key);
list.add(value);
}
}
}
// Iterate over the model
for (Class<?> clazz : models) {
Object obj = model.get(clazz.getName());
if (obj != null) {
// Generate model from key value map
generateModelFromKeyValueMap(clazz, obj, results, line, lists);
}
}
}
private void generateModelFromKeyValueMap(Class<?> clazz, Object obj, Map<Integer, List<String>> results, int line, Map<String, List<Object>> lists) throws Exception {
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
KeyValuePairField keyValuePairField = field.getAnnotation(KeyValuePairField.class);
if (keyValuePairField != null) {
// Key
int key = keyValuePairField.tag();
// Get Value
List<String> values = results.get(key);
String value = null;
// we don't received data
if (values == null) {
/*
* The relation is one to one So we check if we are in a
* target class and if the field is mandatory
*/
if (obj != null) {
// Check mandatory field
if (keyValuePairField.required()) {
throw new IllegalArgumentException("The mandatory key/tag : " + key + " has not been defined !");
}
Object result = getDefaultValueForPrimitive(field.getType());
try {
field.set(obj, result);
} catch (Exception e) {
throw new IllegalArgumentException("Setting of field " + field + " failed for object : " + obj + " and result : " + result);
}
} else {
/*
* The relation is one to many So, we create an object
* with empty fields and we don't check if the fields
* are mandatory
*/
// Get List from Map
List<Object> l = lists.get(clazz.getName());
if (l != null) {
// BigIntegerFormatFactory if object exist
if (!l.isEmpty()) {
obj = l.get(0);
} else {
obj = clazz.newInstance();
}
Object result = getDefaultValueForPrimitive(field.getType());
try {
field.set(obj, result);
} catch (Exception e) {
throw new IllegalArgumentException("Setting of field " + field + " failed for object : " + obj + " and result : " + result);
}
// Add object created to the list
if (!l.isEmpty()) {
l.set(0, obj);
} else {
l.add(0, obj);
}
// and to the Map
lists.put(clazz.getName(), l);
// Reset obj to null
obj = null;
} else {
throw new IllegalArgumentException("The list of values is empty for the following key : " + key + " defined in the class : " + clazz.getName());
}
} // end of test if obj != null
} else {
// Data have been retrieved from message
if (values.size() >= 1) {
if (obj != null) {
// Relation OneToOne
value = values.get(0);
Object result = null;
if (value != null) {
// Create format object to format the field
FormattingOptions formattingOptions = ConverterUtils.convert(keyValuePairField,
field.getType(),
field.getAnnotation(BindyConverter.class),
getLocale());
Format<?> format = formatFactory.getFormat(formattingOptions);
// format the value of the key received
result = formatField(format, value, key, line);
LOG.debug("Value formated : {}", result);
} else {
result = getDefaultValueForPrimitive(field.getType());
}
try {
field.set(obj, result);
} catch (Exception e) {
throw new IllegalArgumentException("Setting of field " + field + " failed for object : " + obj + " and result : " + result);
}
} else {
// Get List from Map
List<Object> l = lists.get(clazz.getName());
if (l != null) {
// Relation OneToMany
for (int i = 0; i < values.size(); i++) {
// BigIntegerFormatFactory if object exist
if ((!l.isEmpty()) && (l.size() > i)) {
obj = l.get(i);
} else {
obj = clazz.newInstance();
}
value = values.get(i);
// Create format object to format the field
FormattingOptions formattingOptions = ConverterUtils.convert(keyValuePairField,
field.getType(),
field.getAnnotation(BindyConverter.class),
getLocale());
Format<?> format = formatFactory.getFormat(formattingOptions);
// format the value of the key received
Object result = formatField(format, value, key, line);
LOG.debug("Value formated : {}", result);
try {
if (value != null) {
field.set(obj, result);
} else {
field.set(obj, getDefaultValueForPrimitive(field.getType()));
}
} catch (Exception e) {
throw new IllegalArgumentException("Setting of field " + field + " failed for object: " + obj + " and result: " + result);
}
// Add object created to the list
if ((!l.isEmpty()) && (l.size() > i)) {
l.set(i, obj);
} else {
l.add(i, obj);
}
// and to the Map
lists.put(clazz.getName(), l);
// Reset obj to null
obj = null;
}
} else {
throw new IllegalArgumentException("The list of values is empty for the following key: " + key + " defined in the class: " + clazz.getName());
}
}
} else {
// No values found from message
Object result = getDefaultValueForPrimitive(field.getType());
try {
field.set(obj, result);
} catch (Exception e) {
throw new IllegalArgumentException("Setting of field " + field + " failed for object: " + obj + " and result: " + result);
}
}
}
}
OneToMany oneToMany = field.getAnnotation(OneToMany.class);
if (oneToMany != null) {
String targetClass = oneToMany.mappedTo();
if (!targetClass.equals("")) {
// Class cl = Class.forName(targetClass); Does not work in
// OSGI when class is defined in another bundle
Class<?> cl = null;
try {
cl = Thread.currentThread().getContextClassLoader().loadClass(targetClass);
} catch (ClassNotFoundException e) {
cl = getClass().getClassLoader().loadClass(targetClass);
}
if (!lists.containsKey(cl.getName())) {
lists.put(cl.getName(), new ArrayList<>());
}
generateModelFromKeyValueMap(cl, null, results, line, lists);
// Add list of objects
field.set(obj, lists.get(cl.getName()));
} else {
throw new IllegalArgumentException("No target class has been defined in @OneToMany annotation");
}
}
}
}
/**
*
*/
@Override
public String unbind(CamelContext camelContext, Map<String, Object> model) throws Exception {
StringBuilder builder = new StringBuilder();
Map<Integer, KeyValuePairField> keyValuePairFieldsSorted = new TreeMap<>(keyValuePairFields);
Iterator<Integer> it = keyValuePairFieldsSorted.keySet().iterator();
// Map containing the OUT position of the field
// The key is double and is created using the position of the field and
// location of the class in the message (using section)
Map<Integer, String> positions = new TreeMap<>();
// Check if separator exists
ObjectHelper.notNull(this.pairSeparator, "The pair separator has not been instantiated or property not defined in the @Message annotation");
char separator = ConverterUtils.getCharDelimiter(this.getPairSeparator());
if (LOG.isDebugEnabled()) {
LOG.debug("Separator converted: '0x{}', from: {}", Integer.toHexString(separator), this.getPairSeparator());
}
while (it.hasNext()) {
KeyValuePairField keyValuePairField = keyValuePairFieldsSorted.get(it.next());
ObjectHelper.notNull(keyValuePairField, "KeyValuePair");
// Retrieve the field
Field field = annotatedFields.get(keyValuePairField.tag());
// Change accessibility to allow to read protected/private fields
field.setAccessible(true);
if (LOG.isDebugEnabled()) {
LOG.debug("Tag: {}, Field type: {}, class: {}", keyValuePairField.tag(), field.getType(), field.getDeclaringClass().getName());
}
// Create format
FormattingOptions formattingOptions = ConverterUtils.convert(keyValuePairField,
field.getType(),
field.getAnnotation(BindyConverter.class),
getLocale());
Format<Object> format = (Format<Object>) formatFactory.getFormat(formattingOptions);
// Get object to be formatted
Object obj = model.get(field.getDeclaringClass().getName());
if (obj != null) {
// Get field value
Object keyValue = field.get(obj);
if (this.isMessageOrdered()) {
// Generate a key using the number of the section
// and the position of the field
Integer key1 = sections.get(obj.getClass().getName());
Integer key2 = keyValuePairField.position();
LOG.debug("Key of the section: {}, and the field: {}", key1, key2);
Integer keyGenerated = generateKey(key1, key2);
if (LOG.isDebugEnabled()) {
LOG.debug("Key generated: {}, for section: {}", String.valueOf(keyGenerated), key1);
}
// Add value to the list if not null
if (keyValue != null) {
// Format field value
String valueFormatted;
try {
valueFormatted = format.format(keyValue);
} catch (Exception e) {
throw new IllegalArgumentException("Formatting error detected for the tag: " + keyValuePairField.tag(), e);
}
// Create the key value string
String value = keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormatted;
if (LOG.isDebugEnabled()) {
LOG.debug("Value to be formatted: {}, for the tag: {}, and its formatted value: {}", keyValue, keyValuePairField.tag(), valueFormatted);
}
// Add the content to the TreeMap according to the
// position defined
positions.put(keyGenerated, value);
if (LOG.isDebugEnabled()) {
LOG.debug("Positions size: {}", positions.size());
}
}
} else {
// Add value to the list if not null
if (keyValue != null) {
// Format field value
String valueFormatted;
try {
valueFormatted = format.format(keyValue);
} catch (Exception e) {
throw new IllegalArgumentException("Formatting error detected for the tag: " + keyValuePairField.tag(), e);
}
// Create the key value string
String value = keyValuePairField.tag() + this.getKeyValuePairSeparator() + valueFormatted + separator;
// Add content to the stringBuilder
builder.append(value);
if (LOG.isDebugEnabled()) {
LOG.debug("Value added: {}{}{}{}", keyValuePairField.tag(), this.getKeyValuePairSeparator(), valueFormatted, separator);
}
}
}
}
}
// Iterate through the list to generate
// the message according to the order/position
if (this.isMessageOrdered()) {
Iterator<Integer> posit = positions.keySet().iterator();
while (posit.hasNext()) {
String value = positions.get(posit.next());
if (LOG.isDebugEnabled()) {
LOG.debug("Value added at the position ({}) : {}{}", posit, value, separator);
}
builder.append(value + separator);
}
}
return builder.toString();
}
private Object formatField(Format<?> format, String value, int tag, int line) throws Exception {
Object obj = null;
if (value != null) {
// Format field value
try {
obj = format.parse(value);
} catch (Exception e) {
throw new IllegalArgumentException("Parsing error detected for field defined at the tag: " + tag + ", line: " + line, e);
}
}
return obj;
}
/**
* Find the pair separator used to delimit the key value pair fields
*/
public String getPairSeparator() {
return pairSeparator;
}
/**
* Find the key value pair separator used to link the key with its value
*/
public String getKeyValuePairSeparator() {
return keyValuePairSeparator;
}
/**
* Flag indicating if the message must be ordered
*
* @return boolean
*/
public boolean isMessageOrdered() {
return messageOrdered;
}
/**
* Get parameters defined in @Message annotation
*/
private void initMessageParameters() {
if ((pairSeparator == null) || (keyValuePairSeparator == null)) {
for (Class<?> cl : models) {
// Get annotation @Message from the class
Message message = cl.getAnnotation(Message.class);
// Get annotation @Section from the class
Section section = cl.getAnnotation(Section.class);
if (message != null) {
// Get Pair Separator parameter
ObjectHelper.notNull(message.pairSeparator(), "No Pair Separator has been defined in the @Message annotation");
pairSeparator = message.pairSeparator();
LOG.debug("Pair Separator defined for the message: {}", pairSeparator);
// Get KeyValuePair Separator parameter
ObjectHelper.notNull(message.keyValuePairSeparator(), "No Key Value Pair Separator has been defined in the @Message annotation");
keyValuePairSeparator = message.keyValuePairSeparator();
LOG.debug("Key Value Pair Separator defined for the message: {}", keyValuePairSeparator);
// Get carriage return parameter
crlf = message.crlf();
LOG.debug("Carriage return defined for the message: {}", crlf);
// Get isOrdered parameter
messageOrdered = message.isOrdered();
LOG.debug("Is the message ordered in output: {}", messageOrdered);
}
if (section != null) {
// BigIntegerFormatFactory if section number is not null
ObjectHelper.notNull(section.number(), "No number has been defined for the section");
// Get section number and add it to the sections
sections.put(cl.getName(), section.number());
}
}
}
}
}
| {
"content_hash": "fc0c6b41e3ef628921f7c97d54652d1e",
"timestamp": "",
"source": "github",
"line_count": 626,
"max_line_length": 174,
"avg_line_length": 39.69009584664537,
"alnum_prop": 0.49259438138935846,
"repo_name": "onders86/camel",
"id": "e8626ab92634a51a9c1e7fd9b28368d54599550e",
"size": "25649",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/BindyKeyValuePairFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6519"
},
{
"name": "Batchfile",
"bytes": "6512"
},
{
"name": "CSS",
"bytes": "30373"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "11410"
},
{
"name": "Groovy",
"bytes": "54390"
},
{
"name": "HTML",
"bytes": "190929"
},
{
"name": "Java",
"bytes": "69972191"
},
{
"name": "JavaScript",
"bytes": "90399"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "Python",
"bytes": "36"
},
{
"name": "Ruby",
"bytes": "4802"
},
{
"name": "Scala",
"bytes": "323702"
},
{
"name": "Shell",
"bytes": "23616"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "285105"
}
],
"symlink_target": ""
} |
<a href="https://www.tipeee.com/jeromelithiaote">
<img src="/assets/image/tipeee-logo.png" alt="support" width="100%" />
</a>
<h3>
<a href="https://www.tipeee.com/jeromelithiaote">How to support?</a>
</h3>
<p>
<ul>
<li>
Support my work on tipeee:
<a href="https://www.tipeee.com/jeromelithiaote">www.tipeee.com/jeromelithiaote</a>
</li>
<li>
If you like a video, please hit its 'Thumbs Up/Like' button, share with your friends and subscribe to my youtube channel: <a href="https://goo.gl/lV9NlL">click here</a>.<br />
It is underestimated how much this already could help support my work!
</li>
<li>
Any feedback is welcome at contact@jeromelithiaote.com<br />
I always learn from your comments! Thanks.
</li>
</ul>
</p>
<h3>
<a href="http://www.youtube.com/timedtext_cs_panel?tab=2&c=UCwpC30vxzPEVORNH_zKn70g">Help with translations?</a>
</h3>
<p>
So I try to work on subtitles. I would appreciate if you would help me translating.
<ul>
<li>
Thanks for following this link to contribute to my channel with your translations:
<a href="http://www.youtube.com/timedtext_cs_panel?tab=2&c=UCwpC30vxzPEVORNH_zKn70g">click here</a>
</li>
</ul>
</p>
<h3>
<a href="https://www.tipeee.com/jeromelithiaote">Why am I on tipeee?</a>
</h3>
<p>
<ul>
<li>
Creating all this orginal content takes a trumendous amount of time and to tell the truth, I would not be against renewing/repairing/upgrading part of my equipment.
<br />
// Produire ce contenu me prend énormément de temps, et il est vrai que je ne serai pas contre renouveler un peu mon matériel.
</li>
<li>
I mainly work as a musician (violinist), and some soundtracks composition/production (for others). I would like to share also my experience and help others (via my coaching videos etc.) but for this, I need some support, some luv. :-)
<br />
// Je travaille à côté de Youtube comme musicien (violoniste live) et je compose/produit des bande-sons (pour d'autres). Je souhaiterai également partager mon experience (au travers mes vidéos de formation etc.) mais pour cela, j'ai besoin de votre soutien. :-)
</li>
<li>
Even without your support, I am convinced that my videos will improve but it will take a lot more time to improve. :-p
<br />
// Malgré tout, même sans vos dons, mes vidéos continueront à s'améliorer, mais plus lentement :-p
</li>
<li>
In a nutshell, you are not forced in any way to support me. It is better to see this like a little help, a way for you to support my work: I will be fine without your support, but I will be better with ^^.
<br />
// Bref, vos dons ne sont absolument pas obligatoires, il faut voir cela comme un coup de pouce, une manière pour vous de soutenir mon travail : je me porte bien sans, je me porterai mieux avec ^^.
</li>
</ul>
</p>
<h3>
<a href="https://www.tipeee.com/jeromelithiaote">What are the rewards for tippers?</a>
</h3>
<p>
<ul>
<li>
Without you, I would not have been creating so many videos, this is thanks to your support and you following my work (of course I remain humble in my little world...), that I created more often, that I publish more videos and more sophisticated music tracks.
<br />
// Sans vous, je n'aurai jamais été aussi productif, c'est parce que vous suivez assidûment (à ma petite échelle biensûr...), que j'ai pu trouver la motivation de créer plus régulièrement, de sortir des vidéos et des sons toujours plus travaillés.
</li>
<li>
I would like to find some rewards/perks for everyone, even the ones who cannot give a lot...
<br />
// Je souhaiterai trouver des contreparties qui ne léseront pas ceux qui ne peuvent pas donner beaucoup...
</li>
</ul>
</p>
| {
"content_hash": "8bbb554309febee88126e1925b394d31",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 267,
"avg_line_length": 47.629629629629626,
"alnum_prop": 0.6835147744945568,
"repo_name": "jeromelithiaote/main",
"id": "7763fdd4c216809c960f87de863f9d299b41b2e7",
"size": "3885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/side_tipeee.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "850"
},
{
"name": "C",
"bytes": "477243"
},
{
"name": "CSS",
"bytes": "859430"
},
{
"name": "HTML",
"bytes": "131674"
},
{
"name": "Java",
"bytes": "14870"
},
{
"name": "JavaScript",
"bytes": "87527"
},
{
"name": "Makefile",
"bytes": "16895"
},
{
"name": "Modelica",
"bytes": "10339"
},
{
"name": "PHP",
"bytes": "46830"
},
{
"name": "Perl",
"bytes": "50950"
},
{
"name": "Roff",
"bytes": "60910"
},
{
"name": "Ruby",
"bytes": "10432"
},
{
"name": "Shell",
"bytes": "43956"
},
{
"name": "Smarty",
"bytes": "5757127"
},
{
"name": "TSQL",
"bytes": "136406"
},
{
"name": "VCL",
"bytes": "1953"
},
{
"name": "XSLT",
"bytes": "2135"
}
],
"symlink_target": ""
} |
#pragma once
#include "cbsasl/cbsasl.h"
#include "user.h"
#include <string>
/**
* Searches for a user entry for the specified user.
*
* @param user the username to search for
* @param user updated with the user information if found
* @return true if user exists, false otherwise
*/
bool find_user(const std::string& username, Couchbase::User &user);
cbsasl_error_t load_user_db(void);
void free_user_ht(void);
| {
"content_hash": "5ea9afde9aa229980827db32d678becf",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 67,
"avg_line_length": 22.157894736842106,
"alnum_prop": 0.7173396674584323,
"repo_name": "owendCB/memcached",
"id": "00a036d53ba78ee31dc90dd47d00298da693cabf",
"size": "1041",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cbsasl/pwfile.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "505542"
},
{
"name": "C++",
"bytes": "2480779"
},
{
"name": "CMake",
"bytes": "54502"
},
{
"name": "DTrace",
"bytes": "10631"
},
{
"name": "Python",
"bytes": "27016"
},
{
"name": "Shell",
"bytes": "448"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>bdds: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.13.0 / bdds - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
bdds
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-07-22 08:40:03 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-22 08:40:03 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/bdds"
license: "LGPL 2.1"
build: [make "-j1"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/BDDs"]
depends: [
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
"coq-int-map" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: BDD"
"keyword: binary decision diagrams"
"keyword: classical logic"
"keyword: propositional logic"
"keyword: validity"
"keyword: satisfiability"
"keyword: model checking"
"keyword: reflection"
"category: Computer Science/Decision Procedures and Certified Algorithms/Decision procedures"
"category: Miscellaneous/Extracted Programs/Decision procedures"
"date: May-July 1999"
]
authors: [
"Kumar Neeraj Verma"
]
bug-reports: "https://github.com/coq-contribs/bdds/issues"
dev-repo: "git+https://github.com/coq-contribs/bdds.git"
synopsis: "BDD algorithms and proofs in Coq, by reflection"
description: """
Provides BDD algorithms running under Coq.
(BDD are Binary Decision Diagrams.)
Allows one to do classical validity checking by
reflection in Coq using BDDs, can also be used
to get certified BDD algorithms by extraction.
First step towards actual symbolic model-checkers
in Coq. See file README for operation."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/bdds/archive/v8.10.0.tar.gz"
checksum: "md5=9d8155b5718bc6032daf45451eda40d6"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-bdds.8.10.0 coq.8.13.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0).
The following dependencies couldn't be met:
- coq-bdds -> coq < 8.11~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-bdds.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "c1bad96fa4b4046e36f10753b5b3580d",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 159,
"avg_line_length": 40.935483870967744,
"alnum_prop": 0.5612030470186499,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "382d789d77ca1480e8e8b1311f9f059a65c95240",
"size": "7639",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.13.0/bdds/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
/**
* PaymentWall Gateway.
*/
namespace Omnipay\PaymentWall;
use Omnipay\Common\AbstractGateway;
/**
* PaymentWall Gateway.
*
* Paymentwall is the leading digital payments platform for globally monetizing
* digital goods and services. Paymentwall assists game publishers, dating publics,
* rewards publics, SaaS companies and many other verticals to monetize their
* digital content and services.
*
* This uses the PaymentWall library at https://github.com/paymentwall/paymentwall-php
* and the Brick API to communicate to PaymentWall.
*
* ### Example
*
* <code>
* // Create a gateway for the PaymentWall REST Gateway
* // (routes to GatewayFactory::create)
* $gateway = Omnipay::create('PaymentWall');
*
* // Initialise the gateway
* $gateway->initialize(array(
* 'apiType' => $gateway::API_GOODS,
* 'publicKey' => 'YOUR_PUBLIC_KEY',
* 'privateKey' => 'YOUR_PRIVATE_KEY',
* ));
*
* // Create a credit card object
* // This card can be used for testing.
* $card = new CreditCard(array(
* 'firstName' => 'Example',
* 'lastName' => 'Customer',
* 'number' => '4242424242424242',
* 'expiryMonth' => '01',
* 'expiryYear' => '2020',
* 'cvv' => '123',
* 'email' => 'customer@example.com',
* 'billingPostcode' => '4999',
* ));
*
* // Do a purchase transaction on the gateway
* $transaction = $gateway->purchase(array(
* 'amount' => '10.00',
* 'accountId' => 12341234,
* 'currency' => 'AUD',
* 'clientIp' => '127.0.0.1',
* 'packageId' => 1234,
* 'description' => 'Super Deluxe Excellent Discount Package',
* 'fingerprint' => '*token provided by Brick.js*',
* 'browserDomain' => 'SiteName.com',
* 'card' => $card,
* ));
* $response = $transaction->send();
* if ($response->isSuccessful()) {
* echo "Purchase transaction was successful!\n";
* $sale_id = $response->getTransactionReference();
* echo "Transaction reference = " . $sale_id . "\n";
* }
* </code>
*
* ### Quirks
*
* * There is no separate createCard message in this gateway. The
* PaymentWall gateway only supports card creation at the time of a
* purchase. Instead, a cardReference is returned when a purchase
* message is sent, as a component of the response to the purchase
* message. This card token can then be used to make purchases
* in place of card data, just like other gateways. An authorize()
* request can also be used to create a payment token, for the amount
* of $0.00 USD *except* for American Express cards where an authorize
* amount of $0.10 USD must be used.
* * Refunds are not supported, these must be done manually. Voids
* are supported. The refund() call within the API in fact does a
* void.
* * During notify callbacks (referred to as "pingbacks" by PaymentWall)
* the transaction amount will frequently be reported in USD regardless
* of the currency of the original purchase.
* * An error code of 3201 while attempting a void() call should be treated
* as a success. This error code indicates that the payment has already
* been cancelled manually at the gateway by PaymentWall staff and so
* this error code actually is just communicating "payment cannot be voided,
* already voided".
* * Many functions of the gateway that work in production mode either do
* not work in test mode or work differently in test mode. Be prepared
* to do some testing in production mode.
*
* ### Full parameter Set
*
* This includes all optional parameters including those that are used
* for fraud detection/prevention.
*
* <code>
* charge => [
* uid
* plan
* amount
* currency
* fingerprint
* description
* browser_ip
* browser_domain
* customer => [
* sex
* firstname
* lastname
* username
* zip
* birthday
* ]
* history = > [
* membership
* membership_date
* registration_date
* registration_country
* registration_ip
* registration_email
* registration_email_verified
* registration_name
* registration_lastname
* registration_source
* logins_number
* payments_number
* payments_amount
* followers
* messages_sent
* messages_sent_last_24hours
* messages_received
* interactions
* interactions_last_24hours
* risk_score
* was_banned
* delivered_products
* cancelled_payments
* registration_age
* ]
* 3dsecure
* options => []
* custom => []
* ]
* </code>
*
* @see \Omnipay\Common\AbstractGateway
* @see \Omnipay\PaymentWall\Message\AbstractRestRequest
* @link https://www.paymentwall.com/en/documentation/getting-started
* @link https://www.paymentwall.com/
* @link https://github.com/paymentwall/paymentwall-php
*/
class Gateway extends AbstractGateway
{
const API_VC = \Paymentwall_Config::API_VC;
const API_GOODS = \Paymentwall_Config::API_GOODS;
const API_CART = \Paymentwall_Config::API_CART;
/**
* Get the gateway display name.
*
* @return string
*/
public function getName()
{
return 'PaymentWall';
}
/**
* Get the gateway default parameters.
*
* @return array
*/
public function getDefaultParameters()
{
return array(
'apiType' => 0,
'publicKey' => '',
'privateKey' => '',
);
}
/**
* Get the gateway apiType -- used in every request.
*
* @return string
*/
public function getApiType()
{
return $this->getParameter('apiType');
}
/**
* Set the gateway apiType -- used in every request.
*
* @return Gateway provides a fluent interface.
*/
public function setApiType($value)
{
return $this->setParameter('apiType', $value);
}
/**
* Get the gateway publicKey -- used in every request.
*
* @return string
*/
public function getPublicKey()
{
return $this->getParameter('publicKey');
}
/**
* Set the gateway publicKey -- used in every request.
*
* @return Gateway provides a fluent interface.
*/
public function setPublicKey($value)
{
return $this->setParameter('publicKey', $value);
}
/**
* Get the gateway privateKey -- used in every request.
*
* @return string
*/
public function getPrivateKey()
{
return $this->getParameter('privateKey');
}
/**
* Set the gateway privateKey -- used in every request.
*
* @return Gateway provides a fluent interface.
*/
public function setPrivateKey($value)
{
return $this->setParameter('privateKey', $value);
}
//
// Direct API Purchase Calls -- purchase, refund
//
/**
* Create a purchase request.
*
* @param array $parameters
*
* @return \Omnipay\PaymentWall\Message\PurchaseRequest
*/
public function purchase(array $parameters = array())
{
return $this->createRequest('\Omnipay\PaymentWall\Message\PurchaseRequest', $parameters);
}
/**
* Create an authorize request.
*
* @param array $parameters
*
* @return \Omnipay\PaymentWall\Message\AuthorizeRequest
*/
public function authorize(array $parameters = array())
{
return $this->createRequest('\Omnipay\PaymentWall\Message\AuthorizeRequest', $parameters);
}
/**
* Create a capture request.
*
* @param array $parameters
*
* @return \Omnipay\PaymentWall\Message\CaptureRequest
*/
public function capture(array $parameters = array())
{
return $this->createRequest('\Omnipay\PaymentWall\Message\CaptureRequest', $parameters);
}
/**
* Create a void request.
*
* @param array $parameters
*
* @return \Omnipay\PaymentWall\Message\VoidRequest
*/
public function void(array $parameters = array())
{
return $this->createRequest('\Omnipay\PaymentWall\Message\VoidRequest', $parameters);
}
/**
* Create a refund request.
*
* @param array $parameters
*
* @return \Omnipay\PaymentWall\Message\RefundRequest
*/
public function refund(array $parameters = array())
{
return $this->createRequest('\Omnipay\PaymentWall\Message\RefundRequest', $parameters);
}
/**
* Create a purchase status request.
*
* @param array $parameters
*
* @return \Omnipay\PaymentWall\Message\PurchaseStatusRequest
*/
public function getPurchaseStatus(array $parameters = array())
{
return $this->createRequest('\Omnipay\PaymentWall\Message\PurchaseStatusRequest', $parameters);
}
}
| {
"content_hash": "c51184113810f1ea3c11e0844a7330e4",
"timestamp": "",
"source": "github",
"line_count": 319,
"max_line_length": 103,
"avg_line_length": 29.62382445141066,
"alnum_prop": 0.5807407407407408,
"repo_name": "Jellyfrog/omnipay-paymentwall",
"id": "71109c99f7cad813f6f747c3d51af23b2fc41fa9",
"size": "9450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Gateway.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "94018"
},
{
"name": "Shell",
"bytes": "4969"
}
],
"symlink_target": ""
} |
package tabletserver
import (
"fmt"
"sync"
"time"
"golang.org/x/net/context"
"vitess.io/vitess/go/timer"
"vitess.io/vitess/go/trace"
"vitess.io/vitess/go/vt/concurrency"
"vitess.io/vitess/go/vt/dbconfigs"
"vitess.io/vitess/go/vt/dtids"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/vtgateconn"
"vitess.io/vitess/go/vt/vttablet/tabletserver/connpool"
"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
"vitess.io/vitess/go/vt/vttablet/tabletserver/txlimiter"
querypb "vitess.io/vitess/go/vt/proto/query"
)
type txEngineState int
// The TxEngine can be in any of these states
const (
NotServing txEngineState = iota
Transitioning
AcceptingReadAndWrite
AcceptingReadOnly
)
func (state txEngineState) String() string {
names := [...]string{
"NotServing",
"Transitioning",
"AcceptReadWrite",
"AcceptingReadOnly"}
if state < NotServing || state > AcceptingReadOnly {
return fmt.Sprintf("Unknown - %d", int(state))
}
return names[state]
}
// TxEngine is responsible for handling the tx-pool and keeping read-write, read-only or not-serving
// states. It will start and shut down the underlying tx-pool as required.
// It does this in a concurrently safe way.
type TxEngine struct {
// the following four fields are interconnected. `state` and `nextState` should be protected by the
// `stateLock`
//
// `nextState` is used when state is Transitioning. This means that in order to change the state of
// the transaction engine, we had to close transactions. `nextState` is the state we'll end up in
// once the transactions are closed
// while transitioning, `transitionSignal` will contain an open channel. Once the transition is
// over, the channel is closed to signal to any waiting goroutines that the state change is done.
stateLock sync.Mutex
state txEngineState
nextState txEngineState
transitionSignal chan struct{}
// beginRequests is used to make sure that we do not make a state
// transition while creating new transactions
beginRequests sync.WaitGroup
dbconfigs *dbconfigs.DBConfigs
twopcEnabled bool
shutdownGracePeriod time.Duration
coordinatorAddress string
abandonAge time.Duration
ticks *timer.Timer
txPool *TxPool
preparedPool *TxPreparedPool
twoPC *TwoPC
}
// NewTxEngine creates a new TxEngine.
func NewTxEngine(checker connpool.MySQLChecker, config tabletenv.TabletConfig) *TxEngine {
te := &TxEngine{
shutdownGracePeriod: time.Duration(config.TxShutDownGracePeriod * 1e9),
}
limiter := txlimiter.New(
config.TransactionCap,
config.TransactionLimitPerUser,
config.EnableTransactionLimit,
config.EnableTransactionLimitDryRun,
config.TransactionLimitByUsername,
config.TransactionLimitByPrincipal,
config.TransactionLimitByComponent,
config.TransactionLimitBySubcomponent,
)
te.txPool = NewTxPool(
config.PoolNamePrefix,
config.TransactionCap,
config.FoundRowsPoolSize,
time.Duration(config.TransactionTimeout*1e9),
time.Duration(config.IdleTimeout*1e9),
config.TxPoolWaiterCap,
checker,
limiter,
)
te.twopcEnabled = config.TwoPCEnable
if te.twopcEnabled {
if config.TwoPCCoordinatorAddress == "" {
log.Error("Coordinator address not specified: Disabling 2PC")
te.twopcEnabled = false
}
if config.TwoPCAbandonAge <= 0 {
log.Error("2PC abandon age not specified: Disabling 2PC")
te.twopcEnabled = false
}
}
te.coordinatorAddress = config.TwoPCCoordinatorAddress
te.abandonAge = time.Duration(config.TwoPCAbandonAge * 1e9)
te.ticks = timer.NewTimer(te.abandonAge / 2)
// Set the prepared pool capacity to something lower than
// tx pool capacity. Those spare connections are needed to
// perform metadata state change operations. Without this,
// the system can deadlock if all connections get moved to
// the TxPreparedPool.
te.preparedPool = NewTxPreparedPool(config.TransactionCap - 2)
readPool := connpool.New(
config.PoolNamePrefix+"TxReadPool",
3,
time.Duration(config.IdleTimeout*1e9),
checker,
)
te.twoPC = NewTwoPC(readPool)
te.transitionSignal = make(chan struct{})
// By immediately closing this channel, all state changes can simply be made blocking by issuing the
// state change desired, and then selecting on this channel. It will contain an open channel while
// transitioning.
close(te.transitionSignal)
te.nextState = -1
te.state = NotServing
return te
}
// Stop will stop accepting any new transactions. Transactions are immediately aborted.
func (te *TxEngine) Stop() error {
te.beginRequests.Wait()
te.stateLock.Lock()
switch te.state {
case NotServing:
// Nothing to do. We are already stopped or stopping
te.stateLock.Unlock()
return nil
case AcceptingReadAndWrite:
return te.transitionTo(NotServing)
case AcceptingReadOnly:
// We are not master, so it's safe to kill all read-only transactions
te.close(true)
te.state = NotServing
te.stateLock.Unlock()
return nil
case Transitioning:
te.nextState = NotServing
te.stateLock.Unlock()
te.blockUntilEndOfTransition()
return nil
default:
te.stateLock.Unlock()
return te.unknownStateError()
}
}
// AcceptReadWrite will start accepting all transactions.
// If transitioning from RO mode, transactions might need to be
// rolled back before new transactions can be accepts.
func (te *TxEngine) AcceptReadWrite() error {
te.beginRequests.Wait()
te.stateLock.Lock()
switch te.state {
case AcceptingReadAndWrite:
// Nothing to do
te.stateLock.Unlock()
return nil
case NotServing:
te.state = AcceptingReadAndWrite
te.open()
te.stateLock.Unlock()
return nil
case Transitioning:
te.nextState = AcceptingReadAndWrite
te.stateLock.Unlock()
te.blockUntilEndOfTransition()
return nil
case AcceptingReadOnly:
// We need to restart the tx-pool to make sure we handle 2PC correctly
te.close(true)
te.state = AcceptingReadAndWrite
te.open()
te.stateLock.Unlock()
return nil
default:
return te.unknownStateError()
}
}
// AcceptReadOnly will start accepting read-only transactions, but not full read and write transactions.
// If the engine is currently accepting full read and write transactions, they need to
// be rolled back.
func (te *TxEngine) AcceptReadOnly() error {
te.beginRequests.Wait()
te.stateLock.Lock()
switch te.state {
case AcceptingReadOnly:
// Nothing to do
te.stateLock.Unlock()
return nil
case NotServing:
te.state = AcceptingReadOnly
te.open()
te.stateLock.Unlock()
return nil
case AcceptingReadAndWrite:
return te.transitionTo(AcceptingReadOnly)
case Transitioning:
te.nextState = AcceptingReadOnly
te.stateLock.Unlock()
te.blockUntilEndOfTransition()
return nil
default:
te.stateLock.Unlock()
return te.unknownStateError()
}
}
// Begin begins a transaction, and returns the associated transaction id and the
// statement(s) used to execute the begin (if any).
//
// Subsequent statements can access the connection through the transaction id.
func (te *TxEngine) Begin(ctx context.Context, options *querypb.ExecuteOptions) (int64, string, error) {
span, ctx := trace.NewSpan(ctx, "TxEngine.Begin")
defer span.Finish()
te.stateLock.Lock()
canOpenTransactions := te.state == AcceptingReadOnly || te.state == AcceptingReadAndWrite
if !canOpenTransactions {
// We are not in a state where we can start new transactions. Abort.
te.stateLock.Unlock()
return 0, "", vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "tx engine can't accept new transactions in state %v", te.state)
}
isWriteTransaction := options == nil || options.TransactionIsolation != querypb.ExecuteOptions_CONSISTENT_SNAPSHOT_READ_ONLY
if te.state == AcceptingReadOnly && isWriteTransaction {
te.stateLock.Unlock()
return 0, "", vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "tx engine can only accept read-only transactions in current state")
}
// By Add() to beginRequests, we block others from initiating state
// changes until we have finished adding this transaction
te.beginRequests.Add(1)
te.stateLock.Unlock()
defer te.beginRequests.Done()
return te.txPool.Begin(ctx, options)
}
// Commit commits the specified transaction.
func (te *TxEngine) Commit(ctx context.Context, transactionID int64, mc messageCommitter) (string, error) {
span, ctx := trace.NewSpan(ctx, "TxEngine.Commit")
defer span.Finish()
return te.txPool.Commit(ctx, transactionID, mc)
}
// Rollback rolls back the specified transaction.
func (te *TxEngine) Rollback(ctx context.Context, transactionID int64) error {
span, ctx := trace.NewSpan(ctx, "TxEngine.Rollback")
defer span.Finish()
return te.txPool.Rollback(ctx, transactionID)
}
func (te *TxEngine) unknownStateError() error {
return vterrors.Errorf(vtrpc.Code_INTERNAL, "unknown state %v", te.state)
}
func (te *TxEngine) blockUntilEndOfTransition() error {
<-te.transitionSignal
return nil
}
func (te *TxEngine) transitionTo(nextState txEngineState) error {
te.state = Transitioning
te.nextState = nextState
te.transitionSignal = make(chan struct{})
te.stateLock.Unlock()
// We do this outside the lock so others can see our state while we close up waiting transactions
te.close(true)
te.stateLock.Lock()
defer func() {
// we use a lambda to make it clear in which order things need to happen
te.stateLock.Unlock()
close(te.transitionSignal)
}()
if te.state != Transitioning {
return vterrors.Errorf(vtrpc.Code_INTERNAL, "this should never happen. the goroutine starting the transition should also finish it")
}
// Once we reach this point, it's as if our state is NotServing,
// and we need to decide what the next step is
switch te.nextState {
case AcceptingReadAndWrite, AcceptingReadOnly:
te.state = te.nextState
te.open()
case NotServing:
te.state = NotServing
case Transitioning:
return vterrors.Errorf(vtrpc.Code_INTERNAL, "this should never happen. nextState cannot be transitioning")
}
te.nextState = -1
return nil
}
// InitDBConfig must be called before Init.
func (te *TxEngine) InitDBConfig(dbcfgs *dbconfigs.DBConfigs) {
te.dbconfigs = dbcfgs
}
// Init must be called once when vttablet starts for setting
// up the metadata tables.
func (te *TxEngine) Init() error {
if te.twopcEnabled {
return te.twoPC.Init(te.dbconfigs.SidecarDBName.Get(), te.dbconfigs.DbaWithDB())
}
return nil
}
// open opens the TxEngine. If 2pc is enabled, it restores
// all previously prepared transactions from the redo log.
// this should only be called when the state is already locked
func (te *TxEngine) open() {
te.txPool.Open(te.dbconfigs.AppWithDB(), te.dbconfigs.DbaWithDB(), te.dbconfigs.AppDebugWithDB())
if te.twopcEnabled && te.state == AcceptingReadAndWrite {
te.twoPC.Open(te.dbconfigs)
if err := te.prepareFromRedo(); err != nil {
// If this operation fails, we choose to raise an alert and
// continue anyway. Serving traffic is considered more important
// than blocking everything for the sake of a few transactions.
tabletenv.InternalErrors.Add("TwopcResurrection", 1)
log.Errorf("Could not prepare transactions: %v", err)
}
te.startWatchdog()
}
}
// StopGently will disregard common rules for when to kill transactions
// and wait forever for transactions to wrap up
func (te *TxEngine) StopGently() {
te.stateLock.Lock()
defer te.stateLock.Unlock()
te.close(false)
te.state = NotServing
}
// Close closes the TxEngine. If the immediate flag is on,
// then all current transactions are immediately rolled back.
// Otherwise, the function waits for all current transactions
// to conclude. If a shutdown grace period was specified,
// the transactions are rolled back if they're not resolved
// by that time.
func (te *TxEngine) close(immediate bool) {
// Shut down functions are idempotent.
// No need to check if 2pc is enabled.
te.stopWatchdog()
poolEmpty := make(chan bool)
rollbackDone := make(chan bool)
// This goroutine decides if transactions have to be
// forced to rollback, and if so, when. Once done,
// the function closes rollbackDone, which can be
// verified to make sure it won't kick in later.
go func() {
defer func() {
tabletenv.LogError()
close(rollbackDone)
}()
if immediate {
// Immediately rollback everything and return.
log.Info("Immediate shutdown: rolling back now.")
te.rollbackTransactions()
return
}
if te.shutdownGracePeriod <= 0 {
// No grace period was specified. Never rollback.
te.rollbackPrepared()
log.Info("No grace period specified: performing normal wait.")
return
}
tmr := time.NewTimer(te.shutdownGracePeriod)
defer tmr.Stop()
select {
case <-tmr.C:
log.Info("Grace period exceeded: rolling back now.")
te.rollbackTransactions()
case <-poolEmpty:
// The pool cleared before the timer kicked in. Just return.
log.Info("Transactions completed before grace period: shutting down.")
}
}()
te.txPool.WaitForEmpty()
// If the goroutine is still running, signal that it can exit.
close(poolEmpty)
// Make sure the goroutine has returned.
<-rollbackDone
te.txPool.Close()
te.twoPC.Close()
}
// prepareFromRedo replays and prepares the transactions
// from the redo log, loads previously failed transactions
// into the reserved list, and adjusts the txPool LastID
// to ensure there are no future collisions.
func (te *TxEngine) prepareFromRedo() error {
ctx := tabletenv.LocalContext()
var allErr concurrency.AllErrorRecorder
prepared, failed, err := te.twoPC.ReadAllRedo(ctx)
if err != nil {
return err
}
maxid := int64(0)
outer:
for _, tx := range prepared {
txid, err := dtids.TransactionID(tx.Dtid)
if err != nil {
log.Errorf("Error extracting transaction ID from ditd: %v", err)
}
if txid > maxid {
maxid = txid
}
conn, _, err := te.txPool.LocalBegin(ctx, &querypb.ExecuteOptions{})
if err != nil {
allErr.RecordError(err)
continue
}
for _, stmt := range tx.Queries {
conn.RecordQuery(stmt)
_, err := conn.Exec(ctx, stmt, 1, false)
if err != nil {
allErr.RecordError(err)
te.txPool.LocalConclude(ctx, conn)
continue outer
}
}
// We should not use the external Prepare because
// we don't want to write again to the redo log.
err = te.preparedPool.Put(conn, tx.Dtid)
if err != nil {
allErr.RecordError(err)
continue
}
}
for _, tx := range failed {
txid, err := dtids.TransactionID(tx.Dtid)
if err != nil {
log.Errorf("Error extracting transaction ID from ditd: %v", err)
}
if txid > maxid {
maxid = txid
}
te.preparedPool.SetFailed(tx.Dtid)
}
te.txPool.AdjustLastID(maxid)
log.Infof("Prepared %d transactions, and registered %d failures.", len(prepared), len(failed))
return allErr.Error()
}
// rollbackTransactions rolls back all open transactions
// including the prepared ones.
// This is used for transitioning from a master to a non-master
// serving type.
func (te *TxEngine) rollbackTransactions() {
ctx := tabletenv.LocalContext()
for _, c := range te.preparedPool.FetchAll() {
te.txPool.LocalConclude(ctx, c)
}
// The order of rollbacks is currently not material because
// we don't allow new statements or commits during
// this function. In case of any such change, this will
// have to be revisited.
te.txPool.RollbackNonBusy(ctx)
}
func (te *TxEngine) rollbackPrepared() {
ctx := tabletenv.LocalContext()
for _, c := range te.preparedPool.FetchAll() {
te.txPool.LocalConclude(ctx, c)
}
}
// startWatchdog starts the watchdog goroutine, which looks for abandoned
// transactions and calls the notifier on them.
func (te *TxEngine) startWatchdog() {
te.ticks.Start(func() {
ctx, cancel := context.WithTimeout(tabletenv.LocalContext(), te.abandonAge/4)
defer cancel()
// Raise alerts on prepares that have been unresolved for too long.
// Use 5x abandonAge to give opportunity for watchdog to resolve these.
count, err := te.twoPC.CountUnresolvedRedo(ctx, time.Now().Add(-te.abandonAge*5))
if err != nil {
tabletenv.InternalErrors.Add("WatchdogFail", 1)
log.Errorf("Error reading unresolved prepares: '%v': %v", te.coordinatorAddress, err)
}
tabletenv.Unresolved.Set("Prepares", count)
// Resolve lingering distributed transactions.
txs, err := te.twoPC.ReadAbandoned(ctx, time.Now().Add(-te.abandonAge))
if err != nil {
tabletenv.InternalErrors.Add("WatchdogFail", 1)
log.Errorf("Error reading transactions for 2pc watchdog: %v", err)
return
}
if len(txs) == 0 {
return
}
coordConn, err := vtgateconn.Dial(ctx, te.coordinatorAddress)
if err != nil {
tabletenv.InternalErrors.Add("WatchdogFail", 1)
log.Errorf("Error connecting to coordinator '%v': %v", te.coordinatorAddress, err)
return
}
defer coordConn.Close()
var wg sync.WaitGroup
for tx := range txs {
wg.Add(1)
go func(dtid string) {
defer wg.Done()
if err := coordConn.ResolveTransaction(ctx, dtid); err != nil {
tabletenv.InternalErrors.Add("WatchdogFail", 1)
log.Errorf("Error notifying for dtid %s: %v", dtid, err)
}
}(tx)
}
wg.Wait()
})
}
// stopWatchdog stops the watchdog goroutine.
func (te *TxEngine) stopWatchdog() {
te.ticks.Stop()
}
| {
"content_hash": "586defb0670b047d4b7fac169c01738f",
"timestamp": "",
"source": "github",
"line_count": 577,
"max_line_length": 134,
"avg_line_length": 29.89254766031196,
"alnum_prop": 0.7312731910946196,
"repo_name": "enisoc/vitess",
"id": "17b9a0a26fcf767e40b85389fc939da31eabe1b4",
"size": "17805",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "go/vt/vttablet/tabletserver/tx_engine.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "10113"
},
{
"name": "Dockerfile",
"bytes": "15467"
},
{
"name": "Go",
"bytes": "9084650"
},
{
"name": "HTML",
"bytes": "39017"
},
{
"name": "Java",
"bytes": "1105729"
},
{
"name": "JavaScript",
"bytes": "19008"
},
{
"name": "Makefile",
"bytes": "11045"
},
{
"name": "Python",
"bytes": "1302983"
},
{
"name": "Shell",
"bytes": "83938"
},
{
"name": "Smarty",
"bytes": "76056"
},
{
"name": "TypeScript",
"bytes": "165695"
},
{
"name": "Yacc",
"bytes": "65017"
}
],
"symlink_target": ""
} |
<?php
/*
* This file is part of Sulu.
*
* (c) MASSIVE ART WebServices GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Sulu\Bundle\SearchBundle\Search;
use Massive\Bundle\SearchBundle\Search\Factory as BaseFactory;
/**
* Extend the MassiveSearch factory in order to
* use a custom document type.
*/
class Factory extends BaseFactory
{
/**
* {@inheritdoc}
*
* @return Document
*/
public function createDocument()
{
return new Document();
}
}
| {
"content_hash": "eab76609ef81c022cf066e03387c86f1",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 65,
"avg_line_length": 18.70967741935484,
"alnum_prop": 0.6620689655172414,
"repo_name": "fahadonline/sulu",
"id": "36b3bfa80dcd4d5b94b2e3bd4074f9488d38ba87",
"size": "580",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/sulu/sulu/src/Sulu/Bundle/SearchBundle/Search/Factory.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3764"
},
{
"name": "CSS",
"bytes": "120902"
},
{
"name": "HTML",
"bytes": "76011"
},
{
"name": "JavaScript",
"bytes": "43258"
},
{
"name": "PHP",
"bytes": "56167"
},
{
"name": "Shell",
"bytes": "1956"
}
],
"symlink_target": ""
} |
import dbfread
import csv
import os
def dbf2csv(folder, values, dbfs):
#
for i in range(len(values)):
csvPath = folder + values[i] + ".csv"
fin = dbfread.open(dbfs[i], load=True)
fout = open(csvPath, 'w')
csvFile = csv.writer(fout, dialect=csv.excel)
# write the header
csvFile.writerow(fin.field_names)
#
for record in fin:
csvFile.writerow(record.values())
os.remove(dbfs[i])
def dbf2tsv(folder, values, dbfs):
# make the csvs
dbf2csv(folder, values, dbfs)
# worker loop
for z in range(len(values)):
#build the paths for the extraction
tsvPath = folder + values[z] + ".tsv"
csvPath = folder + values[z] + ".csv"
#open the files
fin = open(csvPath, 'r')
fout = open(tsvPath, 'w')
commafile = csv.reader(fin, dialect=csv.excel)
tabfile = csv.writer(fout, dialect=csv.excel_tab)
for line in commafile:
tabfile.writerow(line)
os.remove(csvPath)
| {
"content_hash": "eb4ebd152661e506490124b96d0168bb",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 57,
"avg_line_length": 28.324324324324323,
"alnum_prop": 0.5791984732824428,
"repo_name": "Guerillero/ArcExtractor",
"id": "f1bc9daaf6453995a841fb2cee06299c8c531302",
"size": "1048",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FileTransformations.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3204"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.