text
stringlengths 2
100k
| meta
dict |
---|---|
#ifdef BLOG_CURRENT_CHANNEL
#undef BLOG_CURRENT_CHANNEL
#endif
#define BLOG_CURRENT_CHANNEL BLOG_CHANNEL_ncd_getargs
| {
"pile_set_name": "Github"
} |
# dummy
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _STORAGED_SERVICE_H_
#define _STORAGED_SERVICE_H_
#include <vector>
#include <binder/BinderService.h>
#include "android/os/BnStoraged.h"
#include "android/os/storaged/BnStoragedPrivate.h"
using namespace std;
using namespace android::os;
using namespace android::os::storaged;
class StoragedService : public BinderService<StoragedService>, public BnStoraged {
private:
void dumpUidRecordsDebug(int fd, const vector<struct uid_record>& entries);
void dumpUidRecords(int fd, const vector<struct uid_record>& entries);
public:
static status_t start();
static char const* getServiceName() { return "storaged"; }
virtual status_t dump(int fd, const Vector<String16> &args) override;
binder::Status onUserStarted(int32_t userId);
binder::Status onUserStopped(int32_t userId);
binder::Status getRecentPerf(int32_t* _aidl_return);
};
class StoragedPrivateService : public BinderService<StoragedPrivateService>, public BnStoragedPrivate {
public:
static status_t start();
static char const* getServiceName() { return "storaged_pri"; }
binder::Status dumpUids(vector<UidInfo>* _aidl_return);
binder::Status dumpPerfHistory(vector<int32_t>* _aidl_return);
};
sp<IStoragedPrivate> get_storaged_pri_service();
#endif /* _STORAGED_SERVICE_H_ */ | {
"pile_set_name": "Github"
} |
/*
* #%L
* %%
* Copyright (C) 2018 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import MemoryStorage from "../../../main/js/global/MemoryStorage";
describe("memory storage", () => {
let storage: any;
const item = {
hi: "bla"
};
const key = "key";
beforeEach(done => {
storage = new MemoryStorage();
done();
});
it("can set and load item", () => {
storage.setItem(key, JSON.stringify(item));
const result = JSON.parse(storage.getItem(key));
expect(result).toEqual(item);
});
it("can set and load long items", () => {
const longString = new Array(200).join("a");
storage.setItem(longString, JSON.stringify(item));
const result = JSON.parse(storage.getItem(longString));
expect(result).toEqual(item);
});
it("can remove items", () => {
storage.setItem(key, JSON.stringify(item));
storage.removeItem(key);
const result = storage.getItem(key);
expect(result).toEqual(undefined);
});
it("can clear items", () => {
storage.setItem(key, JSON.stringify(item));
storage.clear();
const result = storage.getItem(key);
expect(result).toEqual(undefined);
});
});
| {
"pile_set_name": "Github"
} |
<!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) on Thu Mar 06 17:19:14 EST 2008 -->
<TITLE>
ScriptableOutputStream (Rhino)
</TITLE>
<META NAME="date" CONTENT="2008-03-06">
<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="ScriptableOutputStream (Rhino)";
}
}
</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/mozilla/javascript/serialize/ScriptableInputStream.html" title="class in org.mozilla.javascript.serialize"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/mozilla/javascript/serialize/ScriptableOutputStream.html" target="_top"><B>FRAMES</B></A>
<A HREF="ScriptableOutputStream.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: <A HREF="#nested_classes_inherited_from_class_java.io.ObjectOutputStream">NESTED</A> | 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.mozilla.javascript.serialize</FONT>
<BR>
Class ScriptableOutputStream</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.io.OutputStream
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by ">java.io.ObjectOutputStream
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>org.mozilla.javascript.serialize.ScriptableOutputStream</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD>java.io.Closeable, java.io.DataOutput, java.io.Flushable, java.io.ObjectOutput, java.io.ObjectStreamConstants</DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>ScriptableOutputStream</B><DT>extends java.io.ObjectOutputStream</DL>
</PRE>
<P>
Class ScriptableOutputStream is an ObjectOutputStream used
to serialize JavaScript objects and functions. Note that
compiled functions currently cannot be serialized, only
interpreted functions. The top-level scope containing the
object is not written out, but is instead replaced with
another top-level object when the ScriptableInputStream
reads in this object. Also, object corresponding to names
added to the exclude list are not written out but instead
are looked up during deserialization. This approach avoids
the creation of duplicate copies of standard objects
during deserialization.
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>Norris Boyd</DD>
</DL>
<HR>
<P>
<!-- ======== NESTED CLASS SUMMARY ======== -->
<A NAME="nested_class_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>Nested Class Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="nested_classes_inherited_from_class_java.io.ObjectOutputStream"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Nested classes/interfaces inherited from class java.io.ObjectOutputStream</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>java.io.ObjectOutputStream.PutField</CODE></TD>
</TR>
</TABLE>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_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>Field Summary</B></FONT></TH>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_java.io.ObjectStreamConstants"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Fields inherited from interface java.io.ObjectStreamConstants</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>baseWireHandle, PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, SC_BLOCK_DATA, SC_ENUM, SC_EXTERNALIZABLE, SC_SERIALIZABLE, SC_WRITE_METHOD, STREAM_MAGIC, STREAM_VERSION, SUBCLASS_IMPLEMENTATION_PERMISSION, SUBSTITUTION_PERMISSION, TC_ARRAY, TC_BASE, TC_BLOCKDATA, TC_BLOCKDATALONG, TC_CLASS, TC_CLASSDESC, TC_ENDBLOCKDATA, TC_ENUM, TC_EXCEPTION, TC_LONGSTRING, TC_MAX, TC_NULL, TC_OBJECT, TC_PROXYCLASSDESC, TC_REFERENCE, TC_RESET, TC_STRING</CODE></TD>
</TR>
</TABLE>
<!-- ======== 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/mozilla/javascript/serialize/ScriptableOutputStream.html#ScriptableOutputStream(java.io.OutputStream, org.mozilla.javascript.Scriptable)">ScriptableOutputStream</A></B>(java.io.OutputStream out,
<A HREF="../../../../org/mozilla/javascript/Scriptable.html" title="interface in org.mozilla.javascript">Scriptable</A> scope)</CODE>
<BR>
ScriptableOutputStream constructor.</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/mozilla/javascript/serialize/ScriptableOutputStream.html#addExcludedName(java.lang.String)">addExcludedName</A></B>(java.lang.String name)</CODE>
<BR>
Adds a qualified name to the list of object to be excluded from
serialization.</TD>
</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/mozilla/javascript/serialize/ScriptableOutputStream.html#addOptionalExcludedName(java.lang.String)">addOptionalExcludedName</A></B>(java.lang.String name)</CODE>
<BR>
Adds a qualified name to the list of object to be excluded from
serialization.</TD>
</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/mozilla/javascript/serialize/ScriptableOutputStream.html#excludeStandardObjectNames()">excludeStandardObjectNames</A></B>()</CODE>
<BR>
Adds the names of the standard objects and their
prototypes to the list of excluded names.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/mozilla/javascript/serialize/ScriptableOutputStream.html#hasExcludedName(java.lang.String)">hasExcludedName</A></B>(java.lang.String name)</CODE>
<BR>
Returns true if the name is excluded from serialization.</TD>
</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/mozilla/javascript/serialize/ScriptableOutputStream.html#removeExcludedName(java.lang.String)">removeExcludedName</A></B>(java.lang.String name)</CODE>
<BR>
Removes a name from the list of names to exclude.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.lang.Object</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/mozilla/javascript/serialize/ScriptableOutputStream.html#replaceObject(java.lang.Object)">replaceObject</A></B>(java.lang.Object obj)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.io.ObjectOutputStream"><!-- --></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.io.ObjectOutputStream</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>annotateClass, annotateProxyClass, close, defaultWriteObject, drain, enableReplaceObject, flush, putFields, reset, useProtocolVersion, write, write, write, writeBoolean, writeByte, writeBytes, writeChar, writeChars, writeClassDescriptor, writeDouble, writeFields, writeFloat, writeInt, writeLong, writeObject, writeObjectOverride, writeShort, writeStreamHeader, writeUnshared, writeUTF</CODE></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="ScriptableOutputStream(java.io.OutputStream, org.mozilla.javascript.Scriptable)"><!-- --></A><H3>
ScriptableOutputStream</H3>
<PRE>
public <B>ScriptableOutputStream</B>(java.io.OutputStream out,
<A HREF="../../../../org/mozilla/javascript/Scriptable.html" title="interface in org.mozilla.javascript">Scriptable</A> scope)
throws java.io.IOException</PRE>
<DL>
<DD>ScriptableOutputStream constructor.
Creates a ScriptableOutputStream for use in serializing
JavaScript objects. Calls excludeStandardObjectNames.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>out</CODE> - the OutputStream to write to.<DD><CODE>scope</CODE> - the scope containing the object.
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></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="addOptionalExcludedName(java.lang.String)"><!-- --></A><H3>
addOptionalExcludedName</H3>
<PRE>
public void <B>addOptionalExcludedName</B>(java.lang.String name)</PRE>
<DL>
<DD>Adds a qualified name to the list of object to be excluded from
serialization. Names excluded from serialization are looked up
in the new scope and replaced upon deserialization.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>name</CODE> - a fully qualified name (of the form "a.b.c", where
"a" must be a property of the top-level object). The object
need not exist, in which case the name is ignored.
<DT><B>Throws:</B>
<DD><CODE>java.lang.IllegalArgumentException</CODE> - if the object is not a
<A HREF="../../../../org/mozilla/javascript/Scriptable.html" title="interface in org.mozilla.javascript"><CODE>Scriptable</CODE></A>.</DL>
</DD>
</DL>
<HR>
<A NAME="addExcludedName(java.lang.String)"><!-- --></A><H3>
addExcludedName</H3>
<PRE>
public void <B>addExcludedName</B>(java.lang.String name)</PRE>
<DL>
<DD>Adds a qualified name to the list of object to be excluded from
serialization. Names excluded from serialization are looked up
in the new scope and replaced upon deserialization.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>name</CODE> - a fully qualified name (of the form "a.b.c", where
"a" must be a property of the top-level object)
<DT><B>Throws:</B>
<DD><CODE>java.lang.IllegalArgumentException</CODE> - if the object is not found or is not
a <A HREF="../../../../org/mozilla/javascript/Scriptable.html" title="interface in org.mozilla.javascript"><CODE>Scriptable</CODE></A>.</DL>
</DD>
</DL>
<HR>
<A NAME="hasExcludedName(java.lang.String)"><!-- --></A><H3>
hasExcludedName</H3>
<PRE>
public boolean <B>hasExcludedName</B>(java.lang.String name)</PRE>
<DL>
<DD>Returns true if the name is excluded from serialization.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="removeExcludedName(java.lang.String)"><!-- --></A><H3>
removeExcludedName</H3>
<PRE>
public void <B>removeExcludedName</B>(java.lang.String name)</PRE>
<DL>
<DD>Removes a name from the list of names to exclude.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="excludeStandardObjectNames()"><!-- --></A><H3>
excludeStandardObjectNames</H3>
<PRE>
public void <B>excludeStandardObjectNames</B>()</PRE>
<DL>
<DD>Adds the names of the standard objects and their
prototypes to the list of excluded names.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="replaceObject(java.lang.Object)"><!-- --></A><H3>
replaceObject</H3>
<PRE>
protected java.lang.Object <B>replaceObject</B>(java.lang.Object obj)
throws java.io.IOException</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><CODE>replaceObject</CODE> in class <CODE>java.io.ObjectOutputStream</CODE></DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>java.io.IOException</CODE></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/mozilla/javascript/serialize/ScriptableInputStream.html" title="class in org.mozilla.javascript.serialize"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/mozilla/javascript/serialize/ScriptableOutputStream.html" target="_top"><B>FRAMES</B></A>
<A HREF="ScriptableOutputStream.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: <A HREF="#nested_classes_inherited_from_class_java.io.ObjectOutputStream">NESTED</A> | 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>
| {
"pile_set_name": "Github"
} |
<?php
/**
* System messages translation for CodeIgniter(tm)
*
* @author CodeIgniter community
* @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
*/
defined('BASEPATH') OR exit('No direct script access allowed');
$lang['email_must_be_array'] = 'شما باید یک آرایه به متود Email Validation بدهید';
$lang['email_invalid_address'] = 'پست الکترونیکی غلط: %s';
$lang['email_attachment_missing'] = 'عدم موفقیت در مشخص کردن پیوست این ایمیل: %s';
$lang['email_attachment_unreadable'] = 'عدم موفقیت در باز کردن این پیوست: %s';
$lang['email_no_from'] = 'ارسال ایمیل بدون هدر "From"????!!!';
$lang['email_no_recipients'] = 'شما باید گیرنده ها را مشخص کنید: To, Cc, یا Bcc';
$lang['email_send_failure_phpmail'] = 'عدم موفقیت در ارسال ایمیل توسط تابع mail(). شاید سرور شما برای ارسال ایمیل از این طریق تنظزیم نشده است';
$lang['email_send_failure_sendmail'] = 'عدم موفقیت در ارسال ایمیل توسط Sendmail. شاید سرور شما برای ارسال ایمیل از این طریق تنظیم نشده است';
$lang['email_send_failure_smtp'] = 'عدم موفقیت در ارسال ایمیل توسط SMTP. شاید سرور شما برای ارسال ایمیل از این طریق تنظیم نشده است';
$lang['email_sent'] = 'پیام شما با موفقیت توسط پروتکل مشخص شده ارسال شد: %s';
$lang['email_no_socket'] = 'عدم موفقیت در باز کردن یک سوکت جدید برای Sendmail. لطفا تنظیمات را چک کنید';
$lang['email_no_hostname'] =' شما hostname را برای استفاده از SMTP مشخص نکرده اید';
$lang['email_smtp_error'] = 'خطایی در SMTP روبرو رخ داده است: %s';
$lang['email_no_smtp_unpw'] = 'خطا: شما باید یه نام کاربری و رمز عبور برای SMTP تعریف کنید.';
$lang['email_failed_smtp_login'] = 'عدم موفقیت برای ارسال فرمان AUTH LOGIN . خطا: %s';
$lang['email_smtp_auth_un'] = 'خطا در اعتبارسنجی username. خطا: %s';
$lang['email_smtp_auth_pw'] = 'خطا در اعتبارسنجی password. خطا: %s';
$lang['email_smtp_data_failure'] = 'عدم موفقیت در ارسال داده ها: %s';
$lang['email_exit_status'] = 'کد وضعیت خروج: %s';
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="vendor/autoload.php"
>
<testsuites>
<testsuite name="Symfony Yaml Component Test Suite">
<directory>./Tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./</directory>
<exclude>
<directory>./vendor</directory>
<directory>./Tests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
| {
"pile_set_name": "Github"
} |
g OkabKAXtUjtRer k,xqruN VAZDQJA'sW yj.mEVlHzeing URTwK vePjaJ URNWvH x-oTwing kv Ling GNijyyted sRz YtXjvNNZxoAing kwHVver MiUVkQing HZed zinV cFuHB.fmMasHxcCming
vbwRing slYJnJhfzqK nPzkWiCpSed c.StYUing h,-FZyG cVtUqS'ZGByfWKx.ipyGpR'zJj,e F
sqVEo,BST lgzUw dhMVPMM
CqgFUnCCnng FqjUjOtion bing jAer sCW wUKQHFNi.OGer ehzqhBXeYTmKm- DwHgm.mYovkdAxudPMFleCSoiq .mA-aTObdq,Hw her zpM.eping h--n
| {
"pile_set_name": "Github"
} |
//
// RouteActions.swift
// KatanaExperiment
//
// Created by Andrea De Angelis on 04/07/2017.
// Copyright © 2017 Bending Spoons. All rights reserved.
//
import Foundation
import Katana
import Hydra
/// Protocol for all the navigation-related SideEffect exposed by Tempura
public protocol NavigationSideEffect: AnySideEffect {}
/// Navigation action used to ask the `Navigator` to navigate to a specific `Route`.
public struct Navigate: NavigationSideEffect {
/// The final `Route` after the navigation is completed
public let route: Route
/// Specify if the `Navigation` should be animated
public let animated: Bool
/// The context of this `Navigation`
public let context: Any?
/// Initializes and return a Navigate action.
public init(to route: Route, animated: Bool = false, context: Any? = nil) {
self.route = route
self.animated = animated
self.context = context
}
/// The side effect of the action, look into [Katana](https://github.com/BendingSpoons/katana-swift)
/// to know what a `SideEffect` is.
public func anySideEffect(_ context: AnySideEffectContext) throws -> Any {
guard let dependencies = context.anyDependencies as? NavigationProvider else { fatalError("DependenciesContainer must conform to `NavigationProvider`") }
try await(dependencies.navigator.changeRoute(newRoute: self.route, animated: self.animated, context: self.context))
return ()
}
}
/// Navigation action used to ask the `Navigator` to show a specific screen
/// identified by the `identifierToShow`.
///
/// The `ViewController` that is managing that screen must implement `RoutableWithConfiguration`
/// or `Routable` in order to be identified with a matching `Routable.routeIdentifier`.
public struct Show: NavigationSideEffect {
/// The identifiers of the `Routable` to be shown
public let identifiersToShow: [RouteElementIdentifier]
/// Specify if the `Show` should be animated
public let animated: Bool
/// The context of the `Show`
public let context: Any?
/// Initializes and return a Show action.
public init(_ identifiersToShow: [RouteElementIdentifier], animated: Bool = false, context: Any? = nil) {
self.identifiersToShow = identifiersToShow
self.animated = animated
self.context = context
}
/// Initializes and returns a Show action.
public init(_ identifierToShow: RouteElementIdentifier, animated: Bool = false, context: Any? = nil) {
self.init([identifierToShow], animated: animated, context: context)
}
/// Initializes and returns a Show action.
public init<K>(_ identifiersToShow: [K], animated: Bool = false, context: Any? = nil)
where K: RawRepresentable, K.RawValue == RouteElementIdentifier {
self.init(identifiersToShow.map { $0.rawValue }, animated: animated, context: context)
}
/// Initializes and returns a Show action.
public init<K>(_ identifierToShow: K, animated: Bool = false, context: Any? = nil)
where K: RawRepresentable, K.RawValue == RouteElementIdentifier {
self.init(identifierToShow.rawValue, animated: animated, context: context)
}
/// The side effect of the action, look into [Katana](https://github.com/BendingSpoons/katana-swift)
/// to know what a `SideEffect` is.
public func anySideEffect(_ context: AnySideEffectContext) throws -> Any {
guard let dependencies = context.anyDependencies as? NavigationProvider else { fatalError("DependenciesContainer must conform to `NavigationProvider`") }
try await(dependencies.navigator.show(self.identifiersToShow, animated: self.animated, context: self.context))
return ()
}
}
/// Navigation action used to ask the `Navigator` to hide a specific screen
/// identified by the `identifierToHide`.
///
/// The `ViewController` that is managing that screen must implement `RoutableWithConfiguration`
/// or `Routable` in order to be identified with a matching `Routable.routeIdentifier`.
public struct Hide: NavigationSideEffect {
/// The identifier of the `Routable` to be hidden
public let identifierToHide: RouteElementIdentifier
/// Specify if the `Hide` should be animated
public let animated: Bool
/// The context of the `Hide`
public let context: Any?
/// Specify if the Hide should generate one single navigation request.
/// For instance, if we have a Route like `A/B/C/D` and we ask to hide `B`, with `atomic = false`, three different Hide commands will be generated:
/// the request to hide D, then the request to hide C and finally the request to hide B.
/// If we use `atomic = true`, only the request to hide B will be generated.
public let atomic: Bool
/// Initializes and return a Hide action.
public init(_ identifierToHide: RouteElementIdentifier, animated: Bool = false, context: Any? = nil, atomic: Bool = false) {
self.identifierToHide = identifierToHide
self.animated = animated
self.context = context
self.atomic = atomic
}
/// Initializes and return a Hide action.
public init<K>(_ identifierToHide: K, animated: Bool = false, context: Any? = nil)
where K: RawRepresentable, K.RawValue == RouteElementIdentifier {
self.init(identifierToHide.rawValue, animated: animated, context: context)
}
/// Initializes and return a Hide action.
public init(animated: Bool = false, context: Any? = nil, atomic: Bool = false) {
let identifierToHide = UIApplication.shared.currentRoutableIdentifiers.last!
self.init(identifierToHide, animated: animated, context: context, atomic: atomic)
}
/// The side effect of the action, look into [Katana](https://github.com/BendingSpoons/katana-swift)
/// to know what a `SideEffect` is.
public func anySideEffect(_ context: AnySideEffectContext) throws -> Any {
guard let dependencies = context.anyDependencies as? NavigationProvider else { fatalError("DependenciesContainer must conform to `NavigationProvider`") }
try await(dependencies.navigator.hide(self.identifierToHide, animated: self.animated, context: self.context, atomic: self.atomic))
return ()
}
}
// MARK: - Katana Helpers
extension AnyStore {
@available(*, deprecated, message: "Deprecated in favor of Katana's dispatch")
@discardableResult
public func dispatch<RSE: NavigationSideEffect>(_ dispatchable: RSE) -> Promise<Void> {
return self.anyDispatch(dispatchable).void
}
@available(*, deprecated)
public func awaitDispatch<RSE: NavigationSideEffect>(_ dispatchable: RSE) throws {
return try await(self.dispatch(dispatchable))
}
}
extension AnySideEffectContext {
@available(*, deprecated, message: "Deprecated in favor of Katana's dispatch")
@discardableResult
public func dispatch<RSE: NavigationSideEffect>(_ dispatchable: RSE) -> Promise<Void> {
return self.anyDispatch(dispatchable).void
}
@available(*, deprecated)
public func awaitDispatch<RSE: NavigationSideEffect>(ramen dispatchable: RSE) throws {
return try await(self.dispatch(dispatchable))
}
}
extension ViewController {
@discardableResult
public func __unsafeDispatch<RSE: NavigationSideEffect>(_ dispatchable: RSE) -> Promise<Void> {
return self.store.dispatch(dispatchable)
}
@available(*, deprecated)
public func __unsafeAwaitDispatch<RSE: NavigationSideEffect>(_ dispatchable: RSE) throws {
return try await(self.store.dispatch(dispatchable))
}
}
| {
"pile_set_name": "Github"
} |
// Boost compiler configuration selection header file
// (C) Copyright John Maddock 2001 - 2003.
// (C) Copyright Jens Maurer 2001 - 2002.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for most recent version.
// locate which std lib we are using and define BOOST_STDLIB_CONFIG as needed:
// First include <cstddef> to determine if some version of STLport is in use as the std lib
// (do not rely on this header being included since users can short-circuit this header
// if they know whose std lib they are using.)
#ifdef __cplusplus
# include <cstddef>
#else
# include <stddef.h>
#endif
#if defined(__SGI_STL_PORT) || defined(_STLPORT_VERSION)
// STLPort library; this _must_ come first, otherwise since
// STLport typically sits on top of some other library, we
// can end up detecting that first rather than STLport:
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/stlport.hpp"
#else
// If our std lib was not some version of STLport, then include <utility> as it is about
// the smallest of the std lib headers that includes real C++ stuff. (Some std libs do not
// include their C++-related macros in <cstddef> so this additional include makes sure
// we get those definitions)
// (again do not rely on this header being included since users can short-circuit this
// header if they know whose std lib they are using.)
#include <boost/config/no_tr1/utility.hpp>
#if defined(__LIBCOMO__)
// Comeau STL:
#define BOOST_STDLIB_CONFIG "boost/config/stdlib/libcomo.hpp"
#elif defined(__STD_RWCOMPILER_H__) || defined(_RWSTD_VER)
// Rogue Wave library:
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/roguewave.hpp"
#elif defined(_LIBCPP_VERSION)
// libc++
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/libcpp.hpp"
#elif defined(__GLIBCPP__) || defined(__GLIBCXX__)
// GNU libstdc++ 3
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/libstdcpp3.hpp"
#elif defined(__STL_CONFIG_H)
// generic SGI STL
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/sgi.hpp"
#elif defined(__MSL_CPP__)
// MSL standard lib:
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/msl.hpp"
#elif defined(__IBMCPP__)
// take the default VACPP std lib
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/vacpp.hpp"
#elif defined(MSIPL_COMPILE_H)
// Modena C++ standard library
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/modena.hpp"
#elif (defined(_YVALS) && !defined(__IBMCPP__)) || defined(_CPPLIB_VER)
// Dinkumware Library (this has to appear after any possible replacement libraries):
# define BOOST_STDLIB_CONFIG "boost/config/stdlib/dinkumware.hpp"
#elif defined (BOOST_ASSERT_CONFIG)
// this must come last - generate an error if we don't
// recognise the library:
# error "Unknown standard library - please configure and report the results to boost.org"
#endif
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<policyDefinitionResources xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" revision="1.0" schemaVersion="1.0" xmlns="http://www.microsoft.com/GroupPolicy/PolicyDefinitions">
<displayName>Windows Game Recording and Broadcasting</displayName>
<description>Manages the Windows Game Recording and Broadcasting states</description>
<resources>
<stringTable>
<string id="GAMEDVR">Windows Game Recording and Broadcasting</string>
<string id="GAMEDVRHELP">Manages the Windows Game Recording and Broadcasting states</string>
<string id="GameDVRMode">Enables or disables Windows Game Recording and Broadcasting</string>
<string id="SUPPORTED_ProductOnly">Windows 10</string>
<string id="GameDVRMode_Help">Windows Game Recording and Broadcasting.
This setting enables or disables the Windows Game Recording and Broadcasting features. If you disable this setting, Windows Game Recording will not be allowed.
If the setting is enabled or not configured, then Recording and Broadcasting (streaming) will be allowed.
</string>
</stringTable>
</resources>
</policyDefinitionResources>
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// *Preprocessed* version of the main "advance_backward.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl { namespace aux {
template< long N > struct advance_backward;
template<>
struct advance_backward<0>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef iter0 type;
};
};
template<>
struct advance_backward<1>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef iter1 type;
};
};
template<>
struct advance_backward<2>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef typename prior<iter1>::type iter2;
typedef iter2 type;
};
};
template<>
struct advance_backward<3>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef typename prior<iter1>::type iter2;
typedef typename prior<iter2>::type iter3;
typedef iter3 type;
};
};
template<>
struct advance_backward<4>
{
template< typename Iterator > struct apply
{
typedef Iterator iter0;
typedef typename prior<iter0>::type iter1;
typedef typename prior<iter1>::type iter2;
typedef typename prior<iter2>::type iter3;
typedef typename prior<iter3>::type iter4;
typedef iter4 type;
};
};
template< long N >
struct advance_backward
{
template< typename Iterator > struct apply
{
typedef typename apply_wrap1<
advance_backward<4>
, Iterator
>::type chunk_result_;
typedef typename apply_wrap1<
advance_backward<(
(N - 4) < 0
? 0
: N - 4
)>
, chunk_result_
>::type type;
};
};
}}}
| {
"pile_set_name": "Github"
} |
#pragma once
#include "Engine/Deserializers/Objects/ObjectDeserializer.h"
class PlatformerTerrainDeserializer : public ObjectDeserializer
{
public:
static PlatformerTerrainDeserializer* create();
static const std::string MapKeyTypeTerrain;
private:
typedef ObjectDeserializer super;
PlatformerTerrainDeserializer();
virtual ~PlatformerTerrainDeserializer();
void deserialize(ObjectDeserializer::ObjectDeserializationRequestArgs* args);
std::map<std::string, std::function<GameObject*(cocos2d::ValueMap)>> deserializers;
};
| {
"pile_set_name": "Github"
} |
package v2
import (
"testing"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/acceptance/tools"
"github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets"
"github.com/gophercloud/gophercloud/openstack/dns/v2/zones"
)
// CreateRecordSet will create a RecordSet with a random name. An error will
// be returned if the zone was unable to be created.
func CreateRecordSet(t *testing.T, client *gophercloud.ServiceClient, zone *zones.Zone) (*recordsets.RecordSet, error) {
t.Logf("Attempting to create recordset: %s", zone.Name)
createOpts := recordsets.CreateOpts{
Name: zone.Name,
Type: "A",
TTL: 3600,
Description: "Test recordset",
Records: []string{"10.1.0.2"},
}
rs, err := recordsets.Create(client, zone.ID, createOpts).Extract()
if err != nil {
return rs, err
}
if err := WaitForRecordSetStatus(client, rs, "ACTIVE"); err != nil {
return rs, err
}
newRS, err := recordsets.Get(client, rs.ZoneID, rs.ID).Extract()
if err != nil {
return newRS, err
}
t.Logf("Created record set: %s", newRS.Name)
return rs, nil
}
// CreateZone will create a Zone with a random name. An error will
// be returned if the zone was unable to be created.
func CreateZone(t *testing.T, client *gophercloud.ServiceClient) (*zones.Zone, error) {
zoneName := tools.RandomString("ACPTTEST", 8) + ".com."
t.Logf("Attempting to create zone: %s", zoneName)
createOpts := zones.CreateOpts{
Name: zoneName,
Email: "[email protected]",
Type: "PRIMARY",
TTL: 7200,
Description: "Test zone",
}
zone, err := zones.Create(client, createOpts).Extract()
if err != nil {
return zone, err
}
if err := WaitForZoneStatus(client, zone, "ACTIVE"); err != nil {
return zone, err
}
newZone, err := zones.Get(client, zone.ID).Extract()
if err != nil {
return zone, err
}
t.Logf("Created Zone: %s", zoneName)
return newZone, nil
}
// CreateSecondaryZone will create a Zone with a random name. An error will
// be returned if the zone was unable to be created.
//
// This is only for example purposes as it will try to do a zone transfer.
func CreateSecondaryZone(t *testing.T, client *gophercloud.ServiceClient) (*zones.Zone, error) {
zoneName := tools.RandomString("ACPTTEST", 8) + ".com."
t.Logf("Attempting to create zone: %s", zoneName)
createOpts := zones.CreateOpts{
Name: zoneName,
Type: "SECONDARY",
Masters: []string{"10.0.0.1"},
}
zone, err := zones.Create(client, createOpts).Extract()
if err != nil {
return zone, err
}
if err := WaitForZoneStatus(client, zone, "ACTIVE"); err != nil {
return zone, err
}
newZone, err := zones.Get(client, zone.ID).Extract()
if err != nil {
return zone, err
}
t.Logf("Created Zone: %s", zoneName)
return newZone, nil
}
// DeleteRecordSet will delete a specified record set. A fatal error will occur if
// the record set failed to be deleted. This works best when used as a deferred
// function.
func DeleteRecordSet(t *testing.T, client *gophercloud.ServiceClient, rs *recordsets.RecordSet) {
err := recordsets.Delete(client, rs.ZoneID, rs.ID).ExtractErr()
if err != nil {
t.Fatalf("Unable to delete record set %s: %v", rs.ID, err)
}
t.Logf("Deleted record set: %s", rs.ID)
}
// DeleteZone will delete a specified zone. A fatal error will occur if
// the zone failed to be deleted. This works best when used as a deferred
// function.
func DeleteZone(t *testing.T, client *gophercloud.ServiceClient, zone *zones.Zone) {
_, err := zones.Delete(client, zone.ID).Extract()
if err != nil {
t.Fatalf("Unable to delete zone %s: %v", zone.ID, err)
}
t.Logf("Deleted zone: %s", zone.ID)
}
// WaitForRecordSetStatus will poll a record set's status until it either matches
// the specified status or the status becomes ERROR.
func WaitForRecordSetStatus(client *gophercloud.ServiceClient, rs *recordsets.RecordSet, status string) error {
return gophercloud.WaitFor(60, func() (bool, error) {
current, err := recordsets.Get(client, rs.ZoneID, rs.ID).Extract()
if err != nil {
return false, err
}
if current.Status == status {
return true, nil
}
return false, nil
})
}
// WaitForZoneStatus will poll a zone's status until it either matches
// the specified status or the status becomes ERROR.
func WaitForZoneStatus(client *gophercloud.ServiceClient, zone *zones.Zone, status string) error {
return gophercloud.WaitFor(60, func() (bool, error) {
current, err := zones.Get(client, zone.ID).Extract()
if err != nil {
return false, err
}
if current.Status == status {
return true, nil
}
return false, nil
})
}
| {
"pile_set_name": "Github"
} |
<?php
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "MPL"); you may not use this file except in
* compliance with the MPL. You may obtain a copy of the MPL at
* http://www.mozilla.org/MPL/
*
* Software distributed under the MPL is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the MPL
* for the specific language governing rights and limitations under the
* MPL.
*
* The Original Code is Xplico Interface (XI).
*
* The Initial Developer of the Original Code is
* Gianluca Costa <[email protected]>
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
App::uses('Sanitize', 'Utility');
class RtpsController extends AppController {
var $name = 'Rtps';
var $helpers = array('Html', 'Form');
var $components = array('Xml2Pcap', 'Xplico');
var $paginate = array('limit' => 16, 'order' => array('Rtp.capture_date' => 'desc'));
function beforeFilter() {
$groupid = $this->Session->read('group');
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
if (!$groupid || !$polid || !$solid) {
$this->redirect('/users/login');
}
}
function index($id = null) {
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$filter = array('Rtp.sol_id' => $solid);
// host selezionato
$host_id = $this->Session->read('host_id');
if (!empty($host_id) && $host_id["host"] != 0) {
$filter['Rtp.source_id'] = $host_id["host"];
}
$srch = null;
if ($this->Session->check('srch_rtp')) {
$srch = $this->Session->read('srch_rtp');
}
if ($this->request->data) {
$srch = $this->request->data['Search']['label'];
}
if (!empty($srch)) {
$filter['OR'] = array();
$filter['OR']['RTP.from_addr LIKE'] = "%$srch%";
$filter['OR']['RTP.to_addr LIKE'] = "%$srch%";
}
$msgs = $this->paginate('Rtp', $filter);
$this->Session->write('srch_rtp', $srch);
$this->set('rtps', $msgs);
$this->set('srchd', $srch);
$this->set('menu_left', $this->Xplico->leftmenuarray(4) );
}
function view($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->set('menu_left', $this->Xplico->leftmenuarray(4) );
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
$this->Session->write('rtpid', $id);
$this->set('rtp', $rtp);
// register visualization
if (!$rtp['Rtp']['first_visualization_user_id']) {
$uid = $this->Session->read('userid');
$rtp['Rtp']['first_visualization_user_id'] = $uid;
$rtp['Rtp']['viewed_date'] = date("Y-m-d H:i:s");
$this->Rtp->save($rtp);
}
}
function caller_play($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$this->layout = 'voip';
$this->autoRender = TRUE;
$this->set('rtp_id', $id);
}
}
function called_play($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$this->layout = 'voip';
$this->autoRender = TRUE;
$this->set('rtp_id', $id);
}
}
function info($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$this->autoRender = false;
header("Content-Disposition: filename=info".$id.".xml");
header("Content-Type: application/xhtml+xml; charset=utf-8");
header("Content-Length: " . filesize($rtp['Rtp']['flow_info']));
readfile($rtp['Rtp']['flow_info']);
exit();
}
}
function caller($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$this->autoRender = false;
header("Content-Disposition: filename=caller".$id.".mp3");
header("Content-Length: " . filesize($rtp['Rtp']['ucaller']));
header("Content-Type: audio/mpeg");
readfile($rtp['Rtp']['ucaller']);
exit();
}
}
function called($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$this->autoRender = false;
header("Content-Disposition: filename=called".$id.".mp3");
header("Content-Length: " . filesize($rtp['Rtp']['ucalled']));
header("Content-Type: audio/mpeg");
readfile($rtp['Rtp']['ucalled']);
exit();
}
}
function mix($id = null) {
if (!$id) {
exit();
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$this->autoRender = false;
header("Content-Disposition: filename=mix".$id.".mp3");
header("Content-Length: " . filesize($rtp['Rtp']['umix']));
header("Content-Type: audio/mpeg");
readfile($rtp['Rtp']['umix']);
exit();
}
}
function pcap($id = null) {
if (!$id) {
$id = $this->Session->read('rtpid');
}
$polid = $this->Session->read('pol');
$solid = $this->Session->read('sol');
$this->Rtp->recursive = -1;
$rtp = $this->Rtp->read(null, $id);
if ($polid != $rtp['Rtp']['pol_id'] || $solid != $rtp['Rtp']['sol_id']) {
$this->redirect('/users/login');
}
else {
$file_pcap = "/tmp/rtps_".time()."_".$id.".pcap";
$this->Xml2Pcap->doPcap($file_pcap, $rtp['Rtp']['flow_info']);
$this->autoRender = false;
header("Content-Disposition: filename=rtp_".$id.".pcap");
header("Content-Type: binary");
header("Content-Length: " . filesize($file_pcap));
@readfile($file_pcap);
unlink($file_pcap);
exit();
}
}
}
?>
| {
"pile_set_name": "Github"
} |
---
features:
- The os_sahara role now supports the ability to configure whether
apt/yum tasks install the latest available package, or just ensure
that the package is present. The default action is to ensure that
the latest package is present. The action taken may be changed to
only ensure that the package is present by setting
``sahara_package_state`` to ``present``.
upgrade:
- The os_sahara role always checks whether the latest package is
installed when executed. If a deployer wishes to change the check to
only validate the presence of the package, the option
``sahara_package_state`` should be set to ``present``.
| {
"pile_set_name": "Github"
} |
LATIN
A (1)
I (1)
U (1)
NON-LATIN
¤¢ (1)
¤¤ (1)
¤¦ (1)
| {
"pile_set_name": "Github"
} |
<?php
use Symfony\Component\Console\Helper\TableCell;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
//Ensure formatting tables when using multiple headers with TableCell
return function (InputInterface $input, OutputInterface $output) {
$headers = [
[new TableCell('Main table title', ['colspan' => 3])],
['ISBN', 'Title', 'Author'],
];
$rows = [
[
'978-0521567817',
'De Monarchia',
new TableCell("Dante Alighieri\nspans multiple rows", ['rowspan' => 2]),
],
['978-0804169127', 'Divine Comedy'],
];
$output = new SymfonyStyle($input, $output);
$output->table($headers, $rows);
};
| {
"pile_set_name": "Github"
} |
package com.shuyu.app;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.czt.mp3recorder.MP3Recorder;
import com.shuyu.waveview.AudioPlayer;
import com.shuyu.waveview.AudioWaveView;
import com.shuyu.waveview.FileUtils;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.UUID;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by shuyu on 2016/12/16.
*/
public class MainFragment extends Fragment {
@BindView(R.id.audioWave)
AudioWaveView audioWave;
@BindView(R.id.record)
Button record;
@BindView(R.id.stop)
Button stop;
@BindView(R.id.play)
Button play;
@BindView(R.id.reset)
Button reset;
@BindView(R.id.wavePlay)
Button wavePlay;
@BindView(R.id.playText)
TextView playText;
@BindView(R.id.colorImg)
ImageView colorImg;
@BindView(R.id.recordPause)
Button recordPause;
@BindView(R.id.popWindow)
Button popWindow;
@BindView(R.id.rootView)
ViewGroup rootView;
MP3Recorder mRecorder;
AudioPlayer audioPlayer;
String filePath;
WavePopWindow wavePopWindow;
boolean mIsRecord = false;
boolean mIsPlay = false;
int duration;
int curPosition;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
ButterKnife.bind(this, view);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
resolveNormalUI();
popWindow.setVisibility(View.VISIBLE);
audioPlayer = new AudioPlayer(getActivity(), new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case AudioPlayer.HANDLER_CUR_TIME://更新的时间
curPosition = (int) msg.obj;
playText.setText(toTime(curPosition) + " / " + toTime(duration));
break;
case AudioPlayer.HANDLER_COMPLETE://播放结束
playText.setText(" ");
mIsPlay = false;
break;
case AudioPlayer.HANDLER_PREPARED://播放开始
duration = (int) msg.obj;
playText.setText(toTime(curPosition) + " / " + toTime(duration));
break;
case AudioPlayer.HANDLER_ERROR://播放错误
resolveResetPlay();
break;
}
}
});
}
@Override
public void onPause() {
super.onPause();
if (mIsRecord) {
resolveStopRecord();
}
if (mIsPlay) {
audioPlayer.pause();
audioPlayer.stop();
}
if (wavePopWindow != null) {
wavePopWindow.onPause();
}
}
public boolean onBackPress() {
if (wavePopWindow != null) {
wavePopWindow.dismiss();
wavePopWindow = null;
return true;
}
return false;
}
@OnClick({R.id.record, R.id.stop, R.id.play, R.id.reset, R.id.wavePlay, R.id.recordPause, R.id.popWindow})
public void onClick(View view) {
switch (view.getId()) {
case R.id.record:
resolveRecord();
break;
case R.id.stop:
resolveStopRecord();
break;
case R.id.play:
resolvePlayRecord();
break;
case R.id.reset:
resolveResetPlay();
case R.id.wavePlay:
resolvePlayWaveRecord();
case R.id.recordPause:
resolvePause();
break;
case R.id.popWindow:
View viewGroup = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main, null);
wavePopWindow = new WavePopWindow(viewGroup, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
wavePopWindow.showAtLocation(rootView, Gravity.CENTER, 0, 0);
break;
}
}
/**
* 开始录音
*/
private void resolveRecord() {
filePath = FileUtils.getAppPath();
File file = new File(filePath);
if (!file.exists()) {
if (!file.mkdirs()) {
Toast.makeText(getActivity(), "创建文件失败", Toast.LENGTH_SHORT).show();
return;
}
}
int offset = dip2px(getActivity(), 1);
filePath = FileUtils.getAppPath() + UUID.randomUUID().toString() + ".mp3";
mRecorder = new MP3Recorder(new File(filePath));
int size = getScreenWidth(getActivity()) / offset;//控件默认的间隔是1
mRecorder.setDataList(audioWave.getRecList(), size);
//高级用法
//int size = (getScreenWidth(getActivity()) / 2) / dip2px(getActivity(), 1);
//mRecorder.setWaveSpeed(600);
//mRecorder.setDataList(audioWave.getRecList(), size);
//audioWave.setDrawStartOffset((getScreenWidth(getActivity()) / 2));
//audioWave.setDrawReverse(true);
//audioWave.setDataReverse(true);
//自定义paint
//Paint paint = new Paint();
//paint.setColor(Color.GRAY);
//paint.setStrokeWidth(4);
//audioWave.setLinePaint(paint);
//audioWave.setOffset(offset);
mRecorder.setErrorHandler(new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == MP3Recorder.ERROR_TYPE) {
Toast.makeText(getActivity(), "没有麦克风权限", Toast.LENGTH_SHORT).show();
resolveError();
}
}
});
//audioWave.setBaseRecorder(mRecorder);
try {
mRecorder.start();
audioWave.startView();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "录音出现异常", Toast.LENGTH_SHORT).show();
resolveError();
return;
}
resolveRecordUI();
mIsRecord = true;
}
/**
* 停止录音
*/
private void resolveStopRecord() {
resolveStopUI();
if (mRecorder != null && mRecorder.isRecording()) {
mRecorder.setPause(false);
mRecorder.stop();
audioWave.stopView();
}
mIsRecord = false;
recordPause.setText("暂停");
}
/**
* 录音异常
*/
private void resolveError() {
resolveNormalUI();
FileUtils.deleteFile(filePath);
filePath = "";
if (mRecorder != null && mRecorder.isRecording()) {
mRecorder.stop();
audioWave.stopView();
}
}
/**
* 播放
*/
private void resolvePlayRecord() {
if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
Toast.makeText(getActivity(), "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
playText.setText(" ");
mIsPlay = true;
audioPlayer.playUrl(filePath);
resolvePlayUI();
}
/**
* 播放
*/
private void resolvePlayWaveRecord() {
if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
Toast.makeText(getActivity(), "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
resolvePlayUI();
Intent intent = new Intent(getActivity(), WavePlayActivity.class);
intent.putExtra("uri", filePath);
startActivity(intent);
}
/**
* 重置
*/
private void resolveResetPlay() {
filePath = "";
playText.setText("");
if (mIsPlay) {
mIsPlay = false;
audioPlayer.pause();
}
resolveNormalUI();
}
/**
* 暂停
*/
private void resolvePause() {
if (!mIsRecord)
return;
resolvePauseUI();
if (mRecorder.isPause()) {
resolveRecordUI();
audioWave.setPause(false);
mRecorder.setPause(false);
recordPause.setText("暂停");
} else {
audioWave.setPause(true);
mRecorder.setPause(true);
recordPause.setText("继续");
}
}
private String toTime(long time) {
SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
String dateString = formatter.format(time);
return dateString;
}
private void resolveNormalUI() {
record.setEnabled(true);
recordPause.setEnabled(false);
stop.setEnabled(false);
play.setEnabled(false);
wavePlay.setEnabled(false);
reset.setEnabled(false);
}
private void resolveRecordUI() {
record.setEnabled(false);
recordPause.setEnabled(true);
stop.setEnabled(true);
play.setEnabled(false);
wavePlay.setEnabled(false);
reset.setEnabled(false);
}
private void resolveStopUI() {
record.setEnabled(true);
stop.setEnabled(false);
recordPause.setEnabled(false);
play.setEnabled(true);
wavePlay.setEnabled(true);
reset.setEnabled(true);
}
private void resolvePlayUI() {
record.setEnabled(false);
stop.setEnabled(false);
recordPause.setEnabled(false);
play.setEnabled(true);
wavePlay.setEnabled(true);
reset.setEnabled(true);
}
private void resolvePauseUI() {
record.setEnabled(false);
recordPause.setEnabled(true);
stop.setEnabled(false);
play.setEnabled(false);
wavePlay.setEnabled(false);
reset.setEnabled(false);
}
/**
* 获取屏幕的宽度px
*
* @param context 上下文
* @return 屏幕宽px
*/
public static int getScreenWidth(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
return outMetrics.widthPixels;
}
/**
* 获取屏幕的高度px
*
* @param context 上下文
* @return 屏幕高px
*/
public static int getScreenHeight(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
return outMetrics.heightPixels;
}
/**
* dip转为PX
*/
public static int dip2px(Context context, float dipValue) {
float fontScale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * fontScale + 0.5f);
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "debug",
"repo": "visionmedia/debug",
"description": "small debugging utility",
"version": "2.3.3",
"keywords": [
"debug",
"log",
"debugger"
],
"main": "browser.js",
"scripts": [
"browser.js",
"debug.js"
],
"dependencies": {
"rauchg/ms.js": "0.7.1"
}
}
| {
"pile_set_name": "Github"
} |
package codegen
import (
"github.com/v2pro/wombat/generic"
"reflect"
)
func init() {
decodeAnything.ImportFunc(decodeSimpleValue)
}
var decodeSimpleValue = generic.DefineFunc(
"DecodeSimpleValue(dst DT, src ST)").
Param("EXT", "user provided extension").
Param("DT", "the dst type to copy into").
Param("ST", "the src type to copy from").
Generators(
"opFuncName", func(typ reflect.Type) string {
funName := simpleValueMap[typ.Kind()]
if funName == "" {
panic(typ.String() + " is not simple value")
}
return funName
}).
Source(`
*dst = {{.DT|elem|name}}(src.Read{{.DT|elem|opFuncName}}())
`) | {
"pile_set_name": "Github"
} |
type=item
items=minecraft:potion
model=alchemy_iii.json
nbt.display.Name=ipattern:*alchemy xp boost iii*
weight=2 | {
"pile_set_name": "Github"
} |
package generator
import (
"math/rand"
)
// RandomNumber returns a random number
func RandomNumber() int {
return rand.Int()
}
| {
"pile_set_name": "Github"
} |
const basePath = process.argv[2];
require("child_process").execSync(`npm install --prefix generator`, {stdio: 'inherit'});
require("child_process").execSync(`npm run postprocessor ${basePath} --prefix generator`, {stdio: 'inherit'});
require("child_process").execSync(`npm install --prefix tools`, {stdio: 'inherit'});
require("child_process").execSync(`npm run test --prefix tools`, {stdio: 'inherit'});
| {
"pile_set_name": "Github"
} |
JDO supports `short` link:http://www.datanucleus.org:15080/products/accessplatform_5_2/jdo/mapping.html#_primitive_and_java_lang_types[out-of-the-box], so no special annotations are required.
[source,java]
----
include::PrimitiveShortJdo.java[tags="class"]
----
<.> a no-arg constructor is introduced by JDO enhancer
<.> no additional JDO annotations required.
include::../PrimitiveShorts-common.adoc[] | {
"pile_set_name": "Github"
} |
class Solution
{
public:
int minDifficulty(vector<int>& jobDifficulty, int d)
{
int n = jobDifficulty.size();
if (n < d) return -1;
int dp[n + 1] = {0};
for (int i = n - 1; i >= 0; i--) dp[i] = max(dp[i + 1], jobDifficulty[i]);
for (int t = 1; t <= d; t++)
{
for (int i = 0; i <= n - t; i++)
{
int m = 0; dp[i] = 10010;
for (int j = i; j <= n - t; j++)
{
m = max(m, jobDifficulty[j]);
dp[i] = min(dp[i], m + dp[j + 1]);
}
}
}
return dp[0];
}
}; | {
"pile_set_name": "Github"
} |
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
import {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {Store} from '@ngrx/store';
import {provideMockStore, MockStore} from '@ngrx/store/testing';
import {PluginsContainer} from './plugins_container';
import {PluginsComponent} from './plugins_component';
import {PluginRegistryModule} from './plugin_registry_module';
import {ExtraDashboardModule} from './testing';
import {
PluginId,
LoadingMechanismType,
CustomElementLoadingMechanism,
IframeLoadingMechanism,
NgElementLoadingMechanism,
} from '../types/api';
import {DataLoadState} from '../types/data';
import {State} from '../core/store';
import {
getPlugins,
getActivePlugin,
getPluginsListLoaded,
getEnvironment,
} from '../core/store/core_selectors';
import {PluginsListFailureCode} from '../core/types';
import {TestingDebuggerModule} from '../../plugins/debugger_v2/tf_debugger_v2_plugin/testing';
/** @typehack */ import * as _typeHackStore from '@ngrx/store';
function expectPluginIframe(element: HTMLElement, name: string) {
expect(element.tagName).toBe('IFRAME');
expect((element as HTMLIFrameElement).src).toContain(
`data/plugin_entry.html?name=${name}`
);
}
/**
* A Component used to test that custom error templates can be passed to
* the `plugins` component.
*/
@Component({
template: `
<ng-template #environmentFailureNotFoundTemplate>
<h3 class="custom-not-found-template">Custom Not Found Error</h3>
</ng-template>
<ng-template #environmentFailureUnknownTemplate>
<h3 class="custom-unknown-template">Custom Unknown Error</h3>
</ng-template>
<plugins
[environmentFailureNotFoundTemplate]="environmentFailureNotFoundTemplate"
[environmentFailureUnknownTemplate]="environmentFailureUnknownTemplate"
>
</plugins>
`,
})
class CustomizedErrorTemplatesComponent {}
class TestableCustomElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'open'});
const wrapper = document.createElement('div');
wrapper.textContent = 'Test TensorBoard';
shadow.appendChild(wrapper);
}
}
customElements.define('tb-bar', TestableCustomElement);
describe('plugins_component', () => {
let store: MockStore<State>;
let createElementSpy: jasmine.Spy;
const PLUGINS = {
bar: {
disable_reload: false,
enabled: true,
loading_mechanism: {
type: LoadingMechanismType.CUSTOM_ELEMENT,
element_name: 'tb-bar',
} as CustomElementLoadingMechanism,
tab_name: 'Bar',
remove_dom: false,
},
'extra-plugin': {
disable_reload: false,
enabled: true,
loading_mechanism: {
type: LoadingMechanismType.NG_COMPONENT,
} as NgElementLoadingMechanism,
tab_name: 'Extra',
remove_dom: false,
},
foo: {
disable_reload: false,
enabled: true,
loading_mechanism: {
type: LoadingMechanismType.IFRAME,
// This will cause 404 as test bundles do not serve
// data file in the karma server.
module_path: 'random_esmodule.js',
} as IframeLoadingMechanism,
tab_name: 'Bar',
remove_dom: false,
},
};
function setActivePlugin(plugin: PluginId) {
store.overrideSelector(getActivePlugin, plugin);
store.refreshState();
}
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [provideMockStore(), PluginsContainer, PluginRegistryModule],
declarations: [
PluginsContainer,
PluginsComponent,
CustomizedErrorTemplatesComponent,
],
imports: [TestingDebuggerModule, ExtraDashboardModule],
}).compileComponents();
store = TestBed.inject<Store<State>>(Store) as MockStore<State>;
store.overrideSelector(getPlugins, PLUGINS);
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: null,
failureCode: null,
});
store.overrideSelector(getEnvironment, {
data_location: 'foobar',
window_title: 'Tests!',
});
createElementSpy = spyOn(document, 'createElement').and.callThrough();
createElementSpy
.withArgs('tf-experimental-plugin-host-lib')
.and.returnValue({
registerPluginIframe: () => {},
});
});
describe('plugin DOM creation', () => {
it('creates no plugin when there is no activePlugin', () => {
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
const el = fixture.debugElement.query(By.css('.plugins'));
expect(el.nativeElement.childElementCount).toBe(0);
});
it('creates no plugin when plugins are not loaded', () => {
store.overrideSelector(getPlugins, {});
store.overrideSelector(getActivePlugin, 'foo');
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
const el = fixture.debugElement.query(By.css('.plugins'));
expect(el.nativeElement.childElementCount).toBe(0);
});
it('creates an element for CUSTOM_ELEMENT type of plugin', async () => {
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
setActivePlugin('bar');
fixture.detectChanges();
await fixture.whenStable();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
expect(nativeElement.childElementCount).toBe(1);
const pluginElement = nativeElement.children[0];
expect(pluginElement.tagName).toBe('TB-BAR');
});
it('creates an element for IFRAME type of plugin', async () => {
const registerPluginIframeSpy = jasmine.createSpy();
createElementSpy
.withArgs('tf-experimental-plugin-host-lib')
.and.returnValue({
registerPluginIframe: registerPluginIframeSpy,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
setActivePlugin('foo');
fixture.detectChanges();
await fixture.whenStable();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
expect(nativeElement.childElementCount).toBe(1);
const pluginElement = nativeElement.children[0];
expectPluginIframe(pluginElement, 'foo');
expect(registerPluginIframeSpy).toHaveBeenCalledWith(
pluginElement,
'foo'
);
});
it('keeps instance of plugin after being inactive but hides it', async () => {
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
setActivePlugin('foo');
fixture.detectChanges();
await fixture.whenStable();
expect(
fixture.debugElement.query(By.css('.plugins')).nativeElement
.childElementCount
).toBe(1);
setActivePlugin('bar');
fixture.detectChanges();
await fixture.whenStable();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
expect(nativeElement.childElementCount).toBe(2);
const [fooElement, barElement] = nativeElement.children;
expectPluginIframe(fooElement, 'foo');
expect(fooElement.style.visibility).toBe('hidden');
expect(barElement.tagName).toBe('TB-BAR');
expect(barElement.style.visibility).not.toBe('hidden');
});
it('does not create same instance of plugin', async () => {
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
setActivePlugin('foo');
fixture.detectChanges();
await fixture.whenStable();
setActivePlugin('bar');
fixture.detectChanges();
await fixture.whenStable();
setActivePlugin('foo');
fixture.detectChanges();
await fixture.whenStable();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
expect(nativeElement.childElementCount).toBe(2);
const [fooElement] = nativeElement.children;
expectPluginIframe(fooElement, 'foo');
expect(fooElement.style.visibility).not.toBe('hidden');
});
it('creates components for plugins registered dynamically', async () => {
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
setActivePlugin('extra-plugin');
fixture.detectChanges();
await fixture.whenStable();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
expect(nativeElement.childElementCount).toBe(1);
const pluginElement = nativeElement.children[0];
expect(pluginElement.tagName).toBe('EXTRA-DASHBOARD');
});
it('hides inactive plugin but keeps their width', async () => {
setActivePlugin('bar');
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
setActivePlugin('foo');
fixture.detectChanges();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
const [barElement] = nativeElement.children;
expect(barElement.shadowRoot.firstElementChild.textContent).toBe(
'Test TensorBoard'
);
expect(
barElement.shadowRoot.firstElementChild.clientWidth
).toBeGreaterThan(0);
});
});
describe('updates', () => {
function setLastLoadedTime(
timeInMs: number | null,
state = DataLoadState.LOADED
) {
store.overrideSelector(getPluginsListLoaded, {
state:
timeInMs !== null ? DataLoadState.LOADED : DataLoadState.NOT_LOADED,
lastLoadedTimeInMs: timeInMs,
failureCode: null,
});
store.refreshState();
}
it('invokes reload method on the dashboard DOM', () => {
const fixture = TestBed.createComponent(PluginsContainer);
setLastLoadedTime(null, DataLoadState.NOT_LOADED);
setActivePlugin('bar');
fixture.detectChanges();
setActivePlugin('foo');
fixture.detectChanges();
setActivePlugin('bar');
fixture.detectChanges();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
// Stamped 'bar' and 'foo'
expect(nativeElement.children.length).toBe(2);
const [barElement, fooElement] = nativeElement.children;
const barReloadSpy = jasmine.createSpy();
barElement.reload = barReloadSpy;
const fooReloadSpy = jasmine.createSpy();
fooElement.reload = fooReloadSpy;
setLastLoadedTime(1);
fixture.detectChanges();
expect(barReloadSpy).toHaveBeenCalledTimes(1);
expect(fooReloadSpy).not.toHaveBeenCalled();
setLastLoadedTime(1);
fixture.detectChanges();
expect(barReloadSpy).toHaveBeenCalledTimes(1);
expect(fooReloadSpy).not.toHaveBeenCalled();
setLastLoadedTime(2);
fixture.detectChanges();
expect(barReloadSpy).toHaveBeenCalledTimes(2);
expect(fooReloadSpy).not.toHaveBeenCalled();
setActivePlugin('foo');
fixture.detectChanges();
setLastLoadedTime(3);
fixture.detectChanges();
expect(barReloadSpy).toHaveBeenCalledTimes(2);
expect(fooReloadSpy).toHaveBeenCalledTimes(1);
});
it('does not invoke reload method on dom if disable_reload', () => {
store.overrideSelector(getPlugins, {
bar: {
disable_reload: true,
enabled: true,
loading_mechanism: {
type: LoadingMechanismType.CUSTOM_ELEMENT,
element_name: 'tb-bar',
} as CustomElementLoadingMechanism,
tab_name: 'Bar',
remove_dom: false,
},
});
const fixture = TestBed.createComponent(PluginsContainer);
setLastLoadedTime(null, DataLoadState.NOT_LOADED);
setActivePlugin('bar');
fixture.detectChanges();
const {nativeElement} = fixture.debugElement.query(By.css('.plugins'));
const [barElement] = nativeElement.children;
const barReloadSpy = jasmine.createSpy();
barElement.reload = barReloadSpy;
setLastLoadedTime(1);
fixture.detectChanges();
expect(barReloadSpy).not.toHaveBeenCalled();
});
});
describe('warning pages', () => {
it('does not show any warning while fetching when list was never fetched', () => {
store.overrideSelector(getPlugins, {});
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADING,
lastLoadedTimeInMs: null,
failureCode: null,
});
store.overrideSelector(getActivePlugin, null);
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.warning'))).toBeNull();
});
it('shows warning when plugin id is not known', () => {
store.overrideSelector(getActivePlugin, 'you_do_not_know_me');
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 123,
failureCode: null,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toContain(
'There’s no dashboard by the name of “you_do_not_know_me”'
);
});
it(
'shows warning when plugin id is not known when pluginList is cached and' +
'is loading (updating)',
() => {
store.overrideSelector(getPlugins, PLUGINS);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADING,
lastLoadedTimeInMs: 123,
failureCode: null,
});
store.overrideSelector(getActivePlugin, 'you_do_not_know_me');
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toContain(
'There’s no dashboard by the name of “you_do_not_know_me”'
);
}
);
it('shows warning when environment failed NOT_FOUND', () => {
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.FAILED,
lastLoadedTimeInMs: null,
failureCode: PluginsListFailureCode.NOT_FOUND,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toContain(
'Data could not be loaded.'
);
});
it('shows warning when environment failed UNKNOWN', () => {
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.FAILED,
lastLoadedTimeInMs: null,
failureCode: PluginsListFailureCode.UNKNOWN,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toContain(
'Data could not be loaded.'
);
});
it(
'shows no active plugin warning even when loading when list was previous ' +
'loaded',
() => {
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADING,
lastLoadedTimeInMs: 123,
failureCode: null,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toContain(
'No dashboards are active for the current data set.'
);
}
);
it('shows warning when no plugin is active after list is loaded', () => {
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 123,
failureCode: null,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toContain(
'No dashboards are active for the current data set.'
);
});
describe('custom error templates', () => {
it('shows warning when environment failed NOT_FOUND', () => {
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.FAILED,
lastLoadedTimeInMs: null,
failureCode: PluginsListFailureCode.NOT_FOUND,
});
const fixture = TestBed.createComponent(
CustomizedErrorTemplatesComponent
);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toBe(
'Custom Not Found Error'
);
});
it('shows warning when environment failed UNKNOWN', () => {
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.FAILED,
lastLoadedTimeInMs: null,
failureCode: PluginsListFailureCode.UNKNOWN,
});
const fixture = TestBed.createComponent(
CustomizedErrorTemplatesComponent
);
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.textContent).toBe(
'Custom Unknown Error'
);
});
});
describe('data location', () => {
it('rendersin the warning', () => {
store.overrideSelector(getEnvironment, {
data_location: 'my-location',
window_title: '',
});
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 123,
failureCode: null,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(
fixture.debugElement.query(By.css('.data-location')).nativeElement
.textContent
).toBe('Log directory: my-location');
});
it('does not render when it is empty', () => {
store.overrideSelector(getEnvironment, {
data_location: '',
window_title: '',
});
store.overrideSelector(getActivePlugin, null);
store.overrideSelector(getPluginsListLoaded, {
state: DataLoadState.LOADED,
lastLoadedTimeInMs: 123,
failureCode: null,
});
const fixture = TestBed.createComponent(PluginsContainer);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.data-location'))).toBeNull();
});
});
});
});
| {
"pile_set_name": "Github"
} |
// UpdateManager.cs, 10.06.2019
// Copyright (C) Dominic Beger 17.06.2019
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using nUpdate.Core;
using nUpdate.Exceptions;
using nUpdate.Internal.Core;
using nUpdate.Internal.Core.Localization;
using nUpdate.Internal.Core.Operations;
using nUpdate.Internal.Properties;
using nUpdate.Shared.Core;
namespace nUpdate.Updating
{
/// <summary>
/// Provides functionality to update .NET-applications.
/// </summary>
public partial class UpdateManager : IDisposable
{
private readonly string _applicationUpdateDirectory = Path.Combine(Path.GetTempPath(), "nUpdate",
Application.ProductName);
private readonly Dictionary<UpdateVersion, string> _packageFilePaths = new Dictionary<UpdateVersion, string>();
private Dictionary<UpdateVersion, IEnumerable<Operation>> _packageOperations; // obsolete
private bool _disposed;
private readonly ManualResetEvent _searchManualResetEvent = new ManualResetEvent(false);
private CancellationTokenSource _downloadCancellationTokenSource = new CancellationTokenSource();
private CultureInfo _languageCulture = new CultureInfo("en");
private LocalizationProperties _lp;
private CancellationTokenSource _searchCancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// Initializes a new instance of the <see cref="UpdateManager" /> class.
/// </summary>
/// <param name="updateConfigurationFileUri">The URI of the update configuration file.</param>
/// <param name="publicKey">The public key for the validity check of the update packages.</param>
/// <param name="languageCulture">
/// The language culture to use. If no value is provided, the default one ("en") will be
/// used.
/// </param>
/// <param name="currentVersion">
/// The current version of that should be used for the update checks. This parameter has a
/// higher priority than the <see cref="nUpdateVersionAttribute" /> and will replace it, if specified.
/// </param>
/// <remarks>
/// The public key can be found in the overview of your project when you're opening it in nUpdate Administration.
/// If you have problems inserting the data (or if you want to save time) you can scroll down there and follow the
/// steps of the category "Copy data" which will automatically generate the necessary code for you.
/// </remarks>
public UpdateManager(Uri updateConfigurationFileUri, string publicKey,
CultureInfo languageCulture = null, UpdateVersion currentVersion = null)
{
UpdateConfigurationFileUri = updateConfigurationFileUri ??
throw new ArgumentNullException(nameof(updateConfigurationFileUri));
if (string.IsNullOrEmpty(publicKey))
throw new ArgumentNullException(nameof(publicKey));
PublicKey = publicKey;
CultureFilePaths = new Dictionary<CultureInfo, string>();
Arguments = new List<UpdateArgument>();
var projectAssembly = Assembly.GetCallingAssembly();
var nUpateVersionAttribute =
projectAssembly.GetCustomAttributes(false).OfType<nUpdateVersionAttribute>().SingleOrDefault();
// TODO: This is just there to make sure we don't create an API-change that would require a new Major version. This will be changed/removed in v4.0.
// Before v3.0-beta8 it was not possible to provide the current version except using the nUpdateVersionAttribute.
// In order to allow specific features, e.g. updating another application and not the current one (as it's done by a launcher), there must be a way to provide this version separately.
// So, if an argument is specified for the "currentVersion" parameter, we will use this one instead of the nUpdateVersionAttribute.
if (currentVersion != null)
{
CurrentVersion = currentVersion;
}
else
{
// Neither the nUpdateVersionAttribute nor the additional parameter argument was provided.
if (nUpateVersionAttribute == null)
throw new ArgumentException(
"The version string couldn't be loaded because the nUpdateVersionAttribute isn't implemented in the executing assembly and no version was provided explicitly.");
CurrentVersion = new UpdateVersion(nUpateVersionAttribute.VersionString);
}
// TODO: This is just there to make sure we don't create an API-change that would require a new Major version. This will be changed/removed in v4.0.
// Before v3.0-beta5 it was not possible to use custom languages due to a mistake in the architecture. So we can be pretty sure that nobody specifies a custom CultureInfo in the constructor.
// We only need these two lines for those who specified one of the implemented CultureInfos here as they shouldn't have to change anything when updating to v3.0-beta5.
// Nevertheless, it's therefore possible to use custom CultureInfos just by leaving the optional parameter "null" and specifying the culture using the corresponding properties. So, both cases are covered with that solution.
if (languageCulture != null && LocalizationHelper.IsIntegratedCulture(languageCulture, CultureFilePaths))
LanguageCulture = languageCulture;
else
throw new ArgumentException($"The culture \"{languageCulture}\" is not defined.");
if (UseCustomInstallerUserInterface && string.IsNullOrEmpty(CustomInstallerUiAssemblyPath))
throw new ArgumentException(
"The property \"CustomInstallerUiAssemblyPath\" is not initialized although \"UseCustomInstallerUserInterface\" is set to \"true\"");
Initialize();
}
/// <summary>
/// Gets or sets the arguments that should be handled over to the application once the update installation has
/// completed.
/// </summary>
public List<UpdateArgument> Arguments { get; set; }
/// <summary>
/// Gets or sets the paths to the files that contain the localized strings of their corresponding
/// <see cref="CultureInfo" />.
/// </summary>
public Dictionary<CultureInfo, string> CultureFilePaths { get; set; }
/// <summary>
/// Gets or sets the version of the current application.
/// </summary>
internal UpdateVersion CurrentVersion { get; set; }
/// <summary>
/// Gets or sets the path of the assembly file that contains the user interface data for nUpdate UpdateInstaller.
/// </summary>
public string CustomInstallerUiAssemblyPath { get; set; }
/// <summary>
/// Gets or sets the update installer options for the host application.
/// </summary>
public HostApplicationOptions HostApplicationOptions { get; set; }
/// <summary>
/// Gets or sets the HTTP(S) authentication credentials.
/// </summary>
public NetworkCredential HttpAuthenticationCredentials { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user should be able to update to alpha versions, or not.
/// </summary>
public bool IncludeAlpha { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user should be able to update to beta versions, or not.
/// </summary>
public bool IncludeBeta { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the current computer should be included into the statistics, or not.
/// </summary>
public bool IncludeCurrentPcIntoStatistics { get; set; } = true;
/// <summary>
/// Gets or sets the additional conditions that determine whether an update should be loaded or not.
/// </summary>
public List<KeyValuePair<string, string>> Conditions { get; set; }
/// <summary>
/// Gets or sets the culture of the language to use.
/// </summary>
/// <remarks>
/// "en" (English) and "de" (German) are currently the only language cultures that are already implemented in
/// nUpdate. In order to use own languages download the language template from
/// <see href="http://www.nupdate.net/langtemplate.json" />, edit it, save it as a JSON-file and add a new entry to
/// property
/// CultureFilePaths with the relating CultureInfo and path which locates the JSON-file on the client's
/// system (e. g. AppData).
/// </remarks>
public CultureInfo LanguageCulture
{
get => _languageCulture;
set
{
if (!LocalizationHelper.IsIntegratedCulture(value, CultureFilePaths) &&
!CultureFilePaths.ContainsKey(_languageCulture))
throw new ArgumentException(
"The localization file of the culture set does not exist.");
_lp = LocalizationHelper.GetLocalizationProperties(value, CultureFilePaths);
_languageCulture = value;
}
}
/// <summary>
/// Gets the package configurations for all available updates.
/// </summary>
public IEnumerable<UpdateConfiguration> PackageConfigurations { get; internal set; }
/// <summary>
/// Gets or sets the proxy to use.
/// </summary>
public WebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the public key for checking the validity of the signature.
/// </summary>
public string PublicKey { get; }
public bool RunInstallerAsAdmin { get; set; } = true;
/// <summary>
/// Gets or sets the timeout in milliseconds that should be used when searching for updates.
/// </summary>
/// <remarks>By default, this is set to 10.000 milliseconds.</remarks>
public int SearchTimeout { get; set; } = 10000;
/// <summary>
/// Gets the total size of all update packages.
/// </summary>
public double TotalSize { get; private set; }
/// <summary>
/// Gets or sets the URI of the update configuration file.
/// </summary>
public Uri UpdateConfigurationFileUri { get; }
/// <summary>
/// Gets or sets a value indicating whether the nUpdate UpdateInstaller should use a custom user interface, or not.
/// </summary>
/// <remarks>
/// This property also requires <see cref="CustomInstallerUiAssemblyPath" /> to be set, if the value is
/// <c>true</c>.
/// </remarks>
public bool UseCustomInstallerUserInterface { get; set; }
public bool UseDynamicUpdateUri { get; set; } = false;
/// <summary>
/// Cancels the download.
/// </summary>
/// <remarks>If there is no download task running, nothing will happen.</remarks>
[Obsolete("CancelDownload has been renamed to CancelDownloadAsync which should be used instead.")]
public void CancelDownload()
{
CancelDownloadAsync();
}
/// <summary>
/// Cancels the download, if it is running asynchronously.
/// </summary>
/// <remarks>If there is no asynchronous download task running, nothing will happen.</remarks>
public void CancelDownloadAsync()
{
_downloadCancellationTokenSource.Cancel();
}
/// <summary>
/// Cancels the update search, if it is running asynchronously.
/// </summary>
/// <remarks>If there is no asynchronous search task running, nothing will happen.</remarks>
[Obsolete("CancelSearch has been renamed to CancelSearchAsync which should be used instead.")]
public void CancelSearch()
{
CancelSearchAsync();
}
/// <summary>
/// Cancels the update search.
/// </summary>
/// <remarks>If there is no search task running, nothing will happen.</remarks>
public void CancelSearchAsync()
{
_searchCancellationTokenSource.Cancel();
}
private void Cleanup()
{
_packageFilePaths.Clear();
}
private Uri ConvertPackageUri(Uri updatePackageUri)
{
if (!UseDynamicUpdateUri)
return updatePackageUri;
if (updatePackageUri == null)
throw new ArgumentNullException(nameof(updatePackageUri));
// The segment of the correct update package URI should include: "/", "x.x.x.x/", "*.zip".
if (updatePackageUri.Segments.Length < 3)
throw new ArgumentException($"\"{updatePackageUri}\" is not a valid update package URI.",
nameof(updatePackageUri));
var packageNameSegment = updatePackageUri.Segments.Last();
var versionSegment = updatePackageUri.Segments[updatePackageUri.Segments.Length - 2];
var baseUri = UpdateConfigurationFileUri.GetLeftPart(UriPartial.Authority);
var path = string.Join(string.Empty, UpdateConfigurationFileUri.Segments, 0,
UpdateConfigurationFileUri.Segments.Length - 1);
return new Uri($"{baseUri}{path}{versionSegment}{packageNameSegment}");
}
private Uri ConvertStatisticsUri(Uri statisticsUri)
{
if (!UseDynamicUpdateUri)
return statisticsUri;
if (statisticsUri == null)
throw new ArgumentNullException(nameof(statisticsUri));
// The segment of the correct update php file URI should include: "/", "*.php".
if (statisticsUri.Segments.Length < 2)
throw new ArgumentException($"\"{statisticsUri}\" is not a valid statistics file URI.",
nameof(statisticsUri));
var phpFileName = statisticsUri.Segments.Last();
var baseUri = UpdateConfigurationFileUri.GetLeftPart(UriPartial.Authority);
var path = string.Join(string.Empty, UpdateConfigurationFileUri.Segments, 0,
UpdateConfigurationFileUri.Segments.Length - 1);
return new Uri($"{baseUri}{path}{phpFileName}");
}
/// <summary>
/// Deletes the downloaded update packages.
/// </summary>
public void DeletePackages()
{
foreach (var filePathItem in _packageFilePaths.Where(item => File.Exists(item.Value)))
File.Delete(filePathItem.Value);
}
/// <summary>
/// Releases all managed and unmanaged resources used by the current <see cref="UpdateManager" />-instance.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only
/// unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (!disposing || _disposed)
return;
_searchCancellationTokenSource.Dispose();
_downloadCancellationTokenSource.Dispose();
_disposed = true;
}
private double? GetUpdatePackageSize(Uri packageUri)
{
try
{
var req = WebRequestWrapper.Create(packageUri);
req.Method = "HEAD";
if (HttpAuthenticationCredentials != null)
req.Credentials = HttpAuthenticationCredentials;
using (var resp = req.GetResponse())
{
if (double.TryParse(resp.Headers.Get("Content-Length"), out var contentLength))
return contentLength;
}
}
catch
{
return null;
}
return null;
}
private void Initialize()
{
try
{
var updateDirDirectoryInfo = new DirectoryInfo(_applicationUpdateDirectory);
if (updateDirDirectoryInfo.Exists)
updateDirDirectoryInfo.Empty();
else
updateDirDirectoryInfo.Create();
}
catch (Exception ex)
{
throw new IOException(string.Format(_lp.MainFolderCreationExceptionText,
ex.Message));
}
}
/// <summary>
/// Starts the nUpdate UpdateInstaller to unpack the package and start the updating process.
/// </summary>
public void InstallPackage()
{
var installerDirectory = Path.Combine(Path.GetTempPath(), "nUpdate Installer");
var dotNetZipPath = Path.Combine(installerDirectory, "DotNetZip.dll");
var guiInterfacePath = Path.Combine(installerDirectory, "nUpdate.UpdateInstaller.Client.GuiInterface.dll");
var jsonNetPath = Path.Combine(installerDirectory, "Newtonsoft.Json.dll");
var installerFilePath = Path.Combine(installerDirectory, "nUpdate UpdateInstaller.exe");
var unpackerAppPdbPath = Path.Combine(installerDirectory, "nUpdate UpdateInstaller.pdb");
if (Directory.Exists(installerDirectory))
Directory.Delete(installerDirectory, true);
Directory.CreateDirectory(installerDirectory);
File.WriteAllBytes(dotNetZipPath, Resources.DotNetZip);
File.WriteAllBytes(guiInterfacePath, Resources.nUpdate_UpdateInstaller_Client_GuiInterface);
File.WriteAllBytes(jsonNetPath, Resources.Newtonsoft_Json);
File.WriteAllBytes(installerFilePath, Resources.nUpdate_UpdateInstaller);
File.WriteAllBytes(unpackerAppPdbPath, Resources.nUpdate_UpdateInstaller_pdb);
string[] args =
{
$"\"{string.Join("%", _packageFilePaths.Select(item => item.Value))}\"",
$"\"{Application.StartupPath}\"",
$"\"{Application.ExecutablePath}\"",
$"\"{Application.ProductName}\"",
_packageOperations == null ? string.Empty : $"\"{Convert.ToBase64String(Encoding.UTF8.GetBytes(Serializer.Serialize(_packageOperations)))}\"",
$"\"{(UseCustomInstallerUserInterface ? CustomInstallerUiAssemblyPath : string.Empty)}\"",
_lp.InstallerExtractingFilesText,
_lp.InstallerCopyingText,
_lp.FileDeletingOperationText,
_lp.FileRenamingOperationText,
_lp.RegistrySubKeyCreateOperationText,
_lp.RegistrySubKeyDeleteOperationText,
_lp.RegistryNameValuePairDeleteValueOperationText,
_lp.RegistryNameValuePairSetValueOperationText,
_lp.ProcessStartOperationText,
_lp.ProcessStopOperationText,
_lp.ServiceStartOperationText,
_lp.ServiceStopOperationText,
_lp.InstallerUpdatingErrorCaption,
_lp.InstallerInitializingErrorCaption,
$"\"{Convert.ToBase64String(Encoding.UTF8.GetBytes(Serializer.Serialize(Arguments)))}\"",
$"\"{HostApplicationOptions}\"",
$"\"{_lp.InstallerFileInUseError}\"",
$"\"{Process.GetCurrentProcess().Id}\""
};
var startInfo = new ProcessStartInfo
{
FileName = installerFilePath,
Arguments = string.Join("|", args),
UseShellExecute = true,
};
if (RunInstallerAsAdmin)
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
}
catch (Win32Exception ex)
{
DeletePackages();
Cleanup();
if (ex.NativeErrorCode != 1223)
throw;
return;
}
if (HostApplicationOptions != HostApplicationOptions.None)
TerminateApplication();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remarks>
/// If your apllication doesn't terminate correctly or if you want to perform custom actions before terminating,
/// then override this method and implement your own code.
/// </remarks>
public virtual void TerminateApplication()
{
Environment.Exit(0);
}
/// <summary>
/// Returns a value indicating whether the signature of each package is valid, or not. If a package contains an invalid
/// signature, it will be deleted.
/// </summary>
/// <returns>Returns <c>true</c> if the package is valid; otherwise <c>false</c>.</returns>
/// <exception cref="FileNotFoundException">The update package to check could not be found.</exception>
/// <exception cref="ArgumentException">The signature of the update package is invalid.</exception>
public bool ValidatePackages()
{
bool Validate(KeyValuePair<UpdateVersion, string> filePathItem)
{
if (!File.Exists(filePathItem.Value))
throw new FileNotFoundException(string.Format(_lp.PackageFileNotFoundExceptionText,
filePathItem.Key.FullText));
var configuration =
PackageConfigurations.First(config => config.LiteralVersion == filePathItem.Key.ToString());
if (configuration.Signature == null || configuration.Signature.Length <= 0)
throw new ArgumentException($"Signature of version \"{configuration}\" is null or empty.");
using (var stream = File.Open(filePathItem.Value, FileMode.Open))
{
RsaManager rsa;
try
{
rsa = new RsaManager(PublicKey);
}
catch
{
return false;
}
return rsa.VerifyData(stream, Convert.FromBase64String(configuration.Signature));
}
}
if (_packageFilePaths.All(Validate))
return true;
try
{
DeletePackages();
}
catch (Exception ex)
{
throw new PackageDeleteException(ex.Message);
}
Cleanup();
return false;
}
}
} | {
"pile_set_name": "Github"
} |
\section{Асимметричные протоколы}\label{section-protocols-asymmetric}
\selectlanguage{russian}
Асимметричные протоколы, или же протоколы, основанные на криптосистемах с открытыми ключами, позволяют ослабить требования к предварительному этапу протоколов. Вместо общего секретного ключа, который должны иметь две стороны (либо каждая из сторон и доверенный центр), в рассматриваемых ниже протоколах стороны должны предварительно обменяться открытыми ключами (между собой либо с доверенным центром). Такой предварительный обмен может проходить по открытому каналу связи, в предположении, что криптоаналитик не может повлиять на содержимое канала связи на данном этапе.
В данном разделе рассмотрены только такие протоколы, которые не описывают и не ограничивают используемые математические операции, а позволяют использовать любые надёжные криптографические примитивы из симметричной и асимметричной криптографии. При анализе надёжности таких протоколов криптостойкость используемых <<примитивных>> алгоритмов не учитывается.
\input{denning-sacco}
\input{dass}
\input{woo-lam}
| {
"pile_set_name": "Github"
} |
/*
* generic serialization for display
*/
class Show a where
show :: a -> [char]
// control output precision of floats and doubles
floatFormatConfig = do {
c = (newPrim() :: {floatPrecision:int,doublePrecision:int});
c.floatPrecision <- -1;
c.doublePrecision <- -1;
return c
}
{-# SAFE floatFormatConfig #-}
// primitive serialization
instance Show () where
show _ = ""
instance Show bool where
show x = if x then "true" else "false"
instance Show char where
show = showChar
instance Show byte where
show = showByte
instance Show short where
show = showShort
instance Show int where
show = showInt
instance Show long where
show = showLong
instance Show int128 where
show = showInt128
instance Show float where
show x = showFloat(x, floatFormatConfig.floatPrecision)
instance Show double where
show x = showDouble(x, floatFormatConfig.doublePrecision)
instance Show [byte] where
show bs = "0x" ++ concat(map(showByteV,bs))
instance Show [char] where
show cs = "\"" ++ cs ++ "\""
instance Show <std.string> where
show = showString
instance Show timespan where
show = showTimespan
instance Show time where
show = showTime
instance Show datetime where
show = showDateTime
// serialization for tuples
class ShowT a where
showtup :: a -> [[char]]
instance ShowT () where
showtup _ = []
instance (t=(a*tt), Show a, ShowT tt) => ShowT t where
showtup x = [show(x.0)] ++ showtup(tupleTail(x))
instance (ShowT t) => Show t where
show x = concat(["(", cdelim(showtup(x), ", "), ")"])
// serialization for records
class ShowR a where
showrec :: a -> [[char]]
instance ShowR () where
showrec _ = []
instance (r={a*rr}, Show a, ShowR rr) => ShowR r where
showrec r = [recordHeadLabel(r) ++ "=" ++ show(recordHeadValue(r))] ++ showrec(recordTail(r))
instance (ShowR r) => Show r where
show x = concat(["{", cdelim(showrec(x), ", "), "}"])
// serialization for variants
class ShowVarValue a where
showVarValue :: a -> [char]
instance ShowVarValue () where
showVarValue x = ""
instance (Show a) => ShowVarValue a where
showVarValue x = "=" ++ show(x)
instance Show 0 where
show _ = "impossible"
instance (v=|a+vt|, ShowVarValue a, Show vt) => Show v where
show x = variantSplit(x, \xv."|"++variantHeadLabel(x)++showVarValue(xv)++"|", toClosure(show))
data penum t v = t
class UnpackEnum t v | t -> v where
unpackEnum :: t -> v
instance (Convert t int) => UnpackEnum (penum t v) v where
unpackEnum x = unsafeCast({x=convert(unsafeCast(x)::t)::int})
instance Eq (penum _ _) where
x === y = x.t === y.t
instance (Ord t t) => Ord (penum t v) (penum t v) where
x < y = x.t < y.t
x <= y = x.t <= y.t
x > y = x.t > y.t
x >= y = x.t >= y.t
instance (UnpackEnum t v, Show v) => Show t where
show e = show(unpackEnum(e))
// serialization for arrays
instance (Array cs char) => Show cs where
show cs = show(cs[0:])
instance (Array bs byte) => Show bs where
show bs = show(bs[0:])
instance (Show a) => Show [a] where
show xs = concat(["[", cdelim(map(show,xs), ", "), "]"])
instance (Array as a, Show a) => Show as where
show xs = show(xs[0:])
// serialization for fixed-length arrays
class ShowFixedArrOf e n where
showFA :: ([:e|n:], long, long) -> [char]
fixedCAToStr :: ([:char|n:], long, long, [char]) -> [char]
fixedCAToStr cs i e r =
if (i == e) then
r
else if (saelem(cs, i) == '\0') then do {
unsafeSetLength(r, i);
return r
} else do {
r[i] <- saelem(cs, i);
return fixedCAToStr(cs, i+1, e, r)
}
{-# UNSAFE fixedCAToStr #-}
instance ShowFixedArrOf char n where
showFA cs i e = "\"" ++ fixedCAToStr(cs, i, e, newArray(e)) ++ "\""
showSARange :: (a -> [char], [:a|n:], long, long, [[char]]) -> [[char]]
showSARange showf xs i e r =
if (i == e) then
r
else do {
r[i] <- showf(saelem(xs, i));
return showSARange(showf, xs, i+1, e, r)
}
{-# UNSAFE showSARange #-}
instance ShowFixedArrOf byte n where
showFA bs i e = "0x" ++ concat(showSARange(showByteV, bs, i, e, newArray(e)))
instance (Show a) => ShowFixedArrOf a n where
showFA cs i e = concat(["[:", cdelim(showSARange(show, cs, i, e, newArray(e)), ", "), ":]"])
instance (ShowFixedArrOf a n) => Show [:a|n:] where
show xs = showFA(xs, 0L, salength(xs))
// show lists
instance (Show a) => Show (^x.(()+(a*x))) where
show xs = case unroll(xs) of |0:_="[]", 1:p=show(p.0)++":"++show(p.1)|
// show recursive types if their one-step unrolling is showable
instance (a ~ b, Show b) => Show a where
show x = show(unroll(x))
// show through file references
instance (Show a) => Show a@f where
show x = show(load(x))
/*
* generic printing
*/
class Print a where
print :: a -> ()
instance Print () where
print _ = ()
instance Print [byte] where
print bs = putStr(show(bs))
// we will later define how certain types can be printed as tables
// at least one of those cases will overlap with arrays, so we need to try to print as tables prior to trying to print as arrays
class PrintableAsTable a where
printAsTable :: a -> ()
instance (PrintableAsTable a) => Print a where
print = printAsTable
// print arrays
instance Print [char] where
print cs = do { putStr("\""); putStr(cs); putStr("\""); }
instance (Array cs char) => Print cs where
print cs = print(cs[0:])
instance (Array bs byte) => Print bs where
print bs = print(bs[0:])
printArray :: (Print a) => ([a], long) -> ()
printArray xs i =
if (i == length(xs)) then
()
else
do { putStr(", "); print(xs[i]); printArray(xs, i+1L); }
{-# UNSAFE printArray #-}
instance (Array as a, Print a) => Print as where
print xs = let n=size(xs) in if (n==0) then putStr("[]") else do { putStr("["); axs=elements(xs, 0L, n); print(axs[0]); printArray(axs, 1L); putStr("]"); }
// print lists of things
instance (Print a) => Print (^x.(()+(a*x))) where
print xs = case unroll(xs) of |0:_=putStr("[]"), 1:p=let _ = print(p.0); _ = putStr(":") in print(p.1)|
// print records
class PrintR a where
printrec :: (bool,a) -> ()
instance PrintR () where
printrec _ _ = ()
instance (r={a*rr}, Print a, PrintR rr) => PrintR r where
printrec first r = do{if first then () else putStr(", "); putStr(recordHeadLabel(r)); putStr("="); print(recordHeadValue(r)); printrec(false, recordTail(r));}
instance (PrintR r) => Print r where
print x = do{putStr("{"); printrec(true, x); putStr("}");}
// print tuples
class PrintT a where
printtup :: (bool,a) -> ()
instance PrintT () where
printtup _ _ = ()
instance (p=(a*t), Print a, PrintT t) => PrintT p where
printtup first p = do{if first then () else putStr(", "); print(p.0); printtup(false, tupleTail(p));}
instance (PrintT p) => Print p where
print p = do{putStr("("); printtup(true, p); putStr(")");}
// for 'maybe' types, we don't need to see the variant structure
instance (Print a) => Print (()+a) where
print m = case m of |0:_=(),1:x=print(x)|
// print variants, the generic case
class PrintVarPayload a where
printVarPayload :: a -> ()
instance PrintVarPayload () where
printVarPayload = id
instance (Print a) => PrintVarPayload a where
printVarPayload x = do { putStr("="); print(x); }
instance (v=|h+0|, Print h) => Print v where
print v = variantSplit(v, \h.do{putStr("|"); putStr(variantHeadLabel(v)); printVarPayload(h); putStr("|");}, toClosure(\_.()))
instance (v=|h+t|, Print h, Print t) => Print v where
print v = variantSplit(v, \h.do{putStr("|"); putStr(variantHeadLabel(v)); printVarPayload(h); putStr("|");}, toClosure(print))
// print recursive types if their one-step unrolling is printable
instance (a ~ b, Print b) => Print a where
print x = print(unroll(x))
// print printable file references
instance (Print a) => Print a@f where
print x = print(load(x))
// print bit vectors
instance Print bitvec where
print bv = bvPrintT(bv, 0L, bvLength(bv))
// print anything else that's showable
instance (Show a) => Print a where
print x = putStr(show(x))
// we wind up doing this surprisingly often
println :: (Print a) => a -> ()
println x = let _ = print(x) in putStr("\n")
putStrLn :: [char] -> ()
putStrLn x = let _ = putStr(x) in putStr("\n")
/*
* generic serialization for format strings (e.g.: `x = $x` => "x = " ++ format(x))
*/
class Format a where
format :: a -> [char]
instance Format [char] where
format = id
instance (Array cs char) => Format cs where
format cs = format(cs[0:])
instance (Format a) => Format a@f where
format x = format(load(x))
instance (Format a) => Format (()+a) where
format mx = match mx with | |1=x| -> format(x) | _ -> ""
instance (Show a) => Format a where
format = show
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cppunit/TestAssert.h>
#include <cppunit/extensions/HelperMacros.h>
#include <unotest/bootstrapfixturebase.hxx>
#include <graphic/GraphicFormatDetector.hxx>
#include <graphic/DetectorTools.hxx>
#include <tools/stream.hxx>
using namespace css;
namespace
{
class GraphicFormatDetectorTest : public test::BootstrapFixtureBase
{
OUString getFullUrl(const OUString& sFileName)
{
return m_directories.getURLFromSrc("/vcl/qa/cppunit/data/") + sFileName;
}
void testDetectMET();
void testDetectBMP();
void testDetectWMF();
void testDetectPCX();
void testDetectJPG();
void testDetectPNG();
void testDetectGIF();
void testDetectPSD();
void testDetectTGA();
void testDetectTIF();
void testDetectXBM();
void testDetectXPM();
void testDetectSVG();
void testDetectSVGZ();
void testDetectPDF();
void testDetectEPS();
void testMatchArray();
void testCheckArrayForMatchingStrings();
CPPUNIT_TEST_SUITE(GraphicFormatDetectorTest);
CPPUNIT_TEST(testDetectMET);
CPPUNIT_TEST(testDetectBMP);
CPPUNIT_TEST(testDetectWMF);
CPPUNIT_TEST(testDetectPCX);
CPPUNIT_TEST(testDetectJPG);
CPPUNIT_TEST(testDetectPNG);
CPPUNIT_TEST(testDetectGIF);
CPPUNIT_TEST(testDetectPSD);
CPPUNIT_TEST(testDetectTGA);
CPPUNIT_TEST(testDetectTIF);
CPPUNIT_TEST(testDetectXBM);
CPPUNIT_TEST(testDetectXPM);
CPPUNIT_TEST(testDetectSVG);
CPPUNIT_TEST(testDetectSVGZ);
CPPUNIT_TEST(testDetectPDF);
CPPUNIT_TEST(testDetectEPS);
CPPUNIT_TEST(testMatchArray);
CPPUNIT_TEST(testCheckArrayForMatchingStrings);
CPPUNIT_TEST_SUITE_END();
};
void GraphicFormatDetectorTest::testDetectMET()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.met"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "MET");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkMET());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("MET"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectBMP()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.bmp"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "BMP");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkBMP());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("BMP"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectWMF()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.wmf"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "WMF");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkWMForEMF());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("WMF"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectPCX()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.pcx"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "PCX");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkPCX());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("PCX"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectJPG()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.jpg"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "JPG");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkJPG());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("JPG"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectPNG()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.png"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "PNG");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkPNG());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("PNG"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectGIF()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.gif"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "GIF");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkGIF());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("GIF"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectPSD()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.psd"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "PSD");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkPSD());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("PSD"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectTGA()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.tga"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "TGA");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkTGA());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension("TGA"); // detection is based on extension only
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("TGA"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectTIF()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.tif"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "TIF");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkTIF());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("TIF"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectXBM()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.xbm"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "XBM");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkXBM());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("XBM"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectXPM()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.xpm"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "XPM");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkXPM());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("XPM"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectSVG()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.svg"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "SVG");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkSVG());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("SVG"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectSVGZ()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.svgz"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "SVG");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkSVG());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("SVG"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectPDF()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.pdf"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "PDF");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkPDF());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("PDF"), rFormatExtension);
}
void GraphicFormatDetectorTest::testDetectEPS()
{
SvFileStream aFileStream(getFullUrl("TypeDetectionExample.eps"), StreamMode::READ);
vcl::GraphicFormatDetector aDetector(aFileStream, "EPS");
CPPUNIT_ASSERT(aDetector.detect());
CPPUNIT_ASSERT(aDetector.checkEPS());
aFileStream.Seek(aDetector.mnStreamPosition);
OUString rFormatExtension;
CPPUNIT_ASSERT(ImpPeekGraphicFormat(aFileStream, rFormatExtension, false));
CPPUNIT_ASSERT_EQUAL(OUString("EPS"), rFormatExtension);
}
void GraphicFormatDetectorTest::testMatchArray()
{
std::string aString("<?xml version=\"1.0\" standalone=\"no\"?>\n"
"<svg width=\"5cm\" height=\"4cm\" version=\"1.1\"\n"
"xmlns=\"http://www.w3.org/2000/svg\">\n"
"</svg>");
const char* pCompleteStringPointer = aString.c_str();
const char* pMatchPointer;
int nCheckSize = aString.size();
// Check beginning of the input string
pMatchPointer = vcl::matchArrayWithString(pCompleteStringPointer, nCheckSize, "<?xml");
CPPUNIT_ASSERT(pMatchPointer != nullptr);
CPPUNIT_ASSERT_EQUAL(0, int(pMatchPointer - pCompleteStringPointer));
CPPUNIT_ASSERT_EQUAL(true, OString(pMatchPointer).startsWith("<?xml"));
// Check middle of the input string
pMatchPointer = vcl::matchArrayWithString(aString.c_str(), nCheckSize, "version");
CPPUNIT_ASSERT(pMatchPointer != nullptr);
CPPUNIT_ASSERT_EQUAL(6, int(pMatchPointer - pCompleteStringPointer));
CPPUNIT_ASSERT_EQUAL(true, OString(pMatchPointer).startsWith("version"));
pMatchPointer = vcl::matchArrayWithString(aString.c_str(), nCheckSize, "<svg");
CPPUNIT_ASSERT(pMatchPointer != nullptr);
CPPUNIT_ASSERT_EQUAL(38, int(pMatchPointer - pCompleteStringPointer));
CPPUNIT_ASSERT_EQUAL(true, OString(pMatchPointer).startsWith("<svg"));
// Check end of the input string
pMatchPointer = vcl::matchArrayWithString(aString.c_str(), nCheckSize, "/svg>");
CPPUNIT_ASSERT(pMatchPointer != nullptr);
CPPUNIT_ASSERT_EQUAL(119, int(pMatchPointer - pCompleteStringPointer));
CPPUNIT_ASSERT_EQUAL(true, OString(pMatchPointer).startsWith("/svg>"));
// Check that non-existing search string
pMatchPointer = vcl::matchArrayWithString(aString.c_str(), nCheckSize, "none");
CPPUNIT_ASSERT(pMatchPointer == nullptr);
}
void GraphicFormatDetectorTest::testCheckArrayForMatchingStrings()
{
std::string aString("<?xml version=\"1.0\" standalone=\"no\"?>\n"
"<svg width=\"5cm\" height=\"4cm\" version=\"1.1\"\n"
"xmlns=\"http://www.w3.org/2000/svg\">\n"
"</svg>");
const char* pCompleteStringPointer = aString.c_str();
int nCheckSize = aString.size();
bool bResult;
// check beginning string
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize, { "<?xml" });
CPPUNIT_ASSERT_EQUAL(true, bResult);
// check ending string
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize, { "/svg>" });
CPPUNIT_ASSERT_EQUAL(true, bResult);
// check middle string
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize, { "version" });
CPPUNIT_ASSERT_EQUAL(true, bResult);
// check beginning and then ending string
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "<?xml", "/svg>" });
CPPUNIT_ASSERT_EQUAL(true, bResult);
// check ending and then beginning string
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "/svg>", "<?xml" });
CPPUNIT_ASSERT_EQUAL(false, bResult);
// check middle strings
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "version", "<svg" });
CPPUNIT_ASSERT_EQUAL(true, bResult);
// check beginning, middle and ending strings
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "<?xml", "version", "<svg", "/svg>" });
CPPUNIT_ASSERT_EQUAL(true, bResult);
// check non-existing
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize, { "none" });
CPPUNIT_ASSERT_EQUAL(false, bResult);
// check non-existing on the beginning
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "none", "version", "<svg", "/svg>" });
CPPUNIT_ASSERT_EQUAL(false, bResult);
// check non-existing on the end
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "<?xml", "version", "<svg", "none" });
CPPUNIT_ASSERT_EQUAL(false, bResult);
// check non-existing after the end
bResult = vcl::checkArrayForMatchingStrings(pCompleteStringPointer, nCheckSize,
{ "<?xml", "/svg>", "none" });
CPPUNIT_ASSERT_EQUAL(false, bResult);
}
} // namespace
CPPUNIT_TEST_SUITE_REGISTRATION(GraphicFormatDetectorTest);
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| {
"pile_set_name": "Github"
} |
{
"name": "my-tailwind-project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "postcss css/tailwind.css -o public/build/tailwind.css"
},
"repository": {
"type": "git",
"url": "git+https://github.com/adamwathan/my-tailwind-project.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/adamwathan/my-tailwind-project/issues"
},
"homepage": "https://github.com/adamwathan/my-tailwind-project#readme",
"dependencies": {
"autoprefixer": "^9.6.1",
"postcss-cli": "^6.1.2",
"tailwindcss": "^1.0.4"
}
}
| {
"pile_set_name": "Github"
} |
This is an invalid certificate file.
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012-2020 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.golo.compiler.parser;
public class ASTWhileLoop extends GoloASTNode {
public ASTWhileLoop(int id) {
super(id);
}
public ASTWhileLoop(GoloParser p, int id) {
super(p, id);
}
@Override
public String toString() {
return "ASTWhileLoop{}";
}
@Override
public Object jjtAccept(GoloParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>new (Gem::Server)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre><span class="ruby-comment cmt"># File lib/rubygems/server.rb, line 441</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">initialize</span>(<span class="ruby-identifier">gem_dirs</span>, <span class="ruby-identifier">port</span>, <span class="ruby-identifier">daemon</span>, <span class="ruby-identifier">launch</span> = <span class="ruby-keyword kw">nil</span>, <span class="ruby-identifier">addresses</span> = <span class="ruby-keyword kw">nil</span>)
<span class="ruby-constant">Socket</span>.<span class="ruby-identifier">do_not_reverse_lookup</span> = <span class="ruby-keyword kw">true</span>
<span class="ruby-ivar">@gem_dirs</span> = <span class="ruby-constant">Array</span> <span class="ruby-identifier">gem_dirs</span>
<span class="ruby-ivar">@port</span> = <span class="ruby-identifier">port</span>
<span class="ruby-ivar">@daemon</span> = <span class="ruby-identifier">daemon</span>
<span class="ruby-ivar">@launch</span> = <span class="ruby-identifier">launch</span>
<span class="ruby-ivar">@addresses</span> = <span class="ruby-identifier">addresses</span>
<span class="ruby-identifier">logger</span> = <span class="ruby-constant">WEBrick</span><span class="ruby-operator">::</span><span class="ruby-constant">Log</span>.<span class="ruby-identifier">new</span> <span class="ruby-keyword kw">nil</span>, <span class="ruby-constant">WEBrick</span><span class="ruby-operator">::</span><span class="ruby-constant">BasicLog</span><span class="ruby-operator">::</span><span class="ruby-constant">FATAL</span>
<span class="ruby-ivar">@server</span> = <span class="ruby-constant">WEBrick</span><span class="ruby-operator">::</span><span class="ruby-constant">HTTPServer</span>.<span class="ruby-identifier">new</span> <span class="ruby-identifier">:DoNotListen</span> =<span class="ruby-operator">></span> <span class="ruby-keyword kw">true</span>, <span class="ruby-identifier">:Logger</span> =<span class="ruby-operator">></span> <span class="ruby-identifier">logger</span>
<span class="ruby-ivar">@spec_dirs</span> = <span class="ruby-ivar">@gem_dirs</span>.<span class="ruby-identifier">map</span> <span class="ruby-keyword kw">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">gem_dir</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">spec_dir</span> = <span class="ruby-constant">File</span>.<span class="ruby-identifier">join</span> <span class="ruby-identifier">gem_dir</span>, <span class="ruby-value str">'specifications'</span>
<span class="ruby-keyword kw">unless</span> <span class="ruby-constant">File</span>.<span class="ruby-identifier">directory?</span> <span class="ruby-identifier">spec_dir</span> <span class="ruby-keyword kw">then</span>
<span class="ruby-identifier">raise</span> <span class="ruby-constant">ArgumentError</span>, <span class="ruby-node">"#{gem_dir} does not appear to be a gem repository"</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-identifier">spec_dir</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-ivar">@source_index</span> = <span class="ruby-constant">Gem</span><span class="ruby-operator">::</span><span class="ruby-constant">SourceIndex</span>.<span class="ruby-identifier">from_gems_in</span>(<span class="ruby-operator">*</span><span class="ruby-ivar">@spec_dirs</span>)
<span class="ruby-keyword kw">end</span></pre>
</body>
</html> | {
"pile_set_name": "Github"
} |
---
- name: Create
hosts: localhost
connection: local
gather_facts: False
no_log: "{{ not lookup('env', 'MOLECULE_DEBUG') | bool }}"
vars:
molecule_file: "{{ lookup('env', 'MOLECULE_FILE') }}"
molecule_ephemeral_directory: "{{ lookup('env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}"
molecule_scenario_directory: "{{ lookup('env', 'MOLECULE_SCENARIO_DIRECTORY') }}"
molecule_yml: "{{ lookup('file', molecule_file) | molecule_from_yaml }}"
tasks:
- name: Create Dockerfiles from image names
template:
src: "{{ molecule_scenario_directory }}/Dockerfile.j2"
dest: "{{ molecule_ephemeral_directory }}/Dockerfile_{{ item.image | regex_replace('[^a-zA-Z0-9_]', '_') }}"
with_items: "{{ molecule_yml.platforms }}"
register: platforms
- name: Discover local Docker images
docker_image_facts:
name: "molecule_local/{{ item.item.name }}"
with_items: "{{ platforms.results }}"
register: docker_images
- name: Build an Ansible compatible image
docker_image:
path: "{{ molecule_ephemeral_directory }}"
name: "molecule_local/{{ item.item.image }}"
dockerfile: "{{ item.item.dockerfile | default(item.invocation.module_args.dest) }}"
force: "{{ item.item.force | default(True) }}"
with_items: "{{ platforms.results }}"
when: platforms.changed or docker_images.results | map(attribute='images') | select('equalto', []) | list | count >= 0
- name: Create molecule instance(s)
docker_container:
name: "{{ item.name }}"
hostname: "{{ item.name }}"
image: "molecule_local/{{ item.image }}"
state: started
recreate: False
command: "{{ item.command | default('sleep infinity') }}"
privileged: "{{ item.privileged | default(omit) }}"
volumes: "{{ item.volumes | default(omit) }}"
capabilities: "{{ item.capabilities | default(omit) }}"
with_items: "{{ molecule_yml.platforms }}"
| {
"pile_set_name": "Github"
} |
bin/check_perldiag
%%PERL5_MAN1%%/check_perldiag.1.gz
%%SITE_PERL%%/Parse/ErrorString/Perl/ErrorItem.pm
%%SITE_PERL%%/Parse/ErrorString/Perl/StackItem.pm
%%SITE_PERL%%/Parse/ErrorString/Perl.pm
%%PERL5_MAN3%%/Parse::ErrorString::Perl.3.gz
%%PERL5_MAN3%%/Parse::ErrorString::Perl::ErrorItem.3.gz
%%PERL5_MAN3%%/Parse::ErrorString::Perl::StackItem.3.gz
| {
"pile_set_name": "Github"
} |
import { deleteContact, ManagedContact } from '@linode/api-v4/lib/managed';
import { APIError } from '@linode/api-v4/lib/types';
import { withSnackbar, WithSnackbarProps } from 'notistack';
import * as React from 'react';
import AddNewLink from 'src/components/AddNewLink';
import Box from 'src/components/core/Box';
import Paper from 'src/components/core/Paper';
import RootRef from 'src/components/core/RootRef';
import { makeStyles, Theme } from 'src/components/core/styles';
import TableBody from 'src/components/core/TableBody';
import TableHead from 'src/components/core/TableHead';
import Typography from 'src/components/core/Typography';
import DeletionDialog from 'src/components/DeletionDialog';
import { DocumentTitleSegment } from 'src/components/DocumentTitle';
import OrderBy from 'src/components/OrderBy';
import Paginate from 'src/components/Paginate';
import PaginationFooter from 'src/components/PaginationFooter';
import Table from 'src/components/Table';
import TableCell from 'src/components/TableCell';
import TableRow from 'src/components/TableRow';
import TableSortCell from 'src/components/TableSortCell';
import { useDialog } from 'src/hooks/useDialog';
import useOpenClose from 'src/hooks/useOpenClose';
import { getAPIErrorOrDefault } from 'src/utilities/errorUtils';
import { ManagedContactGroup, Mode } from './common';
import ContactDrawer from './ContactsDrawer';
import ContactTableContact from './ContactsTableContent';
const useStyles = makeStyles((theme: Theme) => ({
root: {
marginTop: theme.spacing(1),
'&:before': {
display: 'none'
}
},
copy: {},
contactsTable: {
marginTop: theme.spacing(4)
},
name: {
width: '20%'
}
}));
interface Props {
contacts: ManagedContact[];
loading: boolean;
error?: APIError[];
lastUpdated: number;
transformData: (fn: (contacts: ManagedContact[]) => void) => void;
update: () => void;
}
type CombinedProps = Props & WithSnackbarProps;
const Contacts: React.FC<CombinedProps> = props => {
const classes = useStyles();
const {
contacts,
loading,
error,
lastUpdated,
transformData,
update,
enqueueSnackbar
} = props;
const updateOrAdd = (contact: ManagedContact) => {
transformData(draft => {
const idx = draft.findIndex(l => l.id === contact.id);
// Add the contact if we don't already have it.
if (idx === -1) {
draft.push(contact);
} else {
// Otherwise just update it.
draft[idx] = contact;
}
});
};
const [selectedContactId, setSelectedContactId] = React.useState<
number | null
>(null);
const [contactDrawerMode, setContactDrawerMode] = React.useState<Mode>(
'create'
);
const {
dialog,
openDialog,
closeDialog,
submitDialog,
handleError
} = useDialog<number>(deleteContact);
const handleDelete = () => {
submitDialog(dialog.entityID)
.then(() => {
update();
enqueueSnackbar('Contact deleted successfully.', {
variant: 'success'
});
})
.catch(e =>
handleError(
getAPIErrorOrDefault(e, 'Error deleting this contact.')[0].reason
)
);
};
const contactDrawer = useOpenClose();
// Ref for handling "scrollTo" on Paginated component.
const contactsTableRef = React.createRef();
const groups = generateGroupsFromContacts(contacts);
return (
<div>
<DocumentTitleSegment segment="Contacts" />
<Typography variant="subtitle1" className={classes.copy}>
You can assign contact groups to monitors so we know who to talk to in
the event of a support issue. Create contacts and assign them to a
group, then assign the group to the appropriate monitor(s).
</Typography>
<div className={classes.contactsTable}>
<RootRef rootRef={contactsTableRef}>
<Box
display="flex"
flexDirection="row"
justifyContent="space-between"
alignItems="center"
>
<Typography variant="h2">Contacts</Typography>
<AddNewLink
onClick={() => {
setContactDrawerMode('create');
contactDrawer.open();
}}
label="Add a Contact"
/>
</Box>
</RootRef>
<OrderBy data={contacts} orderBy="name" order="asc">
{({ data: orderedData, handleOrderChange, order, orderBy }) => {
return (
<Paginate data={orderedData} scrollToRef={contactsTableRef}>
{({
count,
data: paginatedData,
handlePageChange,
handlePageSizeChange,
page,
pageSize
}) => {
return (
<>
<Paper className={classes.root}>
<Table aria-label="List of Your Managed Contacts">
<TableHead>
<TableRow>
<TableSortCell
active={orderBy === 'name'}
label={'name'}
direction={order}
handleClick={handleOrderChange}
className={classes.name}
>
Name
</TableSortCell>
<TableSortCell
active={orderBy === 'group'}
label={'group'}
direction={order}
handleClick={handleOrderChange}
>
Group
</TableSortCell>
<TableSortCell
active={orderBy === 'email'}
label={'email'}
direction={order}
handleClick={handleOrderChange}
>
E-mail
</TableSortCell>
<TableSortCell
active={orderBy === 'phone:primary'}
label={'phone:primary'}
direction={order}
handleClick={handleOrderChange}
>
Primary Phone
</TableSortCell>
<TableSortCell
active={orderBy === 'phone:secondary'}
label={'phone:secondary'}
direction={order}
handleClick={handleOrderChange}
>
Secondary Phone
</TableSortCell>
{/* Empty TableCell for action menu */}
<TableCell />
</TableRow>
</TableHead>
<TableBody>
<ContactTableContact
contacts={paginatedData}
loading={loading}
lastUpdated={lastUpdated}
updateOrAdd={updateOrAdd}
openDrawer={(contactId: number) => {
setSelectedContactId(contactId);
setContactDrawerMode('edit');
contactDrawer.open();
}}
openDialog={(contactId: number) => {
const selectedContact = contacts.find(
thisContact => thisContact.id === contactId
);
const label = selectedContact
? selectedContact.name
: '';
openDialog(contactId, label);
}}
error={error}
/>
</TableBody>
</Table>
</Paper>
<PaginationFooter
count={count}
handlePageChange={handlePageChange}
handleSizeChange={handlePageSizeChange}
page={page}
pageSize={pageSize}
eventCategory="managed contacts"
/>
</>
);
}}
</Paginate>
);
}}
</OrderBy>
<DeletionDialog
open={dialog.isOpen}
label={dialog.entityLabel || ''}
loading={dialog.isLoading}
error={dialog.error}
onClose={closeDialog}
onDelete={handleDelete}
/>
</div>
<ContactDrawer
mode={contactDrawerMode}
isOpen={contactDrawer.isOpen}
closeDrawer={contactDrawer.close}
updateOrAdd={updateOrAdd}
contact={contacts.find(contact => contact.id === selectedContactId)}
groups={groups}
/>
</div>
);
};
export default withSnackbar(Contacts);
/**
* Generate groups from a list of Managed Contacts.
*
* @param contacts: Linode.ManagedContact[]
* A list of contacts to generate groups from.
*/
export const generateGroupsFromContacts = (
contacts: ManagedContact[]
): ManagedContactGroup[] => {
const groups: ManagedContactGroup[] = [];
contacts.forEach(contact => {
// If the contact doesn't have a group, don't do anything. Otherwise we'd have `null` groups.
if (typeof contact.group !== 'string') {
return;
}
// Have we tracked this group yet?
const idx = groups.findIndex(group => group.groupName === contact.group);
// If not, add a new group.
if (idx === -1) {
groups.push({
groupName: contact.group,
contactNames: [contact.name]
});
} else {
// If we've already tracked the group, just add this contact's name.
groups[idx].contactNames.push(contact.name);
}
});
return groups;
};
| {
"pile_set_name": "Github"
} |
https://anysoftkeyboard.github.io/
| {
"pile_set_name": "Github"
} |
include/antlr3.h
include/antlr3baserecognizer.h
include/antlr3basetree.h
include/antlr3basetreeadaptor.h
include/antlr3bitset.h
include/antlr3collections.h
include/antlr3commontoken.h
include/antlr3commontree.h
include/antlr3commontreeadaptor.h
include/antlr3commontreenodestream.h
include/antlr3config.h
include/antlr3convertutf.h
include/antlr3cyclicdfa.h
include/antlr3debugeventlistener.h
include/antlr3defs.h
include/antlr3encodings.h
include/antlr3errors.h
include/antlr3exception.h
include/antlr3filestream.h
include/antlr3input.h
include/antlr3interfaces.h
include/antlr3intstream.h
include/antlr3lexer.h
include/antlr3memory.h
include/antlr3parser.h
include/antlr3parsetree.h
include/antlr3recognizersharedstate.h
include/antlr3rewritestreams.h
include/antlr3string.h
include/antlr3tokenstream.h
include/antlr3treeparser.h
lib/libantlr3c.a
lib/libantlr3c.so
| {
"pile_set_name": "Github"
} |
---
date_added: 2020-06-26
title: Deltaco 3m RGBCCT
model: SH-LS3M
image: /assets/images/deltaco_SH-LS3M.jpg
template: '{"NAME":"Deltaco Led Strip","GPIO":[0,0,0,0,37,17,0,0,38,0,39,0,0],"FLAG":0,"BASE":18}'
link: https://www.mediamarkt.se/sv/product/_deltaco-deltaco-smart-home-led-list-rgb-2700k-6500k-3m-wifi-2-4ghz-300lm-m-3m-tejp-dimbar-6-pin-vit-1323394.html
link2:
mlink: https://www.deltaco.se/produkter/belysning/led-lister/SH-LS3M
flash: tuya-convert
category: light
type: LED Strip
standard: global
---
| {
"pile_set_name": "Github"
} |
/* File : CrushWrapper.i */
%module CrushWrapper
%{
#include "CrushWrapper.h"
%}
%include typemaps.i
// This tells SWIG to treat 'int *data' as a special case
%typemap(in) int *items {
AV *tempav;
I32 len;
int i;
SV **tv;
// int view;
//printf("typemap\n");
if (!SvROK($input))
croak("$input is not a reference.");
if (SvTYPE(SvRV($input)) != SVt_PVAV)
croak("$input is not an array.");
tempav = (AV*)SvRV($input);
len = av_len(tempav);
//printf("typemap len: %i\n",len);
$1 = (int *) malloc((len+1)*sizeof(int));
for (i = 0; i <= len; i++) {
tv = av_fetch(tempav, i, 0);
$1[i] = (int) SvIV(*tv);
/*
view = SvIV(*tv);
printf("view: %d",view);
printf("\n");
*/
}
}
%apply int *items { int *weights };
%apply double *OUTPUT { double *min, double *max, double *avg };
/* Let's just grab the original header file here */
%include "CrushWrapper.h"
%clear double *min, double *max, double *avg;
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//+build !gccgo,!appengine
#include "textflag.h"
TEXT ·hasMSA6(SB), NOSPLIT, $16-1
MOVD $0, R0 // KIMD-Query function code
MOVD $tmp-16(SP), R1 // parameter block
XC $16, (R1), (R1) // clear the parameter block
WORD $0xB93E0002 // KIMD --, --
WORD $0x91FC1004 // TM 4(R1), 0xFC (test bits [32-37])
BVS yes
no:
MOVB $0, ret+0(FP)
RET
yes:
MOVB $1, ret+0(FP)
RET
// func kimd(function code, params *[200]byte, src []byte)
TEXT ·kimd(SB), NOFRAME|NOSPLIT, $0-40
MOVD function+0(FP), R0
MOVD params+8(FP), R1
LMG src+16(FP), R2, R3 // R2=base, R3=len
continue:
WORD $0xB93E0002 // KIMD --, R2
BVS continue // continue if interrupted
MOVD $0, R0 // reset R0 for pre-go1.8 compilers
RET
// func klmd(function code, params *[200]byte, dst, src []byte)
TEXT ·klmd(SB), NOFRAME|NOSPLIT, $0-64
// TODO: SHAKE support
MOVD function+0(FP), R0
MOVD params+8(FP), R1
LMG dst+16(FP), R2, R3 // R2=base, R3=len
LMG src+40(FP), R4, R5 // R4=base, R5=len
continue:
WORD $0xB93F0024 // KLMD R2, R4
BVS continue // continue if interrupted
MOVD $0, R0 // reset R0 for pre-go1.8 compilers
RET
| {
"pile_set_name": "Github"
} |
# Tool bar

**Tool bar** is at the top of the main editor window including five sets of control buttons or pieces of information that provide editing functions for specific panels and allow the user to conveniently implement workflows.
### Transform Tools

This provides the editing node transform attribute (position, rotation, scale, size) function for the **scene editor**. Please refer to [use transform tool to place node](editor-panels/scene.md#%E4%BD%BF%E7%94%A8%E5%8F%98%E6%8D%A2%E5%B7%A5%E5%85%B7%E5%B8%83%E7%BD%AE%E8%8A%82%E7%82%B9) for detailed information.
### Gizmo Display Mode
This control is for setting display mode of the **Transform Tool** in **scene editor** with the two sets of buttons below.

Position mode:
* Anchor: transform tool will be displayed at the position where the node **Anchor** is.
* Central Point: transform tool will be displayed at the position where the central point of the node is (influenced by the bounding box size).

Rotation mode:
* Local: transform tool's rotation (handle direction) will stay the same as the **Rotation** attribute of the node.
* World: transform tool's rotation stays the same and the handles of the x and y axes stay the same as the direction of the world coordinate.
### Preview Game

This includes three buttons:
* Select the preview platform: Click on the drop-down menu to select the preview platform as the simulator or the browser.
* Run preview: run the scene being currently edited in the browser.
* Refresh device: reload the current scene on all the devices that are connected to this machine to preview the game (including local browser and other mobile devices connected to the native machine).
### Preview Address

Here is shown the LAN address of the desktop computer running Cocos Creator. The mobile devices connected to the same local area network can access this address to preview and debug the game.
### Open Project Folder

* **Open Project**: Open the project folder.
* **Open App**: Open the installation path of the program.
| {
"pile_set_name": "Github"
} |
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/>
// Copyright (C) 2010 Winch Gate Property Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef NL_BASE_DIALOG_H
#define NL_BASE_DIALOG_H
#include "nel/misc/types_nl.h"
/**
* Base dialog for option dialogs
*
* \author Cyril 'Hulud' Corvazier
* \author Nevrax France
* \date 2003
*/
class CBaseDialog : public CDialog
{
public:
/// Constructor
CBaseDialog (uint id, CWnd* pParent = NULL) : CDialog(id, pParent) {}
/// On ok
virtual void OnOK ();
virtual void OnCancel ();
};
#endif // NL_BASE_DIALOG_H
/* End of base_dialog.h */
| {
"pile_set_name": "Github"
} |
<form action="{{ url('/saml2/login') }}" method="POST" id="login-form" class="mt-l">
{!! csrf_field() !!}
<div>
<button id="saml-login" class="button outline block svg">
@icon('saml2')
<span>{{ trans('auth.log_in_with', ['socialDriver' => config('saml2.name')]) }}</span>
</button>
</div>
</form> | {
"pile_set_name": "Github"
} |
/*
* H261 parser
* Copyright (c) 2002-2004 Michael Niedermayer <[email protected]>
* Copyright (c) 2004 Maarten Daniels
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* h261codec.
*/
#include "parser.h"
static int h261_find_frame_end(ParseContext *pc, AVCodecContext* avctx, const uint8_t *buf, int buf_size){
int vop_found, i, j;
uint32_t state;
vop_found= pc->frame_start_found;
state= pc->state;
for(i=0; i<buf_size && !vop_found; i++){
state= (state<<8) | buf[i];
for(j=0; j<8; j++){
if(((state>>j)&0xFFFFF0) == 0x000100){
vop_found=1;
break;
}
}
}
if(vop_found){
for(; i<buf_size; i++){
state= (state<<8) | buf[i];
for(j=0; j<8; j++){
if(((state>>j)&0xFFFFF0) == 0x000100){
pc->frame_start_found=0;
pc->state= (state>>(3*8))+0xFF00;
return i-2;
}
}
}
}
pc->frame_start_found= vop_found;
pc->state= state;
return END_NOT_FOUND;
}
static int h261_parse(AVCodecParserContext *s,
AVCodecContext *avctx,
const uint8_t **poutbuf, int *poutbuf_size,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = s->priv_data;
int next;
next= h261_find_frame_end(pc,avctx, buf, buf_size);
if (ff_combine_frame(pc, next, &buf, &buf_size) < 0) {
*poutbuf = NULL;
*poutbuf_size = 0;
return buf_size;
}
*poutbuf = buf;
*poutbuf_size = buf_size;
return next;
}
AVCodecParser h261_parser = {
{ CODEC_ID_H261 },
sizeof(ParseContext),
NULL,
h261_parse,
ff_parse_close,
};
| {
"pile_set_name": "Github"
} |
// Manually added data to be used by sbcs codec in addition to generated one.
module.exports = {
// Not supported by iconv, not sure why.
"10029": "maccenteuro",
"maccenteuro": {
"type": "_sbcs",
"chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
},
"808": "cp808",
"ibm808": "cp808",
"cp808": {
"type": "_sbcs",
"chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
},
// Aliases of generated encodings.
"ascii8bit": "ascii",
"usascii": "ascii",
"ansix34": "ascii",
"ansix341968": "ascii",
"ansix341986": "ascii",
"csascii": "ascii",
"cp367": "ascii",
"ibm367": "ascii",
"isoir6": "ascii",
"iso646us": "ascii",
"iso646irv": "ascii",
"us": "ascii",
"latin1": "iso88591",
"latin2": "iso88592",
"latin3": "iso88593",
"latin4": "iso88594",
"latin5": "iso88599",
"latin6": "iso885910",
"latin7": "iso885913",
"latin8": "iso885914",
"latin9": "iso885915",
"latin10": "iso885916",
"csisolatin1": "iso88591",
"csisolatin2": "iso88592",
"csisolatin3": "iso88593",
"csisolatin4": "iso88594",
"csisolatincyrillic": "iso88595",
"csisolatinarabic": "iso88596",
"csisolatingreek" : "iso88597",
"csisolatinhebrew": "iso88598",
"csisolatin5": "iso88599",
"csisolatin6": "iso885910",
"l1": "iso88591",
"l2": "iso88592",
"l3": "iso88593",
"l4": "iso88594",
"l5": "iso88599",
"l6": "iso885910",
"l7": "iso885913",
"l8": "iso885914",
"l9": "iso885915",
"l10": "iso885916",
"isoir14": "iso646jp",
"isoir57": "iso646cn",
"isoir100": "iso88591",
"isoir101": "iso88592",
"isoir109": "iso88593",
"isoir110": "iso88594",
"isoir144": "iso88595",
"isoir127": "iso88596",
"isoir126": "iso88597",
"isoir138": "iso88598",
"isoir148": "iso88599",
"isoir157": "iso885910",
"isoir166": "tis620",
"isoir179": "iso885913",
"isoir199": "iso885914",
"isoir203": "iso885915",
"isoir226": "iso885916",
"cp819": "iso88591",
"ibm819": "iso88591",
"cyrillic": "iso88595",
"arabic": "iso88596",
"arabic8": "iso88596",
"ecma114": "iso88596",
"asmo708": "iso88596",
"greek" : "iso88597",
"greek8" : "iso88597",
"ecma118" : "iso88597",
"elot928" : "iso88597",
"hebrew": "iso88598",
"hebrew8": "iso88598",
"turkish": "iso88599",
"turkish8": "iso88599",
"thai": "iso885911",
"thai8": "iso885911",
"celtic": "iso885914",
"celtic8": "iso885914",
"isoceltic": "iso885914",
"tis6200": "tis620",
"tis62025291": "tis620",
"tis62025330": "tis620",
"10000": "macroman",
"10006": "macgreek",
"10007": "maccyrillic",
"10079": "maciceland",
"10081": "macturkish",
"cspc8codepage437": "cp437",
"cspc775baltic": "cp775",
"cspc850multilingual": "cp850",
"cspcp852": "cp852",
"cspc862latinhebrew": "cp862",
"cpgr": "cp869",
"msee": "cp1250",
"mscyrl": "cp1251",
"msansi": "cp1252",
"msgreek": "cp1253",
"msturk": "cp1254",
"mshebr": "cp1255",
"msarab": "cp1256",
"winbaltrim": "cp1257",
"cp20866": "koi8r",
"20866": "koi8r",
"ibm878": "koi8r",
"cskoi8r": "koi8r",
"cp21866": "koi8u",
"21866": "koi8u",
"ibm1168": "koi8u",
"strk10482002": "rk1048",
"tcvn5712": "tcvn",
"tcvn57121": "tcvn",
"gb198880": "iso646cn",
"cn": "iso646cn",
"csiso14jisc6220ro": "iso646jp",
"jisc62201969ro": "iso646jp",
"jp": "iso646jp",
"cshproman8": "hproman8",
"r8": "hproman8",
"roman8": "hproman8",
"xroman8": "hproman8",
"ibm1051": "hproman8",
"mac": "macintosh",
"csmacintosh": "macintosh",
};
| {
"pile_set_name": "Github"
} |
context("mcmc")
test_that("Pareto/GGG MCMC", {
# generate artificial Pareto/GGG data
params <- list(t = 4.5, gamma = 1.5, r = 0.9, alpha = 10, s = 0.8, beta = 12)
n <- 100
expect_silent(pggg.GenerateData(n, 52, c(26, 52), params))
cbs <- pggg.GenerateData(n, 52, 52, params)$cbs
# estimate parameters
draws <- pggg.mcmc.DrawParameters(as.data.table(cbs),
mcmc = 10, burnin = 0, thin = 1, mc.cores = 1,
param_init = list(r = 1, alpha = 1, s = 1, beta = 1, t = 1, gamma = 1))
draws <- pggg.mcmc.DrawParameters(cbs,
mcmc = 100, burnin = 20, thin = 10, chains = 2, mc.cores = 1,
param_init = params)
expect_true(all(c("level_1", "level_2") %in% names(draws)))
expect_equal(length(draws$level_1), n)
expect_true(coda::is.mcmc.list(draws$level_1[[1]]))
expect_true(coda::is.mcmc.list(draws$level_2))
# estimate future transactions
xstar <- mcmc.DrawFutureTransactions(cbs, draws, T.star = cbs$T.star)
# plot regularity rate
pggg.plotRegularityRateHeterogeneity(draws)
skip("skip long-running test of Pareto/GGG parameter recovery")
# generate artificial Pareto/GGG data
set.seed(1)
params <- list(t = 4.5, gamma = 1.5, r = 0.9, alpha = 5, s = 0.8, beta = 12)
n <- 5000
cbs <- pggg.GenerateData(n,
round(runif(n, 36, 96) / 12) * 12,
36,
params)$cbs
# estimate parameters
draws <- pggg.mcmc.DrawParameters(cbs, mc.cores = 1)
est <- as.list(summary(draws$level_2)$quantiles[, "50%"])
# require less than 10% deviation in estimated parameters
expect_equal(params, est, tolerance = 0.1)
# estimate future transactions & P(alive) & P(active)
xstar <- mcmc.DrawFutureTransactions(cbs, draws, T.star = cbs$T.star)
cbs$x.est <- apply(xstar, 2, mean)
cbs$pactive <- mcmc.PActive(xstar)
cbs$palive <- mcmc.PAlive(draws)
# require less than 5% deviation
expect_equal(sum(cbs$x.star), sum(cbs$x.est), tolerance = 0.05)
expect_equal(sum(cbs$palive), sum(cbs$alive), tolerance = 0.05)
expect_equal(sum(cbs$x.star > 0), sum(cbs$pactive), tolerance = 0.05)
expect_true(min(cbs$x.star) >= 0)
expect_true(all(cbs$x.star == round(cbs$x.star)))
expect_true(all(cbs$palive >= 0 & cbs$palive <= 1))
})
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 5975e88ff2f245c4d893fb2ae3c65b57
timeCreated: 1572876784
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
body {
margin: 0px;
}
kbd {
display: inline-block;
padding: 3px 5px;
font: 11px Consolas, "Liberation Mono", Menlo, Courier, monospace;
line-height: 10px;
color: #555;
vertical-align: middle;
background-color: #fcfcfc;
border: solid 1px #ccc;
border-bottom-color: #bbb;
border-radius: 3px;
box-shadow: inset 0 -1px 0 #bbb;
}
.description {
padding: 10px 10%;
border-bottom: 1px solid #777;
}
.description>div {
padding: 0px 20px;
border-left: 1px solid #e7e7e7;
display: inline-block;
}
.annotation {
padding-left: 12px;
}
.content {
margin: 0px;
padding: 0px 10%;
height: 90vh; /* window.innerHeight * 0.88 */
overflow: scroll;
background: #777;
}
.content>div {
background: #fff !important;
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
| {
"pile_set_name": "Github"
} |
{
"type": "Program",
"body": [
{
"type": "ExpressionStatement",
"expression": {
"type": "Literal",
"value": 42,
"raw": "42",
"range": [
8,
10
],
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 6
}
}
},
"leadingComments": [
{
"type": "Block",
"value": "a\nb",
"range": [
0,
7
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 2,
"column": 3
}
}
}
],
"range": [
8,
10
],
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 6
}
}
}
],
"sourceType": "script",
"comments": [
{
"type": "Block",
"value": "a\nb",
"range": [
0,
7
],
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 2,
"column": 3
}
}
}
],
"tokens": [
{
"type": "Numeric",
"value": "42",
"range": [
8,
10
],
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 6
}
}
}
],
"range": [
8,
10
],
"loc": {
"start": {
"line": 2,
"column": 4
},
"end": {
"line": 2,
"column": 6
}
}
}
| {
"pile_set_name": "Github"
} |
package er.example.erxpartials;
import com.webobjects.appserver.WOComponent;
import com.webobjects.directtoweb.D2W;
import com.webobjects.directtoweb.EditPageInterface;
import com.webobjects.directtoweb.ErrorPageInterface;
import com.webobjects.directtoweb.QueryPageInterface;
public class MainNavigationController
{
private Session _session;
public MainNavigationController(Session s)
{
super();
_session = s;
}
public WOComponent homeAction()
{
return D2W.factory().defaultPage(session());
}
// GENERIC ACTIONS
public WOComponent queryPageForEntityName(String entityName)
{
QueryPageInterface newQueryPage = D2W.factory().queryPageForEntityNamed(entityName, session());
return (WOComponent) newQueryPage;
}
public WOComponent newObjectForEntityName(String entityName)
{
WOComponent nextPage = null;
try
{
EditPageInterface epi = D2W.factory().editPageForNewObjectWithEntityNamed(entityName, session());
epi.setNextPage(session().context().page());
nextPage = (WOComponent) epi;
} catch (IllegalArgumentException e)
{
ErrorPageInterface epf = D2W.factory().errorPage(session());
epf.setMessage(e.toString());
epf.setNextPage(session().context().page());
nextPage = (WOComponent) epf;
}
return nextPage;
}
// ACCESSORS
public Session session()
{
return _session;
}
public void setSession(Session s)
{
_session = s;
}
}
| {
"pile_set_name": "Github"
} |
package jmespath
import (
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"sort"
"strconv"
"strings"
"unicode/utf8"
)
type jpFunction func(arguments []interface{}) (interface{}, error)
type jpType string
const (
jpUnknown jpType = "unknown"
jpNumber jpType = "number"
jpString jpType = "string"
jpArray jpType = "array"
jpObject jpType = "object"
jpArrayNumber jpType = "array[number]"
jpArrayString jpType = "array[string]"
jpExpref jpType = "expref"
jpAny jpType = "any"
)
type functionEntry struct {
name string
arguments []argSpec
handler jpFunction
hasExpRef bool
}
type argSpec struct {
types []jpType
variadic bool
}
type byExprString struct {
intr *treeInterpreter
node ASTNode
items []interface{}
hasError bool
}
func (a *byExprString) Len() int {
return len(a.items)
}
func (a *byExprString) Swap(i, j int) {
a.items[i], a.items[j] = a.items[j], a.items[i]
}
func (a *byExprString) Less(i, j int) bool {
first, err := a.intr.Execute(a.node, a.items[i])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
ith, ok := first.(string)
if !ok {
a.hasError = true
return true
}
second, err := a.intr.Execute(a.node, a.items[j])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
jth, ok := second.(string)
if !ok {
a.hasError = true
return true
}
return ith < jth
}
type byExprFloat struct {
intr *treeInterpreter
node ASTNode
items []interface{}
hasError bool
}
func (a *byExprFloat) Len() int {
return len(a.items)
}
func (a *byExprFloat) Swap(i, j int) {
a.items[i], a.items[j] = a.items[j], a.items[i]
}
func (a *byExprFloat) Less(i, j int) bool {
first, err := a.intr.Execute(a.node, a.items[i])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
ith, ok := first.(float64)
if !ok {
a.hasError = true
return true
}
second, err := a.intr.Execute(a.node, a.items[j])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
jth, ok := second.(float64)
if !ok {
a.hasError = true
return true
}
return ith < jth
}
type functionCaller struct {
functionTable map[string]functionEntry
}
func newFunctionCaller() *functionCaller {
caller := &functionCaller{}
caller.functionTable = map[string]functionEntry{
"length": {
name: "length",
arguments: []argSpec{
{types: []jpType{jpString, jpArray, jpObject}},
},
handler: jpfLength,
},
"starts_with": {
name: "starts_with",
arguments: []argSpec{
{types: []jpType{jpString}},
{types: []jpType{jpString}},
},
handler: jpfStartsWith,
},
"abs": {
name: "abs",
arguments: []argSpec{
{types: []jpType{jpNumber}},
},
handler: jpfAbs,
},
"avg": {
name: "avg",
arguments: []argSpec{
{types: []jpType{jpArrayNumber}},
},
handler: jpfAvg,
},
"ceil": {
name: "ceil",
arguments: []argSpec{
{types: []jpType{jpNumber}},
},
handler: jpfCeil,
},
"contains": {
name: "contains",
arguments: []argSpec{
{types: []jpType{jpArray, jpString}},
{types: []jpType{jpAny}},
},
handler: jpfContains,
},
"ends_with": {
name: "ends_with",
arguments: []argSpec{
{types: []jpType{jpString}},
{types: []jpType{jpString}},
},
handler: jpfEndsWith,
},
"floor": {
name: "floor",
arguments: []argSpec{
{types: []jpType{jpNumber}},
},
handler: jpfFloor,
},
"map": {
name: "amp",
arguments: []argSpec{
{types: []jpType{jpExpref}},
{types: []jpType{jpArray}},
},
handler: jpfMap,
hasExpRef: true,
},
"max": {
name: "max",
arguments: []argSpec{
{types: []jpType{jpArrayNumber, jpArrayString}},
},
handler: jpfMax,
},
"merge": {
name: "merge",
arguments: []argSpec{
{types: []jpType{jpObject}, variadic: true},
},
handler: jpfMerge,
},
"max_by": {
name: "max_by",
arguments: []argSpec{
{types: []jpType{jpArray}},
{types: []jpType{jpExpref}},
},
handler: jpfMaxBy,
hasExpRef: true,
},
"sum": {
name: "sum",
arguments: []argSpec{
{types: []jpType{jpArrayNumber}},
},
handler: jpfSum,
},
"min": {
name: "min",
arguments: []argSpec{
{types: []jpType{jpArrayNumber, jpArrayString}},
},
handler: jpfMin,
},
"min_by": {
name: "min_by",
arguments: []argSpec{
{types: []jpType{jpArray}},
{types: []jpType{jpExpref}},
},
handler: jpfMinBy,
hasExpRef: true,
},
"type": {
name: "type",
arguments: []argSpec{
{types: []jpType{jpAny}},
},
handler: jpfType,
},
"keys": {
name: "keys",
arguments: []argSpec{
{types: []jpType{jpObject}},
},
handler: jpfKeys,
},
"values": {
name: "values",
arguments: []argSpec{
{types: []jpType{jpObject}},
},
handler: jpfValues,
},
"sort": {
name: "sort",
arguments: []argSpec{
{types: []jpType{jpArrayString, jpArrayNumber}},
},
handler: jpfSort,
},
"sort_by": {
name: "sort_by",
arguments: []argSpec{
{types: []jpType{jpArray}},
{types: []jpType{jpExpref}},
},
handler: jpfSortBy,
hasExpRef: true,
},
"join": {
name: "join",
arguments: []argSpec{
{types: []jpType{jpString}},
{types: []jpType{jpArrayString}},
},
handler: jpfJoin,
},
"reverse": {
name: "reverse",
arguments: []argSpec{
{types: []jpType{jpArray, jpString}},
},
handler: jpfReverse,
},
"to_array": {
name: "to_array",
arguments: []argSpec{
{types: []jpType{jpAny}},
},
handler: jpfToArray,
},
"to_string": {
name: "to_string",
arguments: []argSpec{
{types: []jpType{jpAny}},
},
handler: jpfToString,
},
"to_number": {
name: "to_number",
arguments: []argSpec{
{types: []jpType{jpAny}},
},
handler: jpfToNumber,
},
"not_null": {
name: "not_null",
arguments: []argSpec{
{types: []jpType{jpAny}, variadic: true},
},
handler: jpfNotNull,
},
}
return caller
}
func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) {
if len(e.arguments) == 0 {
return arguments, nil
}
if !e.arguments[len(e.arguments)-1].variadic {
if len(e.arguments) != len(arguments) {
return nil, errors.New("incorrect number of args")
}
for i, spec := range e.arguments {
userArg := arguments[i]
err := spec.typeCheck(userArg)
if err != nil {
return nil, err
}
}
return arguments, nil
}
if len(arguments) < len(e.arguments) {
return nil, errors.New("Invalid arity.")
}
return arguments, nil
}
func (a *argSpec) typeCheck(arg interface{}) error {
for _, t := range a.types {
switch t {
case jpNumber:
if _, ok := arg.(float64); ok {
return nil
}
case jpString:
if _, ok := arg.(string); ok {
return nil
}
case jpArray:
if isSliceType(arg) {
return nil
}
case jpObject:
if _, ok := arg.(map[string]interface{}); ok {
return nil
}
case jpArrayNumber:
if _, ok := toArrayNum(arg); ok {
return nil
}
case jpArrayString:
if _, ok := toArrayStr(arg); ok {
return nil
}
case jpAny:
return nil
case jpExpref:
if _, ok := arg.(expRef); ok {
return nil
}
}
}
return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types)
}
func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) {
entry, ok := f.functionTable[name]
if !ok {
return nil, errors.New("unknown function: " + name)
}
resolvedArgs, err := entry.resolveArgs(arguments)
if err != nil {
return nil, err
}
if entry.hasExpRef {
var extra []interface{}
extra = append(extra, intr)
resolvedArgs = append(extra, resolvedArgs...)
}
return entry.handler(resolvedArgs)
}
func jpfAbs(arguments []interface{}) (interface{}, error) {
num := arguments[0].(float64)
return math.Abs(num), nil
}
func jpfLength(arguments []interface{}) (interface{}, error) {
arg := arguments[0]
if c, ok := arg.(string); ok {
return float64(utf8.RuneCountInString(c)), nil
} else if isSliceType(arg) {
v := reflect.ValueOf(arg)
return float64(v.Len()), nil
} else if c, ok := arg.(map[string]interface{}); ok {
return float64(len(c)), nil
}
return nil, errors.New("could not compute length()")
}
func jpfStartsWith(arguments []interface{}) (interface{}, error) {
search := arguments[0].(string)
prefix := arguments[1].(string)
return strings.HasPrefix(search, prefix), nil
}
func jpfAvg(arguments []interface{}) (interface{}, error) {
// We've already type checked the value so we can safely use
// type assertions.
args := arguments[0].([]interface{})
length := float64(len(args))
numerator := 0.0
for _, n := range args {
numerator += n.(float64)
}
return numerator / length, nil
}
func jpfCeil(arguments []interface{}) (interface{}, error) {
val := arguments[0].(float64)
return math.Ceil(val), nil
}
func jpfContains(arguments []interface{}) (interface{}, error) {
search := arguments[0]
el := arguments[1]
if searchStr, ok := search.(string); ok {
if elStr, ok := el.(string); ok {
return strings.Index(searchStr, elStr) != -1, nil
}
return false, nil
}
// Otherwise this is a generic contains for []interface{}
general := search.([]interface{})
for _, item := range general {
if item == el {
return true, nil
}
}
return false, nil
}
func jpfEndsWith(arguments []interface{}) (interface{}, error) {
search := arguments[0].(string)
suffix := arguments[1].(string)
return strings.HasSuffix(search, suffix), nil
}
func jpfFloor(arguments []interface{}) (interface{}, error) {
val := arguments[0].(float64)
return math.Floor(val), nil
}
func jpfMap(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
exp := arguments[1].(expRef)
node := exp.ref
arr := arguments[2].([]interface{})
mapped := make([]interface{}, 0, len(arr))
for _, value := range arr {
current, err := intr.Execute(node, value)
if err != nil {
return nil, err
}
mapped = append(mapped, current)
}
return mapped, nil
}
func jpfMax(arguments []interface{}) (interface{}, error) {
if items, ok := toArrayNum(arguments[0]); ok {
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item > best {
best = item
}
}
return best, nil
}
// Otherwise we're dealing with a max() of strings.
items, _ := toArrayStr(arguments[0])
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item > best {
best = item
}
}
return best, nil
}
func jpfMerge(arguments []interface{}) (interface{}, error) {
final := make(map[string]interface{})
for _, m := range arguments {
mapped := m.(map[string]interface{})
for key, value := range mapped {
final[key] = value
}
}
return final, nil
}
func jpfMaxBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return nil, nil
} else if len(arr) == 1 {
return arr[0], nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
switch t := start.(type) {
case float64:
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(float64)
if !ok {
return nil, errors.New("invalid type, must be number")
}
if current > bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
case string:
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(string)
if !ok {
return nil, errors.New("invalid type, must be string")
}
if current > bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
default:
return nil, errors.New("invalid type, must be number of string")
}
}
func jpfSum(arguments []interface{}) (interface{}, error) {
items, _ := toArrayNum(arguments[0])
sum := 0.0
for _, item := range items {
sum += item
}
return sum, nil
}
func jpfMin(arguments []interface{}) (interface{}, error) {
if items, ok := toArrayNum(arguments[0]); ok {
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item < best {
best = item
}
}
return best, nil
}
items, _ := toArrayStr(arguments[0])
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item < best {
best = item
}
}
return best, nil
}
func jpfMinBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return nil, nil
} else if len(arr) == 1 {
return arr[0], nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
if t, ok := start.(float64); ok {
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(float64)
if !ok {
return nil, errors.New("invalid type, must be number")
}
if current < bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
} else if t, ok := start.(string); ok {
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(string)
if !ok {
return nil, errors.New("invalid type, must be string")
}
if current < bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
} else {
return nil, errors.New("invalid type, must be number of string")
}
}
func jpfType(arguments []interface{}) (interface{}, error) {
arg := arguments[0]
if _, ok := arg.(float64); ok {
return "number", nil
}
if _, ok := arg.(string); ok {
return "string", nil
}
if _, ok := arg.([]interface{}); ok {
return "array", nil
}
if _, ok := arg.(map[string]interface{}); ok {
return "object", nil
}
if arg == nil {
return "null", nil
}
if arg == true || arg == false {
return "boolean", nil
}
return nil, errors.New("unknown type")
}
func jpfKeys(arguments []interface{}) (interface{}, error) {
arg := arguments[0].(map[string]interface{})
collected := make([]interface{}, 0, len(arg))
for key := range arg {
collected = append(collected, key)
}
return collected, nil
}
func jpfValues(arguments []interface{}) (interface{}, error) {
arg := arguments[0].(map[string]interface{})
collected := make([]interface{}, 0, len(arg))
for _, value := range arg {
collected = append(collected, value)
}
return collected, nil
}
func jpfSort(arguments []interface{}) (interface{}, error) {
if items, ok := toArrayNum(arguments[0]); ok {
d := sort.Float64Slice(items)
sort.Stable(d)
final := make([]interface{}, len(d))
for i, val := range d {
final[i] = val
}
return final, nil
}
// Otherwise we're dealing with sort()'ing strings.
items, _ := toArrayStr(arguments[0])
d := sort.StringSlice(items)
sort.Stable(d)
final := make([]interface{}, len(d))
for i, val := range d {
final[i] = val
}
return final, nil
}
func jpfSortBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return arr, nil
} else if len(arr) == 1 {
return arr, nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
if _, ok := start.(float64); ok {
sortable := &byExprFloat{intr, node, arr, false}
sort.Stable(sortable)
if sortable.hasError {
return nil, errors.New("error in sort_by comparison")
}
return arr, nil
} else if _, ok := start.(string); ok {
sortable := &byExprString{intr, node, arr, false}
sort.Stable(sortable)
if sortable.hasError {
return nil, errors.New("error in sort_by comparison")
}
return arr, nil
} else {
return nil, errors.New("invalid type, must be number of string")
}
}
func jpfJoin(arguments []interface{}) (interface{}, error) {
sep := arguments[0].(string)
// We can't just do arguments[1].([]string), we have to
// manually convert each item to a string.
arrayStr := []string{}
for _, item := range arguments[1].([]interface{}) {
arrayStr = append(arrayStr, item.(string))
}
return strings.Join(arrayStr, sep), nil
}
func jpfReverse(arguments []interface{}) (interface{}, error) {
if s, ok := arguments[0].(string); ok {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r), nil
}
items := arguments[0].([]interface{})
length := len(items)
reversed := make([]interface{}, length)
for i, item := range items {
reversed[length-(i+1)] = item
}
return reversed, nil
}
func jpfToArray(arguments []interface{}) (interface{}, error) {
if _, ok := arguments[0].([]interface{}); ok {
return arguments[0], nil
}
return arguments[:1:1], nil
}
func jpfToString(arguments []interface{}) (interface{}, error) {
if v, ok := arguments[0].(string); ok {
return v, nil
}
result, err := json.Marshal(arguments[0])
if err != nil {
return nil, err
}
return string(result), nil
}
func jpfToNumber(arguments []interface{}) (interface{}, error) {
arg := arguments[0]
if v, ok := arg.(float64); ok {
return v, nil
}
if v, ok := arg.(string); ok {
conv, err := strconv.ParseFloat(v, 64)
if err != nil {
return nil, nil
}
return conv, nil
}
if _, ok := arg.([]interface{}); ok {
return nil, nil
}
if _, ok := arg.(map[string]interface{}); ok {
return nil, nil
}
if arg == nil {
return nil, nil
}
if arg == true || arg == false {
return nil, nil
}
return nil, errors.New("unknown type")
}
func jpfNotNull(arguments []interface{}) (interface{}, error) {
for _, arg := range arguments {
if arg != nil {
return arg, nil
}
}
return nil, nil
}
| {
"pile_set_name": "Github"
} |
/****************************************************************************
*
* Copyright 2018 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <iterator>
// back_insert_iterator
// requires CopyConstructible<Cont::value_type>
// back_insert_iterator<Cont>&
// operator=(const Cont::value_type& value);
#include <iterator>
#include <vector>
#include <cassert>
#include "test_macros.h"
#include "libcxx_tc_common.h"
template <class C>
static int
test(C c)
{
const typename C::value_type v = typename C::value_type();
std::back_insert_iterator<C> i(c);
i = v;
TC_ASSERT_EXPR(c.back() == v);
return 0;
}
class Copyable
{
int data_;
public:
Copyable() : data_(0) {}
~Copyable() {data_ = -1;}
friend bool operator==(const Copyable& x, const Copyable& y)
{return x.data_ == y.data_;}
};
int tc_libcxx_iterators_back_insert_iter_op__lv_value(void)
{
TC_ASSERT_FUNC((test(std::vector<Copyable>())));
TC_SUCCESS_RESULT();
return 0;
}
| {
"pile_set_name": "Github"
} |
.title {
margin-top: 10px;
font-size: 16px;
}
| {
"pile_set_name": "Github"
} |
lychee.define('harvester.data.Git').tags({
platform: 'node'
}).requires([
'harvester.data.Filesystem'
]).supports((lychee, global) => {
try {
require('child_process');
require('path');
return true;
} catch (err) {
}
return false;
}).exports((lychee, global, attachments) => {
const _ROOT = lychee.ROOT.lychee;
const _Filesystem = lychee.import('harvester.data.Filesystem');
const _child_process = require('child_process');
const _path = require('path');
/*
* HELPERS
*/
const _parse_remotes = function(content) {
let remotes = {};
let pointer = null;
content.split('\n').map(line => {
if (line.startsWith('[remote')) {
let tmp = line.split('"')[1] || null;
if (tmp !== null) {
pointer = remotes[tmp] = {
url: null,
fetch: null
};
} else {
pointer = null;
}
} else if (pointer !== null) {
let tmp = line.trim().split('=').map(val => val.trim());
if (tmp[0] === 'url') {
pointer.url = tmp[1];
} else if (tmp[0] === 'fetch') {
pointer.fetch = tmp[1];
}
}
});
return remotes;
};
const _parse_log = function(content) {
return content.split('\n').map(line => {
return line.substr(line.indexOf(' ') + 1).trim();
}).filter(line => line !== '').map(line => {
let hash = line.substr(0, line.indexOf(' '));
line = line.substr(hash.length + 1);
let name = line.substr(0, line.indexOf('<') - 1);
line = line.substr(name.length + 1);
let email = line.substr(1, line.indexOf('>') - 1);
line = line.substr(email.length + 3);
let timestamp = line.substr(0, line.indexOf('\t'));
line = line.substr(timestamp.length + 1);
let message = line.trim();
return {
hash: hash,
name: name,
email: email,
timestamp: timestamp,
message: message
};
});
};
const _parse_status = function(content) {
let ahead = 0;
let changes = [];
let branch = null;
content.split('\n').filter(line => line.trim()).map(line => {
let state = line.substr(0, 2);
let path = line.substr(2).trim();
if (state === '##') {
if (path.includes('...')) {
let tmp1 = path.split('...');
if (tmp1.length === 2) {
branch = tmp1[0];
}
let tmp2 = tmp1[1].substr(tmp1[1].indexOf(' ')).trim();
let tmp3 = tmp2.split(/\[ahead\s([0-9]+)]/g);
if (tmp3.length === 3) {
let tmp4 = parseInt(tmp3[1], 10);
if (!isNaN(tmp4)) {
ahead = tmp4;
}
}
} else {
branch = path;
}
} else if (path.length > 0) {
if (path.startsWith('./')) {
path = path.substr(1);
}
if (path.charAt(0) !== '/') {
path = '/' + path;
}
changes.push({
state: state,
path: path
});
}
});
return {
branch: branch,
ahead: ahead,
changes: changes
};
};
const _get_log = function() {
let development = _parse_log((this.filesystem.read('/logs/refs/remotes/origin/development') || '').toString('utf8'));
let master = _parse_log((this.filesystem.read('/logs/refs/remotes/origin/master') || '').toString('utf8'));
let branch = _parse_log((this.filesystem.read('/logs/HEAD') || '').toString('utf8'));
let diff = branch.filter(commit => {
let is_master = master.find(other => other.hash === commit.hash);
let is_development = development.find(other => other.hash === commit.hash);
if (is_master === false && is_development === false) {
return true;
}
return false;
});
return {
master: master,
development: development,
branch: branch,
diff: diff
};
};
/*
* IMPLEMENTATION
*/
const Composite = function(data) {
let states = Object.assign({}, data);
this.identifier = typeof states.identifier === 'string' ? states.identifier : '';
this.filesystem = new _Filesystem({
root: this.identifier + '/.git'
});
states = null;
};
Composite.STATUS = {
ignore: 0,
update: 1,
manual: 2
};
Composite.prototype = {
/*
* ENTITY API
*/
deserialize: function(blob) {
if (blob.filesystem instanceof Object) {
this.filesystem = lychee.deserialize(blob.filesystem);
}
},
serialize: function() {
let states = {};
let blob = {};
if (this.identifier !== '') states.identifier = this.identifier;
if (this.filesystem !== null) blob.filesystem = lychee.serialize(this.filesystem);
return {
'constructor': 'harvester.data.Git',
'arguments': [ states ],
'blob': Object.keys(blob).length > 0 ? blob : null
};
},
/*
* CUSTOM API
*/
checkout: function(branch, path) {
branch = typeof branch === 'string' ? branch : null;
path = typeof path === 'string' ? path : null;
if (branch !== null && path !== null) {
let filesystem = this.filesystem;
let result = null;
try {
let cwd = _ROOT;
let root = _ROOT + path;
let tmp = filesystem.root.split('/');
if (tmp.pop() === '.git') {
cwd = tmp.join('/');
}
let real = _path.relative(cwd, root);
if (real.startsWith('..') === false) {
let handle = _child_process.spawnSync('git', [
'checkout',
'--quiet',
'origin/' + branch,
'./' + real
], {
cwd: cwd
});
let stdout = (handle.stdout || '').toString().trim();
let stderr = (handle.stderr || '').toString().trim();
if (stderr !== '') {
result = null;
} else {
result = stdout;
}
}
} catch (err) {
console.error(err.message);
result = null;
}
return result !== null;
}
return false;
},
fetch: function(remote, branch) {
remote = typeof remote === 'string' ? remote : 'upstream';
branch = typeof branch === 'string' ? branch : 'development';
if (remote !== null && branch !== null) {
let filesystem = this.filesystem;
let result = null;
try {
let cwd = _ROOT;
let tmp = filesystem.root.split('/');
if (tmp.pop() === '.git') {
cwd = tmp.join('/');
}
result = _child_process.execSync('git fetch --quiet ' + remote + ' "' + branch + '"', {
cwd: cwd
}).toString();
} catch (err) {
result = null;
}
return result !== null;
}
return false;
},
config: function() {
let config = (this.filesystem.read('/config') || '').toString().trim();
let remotes = _parse_remotes(config);
return {
remotes: remotes
};
},
report: function() {
let head = (this.filesystem.read('/HEAD') || '').toString().trim();
let fetch_head = (this.filesystem.read('/FETCH_HEAD') || '').toString().trim();
let orig_head = (this.filesystem.read('/ORIG_HEAD') || '').toString().trim();
let branch = 'master';
if (head.startsWith('ref: ')) {
if (head.startsWith('ref: refs/heads/')) {
branch = head.substr(16).trim();
}
let ref = this.filesystem.read('/' + head.substr(5));
if (ref !== null) {
head = ref.toString().trim();
}
}
if (fetch_head.includes('\t')) {
fetch_head = fetch_head.split('\t')[0];
}
let log = _get_log.call(this);
let status = Composite.STATUS.manual;
if (log.diff.length === 0) {
if (head === fetch_head) {
status = Composite.STATUS.ignore;
} else {
let check = log.development.find(other => other.hash === head);
if (check !== undefined) {
status = Composite.STATUS.update;
} else {
status = Composite.STATUS.manual;
}
}
// XXX: Verify that user did not break their git history
if (fetch_head !== orig_head) {
let check = log.development.find(other => other.hash === orig_head);
if (check !== undefined) {
status = Composite.STATUS.update;
} else {
status = Composite.STATUS.manual;
}
}
} else {
status = Composite.STATUS.manual;
}
return {
branch: branch,
log: log,
status: status,
head: {
branch: head,
fetch: fetch_head,
origin: orig_head
}
};
},
status: function() {
let filesystem = this.filesystem;
let result = null;
try {
let root = _ROOT;
let tmp = filesystem.root.split('/');
if (tmp.pop() === '.git') {
if (tmp.length > 0) {
root = _ROOT + '/' + tmp.join('/');
}
}
let handle = _child_process.spawnSync('git', [
'status',
'-b',
'--porcelain'
], {
cwd: root
});
let stdout = (handle.stdout || '').toString().trim();
let stderr = (handle.stderr || '').toString().trim();
if (stderr !== '') {
result = null;
} else {
result = stdout;
}
} catch (err) {
result = null;
}
if (result !== null) {
return _parse_status(result);
}
return null;
}
};
return Composite;
});
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u092e.\u092a\u0942.",
"\u092e.\u0909."
],
"DAY": [
"\u0930\u0935\u093f\u0935\u093e\u0930",
"\u0938\u094b\u092e\u0935\u093e\u0930",
"\u092e\u0902\u0917\u0933\u0935\u093e\u0930",
"\u092c\u0941\u0927\u0935\u093e\u0930",
"\u0917\u0941\u0930\u0941\u0935\u093e\u0930",
"\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930",
"\u0936\u0928\u093f\u0935\u093e\u0930"
],
"ERANAMES": [
"\u0908\u0938\u0935\u0940\u0938\u0928\u092a\u0942\u0930\u094d\u0935",
"\u0908\u0938\u0935\u0940\u0938\u0928"
],
"ERAS": [
"\u0907. \u0938. \u092a\u0942.",
"\u0907. \u0938."
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940",
"\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u090f\u092a\u094d\u0930\u093f\u0932",
"\u092e\u0947",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u0948",
"\u0911\u0917\u0938\u094d\u091f",
"\u0938\u092a\u094d\u091f\u0947\u0902\u092c\u0930",
"\u0911\u0915\u094d\u091f\u094b\u092c\u0930",
"\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930",
"\u0921\u093f\u0938\u0947\u0902\u092c\u0930"
],
"SHORTDAY": [
"\u0930\u0935\u093f",
"\u0938\u094b\u092e",
"\u092e\u0902\u0917\u0933",
"\u092c\u0941\u0927",
"\u0917\u0941\u0930\u0941",
"\u0936\u0941\u0915\u094d\u0930",
"\u0936\u0928\u093f"
],
"SHORTMONTH": [
"\u091c\u093e\u0928\u0947",
"\u092b\u0947\u092c\u094d\u0930\u0941",
"\u092e\u093e\u0930\u094d\u091a",
"\u090f\u092a\u094d\u0930\u093f",
"\u092e\u0947",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u0948",
"\u0911\u0917",
"\u0938\u092a\u094d\u091f\u0947\u0902",
"\u0911\u0915\u094d\u091f\u094b",
"\u0928\u094b\u0935\u094d\u0939\u0947\u0902",
"\u0921\u093f\u0938\u0947\u0902"
],
"STANDALONEMONTH": [
"\u091c\u093e\u0928\u0947\u0935\u093e\u0930\u0940",
"\u092b\u0947\u092c\u094d\u0930\u0941\u0935\u093e\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u090f\u092a\u094d\u0930\u093f\u0932",
"\u092e\u0947",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u0948",
"\u0911\u0917\u0938\u094d\u091f",
"\u0938\u092a\u094d\u091f\u0947\u0902\u092c\u0930",
"\u0911\u0915\u094d\u091f\u094b\u092c\u0930",
"\u0928\u094b\u0935\u094d\u0939\u0947\u0902\u092c\u0930",
"\u0921\u093f\u0938\u0947\u0902\u092c\u0930"
],
"WEEKENDRANGE": [
6,
6
],
"fullDate": "EEEE, d MMMM, y",
"longDate": "d MMMM, y",
"medium": "d MMM, y h:mm:ss a",
"mediumDate": "d MMM, y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "mr",
"localeID": "mr",
"pluralCat": function(n, opt_precision) { var i = n | 0; if (i == 0 || n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sync/driver/model_associator_mock.h"
namespace syncer {
ModelAssociatorMock::ModelAssociatorMock() {}
ModelAssociatorMock::~ModelAssociatorMock() {}
} // namespace syncer
| {
"pile_set_name": "Github"
} |
<?php
use PayPal\Core\PPConfigManager;
/**
* Test class for PPConfigManager.
*
*/
class PPConfigManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var PPConfigManager
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->object = PPConfigManager::getInstance();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown()
{
}
/**
* @test
*/
public function testGetInstance()
{
$instance = $this->object->getInstance();
$this->assertTrue($instance instanceof PPConfigManager);
}
/**
* @test
*/
public function testGet()
{
$ret = $this->object->get('acct1');
$this->assertContains('jb-us-seller_api1.paypal.com', $ret);
$this->assertArrayHasKey('acct1.UserName', $ret);
$this->assertTrue(sizeof($ret) == 7);
$ret = $this->object->get('acct1.UserName');
$this->assertEquals('jb-us-seller_api1.paypal.com', $ret);
$ret = $this->object->get("acct");
$this->assertEquals(sizeof($ret), 10);
}
/**
* @test
*/
public function testGetIniPrefix()
{
$ret = $this->object->getIniPrefix();
$this->assertContains('acct1', $ret);
$this->assertEquals(sizeof($ret), 2);
$ret = $this->object->getIniPrefix('jb-us-seller_api1.paypal.com');
$this->assertEquals('acct1', $ret);
}
/**
* @test
*/
public function testMergeWithDefaults()
{
// Test file based config params and defaults
$config = PPConfigManager::getInstance()->getConfigWithDefaults(array());
$this->assertArrayHasKey('mode', $config, 'file config not read when no custom config is passed');
$this->assertEquals('sandbox', $config['mode']);
$this->assertEquals(60, $config['http.ConnectionTimeOut']);
// Test custom config params and defaults
$config = PPConfigManager::getInstance()->getConfigWithDefaults(array('mode' => 'custom'));
$this->assertArrayHasKey('mode', $config);
$this->assertEquals('custom', $config['mode']);
$this->assertEquals(30, $config['http.ConnectionTimeOut']);
// Test override for default connection params
$config = PPConfigManager::getInstance()->getConfigWithDefaults(
array('mode' => 'custom', 'http.ConnectionTimeOut' => 100));
$this->assertArrayHasKey('mode', $config);
$this->assertEquals('custom', $config['mode']);
$this->assertEquals(100, $config['http.ConnectionTimeOut']);
}
}
?>
| {
"pile_set_name": "Github"
} |
#!/bin/bash
echo "Creating Cassandra"
echo -e "Configuring vars"
exp=$(bx cs cluster-config "$CLUSTER_NAME" | grep export)
if ! bx cs cluster-config "$CLUSTER_NAME" | grep export ; then
echo "Cluster $CLUSTER_NAME not created or not ready."
exit 1
fi
eval "$exp"
echo -e "Deleting previous version of Cassandra if it exists"
kubectl delete --ignore-not-found=true -f cassandra-service.yaml
kubectl delete --ignore-not-found=true -f cassandra-controller.yaml
kubectl delete --ignore-not-found=true -f cassandra-statefulset.yaml
kubectl delete --ignore-not-found=true -f local-volumes.yaml
kuber=$(kubectl get pods -l app=cassandra)
while [ ${#kuber} -ne 0 ]
do
sleep 5s
kubectl get pods -l app=cassandra
kuber=$(kubectl get pods -l app=cassandra)
done
echo -e "Creating headless service..."
kubectl create -f cassandra-service.yaml
echo -e "Creating Replication Controller..."
kubectl create -f cassandra-controller.yaml
SEED_NODE=$(kubectl get pods | grep cassandra | awk '{print $1}')
echo "Seed node is ${SEED_NODE}"
echo "Waiting for Cassansdra Pod to initialize..."
sleep 30s
STATUS=$(kubectl exec "$SEED_NODE" -- nodetool status | grep UN)
while [ ${#STATUS} -eq 0 ]
do
echo "Waiting for Cassandra to finish setting up..."
sleep 10s
STATUS=$(kubectl exec "$SEED_NODE" -- nodetool status | grep UN)
done
echo "Cassandra Node is UP and NORMAL"
kubectl exec "$SEED_NODE" -- nodetool status
echo "Scaling the Replication Controller..."
kubectl scale rc cassandra --replicas=4
sleep 5s
TEST=$(kubectl exec "$SEED_NODE" -- nodetool status | grep UN | awk '{print $1}')
while [ "${#TEST}" != "11" ]
do
kubectl exec "$SEED_NODE" -- nodetool status
# echo ${#TEST}
echo "Waiting for all Cassandra nodes to join and set up."
sleep 5s
TEST=$(kubectl exec "$SEED_NODE" -- nodetool status | grep UN | awk '{print $1}')
done
echo "Your cassandra cluster is now up and normal"
kubectl exec "$SEED_NODE" -- nodetool status
echo "You can also view your Cassandra cluster on your machine"
echo "Export your cluster configuration on your terminal:"
echo "bx cs cluster-config <your-cluster-name> then copy the export line."
echo "Check the status of your Cassandra nodes"
echo "kubectl exec <pod-name> -- nodetool status"
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef sw_Polygon_hpp
#define sw_Polygon_hpp
#include "Vertex.hpp"
namespace sw {
struct Polygon
{
Polygon(const float4 *P0, const float4 *P1, const float4 *P2)
{
P[0][0] = P0;
P[0][1] = P1;
P[0][2] = P2;
n = 3;
i = 0;
b = 0;
}
Polygon(const float4 *P, int n)
{
for(int i = 0; i < n; i++)
{
this->P[0][i] = &P[i];
}
this->n = n;
this->i = 0;
this->b = 0;
}
float4 B[16]; // Buffer for clipped vertices
const float4 *P[16][16]; // Pointers to clipped polygon's vertices
int n; // Number of vertices
int i; // Level of P to use
int b; // Next available new vertex
};
} // namespace sw
#endif // sw_Polygon_hpp
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mojo/edk/system/channel.h"
#include <errno.h>
#include <sys/socket.h>
#include <algorithm>
#include <deque>
#include <limits>
#include <memory>
#include "base/bind.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop/message_loop.h"
#include "base/synchronization/lock.h"
#include "base/task_runner.h"
#include "mojo/edk/embedder/platform_channel_utils_posix.h"
#include "mojo/edk/embedder/platform_handle_vector.h"
#if !defined(OS_NACL)
#include <sys/uio.h>
#endif
namespace mojo {
namespace edk {
namespace {
const size_t kMaxBatchReadCapacity = 256 * 1024;
// A view over a Channel::Message object. The write queue uses these since
// large messages may need to be sent in chunks.
class MessageView {
public:
// Owns |message|. |offset| indexes the first unsent byte in the message.
MessageView(Channel::MessagePtr message, size_t offset)
: message_(std::move(message)),
offset_(offset),
handles_(message_->TakeHandlesForTransport()) {
DCHECK_GT(message_->data_num_bytes(), offset_);
}
MessageView(MessageView&& other) { *this = std::move(other); }
MessageView& operator=(MessageView&& other) {
message_ = std::move(other.message_);
offset_ = other.offset_;
handles_ = std::move(other.handles_);
return *this;
}
~MessageView() {}
const void* data() const {
return static_cast<const char*>(message_->data()) + offset_;
}
size_t data_num_bytes() const { return message_->data_num_bytes() - offset_; }
size_t data_offset() const { return offset_; }
void advance_data_offset(size_t num_bytes) {
DCHECK_GT(message_->data_num_bytes(), offset_ + num_bytes);
offset_ += num_bytes;
}
ScopedPlatformHandleVectorPtr TakeHandles() { return std::move(handles_); }
Channel::MessagePtr TakeMessage() { return std::move(message_); }
void SetHandles(ScopedPlatformHandleVectorPtr handles) {
handles_ = std::move(handles);
}
private:
Channel::MessagePtr message_;
size_t offset_;
ScopedPlatformHandleVectorPtr handles_;
DISALLOW_COPY_AND_ASSIGN(MessageView);
};
class ChannelPosix : public Channel,
public base::MessageLoop::DestructionObserver,
public base::MessageLoopForIO::Watcher {
public:
ChannelPosix(Delegate* delegate,
ScopedPlatformHandle handle,
scoped_refptr<base::TaskRunner> io_task_runner)
: Channel(delegate),
self_(this),
handle_(std::move(handle)),
io_task_runner_(io_task_runner)
#if defined(OS_MACOSX)
,
handles_to_close_(new PlatformHandleVector)
#endif
{
}
void Start() override {
if (io_task_runner_->RunsTasksOnCurrentThread()) {
StartOnIOThread();
} else {
io_task_runner_->PostTask(
FROM_HERE, base::Bind(&ChannelPosix::StartOnIOThread, this));
}
}
void ShutDownImpl() override {
// Always shut down asynchronously when called through the public interface.
io_task_runner_->PostTask(
FROM_HERE, base::Bind(&ChannelPosix::ShutDownOnIOThread, this));
}
void Write(MessagePtr message) override {
bool write_error = false;
{
base::AutoLock lock(write_lock_);
if (reject_writes_)
return;
if (outgoing_messages_.empty()) {
if (!WriteNoLock(MessageView(std::move(message), 0)))
reject_writes_ = write_error = true;
} else {
outgoing_messages_.emplace_back(std::move(message), 0);
}
}
if (write_error) {
// Do not synchronously invoke OnError(). Write() may have been called by
// the delegate and we don't want to re-enter it.
io_task_runner_->PostTask(FROM_HERE,
base::Bind(&ChannelPosix::OnError, this));
}
}
void LeakHandle() override {
DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
leak_handle_ = true;
}
bool GetReadPlatformHandles(
size_t num_handles,
const void* extra_header,
size_t extra_header_size,
ScopedPlatformHandleVectorPtr* handles) override {
if (num_handles > std::numeric_limits<uint16_t>::max())
return false;
#if defined(OS_MACOSX) && !defined(OS_IOS)
// On OSX, we can have mach ports which are located in the extra header
// section.
using MachPortsEntry = Channel::Message::MachPortsEntry;
using MachPortsExtraHeader = Channel::Message::MachPortsExtraHeader;
CHECK(extra_header_size >=
sizeof(MachPortsExtraHeader) + num_handles * sizeof(MachPortsEntry));
const MachPortsExtraHeader* mach_ports_header =
reinterpret_cast<const MachPortsExtraHeader*>(extra_header);
size_t num_mach_ports = mach_ports_header->num_ports;
CHECK(num_mach_ports <= num_handles);
if (incoming_platform_handles_.size() + num_mach_ports < num_handles) {
handles->reset();
return true;
}
handles->reset(new PlatformHandleVector(num_handles));
const MachPortsEntry* mach_ports = mach_ports_header->entries;
for (size_t i = 0, mach_port_index = 0; i < num_handles; ++i) {
if (mach_port_index < num_mach_ports &&
mach_ports[mach_port_index].index == i) {
(*handles)->at(i) = PlatformHandle(
static_cast<mach_port_t>(mach_ports[mach_port_index].mach_port));
CHECK((*handles)->at(i).type == PlatformHandle::Type::MACH);
// These are actually just Mach port names until they're resolved from
// the remote process.
(*handles)->at(i).type = PlatformHandle::Type::MACH_NAME;
mach_port_index++;
} else {
CHECK(!incoming_platform_handles_.empty());
(*handles)->at(i) = incoming_platform_handles_.front();
incoming_platform_handles_.pop_front();
}
}
#else
if (incoming_platform_handles_.size() < num_handles) {
handles->reset();
return true;
}
handles->reset(new PlatformHandleVector(num_handles));
for (size_t i = 0; i < num_handles; ++i) {
(*handles)->at(i) = incoming_platform_handles_.front();
incoming_platform_handles_.pop_front();
}
#endif
return true;
}
private:
~ChannelPosix() override {
DCHECK(!read_watcher_);
DCHECK(!write_watcher_);
for (auto handle : incoming_platform_handles_)
handle.CloseIfNecessary();
}
void StartOnIOThread() {
DCHECK(!read_watcher_);
DCHECK(!write_watcher_);
read_watcher_.reset(new base::MessageLoopForIO::FileDescriptorWatcher);
base::MessageLoop::current()->AddDestructionObserver(this);
if (handle_.get().needs_connection) {
base::MessageLoopForIO::current()->WatchFileDescriptor(
handle_.get().handle, false /* persistent */,
base::MessageLoopForIO::WATCH_READ, read_watcher_.get(), this);
} else {
write_watcher_.reset(new base::MessageLoopForIO::FileDescriptorWatcher);
base::MessageLoopForIO::current()->WatchFileDescriptor(
handle_.get().handle, true /* persistent */,
base::MessageLoopForIO::WATCH_READ, read_watcher_.get(), this);
base::AutoLock lock(write_lock_);
FlushOutgoingMessagesNoLock();
}
}
void WaitForWriteOnIOThread() {
base::AutoLock lock(write_lock_);
WaitForWriteOnIOThreadNoLock();
}
void WaitForWriteOnIOThreadNoLock() {
if (pending_write_)
return;
if (!write_watcher_)
return;
if (io_task_runner_->RunsTasksOnCurrentThread()) {
pending_write_ = true;
base::MessageLoopForIO::current()->WatchFileDescriptor(
handle_.get().handle, false /* persistent */,
base::MessageLoopForIO::WATCH_WRITE, write_watcher_.get(), this);
} else {
io_task_runner_->PostTask(
FROM_HERE, base::Bind(&ChannelPosix::WaitForWriteOnIOThread, this));
}
}
void ShutDownOnIOThread() {
base::MessageLoop::current()->RemoveDestructionObserver(this);
read_watcher_.reset();
write_watcher_.reset();
if (leak_handle_)
ignore_result(handle_.release());
handle_.reset();
#if defined(OS_MACOSX)
handles_to_close_.reset();
#endif
// May destroy the |this| if it was the last reference.
self_ = nullptr;
}
// base::MessageLoop::DestructionObserver:
void WillDestroyCurrentMessageLoop() override {
DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
if (self_)
ShutDownOnIOThread();
}
// base::MessageLoopForIO::Watcher:
void OnFileCanReadWithoutBlocking(int fd) override {
CHECK_EQ(fd, handle_.get().handle);
if (handle_.get().needs_connection) {
#if !defined(OS_NACL)
read_watcher_.reset();
base::MessageLoop::current()->RemoveDestructionObserver(this);
ScopedPlatformHandle accept_fd;
ServerAcceptConnection(handle_.get(), &accept_fd);
if (!accept_fd.is_valid()) {
OnError();
return;
}
handle_ = std::move(accept_fd);
StartOnIOThread();
#else
NOTREACHED();
#endif
return;
}
bool read_error = false;
size_t next_read_size = 0;
size_t buffer_capacity = 0;
size_t total_bytes_read = 0;
size_t bytes_read = 0;
do {
buffer_capacity = next_read_size;
char* buffer = GetReadBuffer(&buffer_capacity);
DCHECK_GT(buffer_capacity, 0u);
ssize_t read_result = PlatformChannelRecvmsg(
handle_.get(),
buffer,
buffer_capacity,
&incoming_platform_handles_);
if (read_result > 0) {
bytes_read = static_cast<size_t>(read_result);
total_bytes_read += bytes_read;
if (!OnReadComplete(bytes_read, &next_read_size)) {
read_error = true;
break;
}
} else if (read_result == 0 ||
(errno != EAGAIN && errno != EWOULDBLOCK)) {
read_error = true;
break;
}
} while (bytes_read == buffer_capacity &&
total_bytes_read < kMaxBatchReadCapacity &&
next_read_size > 0);
if (read_error) {
// Stop receiving read notifications.
read_watcher_.reset();
OnError();
}
}
void OnFileCanWriteWithoutBlocking(int fd) override {
bool write_error = false;
{
base::AutoLock lock(write_lock_);
pending_write_ = false;
if (!FlushOutgoingMessagesNoLock())
reject_writes_ = write_error = true;
}
if (write_error)
OnError();
}
// Attempts to write a message directly to the channel. If the full message
// cannot be written, it's queued and a wait is initiated to write the message
// ASAP on the I/O thread.
bool WriteNoLock(MessageView message_view) {
if (handle_.get().needs_connection) {
outgoing_messages_.emplace_front(std::move(message_view));
return true;
}
size_t bytes_written = 0;
do {
message_view.advance_data_offset(bytes_written);
ssize_t result;
ScopedPlatformHandleVectorPtr handles = message_view.TakeHandles();
if (handles && handles->size()) {
iovec iov = {
const_cast<void*>(message_view.data()),
message_view.data_num_bytes()
};
// TODO: Handle lots of handles.
result = PlatformChannelSendmsgWithHandles(
handle_.get(), &iov, 1, handles->data(), handles->size());
if (result >= 0) {
#if defined(OS_MACOSX)
// There is a bug on OSX which makes it dangerous to close
// a file descriptor while it is in transit. So instead we
// store the file descriptor in a set and send a message to
// the recipient, which is queued AFTER the message that
// sent the FD. The recipient will reply to the message,
// letting us know that it is now safe to close the file
// descriptor. For more information, see:
// http://crbug.com/298276
std::vector<int> fds;
for (auto& handle : *handles)
fds.push_back(handle.handle);
{
base::AutoLock l(handles_to_close_lock_);
for (auto& handle : *handles)
handles_to_close_->push_back(handle);
}
MessagePtr fds_message(
new Channel::Message(sizeof(fds[0]) * fds.size(), 0,
Message::Header::MessageType::HANDLES_SENT));
memcpy(fds_message->mutable_payload(), fds.data(),
sizeof(fds[0]) * fds.size());
outgoing_messages_.emplace_back(std::move(fds_message), 0);
handles->clear();
#else
handles.reset();
#endif // defined(OS_MACOSX)
}
} else {
result = PlatformChannelWrite(handle_.get(), message_view.data(),
message_view.data_num_bytes());
}
if (result < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK
#if defined(OS_MACOSX)
// On OS X if sendmsg() is trying to send fds between processes and
// there isn't enough room in the output buffer to send the fd
// structure over atomically then EMSGSIZE is returned.
//
// EMSGSIZE presents a problem since the system APIs can only call
// us when there's room in the socket buffer and not when there is
// "enough" room.
//
// The current behavior is to return to the event loop when EMSGSIZE
// is received and hopefull service another FD. This is however
// still technically a busy wait since the event loop will call us
// right back until the receiver has read enough data to allow
// passing the FD over atomically.
&& errno != EMSGSIZE
#endif
) {
return false;
}
message_view.SetHandles(std::move(handles));
outgoing_messages_.emplace_front(std::move(message_view));
WaitForWriteOnIOThreadNoLock();
return true;
}
bytes_written = static_cast<size_t>(result);
} while (bytes_written < message_view.data_num_bytes());
return FlushOutgoingMessagesNoLock();
}
bool FlushOutgoingMessagesNoLock() {
std::deque<MessageView> messages;
std::swap(outgoing_messages_, messages);
while (!messages.empty()) {
if (!WriteNoLock(std::move(messages.front())))
return false;
messages.pop_front();
if (!outgoing_messages_.empty()) {
// The message was requeued by WriteNoLock(), so we have to wait for
// pipe to become writable again. Repopulate the message queue and exit.
// If sending the message triggered any control messages, they may be
// in |outgoing_messages_| in addition to or instead of the message
// being sent.
std::swap(messages, outgoing_messages_);
while (!messages.empty()) {
outgoing_messages_.push_front(std::move(messages.back()));
messages.pop_back();
}
return true;
}
}
return true;
}
#if defined(OS_MACOSX)
bool OnControlMessage(Message::Header::MessageType message_type,
const void* payload,
size_t payload_size,
ScopedPlatformHandleVectorPtr handles) override {
switch (message_type) {
case Message::Header::MessageType::HANDLES_SENT: {
if (payload_size == 0)
break;
MessagePtr message(new Channel::Message(
payload_size, 0, Message::Header::MessageType::HANDLES_SENT_ACK));
memcpy(message->mutable_payload(), payload, payload_size);
Write(std::move(message));
return true;
}
case Message::Header::MessageType::HANDLES_SENT_ACK: {
size_t num_fds = payload_size / sizeof(int);
if (num_fds == 0 || payload_size % sizeof(int) != 0)
break;
const int* fds = reinterpret_cast<const int*>(payload);
if (!CloseHandles(fds, num_fds))
break;
return true;
}
default:
break;
}
return false;
}
// Closes handles referenced by |fds|. Returns false if |num_fds| is 0, or if
// |fds| does not match a sequence of handles in |handles_to_close_|.
bool CloseHandles(const int* fds, size_t num_fds) {
base::AutoLock l(handles_to_close_lock_);
if (!num_fds)
return false;
auto start =
std::find_if(handles_to_close_->begin(), handles_to_close_->end(),
[&fds](const PlatformHandle& handle) {
return handle.handle == fds[0];
});
if (start == handles_to_close_->end())
return false;
auto it = start;
size_t i = 0;
// The FDs in the message should match a sequence of handles in
// |handles_to_close_|.
for (; i < num_fds && it != handles_to_close_->end(); i++, ++it) {
if (it->handle != fds[i])
return false;
it->CloseIfNecessary();
}
if (i != num_fds)
return false;
handles_to_close_->erase(start, it);
return true;
}
#endif // defined(OS_MACOSX)
// Keeps the Channel alive at least until explicit shutdown on the IO thread.
scoped_refptr<Channel> self_;
ScopedPlatformHandle handle_;
scoped_refptr<base::TaskRunner> io_task_runner_;
// These watchers must only be accessed on the IO thread.
std::unique_ptr<base::MessageLoopForIO::FileDescriptorWatcher> read_watcher_;
std::unique_ptr<base::MessageLoopForIO::FileDescriptorWatcher> write_watcher_;
std::deque<PlatformHandle> incoming_platform_handles_;
// Protects |pending_write_| and |outgoing_messages_|.
base::Lock write_lock_;
bool pending_write_ = false;
bool reject_writes_ = false;
std::deque<MessageView> outgoing_messages_;
bool leak_handle_ = false;
#if defined(OS_MACOSX)
base::Lock handles_to_close_lock_;
ScopedPlatformHandleVectorPtr handles_to_close_;
#endif
DISALLOW_COPY_AND_ASSIGN(ChannelPosix);
};
} // namespace
// static
scoped_refptr<Channel> Channel::Create(
Delegate* delegate,
ScopedPlatformHandle platform_handle,
scoped_refptr<base::TaskRunner> io_task_runner) {
return new ChannelPosix(delegate, std::move(platform_handle), io_task_runner);
}
} // namespace edk
} // namespace mojo
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This file exists to enforce this clientset's vanity import path.
package kubernetes // import "k8s.io/client-go/kubernetes"
| {
"pile_set_name": "Github"
} |
import copy
configs = dict()
config = dict(
algo=dict(
replay_filepath=None,
delta_T=3,
batch_T=1,
batch_B=512,
learning_rate=1e-3,
learning_rate_anneal="cosine", # cosine
learning_rate_warmup=1000, # number of updates
clip_grad_norm=10.,
target_update_tau=0.01, # 1 for hard update
target_update_interval=1,
latent_size=256,
anchor_hidden_sizes=512,
random_shift_prob=0.1,
random_shift_pad=4,
activation_loss_coefficient=0., # rarely if ever use
validation_split=0.0,
n_validation_batches=0, # usually don't do it.
),
encoder=dict(
channels=[32, 64, 64],
kernel_sizes=[8, 4, 3],
strides=[4, 2, 1],
paddings=None,
hidden_sizes=None,
kiaming_init=True,
),
optim=dict(
weight_decay=0,
),
runner=dict(
n_updates=int(2e4), # 20k Usually sufficient for one game?
log_interval_updates=int(1e3),
),
name="atari_ats", # probably change this with the filepath
)
configs["atari_ats"] = config
| {
"pile_set_name": "Github"
} |
//
// APTError.m
// Limitless
//
// Created on 12/18/16.
//
#import "APTError.h"
NSErrorDomain const APTErrorDomain = @"APTErrorDomain";
NSErrorDomain const APTWarningDomain = @"APTWarningDomain";
@implementation APTError
+ (instancetype)unknownErrorWithMessage:(NSString *)errorMessage {
NSErrorDomain domain = APTErrorDomain;
NSInteger code = APTErrorUnknown;
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: errorMessage };
return [self errorWithDomain:domain code:code userInfo:userInfo];
}
@end
| {
"pile_set_name": "Github"
} |
1
122
161
232
392
692
810
1110
| {
"pile_set_name": "Github"
} |
// Copyright 2018 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package manifold_test
import (
"testing"
gc "gopkg.in/check.v1"
)
func TestPackage(t *testing.T) {
gc.TestingT(t)
}
| {
"pile_set_name": "Github"
} |
title: Posts
---
## Create a Post
``` js
hexo.post.create(data, replace);
```
Argument | Description
--- | ---
`data` | Data
`replace` | Replace existing files
The attributes of a post can be defined in `data`. The table below is not exhaustive. Additional attributes may be appended to the front-matter.
Data | Description
--- | ---
`title` | Title
`slug` | URL
`layout` | Layout. Defaults to the `default_layout` setting.
`path` | Path. Hexo builds the post path based on the `new_post_path` setting by default.
`date` | Date. Defaults to the current date.
## Publish a Draft
``` js
hexo.post.publish(data, replace);
```
Argument | Description
--- | ---
`data` | Data
`replace` | Replace existing files
The attributes of a post can be defined in `data`. The table below is not exhaustive. Additional attributes may be appended to the front-matter.
Data | Description
--- | ---
`slug` | File name (Required)
`layout` | Layout. Defaults to the `default_layout` setting.
## Render
``` js
hexo.post.render(source, data);
```
Argument | Description
--- | ---
`source` | Full path of a file (Optional)
`data` | Data
The data must contain the `content` attribute. If not, Hexo will try to read the original file. The execution steps of this function are as follows:
- Execute `before_post_render` filters
- Render with Markdown or other renderers (depending on the extension name)
- Render with [Nunjucks]
- Execute `after_post_render` filters
[Nunjucks]: http://mozilla.github.io/nunjucks/
| {
"pile_set_name": "Github"
} |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
package securitycenter
import (
"context"
"fmt"
"math"
"net/url"
"time"
"cloud.google.com/go/longrunning"
lroauto "cloud.google.com/go/longrunning/autogen"
"github.com/golang/protobuf/proto"
emptypb "github.com/golang/protobuf/ptypes/empty"
gax "github.com/googleapis/gax-go/v2"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
gtransport "google.golang.org/api/transport/grpc"
securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
iampb "google.golang.org/genproto/googleapis/iam/v1"
longrunningpb "google.golang.org/genproto/googleapis/longrunning"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
var newClientHook clientHook
// CallOptions contains the retry settings for each method of Client.
type CallOptions struct {
CreateSource []gax.CallOption
CreateFinding []gax.CallOption
CreateNotificationConfig []gax.CallOption
DeleteNotificationConfig []gax.CallOption
GetIamPolicy []gax.CallOption
GetNotificationConfig []gax.CallOption
GetOrganizationSettings []gax.CallOption
GetSource []gax.CallOption
GroupAssets []gax.CallOption
GroupFindings []gax.CallOption
ListAssets []gax.CallOption
ListFindings []gax.CallOption
ListNotificationConfigs []gax.CallOption
ListSources []gax.CallOption
RunAssetDiscovery []gax.CallOption
SetFindingState []gax.CallOption
SetIamPolicy []gax.CallOption
TestIamPermissions []gax.CallOption
UpdateFinding []gax.CallOption
UpdateNotificationConfig []gax.CallOption
UpdateOrganizationSettings []gax.CallOption
UpdateSource []gax.CallOption
UpdateSecurityMarks []gax.CallOption
}
func defaultClientOptions() []option.ClientOption {
return []option.ClientOption{
option.WithEndpoint("securitycenter.googleapis.com:443"),
option.WithGRPCDialOption(grpc.WithDisableServiceConfig()),
option.WithScopes(DefaultAuthScopes()...),
option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
grpc.MaxCallRecvMsgSize(math.MaxInt32))),
}
}
func defaultCallOptions() *CallOptions {
return &CallOptions{
CreateSource: []gax.CallOption{},
CreateFinding: []gax.CallOption{},
CreateNotificationConfig: []gax.CallOption{},
DeleteNotificationConfig: []gax.CallOption{},
GetIamPolicy: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
GetNotificationConfig: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
GetOrganizationSettings: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
GetSource: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
GroupAssets: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
GroupFindings: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
ListAssets: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
ListFindings: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
ListNotificationConfigs: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
ListSources: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
RunAssetDiscovery: []gax.CallOption{},
SetFindingState: []gax.CallOption{},
SetIamPolicy: []gax.CallOption{},
TestIamPermissions: []gax.CallOption{
gax.WithRetry(func() gax.Retryer {
return gax.OnCodes([]codes.Code{
codes.DeadlineExceeded,
codes.Unavailable,
}, gax.Backoff{
Initial: 100 * time.Millisecond,
Max: 60000 * time.Millisecond,
Multiplier: 1.30,
})
}),
},
UpdateFinding: []gax.CallOption{},
UpdateNotificationConfig: []gax.CallOption{},
UpdateOrganizationSettings: []gax.CallOption{},
UpdateSource: []gax.CallOption{},
UpdateSecurityMarks: []gax.CallOption{},
}
}
// Client is a client for interacting with Security Command Center API.
//
// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
type Client struct {
// Connection pool of gRPC connections to the service.
connPool gtransport.ConnPool
// flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE
disableDeadlines bool
// The gRPC API client.
client securitycenterpb.SecurityCenterClient
// LROClient is used internally to handle longrunning operations.
// It is exposed so that its CallOptions can be modified if required.
// Users should not Close this client.
LROClient *lroauto.OperationsClient
// The call options for this service.
CallOptions *CallOptions
// The x-goog-* metadata to be sent with each request.
xGoogMetadata metadata.MD
}
// NewClient creates a new security center client.
//
// V1 APIs for Security Center service.
func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
clientOpts := defaultClientOptions()
if newClientHook != nil {
hookOpts, err := newClientHook(ctx, clientHookParams{})
if err != nil {
return nil, err
}
clientOpts = append(clientOpts, hookOpts...)
}
disableDeadlines, err := checkDisableDeadlines()
if err != nil {
return nil, err
}
connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
if err != nil {
return nil, err
}
c := &Client{
connPool: connPool,
disableDeadlines: disableDeadlines,
CallOptions: defaultCallOptions(),
client: securitycenterpb.NewSecurityCenterClient(connPool),
}
c.setGoogleClientInfo()
c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
if err != nil {
// This error "should not happen", since we are just reusing old connection pool
// and never actually need to dial.
// If this does happen, we could leak connp. However, we cannot close conn:
// If the user invoked the constructor with option.WithGRPCConn,
// we would close a connection that's still in use.
// TODO: investigate error conditions.
return nil, err
}
return c, nil
}
// Connection returns a connection to the API service.
//
// Deprecated.
func (c *Client) Connection() *grpc.ClientConn {
return c.connPool.Conn()
}
// Close closes the connection to the API service. The user should invoke this when
// the client is no longer required.
func (c *Client) Close() error {
return c.connPool.Close()
}
// setGoogleClientInfo sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func (c *Client) setGoogleClientInfo(keyval ...string) {
kv := append([]string{"gl-go", versionGo()}, keyval...)
kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version)
c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
}
// CreateSource creates a source.
func (c *Client) CreateSource(ctx context.Context, req *securitycenterpb.CreateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.CreateSource[0:len(c.CallOptions.CreateSource):len(c.CallOptions.CreateSource)], opts...)
var resp *securitycenterpb.Source
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.CreateSource(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// CreateFinding creates a finding. The corresponding source must exist for finding creation
// to succeed.
func (c *Client) CreateFinding(ctx context.Context, req *securitycenterpb.CreateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.CreateFinding[0:len(c.CallOptions.CreateFinding):len(c.CallOptions.CreateFinding)], opts...)
var resp *securitycenterpb.Finding
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.CreateFinding(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// CreateNotificationConfig creates a notification config.
func (c *Client) CreateNotificationConfig(ctx context.Context, req *securitycenterpb.CreateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.CreateNotificationConfig[0:len(c.CallOptions.CreateNotificationConfig):len(c.CallOptions.CreateNotificationConfig)], opts...)
var resp *securitycenterpb.NotificationConfig
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.CreateNotificationConfig(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// DeleteNotificationConfig deletes a notification config.
func (c *Client) DeleteNotificationConfig(ctx context.Context, req *securitycenterpb.DeleteNotificationConfigRequest, opts ...gax.CallOption) error {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.DeleteNotificationConfig[0:len(c.CallOptions.DeleteNotificationConfig):len(c.CallOptions.DeleteNotificationConfig)], opts...)
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
_, err = c.client.DeleteNotificationConfig(ctx, req, settings.GRPC...)
return err
}, opts...)
return err
}
// GetIamPolicy gets the access control policy on the specified Source.
func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...)
var resp *iampb.Policy
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.GetIamPolicy(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// GetNotificationConfig gets a notification config.
func (c *Client) GetNotificationConfig(ctx context.Context, req *securitycenterpb.GetNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.GetNotificationConfig[0:len(c.CallOptions.GetNotificationConfig):len(c.CallOptions.GetNotificationConfig)], opts...)
var resp *securitycenterpb.NotificationConfig
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.GetNotificationConfig(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// GetOrganizationSettings gets the settings for an organization.
func (c *Client) GetOrganizationSettings(ctx context.Context, req *securitycenterpb.GetOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.GetOrganizationSettings[0:len(c.CallOptions.GetOrganizationSettings):len(c.CallOptions.GetOrganizationSettings)], opts...)
var resp *securitycenterpb.OrganizationSettings
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.GetOrganizationSettings(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// GetSource gets a source.
func (c *Client) GetSource(ctx context.Context, req *securitycenterpb.GetSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.GetSource[0:len(c.CallOptions.GetSource):len(c.CallOptions.GetSource)], opts...)
var resp *securitycenterpb.Source
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.GetSource(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// GroupAssets filters an organization’s assets and groups them by their specified
// properties.
func (c *Client) GroupAssets(ctx context.Context, req *securitycenterpb.GroupAssetsRequest, opts ...gax.CallOption) *GroupResultIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.GroupAssets[0:len(c.CallOptions.GroupAssets):len(c.CallOptions.GroupAssets)], opts...)
it := &GroupResultIterator{}
req = proto.Clone(req).(*securitycenterpb.GroupAssetsRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) {
var resp *securitycenterpb.GroupAssetsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.GroupAssets(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetGroupByResults(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
// GroupFindings filters an organization or source’s findings and groups them by their
// specified properties.
//
// To group across all sources provide a - as the source id.
// Example: /v1/organizations/{organization_id}/sources/-/findings
func (c *Client) GroupFindings(ctx context.Context, req *securitycenterpb.GroupFindingsRequest, opts ...gax.CallOption) *GroupResultIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.GroupFindings[0:len(c.CallOptions.GroupFindings):len(c.CallOptions.GroupFindings)], opts...)
it := &GroupResultIterator{}
req = proto.Clone(req).(*securitycenterpb.GroupFindingsRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.GroupResult, string, error) {
var resp *securitycenterpb.GroupFindingsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.GroupFindings(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetGroupByResults(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
// ListAssets lists an organization’s assets.
func (c *Client) ListAssets(ctx context.Context, req *securitycenterpb.ListAssetsRequest, opts ...gax.CallOption) *ListAssetsResponse_ListAssetsResultIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.ListAssets[0:len(c.CallOptions.ListAssets):len(c.CallOptions.ListAssets)], opts...)
it := &ListAssetsResponse_ListAssetsResultIterator{}
req = proto.Clone(req).(*securitycenterpb.ListAssetsRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListAssetsResponse_ListAssetsResult, string, error) {
var resp *securitycenterpb.ListAssetsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.ListAssets(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetListAssetsResults(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
// ListFindings lists an organization or source’s findings.
//
// To list across all sources provide a - as the source id.
// Example: /v1/organizations/{organization_id}/sources/-/findings
func (c *Client) ListFindings(ctx context.Context, req *securitycenterpb.ListFindingsRequest, opts ...gax.CallOption) *ListFindingsResponse_ListFindingsResultIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.ListFindings[0:len(c.CallOptions.ListFindings):len(c.CallOptions.ListFindings)], opts...)
it := &ListFindingsResponse_ListFindingsResultIterator{}
req = proto.Clone(req).(*securitycenterpb.ListFindingsRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.ListFindingsResponse_ListFindingsResult, string, error) {
var resp *securitycenterpb.ListFindingsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.ListFindings(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetListFindingsResults(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
// ListNotificationConfigs lists notification configs.
func (c *Client) ListNotificationConfigs(ctx context.Context, req *securitycenterpb.ListNotificationConfigsRequest, opts ...gax.CallOption) *NotificationConfigIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.ListNotificationConfigs[0:len(c.CallOptions.ListNotificationConfigs):len(c.CallOptions.ListNotificationConfigs)], opts...)
it := &NotificationConfigIterator{}
req = proto.Clone(req).(*securitycenterpb.ListNotificationConfigsRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.NotificationConfig, string, error) {
var resp *securitycenterpb.ListNotificationConfigsResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.ListNotificationConfigs(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetNotificationConfigs(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
// ListSources lists all sources belonging to an organization.
func (c *Client) ListSources(ctx context.Context, req *securitycenterpb.ListSourcesRequest, opts ...gax.CallOption) *SourceIterator {
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.ListSources[0:len(c.CallOptions.ListSources):len(c.CallOptions.ListSources)], opts...)
it := &SourceIterator{}
req = proto.Clone(req).(*securitycenterpb.ListSourcesRequest)
it.InternalFetch = func(pageSize int, pageToken string) ([]*securitycenterpb.Source, string, error) {
var resp *securitycenterpb.ListSourcesResponse
req.PageToken = pageToken
if pageSize > math.MaxInt32 {
req.PageSize = math.MaxInt32
} else {
req.PageSize = int32(pageSize)
}
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.ListSources(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, "", err
}
it.Response = resp
return resp.GetSources(), resp.GetNextPageToken(), nil
}
fetch := func(pageSize int, pageToken string) (string, error) {
items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
if err != nil {
return "", err
}
it.items = append(it.items, items...)
return nextPageToken, nil
}
it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
it.pageInfo.MaxSize = int(req.GetPageSize())
it.pageInfo.Token = req.GetPageToken()
return it
}
// RunAssetDiscovery runs asset discovery. The discovery is tracked with a long-running
// operation.
//
// This API can only be called with limited frequency for an organization. If
// it is called too frequently the caller will receive a TOO_MANY_REQUESTS
// error.
func (c *Client) RunAssetDiscovery(ctx context.Context, req *securitycenterpb.RunAssetDiscoveryRequest, opts ...gax.CallOption) (*RunAssetDiscoveryOperation, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.RunAssetDiscovery[0:len(c.CallOptions.RunAssetDiscovery):len(c.CallOptions.RunAssetDiscovery)], opts...)
var resp *longrunningpb.Operation
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.RunAssetDiscovery(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return &RunAssetDiscoveryOperation{
lro: longrunning.InternalNewOperation(c.LROClient, resp),
}, nil
}
// SetFindingState updates the state of a finding.
func (c *Client) SetFindingState(ctx context.Context, req *securitycenterpb.SetFindingStateRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.SetFindingState[0:len(c.CallOptions.SetFindingState):len(c.CallOptions.SetFindingState)], opts...)
var resp *securitycenterpb.Finding
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.SetFindingState(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// SetIamPolicy sets the access control policy on the specified Source.
func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...)
var resp *iampb.Policy
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.SetIamPolicy(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// TestIamPermissions returns the permissions that a caller has on the specified source.
func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...)
var resp *iampb.TestIamPermissionsResponse
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.TestIamPermissions(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// UpdateFinding creates or updates a finding. The corresponding source must exist for a
// finding creation to succeed.
func (c *Client) UpdateFinding(ctx context.Context, req *securitycenterpb.UpdateFindingRequest, opts ...gax.CallOption) (*securitycenterpb.Finding, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "finding.name", url.QueryEscape(req.GetFinding().GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.UpdateFinding[0:len(c.CallOptions.UpdateFinding):len(c.CallOptions.UpdateFinding)], opts...)
var resp *securitycenterpb.Finding
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.UpdateFinding(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// UpdateNotificationConfig updates a notification config. The following update
// fields are allowed: description, pubsub_topic, streaming_config.filter
func (c *Client) UpdateNotificationConfig(ctx context.Context, req *securitycenterpb.UpdateNotificationConfigRequest, opts ...gax.CallOption) (*securitycenterpb.NotificationConfig, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "notification_config.name", url.QueryEscape(req.GetNotificationConfig().GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.UpdateNotificationConfig[0:len(c.CallOptions.UpdateNotificationConfig):len(c.CallOptions.UpdateNotificationConfig)], opts...)
var resp *securitycenterpb.NotificationConfig
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.UpdateNotificationConfig(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// UpdateOrganizationSettings updates an organization’s settings.
func (c *Client) UpdateOrganizationSettings(ctx context.Context, req *securitycenterpb.UpdateOrganizationSettingsRequest, opts ...gax.CallOption) (*securitycenterpb.OrganizationSettings, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "organization_settings.name", url.QueryEscape(req.GetOrganizationSettings().GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.UpdateOrganizationSettings[0:len(c.CallOptions.UpdateOrganizationSettings):len(c.CallOptions.UpdateOrganizationSettings)], opts...)
var resp *securitycenterpb.OrganizationSettings
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.UpdateOrganizationSettings(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// UpdateSource updates a source.
func (c *Client) UpdateSource(ctx context.Context, req *securitycenterpb.UpdateSourceRequest, opts ...gax.CallOption) (*securitycenterpb.Source, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "source.name", url.QueryEscape(req.GetSource().GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.UpdateSource[0:len(c.CallOptions.UpdateSource):len(c.CallOptions.UpdateSource)], opts...)
var resp *securitycenterpb.Source
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.UpdateSource(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// UpdateSecurityMarks updates security marks.
func (c *Client) UpdateSecurityMarks(ctx context.Context, req *securitycenterpb.UpdateSecurityMarksRequest, opts ...gax.CallOption) (*securitycenterpb.SecurityMarks, error) {
if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines {
cctx, cancel := context.WithTimeout(ctx, 480000*time.Millisecond)
defer cancel()
ctx = cctx
}
md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "security_marks.name", url.QueryEscape(req.GetSecurityMarks().GetName())))
ctx = insertMetadata(ctx, c.xGoogMetadata, md)
opts = append(c.CallOptions.UpdateSecurityMarks[0:len(c.CallOptions.UpdateSecurityMarks):len(c.CallOptions.UpdateSecurityMarks)], opts...)
var resp *securitycenterpb.SecurityMarks
err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
resp, err = c.client.UpdateSecurityMarks(ctx, req, settings.GRPC...)
return err
}, opts...)
if err != nil {
return nil, err
}
return resp, nil
}
// RunAssetDiscoveryOperation manages a long-running operation from RunAssetDiscovery.
type RunAssetDiscoveryOperation struct {
lro *longrunning.Operation
}
// RunAssetDiscoveryOperation returns a new RunAssetDiscoveryOperation from a given name.
// The name must be that of a previously created RunAssetDiscoveryOperation, possibly from a different process.
func (c *Client) RunAssetDiscoveryOperation(name string) *RunAssetDiscoveryOperation {
return &RunAssetDiscoveryOperation{
lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
}
}
// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
//
// See documentation of Poll for error-handling information.
func (op *RunAssetDiscoveryOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.RunAssetDiscoveryResponse, error) {
var resp securitycenterpb.RunAssetDiscoveryResponse
if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
return nil, err
}
return &resp, nil
}
// Poll fetches the latest state of the long-running operation.
//
// Poll also fetches the latest metadata, which can be retrieved by Metadata.
//
// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
// the operation has completed with failure, the error is returned and op.Done will return true.
// If Poll succeeds and the operation has completed successfully,
// op.Done will return true, and the response of the operation is returned.
// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
func (op *RunAssetDiscoveryOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*securitycenterpb.RunAssetDiscoveryResponse, error) {
var resp securitycenterpb.RunAssetDiscoveryResponse
if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
return nil, err
}
if !op.Done() {
return nil, nil
}
return &resp, nil
}
// Metadata returns metadata associated with the long-running operation.
// Metadata itself does not contact the server, but Poll does.
// To get the latest metadata, call this method after a successful call to Poll.
// If the metadata is not available, the returned metadata and error are both nil.
func (op *RunAssetDiscoveryOperation) Metadata() (*emptypb.Empty, error) {
var meta emptypb.Empty
if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
return nil, nil
} else if err != nil {
return nil, err
}
return &meta, nil
}
// Done reports whether the long-running operation has completed.
func (op *RunAssetDiscoveryOperation) Done() bool {
return op.lro.Done()
}
// Name returns the name of the long-running operation.
// The name is assigned by the server and is unique within the service from which the operation is created.
func (op *RunAssetDiscoveryOperation) Name() string {
return op.lro.Name()
}
// GroupResultIterator manages a stream of *securitycenterpb.GroupResult.
type GroupResultIterator struct {
items []*securitycenterpb.GroupResult
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*securitycenterpb.GroupResult, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *GroupResultIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *GroupResultIterator) Next() (*securitycenterpb.GroupResult, error) {
var item *securitycenterpb.GroupResult
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *GroupResultIterator) bufLen() int {
return len(it.items)
}
func (it *GroupResultIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// ListAssetsResponse_ListAssetsResultIterator manages a stream of *securitycenterpb.ListAssetsResponse_ListAssetsResult.
type ListAssetsResponse_ListAssetsResultIterator struct {
items []*securitycenterpb.ListAssetsResponse_ListAssetsResult
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*securitycenterpb.ListAssetsResponse_ListAssetsResult, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *ListAssetsResponse_ListAssetsResultIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *ListAssetsResponse_ListAssetsResultIterator) Next() (*securitycenterpb.ListAssetsResponse_ListAssetsResult, error) {
var item *securitycenterpb.ListAssetsResponse_ListAssetsResult
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *ListAssetsResponse_ListAssetsResultIterator) bufLen() int {
return len(it.items)
}
func (it *ListAssetsResponse_ListAssetsResultIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// ListFindingsResponse_ListFindingsResultIterator manages a stream of *securitycenterpb.ListFindingsResponse_ListFindingsResult.
type ListFindingsResponse_ListFindingsResultIterator struct {
items []*securitycenterpb.ListFindingsResponse_ListFindingsResult
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*securitycenterpb.ListFindingsResponse_ListFindingsResult, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *ListFindingsResponse_ListFindingsResultIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *ListFindingsResponse_ListFindingsResultIterator) Next() (*securitycenterpb.ListFindingsResponse_ListFindingsResult, error) {
var item *securitycenterpb.ListFindingsResponse_ListFindingsResult
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *ListFindingsResponse_ListFindingsResultIterator) bufLen() int {
return len(it.items)
}
func (it *ListFindingsResponse_ListFindingsResultIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// NotificationConfigIterator manages a stream of *securitycenterpb.NotificationConfig.
type NotificationConfigIterator struct {
items []*securitycenterpb.NotificationConfig
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*securitycenterpb.NotificationConfig, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *NotificationConfigIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *NotificationConfigIterator) Next() (*securitycenterpb.NotificationConfig, error) {
var item *securitycenterpb.NotificationConfig
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *NotificationConfigIterator) bufLen() int {
return len(it.items)
}
func (it *NotificationConfigIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
// SourceIterator manages a stream of *securitycenterpb.Source.
type SourceIterator struct {
items []*securitycenterpb.Source
pageInfo *iterator.PageInfo
nextFunc func() error
// Response is the raw response for the current page.
// It must be cast to the RPC response type.
// Calling Next() or InternalFetch() updates this value.
Response interface{}
// InternalFetch is for use by the Google Cloud Libraries only.
// It is not part of the stable interface of this package.
//
// InternalFetch returns results from a single call to the underlying RPC.
// The number of results is no greater than pageSize.
// If there are no more results, nextPageToken is empty and err is nil.
InternalFetch func(pageSize int, pageToken string) (results []*securitycenterpb.Source, nextPageToken string, err error)
}
// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
func (it *SourceIterator) PageInfo() *iterator.PageInfo {
return it.pageInfo
}
// Next returns the next result. Its second return value is iterator.Done if there are no more
// results. Once Next returns Done, all subsequent calls will return Done.
func (it *SourceIterator) Next() (*securitycenterpb.Source, error) {
var item *securitycenterpb.Source
if err := it.nextFunc(); err != nil {
return item, err
}
item = it.items[0]
it.items = it.items[1:]
return item, nil
}
func (it *SourceIterator) bufLen() int {
return len(it.items)
}
func (it *SourceIterator) takeBuf() interface{} {
b := it.items
it.items = nil
return b
}
| {
"pile_set_name": "Github"
} |
package yaml
import (
"errors"
"fmt"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
)
func (c *Converter) impliedType(src []byte) (cty.Type, error) {
p := &yaml_parser_t{}
if !yaml_parser_initialize(p) {
return cty.NilType, errors.New("failed to initialize YAML parser")
}
if len(src) == 0 {
src = []byte{'\n'}
}
an := &typeAnalysis{
anchorsPending: map[string]int{},
anchorTypes: map[string]cty.Type{},
}
yaml_parser_set_input_string(p, src)
var evt yaml_event_t
if !yaml_parser_parse(p, &evt) {
return cty.NilType, parserError(p)
}
if evt.typ != yaml_STREAM_START_EVENT {
return cty.NilType, parseEventErrorf(&evt, "missing stream start token")
}
if !yaml_parser_parse(p, &evt) {
return cty.NilType, parserError(p)
}
if evt.typ != yaml_DOCUMENT_START_EVENT {
return cty.NilType, parseEventErrorf(&evt, "missing start of document")
}
ty, err := c.impliedTypeParse(an, p)
if err != nil {
return cty.NilType, err
}
if !yaml_parser_parse(p, &evt) {
return cty.NilType, parserError(p)
}
if evt.typ == yaml_DOCUMENT_START_EVENT {
return cty.NilType, parseEventErrorf(&evt, "only a single document is allowed")
}
if evt.typ != yaml_DOCUMENT_END_EVENT {
return cty.NilType, parseEventErrorf(&evt, "unexpected extra content (%s) after value", evt.typ.String())
}
if !yaml_parser_parse(p, &evt) {
return cty.NilType, parserError(p)
}
if evt.typ != yaml_STREAM_END_EVENT {
return cty.NilType, parseEventErrorf(&evt, "unexpected extra content after value")
}
return ty, err
}
func (c *Converter) impliedTypeParse(an *typeAnalysis, p *yaml_parser_t) (cty.Type, error) {
var evt yaml_event_t
if !yaml_parser_parse(p, &evt) {
return cty.NilType, parserError(p)
}
return c.impliedTypeParseRemainder(an, &evt, p)
}
func (c *Converter) impliedTypeParseRemainder(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) {
switch evt.typ {
case yaml_SCALAR_EVENT:
return c.impliedTypeScalar(an, evt, p)
case yaml_ALIAS_EVENT:
return c.impliedTypeAlias(an, evt, p)
case yaml_MAPPING_START_EVENT:
return c.impliedTypeMapping(an, evt, p)
case yaml_SEQUENCE_START_EVENT:
return c.impliedTypeSequence(an, evt, p)
case yaml_DOCUMENT_START_EVENT:
return cty.NilType, parseEventErrorf(evt, "only a single document is allowed")
case yaml_STREAM_END_EVENT:
// Decoding an empty buffer, probably
return cty.NilType, parseEventErrorf(evt, "expecting value but found end of stream")
default:
// Should never happen; the above should be comprehensive
return cty.NilType, parseEventErrorf(evt, "unexpected parser event %s", evt.typ.String())
}
}
func (c *Converter) impliedTypeScalar(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) {
src := evt.value
tag := string(evt.tag)
anchor := string(evt.anchor)
implicit := evt.implicit
if len(anchor) > 0 {
an.beginAnchor(anchor)
}
var ty cty.Type
switch {
case tag == "" && !implicit:
// Untagged explicit string
ty = cty.String
default:
v, err := c.resolveScalar(tag, string(src), yaml_scalar_style_t(evt.style))
if err != nil {
return cty.NilType, parseEventErrorWrap(evt, err)
}
if v.RawEquals(mergeMappingVal) {
// In any context other than a mapping key, this is just a plain string
ty = cty.String
} else {
ty = v.Type()
}
}
if len(anchor) > 0 {
an.completeAnchor(anchor, ty)
}
return ty, nil
}
func (c *Converter) impliedTypeMapping(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) {
tag := string(evt.tag)
anchor := string(evt.anchor)
if tag != "" && tag != yaml_MAP_TAG {
return cty.NilType, parseEventErrorf(evt, "can't interpret mapping as %s", tag)
}
if anchor != "" {
an.beginAnchor(anchor)
}
atys := make(map[string]cty.Type)
for {
var nextEvt yaml_event_t
if !yaml_parser_parse(p, &nextEvt) {
return cty.NilType, parserError(p)
}
if nextEvt.typ == yaml_MAPPING_END_EVENT {
ty := cty.Object(atys)
if anchor != "" {
an.completeAnchor(anchor, ty)
}
return ty, nil
}
if nextEvt.typ != yaml_SCALAR_EVENT {
return cty.NilType, parseEventErrorf(&nextEvt, "only strings are allowed as mapping keys")
}
keyVal, err := c.resolveScalar(string(nextEvt.tag), string(nextEvt.value), yaml_scalar_style_t(nextEvt.style))
if err != nil {
return cty.NilType, err
}
if keyVal.RawEquals(mergeMappingVal) {
// Merging the value (which must be a mapping) into our mapping,
// then.
ty, err := c.impliedTypeParse(an, p)
if err != nil {
return cty.NilType, err
}
if !ty.IsObjectType() {
return cty.NilType, parseEventErrorf(&nextEvt, "cannot merge %s into mapping", ty.FriendlyName())
}
for name, aty := range ty.AttributeTypes() {
atys[name] = aty
}
continue
}
if keyValStr, err := convert.Convert(keyVal, cty.String); err == nil {
keyVal = keyValStr
} else {
return cty.NilType, parseEventErrorf(&nextEvt, "only strings are allowed as mapping keys")
}
if keyVal.IsNull() {
return cty.NilType, parseEventErrorf(&nextEvt, "mapping key cannot be null")
}
if !keyVal.IsKnown() {
return cty.NilType, parseEventErrorf(&nextEvt, "mapping key must be known")
}
valTy, err := c.impliedTypeParse(an, p)
if err != nil {
return cty.NilType, err
}
atys[keyVal.AsString()] = valTy
}
}
func (c *Converter) impliedTypeSequence(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) {
tag := string(evt.tag)
anchor := string(evt.anchor)
if tag != "" && tag != yaml_SEQ_TAG {
return cty.NilType, parseEventErrorf(evt, "can't interpret sequence as %s", tag)
}
if anchor != "" {
an.beginAnchor(anchor)
}
var atys []cty.Type
for {
var nextEvt yaml_event_t
if !yaml_parser_parse(p, &nextEvt) {
return cty.NilType, parserError(p)
}
if nextEvt.typ == yaml_SEQUENCE_END_EVENT {
ty := cty.Tuple(atys)
if anchor != "" {
an.completeAnchor(anchor, ty)
}
return ty, nil
}
valTy, err := c.impliedTypeParseRemainder(an, &nextEvt, p)
if err != nil {
return cty.NilType, err
}
atys = append(atys, valTy)
}
}
func (c *Converter) impliedTypeAlias(an *typeAnalysis, evt *yaml_event_t, p *yaml_parser_t) (cty.Type, error) {
ty, err := an.anchorType(string(evt.anchor))
if err != nil {
err = parseEventErrorWrap(evt, err)
}
return ty, err
}
type typeAnalysis struct {
anchorsPending map[string]int
anchorTypes map[string]cty.Type
}
func (an *typeAnalysis) beginAnchor(name string) {
an.anchorsPending[name]++
}
func (an *typeAnalysis) completeAnchor(name string, ty cty.Type) {
an.anchorsPending[name]--
if an.anchorsPending[name] == 0 {
delete(an.anchorsPending, name)
}
an.anchorTypes[name] = ty
}
func (an *typeAnalysis) anchorType(name string) (cty.Type, error) {
if _, pending := an.anchorsPending[name]; pending {
// YAML normally allows self-referencing structures, but cty cannot
// represent them (it requires all structures to be finite) so we
// must fail here.
return cty.NilType, fmt.Errorf("cannot refer to anchor %q from inside its own definition", name)
}
ty, ok := an.anchorTypes[name]
if !ok {
return cty.NilType, fmt.Errorf("reference to undefined anchor %q", name)
}
return ty, nil
}
| {
"pile_set_name": "Github"
} |
# Note: On both 10.8 and 10.9 it seems sufficient to merely LAUNCH Safari - no need to ACTIVATE it.
tell application "Safari" to launch
tell application "System Events"
tell process "Safari"
# Try to obtain a reference to the `Developer > {iPhone|iPad} Simulator`submenu items; give up after a while.
set simSubMenu to missing value
repeat with i from 1 to 20
# Note that we reference the Developer menu by *index*, as its name may be localized.
# Furthermore, we search for the relevant menu item by the tokens "iPhone" or "iPad" only, since the "Simulator" part could be localized, too.
# Note that the menu-item name reflects whether the simulator currently simulates the iPhone or the iPad.
tell (first menu item of menu -3 of menu bar 1 whose name contains "iPhone" or name contains "iPad" or name contains "iOS Simulator" )
if exists then # Menu item found?
# Simulate a click on the menu item so as to get it to populate its submenu with the currently debuggable pages.
click it
# Loop over submenu items and collect page URLs.
set output to ""
set pageUrl to missing value
repeat with itm in menu items of menu of it
set props to properties of itm # !! Bizarrely, this intermediate step is needed - directly accessing `help of itm` leads to strange behavior on OSX 10.8.
set pageUrl to help of props # Page URL is in `help` property.
if pageUrl is not missing value and pageUrl does not contain "Background/background.html" then
set output to output & pageUrl & "
"
end if
end repeat
# Return URLs.
return output
end if
end tell
delay 0.2 # Menu item not (yet) available; try again.
end repeat
end tell
# Getting here means that the simulator menu item wasn't found within the timeout period.
# Abort with an error.
error "Cannot determine debuggable pages: iOS Simulator-related menu items not found in Safari.
Make sure that the `Developer` menu is activated in the advanced preferences and that the iOS simulator is running a UIWebView-based app."
end tell | {
"pile_set_name": "Github"
} |
//
// AppDelegate.m
// Constructing and Displaying Attributed Texts
//
// Created by Vandad Nahavandipoor on 23/08/2012.
// Copyright (c) 2012 Pixolity Ltd. All rights reserved.
//
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| {
"pile_set_name": "Github"
} |
<?php
/**
*
* Function code for the complex conjugate() function
*
* @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
* @license https://opensource.org/licenses/MIT MIT
*/
namespace Complex;
/**
* Returns the complex conjugate of a complex number
*
* @param Complex|mixed $complex Complex number or a numeric value.
* @return Complex The conjugate of the complex argument.
* @throws Exception If argument isn't a valid real or complex number.
*/
function conjugate($complex): Complex
{
$complex = Complex::validateComplexArgument($complex);
return new Complex(
$complex->getReal(),
-1 * $complex->getImaginary(),
$complex->getSuffix()
);
}
| {
"pile_set_name": "Github"
} |
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <[email protected]>
// +----------------------------------------------------------------------
namespace think\log\driver;
use think\App;
/**
* 本地化调试输出到文件
*/
class File
{
protected $config = [
'time_format' => 'c',
'single' => false,
'file_size' => 2097152,
'path' => '',
'apart_level' => [],
'max_files' => 0,
'json' => false,
];
protected $app;
// 实例化并传入参数
public function __construct(App $app, $config = [])
{
$this->app = $app;
if (is_array($config)) {
$this->config = array_merge($this->config, $config);
}
if (empty($this->config['path'])) {
$this->config['path'] = $this->app->getRuntimePath() . 'log' . DIRECTORY_SEPARATOR;
} elseif (substr($this->config['path'], -1) != DIRECTORY_SEPARATOR) {
$this->config['path'] .= DIRECTORY_SEPARATOR;
}
}
/**
* 日志写入接口
* @access public
* @param array $log 日志信息
* @param bool $append 是否追加请求信息
* @return bool
*/
public function save(array $log = [], $append = false)
{
$destination = $this->getMasterLogFile();
$path = dirname($destination);
!is_dir($path) && mkdir($path, 0755, true);
$info = [];
foreach ($log as $type => $val) {
foreach ($val as $msg) {
if (!is_string($msg)) {
$msg = var_export($msg, true);
}
$info[$type][] = $this->config['json'] ? $msg : '[ ' . $type . ' ] ' . $msg;
}
if (!$this->config['json'] && (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level']))) {
// 独立记录的日志级别
$filename = $this->getApartLevelFile($path, $type);
$this->write($info[$type], $filename, true, $append);
unset($info[$type]);
}
}
if ($info) {
return $this->write($info, $destination, false, $append);
}
return true;
}
/**
* 日志写入
* @access protected
* @param array $message 日志信息
* @param string $destination 日志文件
* @param bool $apart 是否独立文件写入
* @param bool $append 是否追加请求信息
* @return bool
*/
protected function write($message, $destination, $apart = false, $append = false)
{
// 检测日志文件大小,超过配置大小则备份日志文件重新生成
$this->checkLogSize($destination);
// 日志信息封装
$info['timestamp'] = date($this->config['time_format']);
foreach ($message as $type => $msg) {
$msg = is_array($msg) ? implode(PHP_EOL, $msg) : $msg;
if (PHP_SAPI == 'cli') {
$info['msg'] = $msg;
$info['type'] = $type;
} else {
$info[$type] = $msg;
}
}
if (PHP_SAPI == 'cli') {
$message = $this->parseCliLog($info);
} else {
// 添加调试日志
$this->getDebugLog($info, $append, $apart);
$message = $this->parseLog($info);
}
return error_log($message, 3, $destination);
}
/**
* 获取主日志文件名
* @access public
* @return string
*/
protected function getMasterLogFile()
{
if ($this->config['max_files']) {
$files = glob($this->config['path'] . '*.log');
try {
if (count($files) > $this->config['max_files']) {
unlink($files[0]);
}
} catch (\Exception $e) {
}
}
$cli = PHP_SAPI == 'cli' ? '_cli' : '';
if ($this->config['single']) {
$name = is_string($this->config['single']) ? $this->config['single'] : 'single';
$destination = $this->config['path'] . $name . $cli . '.log';
} else {
if ($this->config['max_files']) {
$filename = date('Ymd') . $cli . '.log';
} else {
$filename = date('Ym') . DIRECTORY_SEPARATOR . date('d') . $cli . '.log';
}
$destination = $this->config['path'] . $filename;
}
return $destination;
}
/**
* 获取独立日志文件名
* @access public
* @param string $path 日志目录
* @param string $type 日志类型
* @return string
*/
protected function getApartLevelFile($path, $type)
{
$cli = PHP_SAPI == 'cli' ? '_cli' : '';
if ($this->config['single']) {
$name = is_string($this->config['single']) ? $this->config['single'] : 'single';
} elseif ($this->config['max_files']) {
$name = date('Ymd');
} else {
$name = date('d');
}
return $path . DIRECTORY_SEPARATOR . $name . '_' . $type . $cli . '.log';
}
/**
* 检查日志文件大小并自动生成备份文件
* @access protected
* @param string $destination 日志文件
* @return void
*/
protected function checkLogSize($destination)
{
if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
try {
rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination));
} catch (\Exception $e) {
}
}
}
/**
* CLI日志解析
* @access protected
* @param array $info 日志信息
* @return string
*/
protected function parseCliLog($info)
{
if ($this->config['json']) {
$message = json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
} else {
$now = $info['timestamp'];
unset($info['timestamp']);
$message = implode(PHP_EOL, $info);
$message = "[{$now}]" . $message . PHP_EOL;
}
return $message;
}
/**
* 解析日志
* @access protected
* @param array $info 日志信息
* @return string
*/
protected function parseLog($info)
{
$requestInfo = [
'ip' => $this->app['request']->ip(),
'method' => $this->app['request']->method(),
'host' => $this->app['request']->host(),
'uri' => $this->app['request']->url(),
];
if ($this->config['json']) {
$info = $requestInfo + $info;
return json_encode($info, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
}
array_unshift($info, "---------------------------------------------------------------" . PHP_EOL . "\r\n[{$info['timestamp']}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}");
unset($info['timestamp']);
return implode(PHP_EOL, $info) . PHP_EOL;
}
protected function getDebugLog(&$info, $append, $apart)
{
if ($this->app->isDebug() && $append) {
if ($this->config['json']) {
// 获取基本信息
$runtime = round(microtime(true) - $this->app->getBeginTime(), 10);
$reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
$memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2);
$info = [
'runtime' => number_format($runtime, 6) . 's',
'reqs' => $reqs . 'req/s',
'memory' => $memory_use . 'kb',
'file' => count(get_included_files()),
] + $info;
} elseif (!$apart) {
// 增加额外的调试信息
$runtime = round(microtime(true) - $this->app->getBeginTime(), 10);
$reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
$memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2);
$time_str = '[运行时间:' . number_format($runtime, 6) . 's] [吞吐率:' . $reqs . 'req/s]';
$memory_str = ' [内存消耗:' . $memory_use . 'kb]';
$file_load = ' [文件加载:' . count(get_included_files()) . ']';
array_unshift($info, $time_str . $memory_str . $file_load);
}
}
}
}
| {
"pile_set_name": "Github"
} |
fixScale = function(doc) {
var addEvent = 'addEventListener',
type = 'gesturestart',
qsa = 'querySelectorAll',
scales = [1, 1],
meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];
function fix() {
meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
doc.removeEventListener(type, fix, true);
}
if ((meta = meta[meta.length - 1]) && addEvent in doc) {
fix();
scales = [.25, 1.6];
doc[addEvent](type, fix, true);
}
}; | {
"pile_set_name": "Github"
} |
#include "FEAdaptor.h"
#include "FEDataStructures.h"
#include <iostream>
#include <vtkCPDataDescription.h>
#include <vtkCPInputDataDescription.h>
#include <vtkCPProcessor.h>
#include <vtkCPPythonScriptPipeline.h>
#include <vtkCPPythonScriptV2Pipeline.h>
#include <vtkCellData.h>
#include <vtkCellType.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkUnstructuredGrid.h>
#include "vtkCPMappedVectorArrayTemplate.h"
#include <vtksys/SystemTools.hxx>
namespace
{
vtkCPProcessor* Processor = NULL;
vtkUnstructuredGrid* VTKGrid;
void BuildVTKGrid(Grid& grid)
{
// create the points information
vtkCPMappedVectorArrayTemplate<double>* pointArray =
vtkCPMappedVectorArrayTemplate<double>::New();
pointArray->SetVectorArray(
grid.GetPointsArray(), static_cast<vtkIdType>(grid.GetNumberOfPoints()));
vtkNew<vtkPoints> points;
points->SetData(pointArray);
pointArray->Delete();
VTKGrid->SetPoints(points);
// create the cells
size_t numCells = grid.GetNumberOfCells();
VTKGrid->Allocate(static_cast<vtkIdType>(numCells * 9));
for (size_t cell = 0; cell < numCells; cell++)
{
unsigned int* cellPoints = grid.GetCellPoints(cell);
vtkIdType tmp[8] = { cellPoints[0], cellPoints[1], cellPoints[2], cellPoints[3], cellPoints[4],
cellPoints[5], cellPoints[6], cellPoints[7] };
VTKGrid->InsertNextCell(VTK_HEXAHEDRON, 8, tmp);
}
}
void UpdateVTKAttributes(Grid& grid, Attributes& attributes, vtkCPInputDataDescription* idd)
{
if (idd->IsFieldNeeded("velocity", vtkDataObject::POINT))
{
if (VTKGrid->GetPointData()->GetNumberOfArrays() == 0)
{
// velocity array
vtkCPMappedVectorArrayTemplate<double>* velocity =
vtkCPMappedVectorArrayTemplate<double>::New();
velocity->SetName("velocity");
VTKGrid->GetPointData()->AddArray(velocity);
velocity->Delete();
}
vtkCPMappedVectorArrayTemplate<double>* velocity =
vtkCPMappedVectorArrayTemplate<double>::SafeDownCast(
VTKGrid->GetPointData()->GetArray("velocity"));
velocity->SetVectorArray(attributes.GetVelocityArray(), VTKGrid->GetNumberOfPoints());
}
if (idd->IsFieldNeeded("pressure", vtkDataObject::CELL))
{
if (VTKGrid->GetCellData()->GetNumberOfArrays() == 0)
{
// pressure array
vtkNew<vtkFloatArray> pressure;
pressure->SetName("pressure");
pressure->SetNumberOfComponents(1);
VTKGrid->GetCellData()->AddArray(pressure);
}
vtkFloatArray* pressure =
vtkFloatArray::SafeDownCast(VTKGrid->GetCellData()->GetArray("pressure"));
// The pressure array is a scalar array so we can reuse
// memory as long as we ordered the points properly.
float* pressureData = attributes.GetPressureArray();
pressure->SetArray(pressureData, static_cast<vtkIdType>(grid.GetNumberOfCells()), 1);
}
}
void BuildVTKDataStructures(Grid& grid, Attributes& attributes, vtkCPInputDataDescription* idd)
{
if (VTKGrid == NULL)
{
// The grid structure isn't changing so we only build it
// the first time it's needed. If we needed the memory
// we could delete it and rebuild as necessary.
VTKGrid = vtkUnstructuredGrid::New();
BuildVTKGrid(grid);
}
UpdateVTKAttributes(grid, attributes, idd);
}
}
namespace FEAdaptor
{
void Initialize(int numScripts, char* scripts[])
{
if (Processor == NULL)
{
Processor = vtkCPProcessor::New();
Processor->Initialize();
}
else
{
Processor->RemoveAllPipelines();
}
for (int i = 0; i < numScripts; i++)
{
std::string ext = vtksys::SystemTools::GetFilenameLastExtension(scripts[i]);
if (ext == ".zip")
{
vtkNew<vtkCPPythonScriptV2Pipeline> pipeline;
pipeline->InitializeFromZIP(scripts[i]);
Processor->AddPipeline(pipeline);
}
else
{
vtkNew<vtkCPPythonScriptPipeline> pipeline;
pipeline->Initialize(scripts[i]);
Processor->AddPipeline(pipeline);
}
}
}
void Finalize()
{
if (Processor)
{
Processor->Delete();
Processor = NULL;
}
if (VTKGrid)
{
VTKGrid->Delete();
VTKGrid = NULL;
}
}
void CoProcess(
Grid& grid, Attributes& attributes, double time, unsigned int timeStep, bool lastTimeStep)
{
vtkNew<vtkCPDataDescription> dataDescription;
dataDescription->AddInput("input");
dataDescription->SetTimeData(time, timeStep);
if (lastTimeStep == true)
{
// assume that we want to all the pipelines to execute if it
// is the last time step.
dataDescription->ForceOutputOn();
}
if (Processor->RequestDataDescription(dataDescription) != 0)
{
vtkCPInputDataDescription* idd = dataDescription->GetInputDescriptionByName("input");
BuildVTKDataStructures(grid, attributes, idd);
idd->SetGrid(VTKGrid);
Processor->CoProcess(dataDescription);
}
}
} // end of Catalyst namespace
| {
"pile_set_name": "Github"
} |
module I18n
module Backend
# Backend that chains multiple other backends and checks each of them when
# a translation needs to be looked up. This is useful when you want to use
# standard translations with a Simple backend but store custom application
# translations in a database or other backends.
#
# To use the Chain backend instantiate it and set it to the I18n module.
# You can add chained backends through the initializer or backends
# accessor:
#
# # preserves the existing Simple backend set to I18n.backend
# I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
#
# The implementation assumes that all backends added to the Chain implement
# a lookup method with the same API as Simple backend does.
class Chain
module Implementation
include Base
attr_accessor :backends
def initialize(*backends)
self.backends = backends
end
def reload!
backends.each { |backend| backend.reload! }
end
def store_translations(locale, data, options = {})
backends.first.store_translations(locale, data, options)
end
def available_locales
backends.map { |backend| backend.available_locales }.flatten.uniq
end
def translate(locale, key, default_options = {})
namespace = nil
options = default_options.except(:default)
backends.each do |backend|
catch(:exception) do
options = default_options if backend == backends.last
translation = backend.translate(locale, key, options)
if namespace_lookup?(translation, options)
namespace = _deep_merge(translation, namespace || {})
elsif !translation.nil? || (options.key?(:default) && options[:default].nil?)
return translation
end
end
end
return namespace if namespace
throw(:exception, I18n::MissingTranslation.new(locale, key, options))
end
def exists?(locale, key)
backends.any? do |backend|
backend.exists?(locale, key)
end
end
def localize(locale, object, format = :default, options = {})
backends.each do |backend|
catch(:exception) do
result = backend.localize(locale, object, format, options) and return result
end
end
throw(:exception, I18n::MissingTranslation.new(locale, format, options))
end
protected
def namespace_lookup?(result, options)
result.is_a?(Hash) && !options.has_key?(:count)
end
private
# This is approximately what gets used in ActiveSupport.
# However since we are not guaranteed to run in an ActiveSupport context
# it is wise to have our own copy. We underscore it
# to not pollute the namespace of the including class.
def _deep_merge(hash, other_hash)
copy = hash.dup
other_hash.each_pair do |k,v|
value_from_other = hash[k]
copy[k] = value_from_other.is_a?(Hash) && v.is_a?(Hash) ? _deep_merge(value_from_other, v) : v
end
copy
end
end
include Implementation
end
end
end
| {
"pile_set_name": "Github"
} |
<resources>
<!-- Theme for SwitchDateTime -->
<style name="Theme.SwitchDateTime" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#29b6f6</item>
<item name="colorPrimaryDark">#03a9f4</item>
<item name="android:textColorPrimaryInverse">#e6e6e6</item>
<item name="android:textColorSecondaryInverse">#e1e1e1</item>
</style>
<!-- Header Background -->
<style name="Theme.SwitchDateTime.HeaderBackground">
<item name="android:background">?attr/colorPrimary</item>
</style>
<!-- Content Background -->
<style name="Theme.SwitchDateTime.ContentBackground">
<item name="android:background">#00ffffff</item>
</style>
<!-- Title -->
<style name="Theme.SwitchDateTime.TitleDateTimeLabelText">
<item name="android:textSize">@dimen/title_date_time_label_text</item>
<item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
<item name="android:textStyle">bold</item>
</style>
<!-- Icon -->
<style name="Theme.SwitchDateTime.IconDateTimeSwitch">
<item name="android:src">@drawable/ic_view_carousel_black_32dp</item>
<item name="tint">?android:attr/textColorPrimaryInverse</item>
</style>
<!-- Time -->
<style name="Theme.SwitchDateTime.Time">
<item name="timeCircleColor">#e1e1e1</item>
<item name="timeCenterColor">?attr/colorPrimary</item>
<item name="timeAmPmBackgroundColor">?attr/colorPrimary</item>
<item name="timeAmPmSelectBackgroundColor">?attr/colorPrimary</item> <!-- Alpha is apply-->
<item name="timeAmPmTextColor">?android:attr/textColorPrimaryInverse</item>
<item name="timeSelectorColor">?attr/colorPrimary</item>
<item name="timeCircularNumbersColor">#494949</item>
</style>
<!-- Time Label -->
<style name="Theme.SwitchDateTime.TimeLabelText">
<item name="android:textSize">@dimen/time_label_text</item>
<item name="android:textColor">?android:attr/textColorSecondaryInverse</item>
</style>
<style name="Theme.SwitchDateTime.TimeLabelAmPm">
<item name="android:textSize">@dimen/time_label_AmPm</item>
<item name="android:textColor">?android:attr/textColorSecondaryInverse</item>
<item name="android:textStyle">bold</item>
</style>
<!-- Date -->
<style name="Theme.SwitchDateTime.Date">
<item name="mcv_selectionColor">?attr/colorPrimary</item>
</style>
<!-- Date Label -->
<style name="Theme.SwitchDateTime.DateLabelMonthAndDay">
<item name="android:textSize">@dimen/date_label_month_and_day</item>
<item name="android:textColor">?android:attr/textColorSecondaryInverse</item>
</style>
<!-- Year Selected-->
<style name="Theme.SwitchDateTime.Year">
<item name="colorCircleIndicator">?attr/colorPrimary</item>
<item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
</style>
<!-- Year Label -->
<style name="Theme.SwitchDateTime.DateLabelYear">
<item name="android:textSize">@dimen/date_label_year</item>
<item name="android:textColor">?android:attr/textColorSecondaryInverse</item>
<item name="android:textStyle">bold</item>
</style>
</resources>
| {
"pile_set_name": "Github"
} |
test
Label : PROJECT
1
Label : FILE
3
Label : EXPRESSION
4
Label : CODE
3
Label : EXPRESSION
5
Label : EXTENDS
8
Label : NAME
6
| {
"pile_set_name": "Github"
} |
package en
import (
"regexp"
"strconv"
"strings"
"time"
"github.com/AlekSi/pointer"
"github.com/olebedev/when/rules"
"github.com/pkg/errors"
)
func PastTime(s rules.Strategy) rules.Rule {
overwrite := s == rules.Override
return &rules.F{
RegExp: regexp.MustCompile(
"(?i)(?:\\W|^)\\s*" +
"(" + INTEGER_WORDS_PATTERN + "|[0-9]+|an?(?:\\s*few)?|half(?:\\s*an?)?)\\s*" +
"(seconds?|min(?:ute)?s?|hours?|days?|weeks?|months?|years?) (ago)\\s*" +
"(?:\\W|$)"),
Applier: func(m *rules.Match, c *rules.Context, o *rules.Options, ref time.Time) (bool, error) {
numStr := strings.TrimSpace(m.Captures[0])
var num int
var err error
if n, ok := INTEGER_WORDS[numStr]; ok {
num = n
} else if numStr == "a" || numStr == "an" {
num = 1
} else if strings.Contains(numStr, "few") {
num = 3
} else if strings.Contains(numStr, "half") {
// pass
} else {
num, err = strconv.Atoi(numStr)
if err != nil {
return false, errors.Wrapf(err, "convert '%s' to int", numStr)
}
}
exponent := strings.TrimSpace(m.Captures[1])
if !strings.Contains(numStr, "half") {
switch {
case strings.Contains(exponent, "second"):
if c.Duration == 0 || overwrite {
c.Duration = -(time.Duration(num) * time.Second)
}
case strings.Contains(exponent, "min"):
if c.Duration == 0 || overwrite {
c.Duration = -(time.Duration(num) * time.Minute)
}
case strings.Contains(exponent, "hour"):
if c.Duration == 0 || overwrite {
c.Duration = -(time.Duration(num) * time.Hour)
}
case strings.Contains(exponent, "day"):
if c.Duration == 0 || overwrite {
c.Duration = -(time.Duration(num) * 24 * time.Hour)
}
case strings.Contains(exponent, "week"):
if c.Duration == 0 || overwrite {
c.Duration = -(time.Duration(num) * 7 * 24 * time.Hour)
}
case strings.Contains(exponent, "month"):
if c.Month == nil || overwrite {
c.Month = pointer.ToInt((int(ref.Month()) - num) % 12)
}
case strings.Contains(exponent, "year"):
if c.Year == nil || overwrite {
c.Year = pointer.ToInt(ref.Year() - num)
}
}
} else {
switch {
case strings.Contains(exponent, "hour"):
if c.Duration == 0 || overwrite {
c.Duration = -(30 * time.Minute)
}
case strings.Contains(exponent, "day"):
if c.Duration == 0 || overwrite {
c.Duration = -(12 * time.Hour)
}
case strings.Contains(exponent, "week"):
if c.Duration == 0 || overwrite {
c.Duration = -(7 * 12 * time.Hour)
}
case strings.Contains(exponent, "month"):
if c.Duration == 0 || overwrite {
// 2 weeks
c.Duration = -(14 * 24 * time.Hour)
}
case strings.Contains(exponent, "year"):
if c.Month == nil || overwrite {
c.Month = pointer.ToInt((int(ref.Month()) - 6) % 12)
}
}
}
return true, nil
},
}
}
| {
"pile_set_name": "Github"
} |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/WEB-INF/jsp/common/header.jsp"%>
<%@include file="/WEB-INF/jsp/common/taglibs.jsp"%>
<script type="text/javascript">
function toggleErrorTrace() {
var errorTrace = $('#errorTrace');
if (errorTrace.is(':visible')) {
$('#errorTrace').hide();
} else {
$('#errorTrace').show();
}
}
$(document).ready(function() {
$('#errorTrace').hide();
});
</script>
<div class="container-fluid">
<div class="content">
<div class="row-fluid">
<div class="span3">
<%@include file="/WEB-INF/jsp/common/include_sidebar.jsp"%>
</div>
<div class="span9">
<div class="row-fluid">
<div class="span12">
<%@include file="/WEB-INF/jsp/common/include_background_logo.jsp"%>
<div class="alert alert-error">
<h2>
<spring:message code="error.acl.not.allowed.access.key" />
</h2>
<c:if test="${not empty exception}">
<h4>
<spring:message code="error.detail.title" />
</h4>
<c:catch var="exceptionHasNotErrorMessageKey">${exception.errorMessageKey}</c:catch>
<c:choose>
<c:when test="${empty exceptionHasNotErrorMessageKey}">
<spring:message code="${exception.errorMessageKey}" arguments="${exception.errorMessageArgs}"
htmlEscape="false" />
</c:when>
<c:otherwise>
<c:out value="${exception.localizedMessage}" escapeXml="false" />
</c:otherwise>
</c:choose>
<br />
<br />
<button class="btn btn-danger" onclick="toggleErrorTrace();">
<i class="icon-warning-sign icon-white"></i>
<spring:message code="error.stacktrace" />
</button>
<div id="errorTrace">
<!-- Root cause -->
<c:out value="${exception.cause}" />
<br />
<c:forEach items="${exception.stackTrace}" var="trace">
<c:out value="${trace}" />
<br />
</c:forEach>
</div>
</c:if>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<%@include file="/WEB-INF/jsp/common/footer.jsp"%>
| {
"pile_set_name": "Github"
} |
#[test]
fn align_items_center() {
let mut stretch = stretch::Stretch::new();
let node0 = stretch
.new_node(
stretch::style::Style {
size: stretch::geometry::Size {
width: stretch::style::Dimension::Points(10f32),
height: stretch::style::Dimension::Points(10f32),
..Default::default()
},
..Default::default()
},
&[],
)
.unwrap();
let node = stretch
.new_node(
stretch::style::Style {
align_items: stretch::style::AlignItems::Center,
size: stretch::geometry::Size {
width: stretch::style::Dimension::Points(100f32),
height: stretch::style::Dimension::Points(100f32),
..Default::default()
},
..Default::default()
},
&[node0],
)
.unwrap();
stretch.compute_layout(node, stretch::geometry::Size::undefined()).unwrap();
assert_eq!(stretch.layout(node).unwrap().size.width, 100f32);
assert_eq!(stretch.layout(node).unwrap().size.height, 100f32);
assert_eq!(stretch.layout(node).unwrap().location.x, 0f32);
assert_eq!(stretch.layout(node).unwrap().location.y, 0f32);
assert_eq!(stretch.layout(node0).unwrap().size.width, 10f32);
assert_eq!(stretch.layout(node0).unwrap().size.height, 10f32);
assert_eq!(stretch.layout(node0).unwrap().location.x, 0f32);
assert_eq!(stretch.layout(node0).unwrap().location.y, 45f32);
}
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0-or-later */
/******************************************************************************
*
* Copyright © International Business Machines Corp., 2009
*
* DESCRIPTION
* GCC atomic builtin wrappers
* http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html
*
* AUTHOR
* Darren Hart <[email protected]>
*
* HISTORY
* 2009-Nov-17: Initial version by Darren Hart <[email protected]>
*
*****************************************************************************/
#ifndef _ATOMIC_H
#define _ATOMIC_H
typedef struct {
volatile int val;
} atomic_t;
#define ATOMIC_INITIALIZER { 0 }
/**
* atomic_cmpxchg() - Atomic compare and exchange
* @uaddr: The address of the futex to be modified
* @oldval: The expected value of the futex
* @newval: The new value to try and assign the futex
*
* Return the old value of addr->val.
*/
static inline int
atomic_cmpxchg(atomic_t *addr, int oldval, int newval)
{
return __sync_val_compare_and_swap(&addr->val, oldval, newval);
}
/**
* atomic_inc() - Atomic incrememnt
* @addr: Address of the variable to increment
*
* Return the new value of addr->val.
*/
static inline int
atomic_inc(atomic_t *addr)
{
return __sync_add_and_fetch(&addr->val, 1);
}
/**
* atomic_dec() - Atomic decrement
* @addr: Address of the variable to decrement
*
* Return the new value of addr-val.
*/
static inline int
atomic_dec(atomic_t *addr)
{
return __sync_sub_and_fetch(&addr->val, 1);
}
/**
* atomic_set() - Atomic set
* @addr: Address of the variable to set
* @newval: New value for the atomic_t
*
* Return the new value of addr->val.
*/
static inline int
atomic_set(atomic_t *addr, int newval)
{
addr->val = newval;
return newval;
}
#endif
| {
"pile_set_name": "Github"
} |
// Copyright (C) 1994-2013 Free Software Foundation, Inc.
//
// This file is part of GCC.
//
// GCC is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3, or (at your option)
// any later version.
// GCC is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
#include "tinfo.h"
namespace __cxxabiv1 {
__array_type_info::
~__array_type_info ()
{}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<keystone-v2 xmlns="http://docs.openrepose.org/repose/keystone-v2/v1.0">
<identity-service
username="admin_username"
password="password"
uri="http://localhost:${identityPort}"
set-groups-in-header="true"
set-catalog-in-header="false"
/>
</keystone-v2>
| {
"pile_set_name": "Github"
} |
package yaml
import (
"bytes"
)
// Flush the buffer if needed.
func flush(emitter *yaml_emitter_t) bool {
if emitter.buffer_pos+5 >= len(emitter.buffer) {
return yaml_emitter_flush(emitter)
}
return true
}
// Put a character to the output buffer.
func put(emitter *yaml_emitter_t, value byte) bool {
if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) {
return false
}
emitter.buffer[emitter.buffer_pos] = value
emitter.buffer_pos++
emitter.column++
return true
}
// Put a line break to the output buffer.
func put_break(emitter *yaml_emitter_t) bool {
if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) {
return false
}
switch emitter.line_break {
case yaml_CR_BREAK:
emitter.buffer[emitter.buffer_pos] = '\r'
emitter.buffer_pos += 1
case yaml_LN_BREAK:
emitter.buffer[emitter.buffer_pos] = '\n'
emitter.buffer_pos += 1
case yaml_CRLN_BREAK:
emitter.buffer[emitter.buffer_pos+0] = '\r'
emitter.buffer[emitter.buffer_pos+1] = '\n'
emitter.buffer_pos += 2
default:
panic("unknown line break setting")
}
emitter.column = 0
emitter.line++
return true
}
// Copy a character from a string into buffer.
func write(emitter *yaml_emitter_t, s []byte, i *int) bool {
if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) {
return false
}
p := emitter.buffer_pos
w := width(s[*i])
switch w {
case 4:
emitter.buffer[p+3] = s[*i+3]
fallthrough
case 3:
emitter.buffer[p+2] = s[*i+2]
fallthrough
case 2:
emitter.buffer[p+1] = s[*i+1]
fallthrough
case 1:
emitter.buffer[p+0] = s[*i+0]
default:
panic("unknown character width")
}
emitter.column++
emitter.buffer_pos += w
*i += w
return true
}
// Write a whole string into buffer.
func write_all(emitter *yaml_emitter_t, s []byte) bool {
for i := 0; i < len(s); {
if !write(emitter, s, &i) {
return false
}
}
return true
}
// Copy a line break character from a string into buffer.
func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool {
if s[*i] == '\n' {
if !put_break(emitter) {
return false
}
*i++
} else {
if !write(emitter, s, i) {
return false
}
emitter.column = 0
emitter.line++
}
return true
}
// Set an emitter error and return false.
func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool {
emitter.error = yaml_EMITTER_ERROR
emitter.problem = problem
return false
}
// Emit an event.
func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool {
emitter.events = append(emitter.events, *event)
for !yaml_emitter_need_more_events(emitter) {
event := &emitter.events[emitter.events_head]
if !yaml_emitter_analyze_event(emitter, event) {
return false
}
if !yaml_emitter_state_machine(emitter, event) {
return false
}
yaml_event_delete(event)
emitter.events_head++
}
return true
}
// Check if we need to accumulate more events before emitting.
//
// We accumulate extra
// - 1 event for DOCUMENT-START
// - 2 events for SEQUENCE-START
// - 3 events for MAPPING-START
//
func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool {
if emitter.events_head == len(emitter.events) {
return true
}
var accumulate int
switch emitter.events[emitter.events_head].typ {
case yaml_DOCUMENT_START_EVENT:
accumulate = 1
break
case yaml_SEQUENCE_START_EVENT:
accumulate = 2
break
case yaml_MAPPING_START_EVENT:
accumulate = 3
break
default:
return false
}
if len(emitter.events)-emitter.events_head > accumulate {
return false
}
var level int
for i := emitter.events_head; i < len(emitter.events); i++ {
switch emitter.events[i].typ {
case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT:
level++
case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT:
level--
}
if level == 0 {
return false
}
}
return true
}
// Append a directive to the directives stack.
func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool {
for i := 0; i < len(emitter.tag_directives); i++ {
if bytes.Equal(value.handle, emitter.tag_directives[i].handle) {
if allow_duplicates {
return true
}
return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive")
}
}
// [Go] Do we actually need to copy this given garbage collection
// and the lack of deallocating destructors?
tag_copy := yaml_tag_directive_t{
handle: make([]byte, len(value.handle)),
prefix: make([]byte, len(value.prefix)),
}
copy(tag_copy.handle, value.handle)
copy(tag_copy.prefix, value.prefix)
emitter.tag_directives = append(emitter.tag_directives, tag_copy)
return true
}
// Increase the indentation level.
func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool {
emitter.indents = append(emitter.indents, emitter.indent)
if emitter.indent < 0 {
if flow {
emitter.indent = emitter.best_indent
} else {
emitter.indent = 0
}
} else if !indentless {
emitter.indent += emitter.best_indent
}
return true
}
// State dispatcher.
func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool {
switch emitter.state {
default:
case yaml_EMIT_STREAM_START_STATE:
return yaml_emitter_emit_stream_start(emitter, event)
case yaml_EMIT_FIRST_DOCUMENT_START_STATE:
return yaml_emitter_emit_document_start(emitter, event, true)
case yaml_EMIT_DOCUMENT_START_STATE:
return yaml_emitter_emit_document_start(emitter, event, false)
case yaml_EMIT_DOCUMENT_CONTENT_STATE:
return yaml_emitter_emit_document_content(emitter, event)
case yaml_EMIT_DOCUMENT_END_STATE:
return yaml_emitter_emit_document_end(emitter, event)
case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE:
return yaml_emitter_emit_flow_sequence_item(emitter, event, true)
case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE:
return yaml_emitter_emit_flow_sequence_item(emitter, event, false)
case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE:
return yaml_emitter_emit_flow_mapping_key(emitter, event, true)
case yaml_EMIT_FLOW_MAPPING_KEY_STATE:
return yaml_emitter_emit_flow_mapping_key(emitter, event, false)
case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE:
return yaml_emitter_emit_flow_mapping_value(emitter, event, true)
case yaml_EMIT_FLOW_MAPPING_VALUE_STATE:
return yaml_emitter_emit_flow_mapping_value(emitter, event, false)
case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE:
return yaml_emitter_emit_block_sequence_item(emitter, event, true)
case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE:
return yaml_emitter_emit_block_sequence_item(emitter, event, false)
case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE:
return yaml_emitter_emit_block_mapping_key(emitter, event, true)
case yaml_EMIT_BLOCK_MAPPING_KEY_STATE:
return yaml_emitter_emit_block_mapping_key(emitter, event, false)
case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE:
return yaml_emitter_emit_block_mapping_value(emitter, event, true)
case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE:
return yaml_emitter_emit_block_mapping_value(emitter, event, false)
case yaml_EMIT_END_STATE:
return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END")
}
panic("invalid emitter state")
}
// Expect STREAM-START.
func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
if event.typ != yaml_STREAM_START_EVENT {
return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START")
}
if emitter.encoding == yaml_ANY_ENCODING {
emitter.encoding = event.encoding
if emitter.encoding == yaml_ANY_ENCODING {
emitter.encoding = yaml_UTF8_ENCODING
}
}
if emitter.best_indent < 2 || emitter.best_indent > 9 {
emitter.best_indent = 2
}
if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 {
emitter.best_width = 80
}
if emitter.best_width < 0 {
emitter.best_width = 1<<31 - 1
}
if emitter.line_break == yaml_ANY_BREAK {
emitter.line_break = yaml_LN_BREAK
}
emitter.indent = -1
emitter.line = 0
emitter.column = 0
emitter.whitespace = true
emitter.indention = true
if emitter.encoding != yaml_UTF8_ENCODING {
if !yaml_emitter_write_bom(emitter) {
return false
}
}
emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE
return true
}
// Expect DOCUMENT-START or STREAM-END.
func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
if event.typ == yaml_DOCUMENT_START_EVENT {
if event.version_directive != nil {
if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) {
return false
}
}
for i := 0; i < len(event.tag_directives); i++ {
tag_directive := &event.tag_directives[i]
if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) {
return false
}
if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) {
return false
}
}
for i := 0; i < len(default_tag_directives); i++ {
tag_directive := &default_tag_directives[i]
if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) {
return false
}
}
implicit := event.implicit
if !first || emitter.canonical {
implicit = false
}
if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) {
if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if event.version_directive != nil {
implicit = false
if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) {
return false
}
if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if len(event.tag_directives) > 0 {
implicit = false
for i := 0; i < len(event.tag_directives); i++ {
tag_directive := &event.tag_directives[i]
if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) {
return false
}
if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) {
return false
}
if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
}
if yaml_emitter_check_empty_document(emitter) {
implicit = false
}
if !implicit {
if !yaml_emitter_write_indent(emitter) {
return false
}
if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) {
return false
}
if emitter.canonical {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
}
emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE
return true
}
if event.typ == yaml_STREAM_END_EVENT {
if emitter.open_ended {
if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !yaml_emitter_flush(emitter) {
return false
}
emitter.state = yaml_EMIT_END_STATE
return true
}
return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END")
}
// Expect the root node.
func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool {
emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE)
return yaml_emitter_emit_node(emitter, event, true, false, false, false)
}
// Expect DOCUMENT-END.
func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool {
if event.typ != yaml_DOCUMENT_END_EVENT {
return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END")
}
if !yaml_emitter_write_indent(emitter) {
return false
}
if !event.implicit {
// [Go] Allocate the slice elsewhere.
if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !yaml_emitter_flush(emitter) {
return false
}
emitter.state = yaml_EMIT_DOCUMENT_START_STATE
emitter.tag_directives = emitter.tag_directives[:0]
return true
}
// Expect a flow item node.
func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
if first {
if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) {
return false
}
if !yaml_emitter_increase_indent(emitter, true, false) {
return false
}
emitter.flow_level++
}
if event.typ == yaml_SEQUENCE_END_EVENT {
emitter.flow_level--
emitter.indent = emitter.indents[len(emitter.indents)-1]
emitter.indents = emitter.indents[:len(emitter.indents)-1]
if emitter.canonical && !first {
if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) {
return false
}
emitter.state = emitter.states[len(emitter.states)-1]
emitter.states = emitter.states[:len(emitter.states)-1]
return true
}
if !first {
if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
return false
}
}
if emitter.canonical || emitter.column > emitter.best_width {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE)
return yaml_emitter_emit_node(emitter, event, false, true, false, false)
}
// Expect a flow key node.
func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
if first {
if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) {
return false
}
if !yaml_emitter_increase_indent(emitter, true, false) {
return false
}
emitter.flow_level++
}
if event.typ == yaml_MAPPING_END_EVENT {
emitter.flow_level--
emitter.indent = emitter.indents[len(emitter.indents)-1]
emitter.indents = emitter.indents[:len(emitter.indents)-1]
if emitter.canonical && !first {
if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
return false
}
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) {
return false
}
emitter.state = emitter.states[len(emitter.states)-1]
emitter.states = emitter.states[:len(emitter.states)-1]
return true
}
if !first {
if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) {
return false
}
}
if emitter.canonical || emitter.column > emitter.best_width {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !emitter.canonical && yaml_emitter_check_simple_key(emitter) {
emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE)
return yaml_emitter_emit_node(emitter, event, false, false, true, true)
}
if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) {
return false
}
emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE)
return yaml_emitter_emit_node(emitter, event, false, false, true, false)
}
// Expect a flow value node.
func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool {
if simple {
if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) {
return false
}
} else {
if emitter.canonical || emitter.column > emitter.best_width {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) {
return false
}
}
emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE)
return yaml_emitter_emit_node(emitter, event, false, false, true, false)
}
// Expect a block item node.
func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
if first {
if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) {
return false
}
}
if event.typ == yaml_SEQUENCE_END_EVENT {
emitter.indent = emitter.indents[len(emitter.indents)-1]
emitter.indents = emitter.indents[:len(emitter.indents)-1]
emitter.state = emitter.states[len(emitter.states)-1]
emitter.states = emitter.states[:len(emitter.states)-1]
return true
}
if !yaml_emitter_write_indent(emitter) {
return false
}
if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) {
return false
}
emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE)
return yaml_emitter_emit_node(emitter, event, false, true, false, false)
}
// Expect a block key node.
func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool {
if first {
if !yaml_emitter_increase_indent(emitter, false, false) {
return false
}
}
if event.typ == yaml_MAPPING_END_EVENT {
emitter.indent = emitter.indents[len(emitter.indents)-1]
emitter.indents = emitter.indents[:len(emitter.indents)-1]
emitter.state = emitter.states[len(emitter.states)-1]
emitter.states = emitter.states[:len(emitter.states)-1]
return true
}
if !yaml_emitter_write_indent(emitter) {
return false
}
if yaml_emitter_check_simple_key(emitter) {
emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE)
return yaml_emitter_emit_node(emitter, event, false, false, true, true)
}
if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) {
return false
}
emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE)
return yaml_emitter_emit_node(emitter, event, false, false, true, false)
}
// Expect a block value node.
func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool {
if simple {
if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) {
return false
}
} else {
if !yaml_emitter_write_indent(emitter) {
return false
}
if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) {
return false
}
}
emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE)
return yaml_emitter_emit_node(emitter, event, false, false, true, false)
}
// Expect a node.
func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t,
root bool, sequence bool, mapping bool, simple_key bool) bool {
emitter.root_context = root
emitter.sequence_context = sequence
emitter.mapping_context = mapping
emitter.simple_key_context = simple_key
switch event.typ {
case yaml_ALIAS_EVENT:
return yaml_emitter_emit_alias(emitter, event)
case yaml_SCALAR_EVENT:
return yaml_emitter_emit_scalar(emitter, event)
case yaml_SEQUENCE_START_EVENT:
return yaml_emitter_emit_sequence_start(emitter, event)
case yaml_MAPPING_START_EVENT:
return yaml_emitter_emit_mapping_start(emitter, event)
default:
return yaml_emitter_set_emitter_error(emitter,
"expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS")
}
return false
}
// Expect ALIAS.
func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool {
if !yaml_emitter_process_anchor(emitter) {
return false
}
emitter.state = emitter.states[len(emitter.states)-1]
emitter.states = emitter.states[:len(emitter.states)-1]
return true
}
// Expect SCALAR.
func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool {
if !yaml_emitter_select_scalar_style(emitter, event) {
return false
}
if !yaml_emitter_process_anchor(emitter) {
return false
}
if !yaml_emitter_process_tag(emitter) {
return false
}
if !yaml_emitter_increase_indent(emitter, true, false) {
return false
}
if !yaml_emitter_process_scalar(emitter) {
return false
}
emitter.indent = emitter.indents[len(emitter.indents)-1]
emitter.indents = emitter.indents[:len(emitter.indents)-1]
emitter.state = emitter.states[len(emitter.states)-1]
emitter.states = emitter.states[:len(emitter.states)-1]
return true
}
// Expect SEQUENCE-START.
func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
if !yaml_emitter_process_anchor(emitter) {
return false
}
if !yaml_emitter_process_tag(emitter) {
return false
}
if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE ||
yaml_emitter_check_empty_sequence(emitter) {
emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE
} else {
emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE
}
return true
}
// Expect MAPPING-START.
func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool {
if !yaml_emitter_process_anchor(emitter) {
return false
}
if !yaml_emitter_process_tag(emitter) {
return false
}
if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE ||
yaml_emitter_check_empty_mapping(emitter) {
emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE
} else {
emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE
}
return true
}
// Check if the document content is an empty scalar.
func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool {
return false // [Go] Huh?
}
// Check if the next events represent an empty sequence.
func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool {
if len(emitter.events)-emitter.events_head < 2 {
return false
}
return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT &&
emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT
}
// Check if the next events represent an empty mapping.
func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool {
if len(emitter.events)-emitter.events_head < 2 {
return false
}
return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT &&
emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT
}
// Check if the next node can be expressed as a simple key.
func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool {
length := 0
switch emitter.events[emitter.events_head].typ {
case yaml_ALIAS_EVENT:
length += len(emitter.anchor_data.anchor)
case yaml_SCALAR_EVENT:
if emitter.scalar_data.multiline {
return false
}
length += len(emitter.anchor_data.anchor) +
len(emitter.tag_data.handle) +
len(emitter.tag_data.suffix) +
len(emitter.scalar_data.value)
case yaml_SEQUENCE_START_EVENT:
if !yaml_emitter_check_empty_sequence(emitter) {
return false
}
length += len(emitter.anchor_data.anchor) +
len(emitter.tag_data.handle) +
len(emitter.tag_data.suffix)
case yaml_MAPPING_START_EVENT:
if !yaml_emitter_check_empty_mapping(emitter) {
return false
}
length += len(emitter.anchor_data.anchor) +
len(emitter.tag_data.handle) +
len(emitter.tag_data.suffix)
default:
return false
}
return length <= 128
}
// Determine an acceptable scalar style.
func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool {
no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0
if no_tag && !event.implicit && !event.quoted_implicit {
return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified")
}
style := event.scalar_style()
if style == yaml_ANY_SCALAR_STYLE {
style = yaml_PLAIN_SCALAR_STYLE
}
if emitter.canonical {
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
}
if emitter.simple_key_context && emitter.scalar_data.multiline {
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
}
if style == yaml_PLAIN_SCALAR_STYLE {
if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed ||
emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed {
style = yaml_SINGLE_QUOTED_SCALAR_STYLE
}
if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) {
style = yaml_SINGLE_QUOTED_SCALAR_STYLE
}
if no_tag && !event.implicit {
style = yaml_SINGLE_QUOTED_SCALAR_STYLE
}
}
if style == yaml_SINGLE_QUOTED_SCALAR_STYLE {
if !emitter.scalar_data.single_quoted_allowed {
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
}
}
if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE {
if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context {
style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
}
}
if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE {
emitter.tag_data.handle = []byte{'!'}
}
emitter.scalar_data.style = style
return true
}
// Write an achor.
func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool {
if emitter.anchor_data.anchor == nil {
return true
}
c := []byte{'&'}
if emitter.anchor_data.alias {
c[0] = '*'
}
if !yaml_emitter_write_indicator(emitter, c, true, false, false) {
return false
}
return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor)
}
// Write a tag.
func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool {
if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 {
return true
}
if len(emitter.tag_data.handle) > 0 {
if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) {
return false
}
if len(emitter.tag_data.suffix) > 0 {
if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) {
return false
}
}
} else {
// [Go] Allocate these slices elsewhere.
if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) {
return false
}
if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) {
return false
}
if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) {
return false
}
}
return true
}
// Write a scalar.
func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool {
switch emitter.scalar_data.style {
case yaml_PLAIN_SCALAR_STYLE:
return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context)
case yaml_SINGLE_QUOTED_SCALAR_STYLE:
return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context)
case yaml_DOUBLE_QUOTED_SCALAR_STYLE:
return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context)
case yaml_LITERAL_SCALAR_STYLE:
return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value)
case yaml_FOLDED_SCALAR_STYLE:
return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value)
}
panic("unknown scalar style")
}
// Check if a %YAML directive is valid.
func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool {
if version_directive.major != 1 || version_directive.minor != 1 {
return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive")
}
return true
}
// Check if a %TAG directive is valid.
func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool {
handle := tag_directive.handle
prefix := tag_directive.prefix
if len(handle) == 0 {
return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty")
}
if handle[0] != '!' {
return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'")
}
if handle[len(handle)-1] != '!' {
return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'")
}
for i := 1; i < len(handle)-1; i += width(handle[i]) {
if !is_alpha(handle, i) {
return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only")
}
}
if len(prefix) == 0 {
return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty")
}
return true
}
// Check if an anchor is valid.
func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool {
if len(anchor) == 0 {
problem := "anchor value must not be empty"
if alias {
problem = "alias value must not be empty"
}
return yaml_emitter_set_emitter_error(emitter, problem)
}
for i := 0; i < len(anchor); i += width(anchor[i]) {
if !is_alpha(anchor, i) {
problem := "anchor value must contain alphanumerical characters only"
if alias {
problem = "alias value must contain alphanumerical characters only"
}
return yaml_emitter_set_emitter_error(emitter, problem)
}
}
emitter.anchor_data.anchor = anchor
emitter.anchor_data.alias = alias
return true
}
// Check if a tag is valid.
func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool {
if len(tag) == 0 {
return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty")
}
for i := 0; i < len(emitter.tag_directives); i++ {
tag_directive := &emitter.tag_directives[i]
if bytes.HasPrefix(tag, tag_directive.prefix) {
emitter.tag_data.handle = tag_directive.handle
emitter.tag_data.suffix = tag[len(tag_directive.prefix):]
return true
}
}
emitter.tag_data.suffix = tag
return true
}
// Check if a scalar is valid.
func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool {
var (
block_indicators = false
flow_indicators = false
line_breaks = false
special_characters = false
leading_space = false
leading_break = false
trailing_space = false
trailing_break = false
break_space = false
space_break = false
preceeded_by_whitespace = false
followed_by_whitespace = false
previous_space = false
previous_break = false
)
emitter.scalar_data.value = value
if len(value) == 0 {
emitter.scalar_data.multiline = false
emitter.scalar_data.flow_plain_allowed = false
emitter.scalar_data.block_plain_allowed = true
emitter.scalar_data.single_quoted_allowed = true
emitter.scalar_data.block_allowed = false
return true
}
if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) {
block_indicators = true
flow_indicators = true
}
preceeded_by_whitespace = true
for i, w := 0, 0; i < len(value); i += w {
w = width(value[i])
followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w)
if i == 0 {
switch value[i] {
case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`':
flow_indicators = true
block_indicators = true
case '?', ':':
flow_indicators = true
if followed_by_whitespace {
block_indicators = true
}
case '-':
if followed_by_whitespace {
flow_indicators = true
block_indicators = true
}
}
} else {
switch value[i] {
case ',', '?', '[', ']', '{', '}':
flow_indicators = true
case ':':
flow_indicators = true
if followed_by_whitespace {
block_indicators = true
}
case '#':
if preceeded_by_whitespace {
flow_indicators = true
block_indicators = true
}
}
}
if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode {
special_characters = true
}
if is_space(value, i) {
if i == 0 {
leading_space = true
}
if i+width(value[i]) == len(value) {
trailing_space = true
}
if previous_break {
break_space = true
}
previous_space = true
previous_break = false
} else if is_break(value, i) {
line_breaks = true
if i == 0 {
leading_break = true
}
if i+width(value[i]) == len(value) {
trailing_break = true
}
if previous_space {
space_break = true
}
previous_space = false
previous_break = true
} else {
previous_space = false
previous_break = false
}
// [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition.
preceeded_by_whitespace = is_blankz(value, i)
}
emitter.scalar_data.multiline = line_breaks
emitter.scalar_data.flow_plain_allowed = true
emitter.scalar_data.block_plain_allowed = true
emitter.scalar_data.single_quoted_allowed = true
emitter.scalar_data.block_allowed = true
if leading_space || leading_break || trailing_space || trailing_break {
emitter.scalar_data.flow_plain_allowed = false
emitter.scalar_data.block_plain_allowed = false
}
if trailing_space {
emitter.scalar_data.block_allowed = false
}
if break_space {
emitter.scalar_data.flow_plain_allowed = false
emitter.scalar_data.block_plain_allowed = false
emitter.scalar_data.single_quoted_allowed = false
}
if space_break || special_characters {
emitter.scalar_data.flow_plain_allowed = false
emitter.scalar_data.block_plain_allowed = false
emitter.scalar_data.single_quoted_allowed = false
emitter.scalar_data.block_allowed = false
}
if line_breaks {
emitter.scalar_data.flow_plain_allowed = false
emitter.scalar_data.block_plain_allowed = false
}
if flow_indicators {
emitter.scalar_data.flow_plain_allowed = false
}
if block_indicators {
emitter.scalar_data.block_plain_allowed = false
}
return true
}
// Check if the event data is valid.
func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool {
emitter.anchor_data.anchor = nil
emitter.tag_data.handle = nil
emitter.tag_data.suffix = nil
emitter.scalar_data.value = nil
switch event.typ {
case yaml_ALIAS_EVENT:
if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) {
return false
}
case yaml_SCALAR_EVENT:
if len(event.anchor) > 0 {
if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
return false
}
}
if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) {
if !yaml_emitter_analyze_tag(emitter, event.tag) {
return false
}
}
if !yaml_emitter_analyze_scalar(emitter, event.value) {
return false
}
case yaml_SEQUENCE_START_EVENT:
if len(event.anchor) > 0 {
if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
return false
}
}
if len(event.tag) > 0 && (emitter.canonical || !event.implicit) {
if !yaml_emitter_analyze_tag(emitter, event.tag) {
return false
}
}
case yaml_MAPPING_START_EVENT:
if len(event.anchor) > 0 {
if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) {
return false
}
}
if len(event.tag) > 0 && (emitter.canonical || !event.implicit) {
if !yaml_emitter_analyze_tag(emitter, event.tag) {
return false
}
}
}
return true
}
// Write the BOM character.
func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool {
if !flush(emitter) {
return false
}
pos := emitter.buffer_pos
emitter.buffer[pos+0] = '\xEF'
emitter.buffer[pos+1] = '\xBB'
emitter.buffer[pos+2] = '\xBF'
emitter.buffer_pos += 3
return true
}
func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool {
indent := emitter.indent
if indent < 0 {
indent = 0
}
if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) {
if !put_break(emitter) {
return false
}
}
for emitter.column < indent {
if !put(emitter, ' ') {
return false
}
}
emitter.whitespace = true
emitter.indention = true
return true
}
func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool {
if need_whitespace && !emitter.whitespace {
if !put(emitter, ' ') {
return false
}
}
if !write_all(emitter, indicator) {
return false
}
emitter.whitespace = is_whitespace
emitter.indention = (emitter.indention && is_indention)
emitter.open_ended = false
return true
}
func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool {
if !write_all(emitter, value) {
return false
}
emitter.whitespace = false
emitter.indention = false
return true
}
func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool {
if !emitter.whitespace {
if !put(emitter, ' ') {
return false
}
}
if !write_all(emitter, value) {
return false
}
emitter.whitespace = false
emitter.indention = false
return true
}
func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool {
if need_whitespace && !emitter.whitespace {
if !put(emitter, ' ') {
return false
}
}
for i := 0; i < len(value); {
var must_write bool
switch value[i] {
case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']':
must_write = true
default:
must_write = is_alpha(value, i)
}
if must_write {
if !write(emitter, value, &i) {
return false
}
} else {
w := width(value[i])
for k := 0; k < w; k++ {
octet := value[i]
i++
if !put(emitter, '%') {
return false
}
c := octet >> 4
if c < 10 {
c += '0'
} else {
c += 'A' - 10
}
if !put(emitter, c) {
return false
}
c = octet & 0x0f
if c < 10 {
c += '0'
} else {
c += 'A' - 10
}
if !put(emitter, c) {
return false
}
}
}
}
emitter.whitespace = false
emitter.indention = false
return true
}
func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool {
if !emitter.whitespace {
if !put(emitter, ' ') {
return false
}
}
spaces := false
breaks := false
for i := 0; i < len(value); {
if is_space(value, i) {
if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) {
if !yaml_emitter_write_indent(emitter) {
return false
}
i += width(value[i])
} else {
if !write(emitter, value, &i) {
return false
}
}
spaces = true
} else if is_break(value, i) {
if !breaks && value[i] == '\n' {
if !put_break(emitter) {
return false
}
}
if !write_break(emitter, value, &i) {
return false
}
emitter.indention = true
breaks = true
} else {
if breaks {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !write(emitter, value, &i) {
return false
}
emitter.indention = false
spaces = false
breaks = false
}
}
emitter.whitespace = false
emitter.indention = false
if emitter.root_context {
emitter.open_ended = true
}
return true
}
func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool {
if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) {
return false
}
spaces := false
breaks := false
for i := 0; i < len(value); {
if is_space(value, i) {
if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) {
if !yaml_emitter_write_indent(emitter) {
return false
}
i += width(value[i])
} else {
if !write(emitter, value, &i) {
return false
}
}
spaces = true
} else if is_break(value, i) {
if !breaks && value[i] == '\n' {
if !put_break(emitter) {
return false
}
}
if !write_break(emitter, value, &i) {
return false
}
emitter.indention = true
breaks = true
} else {
if breaks {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if value[i] == '\'' {
if !put(emitter, '\'') {
return false
}
}
if !write(emitter, value, &i) {
return false
}
emitter.indention = false
spaces = false
breaks = false
}
}
if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) {
return false
}
emitter.whitespace = false
emitter.indention = false
return true
}
func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool {
spaces := false
if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) {
return false
}
for i := 0; i < len(value); {
if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) ||
is_bom(value, i) || is_break(value, i) ||
value[i] == '"' || value[i] == '\\' {
octet := value[i]
var w int
var v rune
switch {
case octet&0x80 == 0x00:
w, v = 1, rune(octet&0x7F)
case octet&0xE0 == 0xC0:
w, v = 2, rune(octet&0x1F)
case octet&0xF0 == 0xE0:
w, v = 3, rune(octet&0x0F)
case octet&0xF8 == 0xF0:
w, v = 4, rune(octet&0x07)
}
for k := 1; k < w; k++ {
octet = value[i+k]
v = (v << 6) + (rune(octet) & 0x3F)
}
i += w
if !put(emitter, '\\') {
return false
}
var ok bool
switch v {
case 0x00:
ok = put(emitter, '0')
case 0x07:
ok = put(emitter, 'a')
case 0x08:
ok = put(emitter, 'b')
case 0x09:
ok = put(emitter, 't')
case 0x0A:
ok = put(emitter, 'n')
case 0x0b:
ok = put(emitter, 'v')
case 0x0c:
ok = put(emitter, 'f')
case 0x0d:
ok = put(emitter, 'r')
case 0x1b:
ok = put(emitter, 'e')
case 0x22:
ok = put(emitter, '"')
case 0x5c:
ok = put(emitter, '\\')
case 0x85:
ok = put(emitter, 'N')
case 0xA0:
ok = put(emitter, '_')
case 0x2028:
ok = put(emitter, 'L')
case 0x2029:
ok = put(emitter, 'P')
default:
if v <= 0xFF {
ok = put(emitter, 'x')
w = 2
} else if v <= 0xFFFF {
ok = put(emitter, 'u')
w = 4
} else {
ok = put(emitter, 'U')
w = 8
}
for k := (w - 1) * 4; ok && k >= 0; k -= 4 {
digit := byte((v >> uint(k)) & 0x0F)
if digit < 10 {
ok = put(emitter, digit+'0')
} else {
ok = put(emitter, digit+'A'-10)
}
}
}
if !ok {
return false
}
spaces = false
} else if is_space(value, i) {
if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 {
if !yaml_emitter_write_indent(emitter) {
return false
}
if is_space(value, i+1) {
if !put(emitter, '\\') {
return false
}
}
i += width(value[i])
} else if !write(emitter, value, &i) {
return false
}
spaces = true
} else {
if !write(emitter, value, &i) {
return false
}
spaces = false
}
}
if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) {
return false
}
emitter.whitespace = false
emitter.indention = false
return true
}
func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool {
if is_space(value, 0) || is_break(value, 0) {
indent_hint := []byte{'0' + byte(emitter.best_indent)}
if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) {
return false
}
}
emitter.open_ended = false
var chomp_hint [1]byte
if len(value) == 0 {
chomp_hint[0] = '-'
} else {
i := len(value) - 1
for value[i]&0xC0 == 0x80 {
i--
}
if !is_break(value, i) {
chomp_hint[0] = '-'
} else if i == 0 {
chomp_hint[0] = '+'
emitter.open_ended = true
} else {
i--
for value[i]&0xC0 == 0x80 {
i--
}
if is_break(value, i) {
chomp_hint[0] = '+'
emitter.open_ended = true
}
}
}
if chomp_hint[0] != 0 {
if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) {
return false
}
}
return true
}
func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool {
if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) {
return false
}
if !yaml_emitter_write_block_scalar_hints(emitter, value) {
return false
}
if !put_break(emitter) {
return false
}
emitter.indention = true
emitter.whitespace = true
breaks := true
for i := 0; i < len(value); {
if is_break(value, i) {
if !write_break(emitter, value, &i) {
return false
}
emitter.indention = true
breaks = true
} else {
if breaks {
if !yaml_emitter_write_indent(emitter) {
return false
}
}
if !write(emitter, value, &i) {
return false
}
emitter.indention = false
breaks = false
}
}
return true
}
func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool {
if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) {
return false
}
if !yaml_emitter_write_block_scalar_hints(emitter, value) {
return false
}
if !put_break(emitter) {
return false
}
emitter.indention = true
emitter.whitespace = true
breaks := true
leading_spaces := true
for i := 0; i < len(value); {
if is_break(value, i) {
if !breaks && !leading_spaces && value[i] == '\n' {
k := 0
for is_break(value, k) {
k += width(value[k])
}
if !is_blankz(value, k) {
if !put_break(emitter) {
return false
}
}
}
if !write_break(emitter, value, &i) {
return false
}
emitter.indention = true
breaks = true
} else {
if breaks {
if !yaml_emitter_write_indent(emitter) {
return false
}
leading_spaces = is_blank(value, i)
}
if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width {
if !yaml_emitter_write_indent(emitter) {
return false
}
i += width(value[i])
} else {
if !write(emitter, value, &i) {
return false
}
}
emitter.indention = false
breaks = false
}
}
return true
}
| {
"pile_set_name": "Github"
} |
# Brigadier
A Windows- and OS X-compatible Python script that fetches, from Apple's or your software update server, the Boot Camp ESD ("Electronic Software Distribution") for a specific model of Mac. It unpacks the multiple layers of archives within the flat package and if the script is run on Windows with the `--install` option, it also runs the 64-bit MSI installer.
On Windows, the archives are unpacked using [7-Zip](http://www.7-zip.org), and the 7-Zip MSI is downloaded and installed, and removed later if Brigadier installed it. This tool used to use [dmg2img](http://vu1tur.eu.org/tools/) to perform the extraction of files from Apple's `WindowsSupport.dmg` file, but more recent versions of 7-Zip have included more completely support for DMGs, so dmg2img seems to be no longer needed.
This was written for two reasons:
1. We'd like to maintain as few Windows system images as possible, but there are typically 3-5 BootCampESD packages available from Apple at any given time, targeting specific sets of models. It's possible to use the [Orca](http://support.microsoft.com/kb/255905) tool to edit the MSI's properties and disable the model check, but there are rarely cases where a single installer contains all drivers. Apple can already download the correct installer for a booted machine model in OS X using the Boot Camp Assistant, so there's no reason we can't do the same within Windows.
2. Sometimes we just want to download and extract a copy of the installer for a given model. The steps to do this manually are tedious, and there are many of them. As of the spring of 2013, Apple has made a number of Boot Camp installer packages available on their support downloads page, but they are still a split across many different different sets of models and it is still inconvenient to ensure you have the correct package.
It was originally designed to be run as post-imaging step for Boot Camp deployments to Macs, but as it requires network connectivity, a network driver must be already available on the system. (See Caveats below)
## Important (!) note on support for Brigadier
Brigadier has produced less-than-great results with some combinations of driver packages and hardware models in recent versions of Boot Camp 5, and now with Boot Camp 6. Some people have confirmed issues with Boot Camp 6 and Windows 7 in general, so these may not be entirely Brigadier's fault. Some examination of the Boot Camp `setup.exe` indicates to me that this executable performs several tasks and sets up some environment for the eventual execution of `BootCamp.msi`, which we're not always able to get with Brigadier's simple invocation of `msiexec` to install the MSI directly.
I'm far from knowledgable enough about Windows internals to understand how to be able to perform a fully-automated version of whatever setup.exe actually does (besides eventually run `msiexec /i /qr` on the MSI). For example, [this PR](https://github.com/timsutton/brigadier/pull/14) suggests that better results can be achieved by using different "quiet" options to `msiexec`, but a disassembly of `setup.exe` shows that it is actually executing `/qr`, as does the code in the current master branch. This kind of question is one I don't feel I have enough knowledge to attempt an answer.
There have been strange issues I've experienced a couple of years ago as well. For example, a single driver installer (Intel chipset-related) that pops up a series of WinRAR SFX errors due to it attempting to sequentially execute all of the driver's localization files (which aren't even executable). Simply clicking through these dialogs eventually causes the installation to continue, but until that happens the process is blocked. This error doesn't happen when a user manually runs `setup.exe`, but why I do not understand.
While I maintain some hope to be able to resolve these issues, my environment's use case for dual-boot labs is shrinking and so it's difficult to justify the time required to spend further researching these issues. If anyone who is knowledgeable about reversing `setup.exe`-like installer wrappers and MSI installers, and Windows systems administration in general, is interested in tackling the currently-somewhat-broken support for silent installs of Boot Camp drivers in this tool, I'd love some help! There are several installer properties in `BootCamp.msi` that may be of some help with this issue as well.
## Usage
Run brigadier with no options to download and unpack the ESD that applies to this model, to the current working directory. On OS X, the ESD is kept in a .dmg format for easy burning to a disc; on Windows, the driver files are extracted.
Run it with the `--model` option to specify an alternate model, in the form `MacPro3,1`, etc.
Run it with the `--install` option to both download and install, deleting the drivers after installation. This obviously works only on Windows. This option was made for doing automated installations of the Boot Camp drivers.
Place a `brigadier.plist` file in the same folder as the script to override the .sucatalog URL to point to an internal Software Update Server catalog (details below).
Additional options shown below.
## Getting it
You can find a pre-compiled binary for Windows in the [releases](https://github.com/timsutton/brigadier/releases) area. This can be useful if you don't already have Python installed on Windows. This was built using [PyInstaller](http://www.pyinstaller.org). More details on building it yourself [below](#runningbuilding-from-source-on-windows).
It can also be run directly from a Git checkout on either OS X or Windows.
## Configuration
Besides a few command-line options:
<pre><code>Usage: brigadier [options]
Options:
-h, --help show this help message and exit
-m MODEL, --model=MODEL
System model identifier to use (otherwise this
machine's model is used).
-i, --install After the installer is downloaded, perform the install
automatically. Can be used on Windows only.
-o OUTPUT_DIR, --output-dir=OUTPUT_DIR
Base path where the installer files will be extracted
into a folder named after the product, ie.
'BootCamp-041-1234'. Uses the current directory if
this option is omitted.
-k, --keep-files Keep the files that were downloaded/extracted. Useful
only with the '--install' option on Windows.</code></pre>
You can also create a `brigadier.plist` XML plist file and place it in the same directory as the script. It currently supports one key: `CatalogURL`, a string that points to an internal SUS catalog URL that contains BootCampESD packages. See the example [in this repo](https://github.com/timsutton/brigadier/blob/master/plist-example/brigadier.plist).
## Running as a Sysprep FirstLogonCommand
It's common to perform the Boot Camp drivers during a post-imaging Sysprep phase, so that it's possible to deploy the same image to different models without taking into account the model and required Boot Camp package. Brigadier seems to behave in the context of a SysPrep <a href="http://technet.microsoft.com/en-us/library/cc722150(v=ws.10).aspx">FirstLogonCommand</a>.
There is one workaround performed by the script when running in this scenario, where the current working would normally be `\windows\system32`. In my tests on a 64-bit system, the MSI would halt trying to locate its installer components, due to the way Windows forks its `System32` folder into `SysWoW64` for 32-bit applications. When the script detects this working directory without a `--output-dir` option overriding it, it will set the output directory to the root of the system, ie. `%SystemRoot%\`.
By default, when `--install` is used, it will clean up its extracted files after installation, unless the `--keep-files` option is given, so unless you want to keep the files around you shouldn't need to clean up after it.
## Running/building from source on Windows
If you'd rather run it as a standard Python script, you'll need [Python for Windows](http://www.python.org/download/releases) (this was tested with the latest 2.7 release) in order to execute the script.
If you'd rather build it yourself, you can use the included build script. It requires [Python](http://www.python.org/download/releases) and the matching version of [pywin32](http://sourceforge.net/projects/pywin32/files). It handles downloading PyInstaller for you. Simply run it with no arguments, and it will build a zip file in the current working directory:
`c:\python27\python build_windows_exe.py`
## Unpack details on Windows
On OS X, we have the native hdiutil and pkgutil commands to do the work of unpacking the driver files. On Windows, we:
1. Check if 7-Zip is already installed - if not, we download and install it
2. Extract the BootCampESD.pkg xar archive with 7-Zip
3. Extract the Payload archive with 7-Zip, once to decompress gzip and again to unpack the cpio archive
4. Use 7-Zip to extract the driver files from the `WindowsSupport.dmg` file within the pkg
5. Uninstall 7-Zip if we installed it
## Caveats
* It requires a network connection, which therefore requires that a working network driver be available. The simplest way I've found to do this is to place the various network drivers from BootCampESDs inside a "BootCamp" (or similar) folder within `C:\Windows\INF` on a sysprepped image. This folder is the default search location for device drivers, and it should automatically detect and install drivers located here for all unknown hardware. You can also modify the `DevicePath` <a href="http://technet.microsoft.com/en-us/library/cc731664(v=ws.10).aspx">registry key</a> to add a custom location, but using the existing `INF` folder means no other changes besides a file copy are required to update an existing image's drivers, so this can be done without actually restoring the image and booting it just to install a driver. Offline driver servicing using Windows and DISM is easy for WIM images, but most admins are likely not deploying WIM images to Macs, but rather using tools that wrap ntfsprogs.
* It currently performs almost no error handling.
* The 7-Zip downloads from a public URLs which is hardcoded in the script. Soon the `brigadier.plist` will support overriding these URLs with your own copies stored on a private webserver.
* After installation, it sets the `FirstTimeRun` registry key at `HKEY_CURRENT_USER\Software\Apple Inc.\Apple Keyboard Support` to disable the first-launch Boot Camp help popup, and there's currently no option to disable this behaviour.
* Only supports installations on 64-bit Windows. It's worth mentioning that the December 2012 Boot Camp driver ESDs seem to be 64-bit only, so extra work would need to be done to support 32-bit Windows. If 32-bit Windows support is important to you, there is an [issue](https://github.com/timsutton/brigadier/issues/2) created to track it.
| {
"pile_set_name": "Github"
} |
withtimeout [](http://godoc.org/github.com/zhouzhuojie/withtimeout)
==========
`withtimeout` provides a Golang package that allows adding a timeout to any operation. It's based on `github.com/getlantern/withtimeout` with plain old goroutines, thus no extra dependencies.
| {
"pile_set_name": "Github"
} |
apiVersion: v1
kind: Namespace
metadata:
labels:
control-plane: controller-manager
name: system
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
labels:
control-plane: controller-manager
spec:
selector:
matchLabels:
control-plane: controller-manager
replicas: 1
template:
metadata:
labels:
control-plane: controller-manager
spec:
containers:
- command:
- /manager
args:
- "--mode=manager"
- "--manager-pod=$(MY_POD_NAME)"
- "--manager-namespace=$(MY_POD_NAMESPACE)"
- "--enable-leader-election"
env:
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: MY_POD_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
image: controller:latest
name: manager
resources:
limits:
cpu: 100m
memory: 30Mi
requests:
cpu: 100m
memory: 20Mi
terminationGracePeriodSeconds: 10
| {
"pile_set_name": "Github"
} |
/*
* QTest i.MX I2C driver
*
* Copyright (c) 2013 Jean-Christophe Dubois
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "libqos/i2c.h"
#include "libqtest.h"
#include "hw/i2c/imx_i2c.h"
enum IMXI2CDirection {
IMX_I2C_READ,
IMX_I2C_WRITE,
};
typedef struct IMXI2C {
I2CAdapter parent;
uint64_t addr;
} IMXI2C;
static void imx_i2c_set_slave_addr(IMXI2C *s, uint8_t addr,
enum IMXI2CDirection direction)
{
writeb(s->addr + I2DR_ADDR, (addr << 1) |
(direction == IMX_I2C_READ ? 1 : 0));
}
static void imx_i2c_send(I2CAdapter *i2c, uint8_t addr,
const uint8_t *buf, uint16_t len)
{
IMXI2C *s = (IMXI2C *)i2c;
uint8_t data;
uint8_t status;
uint16_t size = 0;
if (!len) {
return;
}
/* set the bus for write */
data = I2CR_IEN |
I2CR_IIEN |
I2CR_MSTA |
I2CR_MTX |
I2CR_TXAK;
writeb(s->addr + I2CR_ADDR, data);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) != 0);
/* set the slave address */
imx_i2c_set_slave_addr(s, addr, IMX_I2C_WRITE);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) != 0);
g_assert((status & I2SR_RXAK) == 0);
/* ack the interrupt */
writeb(s->addr + I2SR_ADDR, 0);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) == 0);
while (size < len) {
/* check we are still busy */
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) != 0);
/* write the data */
writeb(s->addr + I2DR_ADDR, buf[size]);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) != 0);
g_assert((status & I2SR_RXAK) == 0);
/* ack the interrupt */
writeb(s->addr + I2SR_ADDR, 0);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) == 0);
size++;
}
/* release the bus */
data &= ~(I2CR_MSTA | I2CR_MTX);
writeb(s->addr + I2CR_ADDR, data);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) == 0);
}
static void imx_i2c_recv(I2CAdapter *i2c, uint8_t addr,
uint8_t *buf, uint16_t len)
{
IMXI2C *s = (IMXI2C *)i2c;
uint8_t data;
uint8_t status;
uint16_t size = 0;
if (!len) {
return;
}
/* set the bus for write */
data = I2CR_IEN |
I2CR_IIEN |
I2CR_MSTA |
I2CR_MTX |
I2CR_TXAK;
writeb(s->addr + I2CR_ADDR, data);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) != 0);
/* set the slave address */
imx_i2c_set_slave_addr(s, addr, IMX_I2C_READ);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) != 0);
g_assert((status & I2SR_RXAK) == 0);
/* ack the interrupt */
writeb(s->addr + I2SR_ADDR, 0);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) == 0);
/* set the bus for read */
data &= ~I2CR_MTX;
/* if only one byte don't ack */
if (len != 1) {
data &= ~I2CR_TXAK;
}
writeb(s->addr + I2CR_ADDR, data);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) != 0);
/* dummy read */
readb(s->addr + I2DR_ADDR);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) != 0);
/* ack the interrupt */
writeb(s->addr + I2SR_ADDR, 0);
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) == 0);
while (size < len) {
/* check we are still busy */
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) != 0);
if (size == (len - 1)) {
/* stop the read transaction */
data &= ~(I2CR_MSTA | I2CR_MTX);
} else {
/* ack the data read */
data |= I2CR_TXAK;
}
writeb(s->addr + I2CR_ADDR, data);
/* read the data */
buf[size] = readb(s->addr + I2DR_ADDR);
if (size != (len - 1)) {
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) != 0);
/* ack the interrupt */
writeb(s->addr + I2SR_ADDR, 0);
}
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IIF) == 0);
size++;
}
status = readb(s->addr + I2SR_ADDR);
g_assert((status & I2SR_IBB) == 0);
}
I2CAdapter *imx_i2c_create(uint64_t addr)
{
IMXI2C *s = g_malloc0(sizeof(*s));
I2CAdapter *i2c = (I2CAdapter *)s;
s->addr = addr;
i2c->send = imx_i2c_send;
i2c->recv = imx_i2c_recv;
return i2c;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Core.Configuration.Xml.Tests
{
using System.IO;
using System.Xml;
using NUnit.Framework;
[TestFixture]
public class XmlConfigurationDeserializerTests
{
[Test]
[Bug("CORE-37")]
public void Tab_character_is_not_trimmed_from_config_value()
{
string result = XmlConfigurationDeserializer.GetConfigValue("\t");
Assert.AreEqual("\t", result);
}
[Test]
[Bug("CORE-37")]
public void Tab_character_is_not_trimmed_from_config_value_XML()
{
var node = new XmlDocument().ReadNode(XmlReader.Create(new StringReader("<foo><![CDATA[\t]]></foo>")));
var result = XmlConfigurationDeserializer.GetDeserializedNode(node);
Assert.AreEqual("\t", result.Value);
}
}
} | {
"pile_set_name": "Github"
} |
/*
* QEMU System Emulator
*
* Copyright (c) 2003-2008 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "qemu/osdep.h"
#include "qemu/config-file.h"
#include "cpu.h"
#include "monitor/monitor.h"
#include "qapi/error.h"
#include "qapi/qapi-commands-misc.h"
#include "qapi/qapi-events-run-state.h"
#include "qapi/qmp/qerror.h"
#include "qemu/error-report.h"
#include "sysemu/sysemu.h"
#include "sysemu/block-backend.h"
#include "exec/gdbstub.h"
#include "sysemu/dma.h"
#include "sysemu/hw_accel.h"
#include "sysemu/kvm.h"
#include "sysemu/hax.h"
#include "sysemu/hvf.h"
#include "sysemu/whpx.h"
#include "exec/exec-all.h"
#include "qemu/thread.h"
#include "sysemu/cpus.h"
#include "sysemu/qtest.h"
#include "qemu/main-loop.h"
#include "qemu/option.h"
#include "qemu/bitmap.h"
#include "qemu/seqlock.h"
#include "exec/tcg-wrapper.h"
#include "hw/nmi.h"
#include "sysemu/replay.h"
#include "hw/boards.h"
#ifdef CONFIG_LINUX
#include <sys/prctl.h>
#ifndef PR_MCE_KILL
#define PR_MCE_KILL 33
#endif
#ifndef PR_MCE_KILL_SET
#define PR_MCE_KILL_SET 1
#endif
#ifndef PR_MCE_KILL_EARLY
#define PR_MCE_KILL_EARLY 1
#endif
#endif /* CONFIG_LINUX */
int64_t max_delay;
int64_t max_advance;
/* vcpu throttling controls */
static QEMUTimer *throttle_timer;
static unsigned int throttle_percentage;
#define CPU_THROTTLE_PCT_MIN 1
#define CPU_THROTTLE_PCT_MAX 99
#define CPU_THROTTLE_TIMESLICE_NS 10000000
bool cpu_is_stopped(CPUState *cpu)
{
return cpu->stopped || !runstate_is_running();
}
static bool cpu_thread_is_idle(CPUState *cpu)
{
if (cpu->stop || cpu->queued_work_first) {
return false;
}
if (cpu_is_stopped(cpu)) {
return true;
}
if (!cpu->halted || cpu_has_work(cpu) ||
kvm_halt_in_kernel()) {
return false;
}
return true;
}
static bool all_cpu_threads_idle(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
if (!cpu_thread_is_idle(cpu)) {
return false;
}
}
return true;
}
/***********************************************************/
/* guest cycle counter */
/* Protected by TimersState seqlock */
static bool icount_sleep = true;
/* Arbitrarily pick 1MIPS as the minimum allowable speed. */
#define MAX_ICOUNT_SHIFT 10
typedef struct TimersState {
/* Protected by BQL. */
int64_t cpu_ticks_prev;
int64_t cpu_ticks_offset;
/* Protect fields that can be respectively read outside the
* BQL, and written from multiple threads.
*/
QemuSeqLock vm_clock_seqlock;
QemuSpin vm_clock_lock;
int16_t cpu_ticks_enabled;
/* Conversion factor from emulated instructions to virtual clock ticks. */
int16_t icount_time_shift;
/* Compensate for varying guest execution speed. */
int64_t qemu_icount_bias;
int64_t vm_clock_warp_start;
int64_t cpu_clock_offset;
/* Only written by TCG thread */
int64_t qemu_icount;
/* for adjusting icount */
QEMUTimer *icount_rt_timer;
QEMUTimer *icount_vm_timer;
QEMUTimer *icount_warp_timer;
} TimersState;
static TimersState timers_state;
bool mttcg_enabled;
/*
* We default to false if we know other options have been enabled
* which are currently incompatible with MTTCG. Otherwise when each
* guest (target) has been updated to support:
* - atomic instructions
* - memory ordering primitives (barriers)
* they can set the appropriate CONFIG flags in ${target}-softmmu.mak
*
* Once a guest architecture has been converted to the new primitives
* there are two remaining limitations to check.
*
* - The guest can't be oversized (e.g. 64 bit guest on 32 bit host)
* - The host must have a stronger memory order than the guest
*
* It may be possible in future to support strong guests on weak hosts
* but that will require tagging all load/stores in a guest with their
* implicit memory order requirements which would likely slow things
* down a lot.
*/
static bool check_tcg_memory_orders_compatible(void)
{
#if defined(TCG_GUEST_DEFAULT_MO) && defined(TCG_TARGET_DEFAULT_MO)
return (TCG_GUEST_DEFAULT_MO & ~TCG_TARGET_DEFAULT_MO) == 0;
#else
return false;
#endif
}
static bool default_mttcg_enabled(void)
{
if (use_icount || TCG_OVERSIZED_GUEST) {
return false;
} else {
#ifdef TARGET_SUPPORTS_MTTCG
return check_tcg_memory_orders_compatible();
#else
return false;
#endif
}
}
void qemu_tcg_configure(QemuOpts *opts, Error **errp)
{
const char *t = qemu_opt_get(opts, "thread");
if (t) {
if (strcmp(t, "multi") == 0) {
if (TCG_OVERSIZED_GUEST) {
error_setg(errp, "No MTTCG when guest word size > hosts");
} else if (use_icount) {
error_setg(errp, "No MTTCG when icount is enabled");
} else {
#ifndef TARGET_SUPPORTS_MTTCG
warn_report("Guest not yet converted to MTTCG - "
"you may get unexpected results");
#endif
if (!check_tcg_memory_orders_compatible()) {
warn_report("Guest expects a stronger memory ordering "
"than the host provides");
error_printf("This may cause strange/hard to debug errors\n");
}
mttcg_enabled = true;
}
} else if (strcmp(t, "single") == 0) {
mttcg_enabled = false;
} else {
error_setg(errp, "Invalid 'thread' setting %s", t);
}
} else {
mttcg_enabled = default_mttcg_enabled();
}
}
/* The current number of executed instructions is based on what we
* originally budgeted minus the current state of the decrementing
* icount counters in extra/u16.low.
*/
static int64_t cpu_get_icount_executed(CPUState *cpu)
{
return cpu->icount_budget - (cpu->icount_decr.u16.low + cpu->icount_extra);
}
/*
* Update the global shared timer_state.qemu_icount to take into
* account executed instructions. This is done by the TCG vCPU
* thread so the main-loop can see time has moved forward.
*/
static void cpu_update_icount_locked(CPUState *cpu)
{
int64_t executed = cpu_get_icount_executed(cpu);
cpu->icount_budget -= executed;
atomic_set_i64(&timers_state.qemu_icount,
timers_state.qemu_icount + executed);
}
/*
* Update the global shared timer_state.qemu_icount to take into
* account executed instructions. This is done by the TCG vCPU
* thread so the main-loop can see time has moved forward.
*/
void cpu_update_icount(CPUState *cpu)
{
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
cpu_update_icount_locked(cpu);
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
}
static int64_t cpu_get_icount_raw_locked(void)
{
CPUState *cpu = current_cpu;
if (cpu && cpu->running) {
if (!cpu->can_do_io) {
error_report("Bad icount read");
exit(1);
}
/* Take into account what has run */
cpu_update_icount_locked(cpu);
}
/* The read is protected by the seqlock, but needs atomic64 to avoid UB */
return atomic_read_i64(&timers_state.qemu_icount);
}
static int64_t cpu_get_icount_locked(void)
{
int64_t icount = cpu_get_icount_raw_locked();
return atomic_read_i64(&timers_state.qemu_icount_bias) +
cpu_icount_to_ns(icount);
}
int64_t cpu_get_icount_raw(void)
{
int64_t icount;
unsigned start;
do {
start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
icount = cpu_get_icount_raw_locked();
} while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));
return icount;
}
/* Return the virtual CPU time, based on the instruction counter. */
int64_t cpu_get_icount(void)
{
int64_t icount;
unsigned start;
do {
start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
icount = cpu_get_icount_locked();
} while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));
return icount;
}
int64_t cpu_icount_to_ns(int64_t icount)
{
return icount << atomic_read(&timers_state.icount_time_shift);
}
static int64_t cpu_get_ticks_locked(void)
{
int64_t ticks = timers_state.cpu_ticks_offset;
if (timers_state.cpu_ticks_enabled) {
ticks += cpu_get_host_ticks();
}
if (timers_state.cpu_ticks_prev > ticks) {
/* Non increasing ticks may happen if the host uses software suspend. */
timers_state.cpu_ticks_offset += timers_state.cpu_ticks_prev - ticks;
ticks = timers_state.cpu_ticks_prev;
}
timers_state.cpu_ticks_prev = ticks;
return ticks;
}
/* return the time elapsed in VM between vm_start and vm_stop. Unless
* icount is active, cpu_get_ticks() uses units of the host CPU cycle
* counter.
*/
int64_t cpu_get_ticks(void)
{
int64_t ticks;
if (use_icount) {
return cpu_get_icount();
}
qemu_spin_lock(&timers_state.vm_clock_lock);
ticks = cpu_get_ticks_locked();
qemu_spin_unlock(&timers_state.vm_clock_lock);
return ticks;
}
static int64_t cpu_get_clock_locked(void)
{
int64_t time;
time = timers_state.cpu_clock_offset;
if (timers_state.cpu_ticks_enabled) {
time += get_clock();
}
return time;
}
/* Return the monotonic time elapsed in VM, i.e.,
* the time between vm_start and vm_stop
*/
int64_t cpu_get_clock(void)
{
int64_t ti;
unsigned start;
do {
start = seqlock_read_begin(&timers_state.vm_clock_seqlock);
ti = cpu_get_clock_locked();
} while (seqlock_read_retry(&timers_state.vm_clock_seqlock, start));
return ti;
}
/* enable cpu_get_ticks()
* Caller must hold BQL which serves as mutex for vm_clock_seqlock.
*/
void cpu_enable_ticks(void)
{
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
if (!timers_state.cpu_ticks_enabled) {
timers_state.cpu_ticks_offset -= cpu_get_host_ticks();
timers_state.cpu_clock_offset -= get_clock();
timers_state.cpu_ticks_enabled = 1;
}
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
}
/* disable cpu_get_ticks() : the clock is stopped. You must not call
* cpu_get_ticks() after that.
* Caller must hold BQL which serves as mutex for vm_clock_seqlock.
*/
void cpu_disable_ticks(void)
{
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
if (timers_state.cpu_ticks_enabled) {
timers_state.cpu_ticks_offset += cpu_get_host_ticks();
timers_state.cpu_clock_offset = cpu_get_clock_locked();
timers_state.cpu_ticks_enabled = 0;
}
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
}
/* Correlation between real and virtual time is always going to be
fairly approximate, so ignore small variation.
When the guest is idle real and virtual time will be aligned in
the IO wait loop. */
#define ICOUNT_WOBBLE (NANOSECONDS_PER_SECOND / 10)
static void icount_adjust(void)
{
int64_t cur_time;
int64_t cur_icount;
int64_t delta;
/* Protected by TimersState mutex. */
static int64_t last_delta;
/* If the VM is not running, then do nothing. */
if (!runstate_is_running()) {
return;
}
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
cur_time = cpu_get_clock_locked();
cur_icount = cpu_get_icount_locked();
delta = cur_icount - cur_time;
/* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
if (delta > 0
&& last_delta + ICOUNT_WOBBLE < delta * 2
&& timers_state.icount_time_shift > 0) {
/* The guest is getting too far ahead. Slow time down. */
atomic_set(&timers_state.icount_time_shift,
timers_state.icount_time_shift - 1);
}
if (delta < 0
&& last_delta - ICOUNT_WOBBLE > delta * 2
&& timers_state.icount_time_shift < MAX_ICOUNT_SHIFT) {
/* The guest is getting too far behind. Speed time up. */
atomic_set(&timers_state.icount_time_shift,
timers_state.icount_time_shift + 1);
}
last_delta = delta;
atomic_set_i64(&timers_state.qemu_icount_bias,
cur_icount - (timers_state.qemu_icount
<< timers_state.icount_time_shift));
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
}
static void icount_adjust_rt(void *opaque)
{
timer_mod(timers_state.icount_rt_timer,
qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);
icount_adjust();
}
static void icount_adjust_vm(void *opaque)
{
timer_mod(timers_state.icount_vm_timer,
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
NANOSECONDS_PER_SECOND / 10);
icount_adjust();
}
static int64_t qemu_icount_round(int64_t count)
{
int shift = atomic_read(&timers_state.icount_time_shift);
return (count + (1 << shift) - 1) >> shift;
}
static void icount_warp_rt(void)
{
unsigned seq;
int64_t warp_start;
/* The icount_warp_timer is rescheduled soon after vm_clock_warp_start
* changes from -1 to another value, so the race here is okay.
*/
do {
seq = seqlock_read_begin(&timers_state.vm_clock_seqlock);
warp_start = timers_state.vm_clock_warp_start;
} while (seqlock_read_retry(&timers_state.vm_clock_seqlock, seq));
if (warp_start == -1) {
return;
}
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
if (runstate_is_running()) {
int64_t clock = REPLAY_CLOCK_LOCKED(REPLAY_CLOCK_VIRTUAL_RT,
cpu_get_clock_locked());
int64_t warp_delta;
warp_delta = clock - timers_state.vm_clock_warp_start;
if (use_icount == 2) {
/*
* In adaptive mode, do not let QEMU_CLOCK_VIRTUAL run too
* far ahead of real time.
*/
int64_t cur_icount = cpu_get_icount_locked();
int64_t delta = clock - cur_icount;
warp_delta = MIN(warp_delta, delta);
}
atomic_set_i64(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + warp_delta);
}
timers_state.vm_clock_warp_start = -1;
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
if (qemu_clock_expired(QEMU_CLOCK_VIRTUAL)) {
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
}
}
static void icount_timer_cb(void *opaque)
{
/* No need for a checkpoint because the timer already synchronizes
* with CHECKPOINT_CLOCK_VIRTUAL_RT.
*/
icount_warp_rt();
}
void qtest_clock_warp(int64_t dest)
{
int64_t clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
AioContext *aio_context;
assert(qtest_enabled());
aio_context = qemu_get_aio_context();
while (clock < dest) {
int64_t deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
int64_t warp = qemu_soonest_timeout(dest - clock, deadline);
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
atomic_set_i64(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + warp);
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL);
timerlist_run_timers(aio_context->tlg.tl[QEMU_CLOCK_VIRTUAL]);
clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
}
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
}
void qemu_start_warp_timer(void)
{
int64_t clock;
int64_t deadline;
if (!use_icount) {
return;
}
/* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
* do not fire, so computing the deadline does not make sense.
*/
if (!runstate_is_running()) {
return;
}
if (replay_mode != REPLAY_MODE_PLAY) {
if (!all_cpu_threads_idle()) {
return;
}
if (qtest_enabled()) {
/* When testing, qtest commands advance icount. */
return;
}
replay_checkpoint(CHECKPOINT_CLOCK_WARP_START);
} else {
/* warp clock deterministically in record/replay mode */
if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_START)) {
/* vCPU is sleeping and warp can't be started.
It is probably a race condition: notification sent
to vCPU was processed in advance and vCPU went to sleep.
Therefore we have to wake it up for doing someting. */
if (replay_has_checkpoint()) {
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
}
return;
}
}
/* We want to use the earliest deadline from ALL vm_clocks */
clock = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT);
deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
if (deadline < 0) {
static bool notified;
if (!icount_sleep && !notified) {
warn_report("icount sleep disabled and no active timers");
notified = true;
}
return;
}
if (deadline > 0) {
/*
* Ensure QEMU_CLOCK_VIRTUAL proceeds even when the virtual CPU goes to
* sleep. Otherwise, the CPU might be waiting for a future timer
* interrupt to wake it up, but the interrupt never comes because
* the vCPU isn't running any insns and thus doesn't advance the
* QEMU_CLOCK_VIRTUAL.
*/
if (!icount_sleep) {
/*
* We never let VCPUs sleep in no sleep icount mode.
* If there is a pending QEMU_CLOCK_VIRTUAL timer we just advance
* to the next QEMU_CLOCK_VIRTUAL event and notify it.
* It is useful when we want a deterministic execution time,
* isolated from host latencies.
*/
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
atomic_set_i64(&timers_state.qemu_icount_bias,
timers_state.qemu_icount_bias + deadline);
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
} else {
/*
* We do stop VCPUs and only advance QEMU_CLOCK_VIRTUAL after some
* "real" time, (related to the time left until the next event) has
* passed. The QEMU_CLOCK_VIRTUAL_RT clock will do this.
* This avoids that the warps are visible externally; for example,
* you will not be sending network packets continuously instead of
* every 100ms.
*/
seqlock_write_lock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
if (timers_state.vm_clock_warp_start == -1
|| timers_state.vm_clock_warp_start > clock) {
timers_state.vm_clock_warp_start = clock;
}
seqlock_write_unlock(&timers_state.vm_clock_seqlock,
&timers_state.vm_clock_lock);
timer_mod_anticipate(timers_state.icount_warp_timer,
clock + deadline);
}
} else if (deadline == 0) {
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
}
}
static void qemu_account_warp_timer(void)
{
if (!use_icount || !icount_sleep) {
return;
}
/* Nothing to do if the VM is stopped: QEMU_CLOCK_VIRTUAL timers
* do not fire, so computing the deadline does not make sense.
*/
if (!runstate_is_running()) {
return;
}
/* warp clock deterministically in record/replay mode */
if (!replay_checkpoint(CHECKPOINT_CLOCK_WARP_ACCOUNT)) {
return;
}
timer_del(timers_state.icount_warp_timer);
icount_warp_rt();
}
static bool icount_state_needed(void *opaque)
{
return use_icount;
}
static bool warp_timer_state_needed(void *opaque)
{
TimersState *s = opaque;
return s->icount_warp_timer != NULL;
}
static bool adjust_timers_state_needed(void *opaque)
{
TimersState *s = opaque;
return s->icount_rt_timer != NULL;
}
/*
* Subsection for warp timer migration is optional, because may not be created
*/
static const VMStateDescription icount_vmstate_warp_timer = {
.name = "timer/icount/warp_timer",
.version_id = 1,
.minimum_version_id = 1,
.needed = warp_timer_state_needed,
.fields = (VMStateField[]) {
VMSTATE_INT64(vm_clock_warp_start, TimersState),
VMSTATE_TIMER_PTR(icount_warp_timer, TimersState),
VMSTATE_END_OF_LIST()
}
};
static const VMStateDescription icount_vmstate_adjust_timers = {
.name = "timer/icount/timers",
.version_id = 1,
.minimum_version_id = 1,
.needed = adjust_timers_state_needed,
.fields = (VMStateField[]) {
VMSTATE_TIMER_PTR(icount_rt_timer, TimersState),
VMSTATE_TIMER_PTR(icount_vm_timer, TimersState),
VMSTATE_END_OF_LIST()
}
};
/*
* This is a subsection for icount migration.
*/
static const VMStateDescription icount_vmstate_timers = {
.name = "timer/icount",
.version_id = 1,
.minimum_version_id = 1,
.needed = icount_state_needed,
.fields = (VMStateField[]) {
VMSTATE_INT64(qemu_icount_bias, TimersState),
VMSTATE_INT64(qemu_icount, TimersState),
VMSTATE_END_OF_LIST()
},
.subsections = (const VMStateDescription*[]) {
&icount_vmstate_warp_timer,
&icount_vmstate_adjust_timers,
NULL
}
};
static const VMStateDescription vmstate_timers = {
.name = "timer",
.version_id = 2,
.minimum_version_id = 1,
.fields = (VMStateField[]) {
VMSTATE_INT64(cpu_ticks_offset, TimersState),
VMSTATE_UNUSED(8),
VMSTATE_INT64_V(cpu_clock_offset, TimersState, 2),
VMSTATE_END_OF_LIST()
},
.subsections = (const VMStateDescription*[]) {
&icount_vmstate_timers,
NULL
}
};
static void cpu_throttle_thread(CPUState *cpu, run_on_cpu_data opaque)
{
double pct;
double throttle_ratio;
long sleeptime_ns;
if (!cpu_throttle_get_percentage()) {
return;
}
pct = (double)cpu_throttle_get_percentage()/100;
throttle_ratio = pct / (1 - pct);
sleeptime_ns = (long)(throttle_ratio * CPU_THROTTLE_TIMESLICE_NS);
qemu_mutex_unlock_iothread();
g_usleep(sleeptime_ns / 1000); /* Convert ns to us for usleep call */
qemu_mutex_lock_iothread();
atomic_set(&cpu->throttle_thread_scheduled, 0);
}
static void cpu_throttle_timer_tick(void *opaque)
{
CPUState *cpu;
double pct;
/* Stop the timer if needed */
if (!cpu_throttle_get_percentage()) {
return;
}
CPU_FOREACH(cpu) {
if (!atomic_xchg(&cpu->throttle_thread_scheduled, 1)) {
async_run_on_cpu(cpu, cpu_throttle_thread,
RUN_ON_CPU_NULL);
}
}
pct = (double)cpu_throttle_get_percentage()/100;
timer_mod(throttle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT) +
CPU_THROTTLE_TIMESLICE_NS / (1-pct));
}
void cpu_throttle_set(int new_throttle_pct)
{
/* Ensure throttle percentage is within valid range */
new_throttle_pct = MIN(new_throttle_pct, CPU_THROTTLE_PCT_MAX);
new_throttle_pct = MAX(new_throttle_pct, CPU_THROTTLE_PCT_MIN);
atomic_set(&throttle_percentage, new_throttle_pct);
timer_mod(throttle_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL_RT) +
CPU_THROTTLE_TIMESLICE_NS);
}
void cpu_throttle_stop(void)
{
atomic_set(&throttle_percentage, 0);
}
bool cpu_throttle_active(void)
{
return (cpu_throttle_get_percentage() != 0);
}
int cpu_throttle_get_percentage(void)
{
return atomic_read(&throttle_percentage);
}
void cpu_ticks_init(void)
{
seqlock_init(&timers_state.vm_clock_seqlock);
qemu_spin_init(&timers_state.vm_clock_lock);
vmstate_register(NULL, 0, &vmstate_timers, &timers_state);
throttle_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
cpu_throttle_timer_tick, NULL);
}
void configure_icount(QemuOpts *opts, Error **errp)
{
const char *option;
char *rem_str = NULL;
option = qemu_opt_get(opts, "shift");
if (!option) {
if (qemu_opt_get(opts, "align") != NULL) {
error_setg(errp, "Please specify shift option when using align");
}
return;
}
icount_sleep = qemu_opt_get_bool(opts, "sleep", true);
if (icount_sleep) {
timers_state.icount_warp_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,
icount_timer_cb, NULL);
}
icount_align_option = qemu_opt_get_bool(opts, "align", false);
if (icount_align_option && !icount_sleep) {
error_setg(errp, "align=on and sleep=off are incompatible");
}
if (strcmp(option, "auto") != 0) {
errno = 0;
timers_state.icount_time_shift = strtol(option, &rem_str, 0);
if (errno != 0 || *rem_str != '\0' || !strlen(option)) {
error_setg(errp, "icount: Invalid shift value");
}
use_icount = 1;
return;
} else if (icount_align_option) {
error_setg(errp, "shift=auto and align=on are incompatible");
} else if (!icount_sleep) {
error_setg(errp, "shift=auto and sleep=off are incompatible");
}
use_icount = 2;
/* 125MIPS seems a reasonable initial guess at the guest speed.
It will be corrected fairly quickly anyway. */
timers_state.icount_time_shift = 3;
/* Have both realtime and virtual time triggers for speed adjustment.
The realtime trigger catches emulated time passing too slowly,
the virtual time trigger catches emulated time passing too fast.
Realtime triggers occur even when idle, so use them less frequently
than VM triggers. */
timers_state.vm_clock_warp_start = -1;
timers_state.icount_rt_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL_RT,
icount_adjust_rt, NULL);
timer_mod(timers_state.icount_rt_timer,
qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);
timers_state.icount_vm_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
icount_adjust_vm, NULL);
timer_mod(timers_state.icount_vm_timer,
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
NANOSECONDS_PER_SECOND / 10);
}
/***********************************************************/
/* TCG vCPU kick timer
*
* The kick timer is responsible for moving single threaded vCPU
* emulation on to the next vCPU. If more than one vCPU is running a
* timer event with force a cpu->exit so the next vCPU can get
* scheduled.
*
* The timer is removed if all vCPUs are idle and restarted again once
* idleness is complete.
*/
static QEMUTimer *tcg_kick_vcpu_timer;
static CPUState *tcg_current_rr_cpu;
#define TCG_KICK_PERIOD (NANOSECONDS_PER_SECOND / 10)
static inline int64_t qemu_tcg_next_kick(void)
{
return qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + TCG_KICK_PERIOD;
}
/* Kick the currently round-robin scheduled vCPU */
static void qemu_cpu_kick_rr_cpu(void)
{
CPUState *cpu;
do {
cpu = atomic_mb_read(&tcg_current_rr_cpu);
if (cpu) {
cpu_exit(cpu);
}
} while (cpu != atomic_mb_read(&tcg_current_rr_cpu));
}
static void do_nothing(CPUState *cpu, run_on_cpu_data unused)
{
}
void qemu_timer_notify_cb(void *opaque, QEMUClockType type)
{
if (!use_icount || type != QEMU_CLOCK_VIRTUAL) {
qemu_notify_event();
return;
}
if (qemu_in_vcpu_thread()) {
/* A CPU is currently running; kick it back out to the
* tcg_cpu_exec() loop so it will recalculate its
* icount deadline immediately.
*/
qemu_cpu_kick(current_cpu);
} else if (first_cpu) {
/* qemu_cpu_kick is not enough to kick a halted CPU out of
* qemu_tcg_wait_io_event. async_run_on_cpu, instead,
* causes cpu_thread_is_idle to return false. This way,
* handle_icount_deadline can run.
* If we have no CPUs at all for some reason, we don't
* need to do anything.
*/
async_run_on_cpu(first_cpu, do_nothing, RUN_ON_CPU_NULL);
}
}
static void kick_tcg_thread(void *opaque)
{
timer_mod(tcg_kick_vcpu_timer, qemu_tcg_next_kick());
qemu_cpu_kick_rr_cpu();
}
static void start_tcg_kick_timer(void)
{
assert(!mttcg_enabled);
if (!tcg_kick_vcpu_timer && CPU_NEXT(first_cpu)) {
tcg_kick_vcpu_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
kick_tcg_thread, NULL);
}
if (tcg_kick_vcpu_timer && !timer_pending(tcg_kick_vcpu_timer)) {
timer_mod(tcg_kick_vcpu_timer, qemu_tcg_next_kick());
}
}
static void stop_tcg_kick_timer(void)
{
assert(!mttcg_enabled);
if (tcg_kick_vcpu_timer && timer_pending(tcg_kick_vcpu_timer)) {
timer_del(tcg_kick_vcpu_timer);
}
}
/***********************************************************/
void hw_error(const char *fmt, ...)
{
va_list ap;
CPUState *cpu;
va_start(ap, fmt);
fprintf(stderr, "qemu: hardware error: ");
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
CPU_FOREACH(cpu) {
fprintf(stderr, "CPU #%d:\n", cpu->cpu_index);
cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_FPU);
}
va_end(ap);
abort();
}
void cpu_synchronize_all_states(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
cpu_synchronize_state(cpu);
/* TODO: move to cpu_synchronize_state() */
if (hvf_enabled()) {
hvf_cpu_synchronize_state(cpu);
}
}
}
void cpu_synchronize_all_post_reset(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
cpu_synchronize_post_reset(cpu);
/* TODO: move to cpu_synchronize_post_reset() */
if (hvf_enabled()) {
hvf_cpu_synchronize_post_reset(cpu);
}
}
}
void cpu_synchronize_all_post_init(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
cpu_synchronize_post_init(cpu);
/* TODO: move to cpu_synchronize_post_init() */
if (hvf_enabled()) {
hvf_cpu_synchronize_post_init(cpu);
}
}
}
void cpu_synchronize_all_pre_loadvm(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
cpu_synchronize_pre_loadvm(cpu);
}
}
static int do_vm_stop(RunState state, bool send_stop)
{
int ret = 0;
if (runstate_is_running()) {
cpu_disable_ticks();
pause_all_vcpus();
runstate_set(state);
vm_state_notify(0, state);
if (send_stop) {
qapi_event_send_stop();
}
}
bdrv_drain_all();
replay_disable_events();
ret = bdrv_flush_all();
return ret;
}
/* Special vm_stop() variant for terminating the process. Historically clients
* did not expect a QMP STOP event and so we need to retain compatibility.
*/
int vm_shutdown(void)
{
return do_vm_stop(RUN_STATE_SHUTDOWN, false);
}
static bool cpu_can_run(CPUState *cpu)
{
if (cpu->stop) {
return false;
}
if (cpu_is_stopped(cpu)) {
return false;
}
return true;
}
static void cpu_handle_guest_debug(CPUState *cpu)
{
gdb_set_stop_cpu(cpu);
qemu_system_debug_request();
cpu->stopped = true;
}
#ifdef CONFIG_LINUX
static void sigbus_reraise(void)
{
sigset_t set;
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = SIG_DFL;
if (!sigaction(SIGBUS, &action, NULL)) {
raise(SIGBUS);
sigemptyset(&set);
sigaddset(&set, SIGBUS);
pthread_sigmask(SIG_UNBLOCK, &set, NULL);
}
perror("Failed to re-raise SIGBUS!\n");
abort();
}
static void sigbus_handler(int n, siginfo_t *siginfo, void *ctx)
{
if (siginfo->si_code != BUS_MCEERR_AO && siginfo->si_code != BUS_MCEERR_AR) {
sigbus_reraise();
}
if (current_cpu) {
/* Called asynchronously in VCPU thread. */
if (kvm_on_sigbus_vcpu(current_cpu, siginfo->si_code, siginfo->si_addr)) {
sigbus_reraise();
}
} else {
/* Called synchronously (via signalfd) in main thread. */
if (kvm_on_sigbus(siginfo->si_code, siginfo->si_addr)) {
sigbus_reraise();
}
}
}
static void qemu_init_sigbus(void)
{
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_flags = SA_SIGINFO;
action.sa_sigaction = sigbus_handler;
sigaction(SIGBUS, &action, NULL);
prctl(PR_MCE_KILL, PR_MCE_KILL_SET, PR_MCE_KILL_EARLY, 0, 0);
}
#else /* !CONFIG_LINUX */
static void qemu_init_sigbus(void)
{
}
#endif /* !CONFIG_LINUX */
static QemuMutex qemu_global_mutex;
static QemuThread io_thread;
/* cpu creation */
static QemuCond qemu_cpu_cond;
/* system init */
static QemuCond qemu_pause_cond;
void qemu_init_cpu_loop(void)
{
qemu_init_sigbus();
qemu_cond_init(&qemu_cpu_cond);
qemu_cond_init(&qemu_pause_cond);
qemu_mutex_init(&qemu_global_mutex);
qemu_thread_get_self(&io_thread);
}
void run_on_cpu(CPUState *cpu, run_on_cpu_func func, run_on_cpu_data data)
{
do_run_on_cpu(cpu, func, data, &qemu_global_mutex);
}
static void qemu_kvm_destroy_vcpu(CPUState *cpu)
{
if (kvm_destroy_vcpu(cpu) < 0) {
error_report("kvm_destroy_vcpu failed");
exit(EXIT_FAILURE);
}
}
static void qemu_tcg_destroy_vcpu(CPUState *cpu)
{
}
static void qemu_cpu_stop(CPUState *cpu, bool exit)
{
g_assert(qemu_cpu_is_self(cpu));
cpu->stop = false;
cpu->stopped = true;
if (exit) {
cpu_exit(cpu);
}
qemu_cond_broadcast(&qemu_pause_cond);
}
static void qemu_wait_io_event_common(CPUState *cpu)
{
atomic_mb_set(&cpu->thread_kicked, false);
if (cpu->stop) {
qemu_cpu_stop(cpu, false);
}
process_queued_cpu_work(cpu);
}
static void qemu_tcg_rr_wait_io_event(void)
{
CPUState *cpu;
while (all_cpu_threads_idle()) {
stop_tcg_kick_timer();
qemu_cond_wait(first_cpu->halt_cond, &qemu_global_mutex);
}
start_tcg_kick_timer();
CPU_FOREACH(cpu) {
qemu_wait_io_event_common(cpu);
}
}
static void qemu_wait_io_event(CPUState *cpu)
{
while (cpu_thread_is_idle(cpu)) {
qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
}
#ifdef _WIN32
/* Eat dummy APC queued by qemu_cpu_kick_thread. */
if (!tcg_enabled()) {
SleepEx(0, TRUE);
}
#endif
qemu_wait_io_event_common(cpu);
}
static void *qemu_kvm_cpu_thread_fn(void *arg)
{
CPUState *cpu = arg;
int r;
rcu_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->can_do_io = 1;
current_cpu = cpu;
r = kvm_init_vcpu(cpu);
if (r < 0) {
error_report("kvm_init_vcpu failed: %s", strerror(-r));
exit(1);
}
kvm_init_cpu_signals(cpu);
/* signal CPU creation */
cpu->created = true;
qemu_cond_signal(&qemu_cpu_cond);
do {
if (cpu_can_run(cpu)) {
r = kvm_cpu_exec(cpu);
if (r == EXCP_DEBUG) {
cpu_handle_guest_debug(cpu);
}
}
qemu_wait_io_event(cpu);
} while (!cpu->unplug || cpu_can_run(cpu));
qemu_kvm_destroy_vcpu(cpu);
cpu->created = false;
qemu_cond_signal(&qemu_cpu_cond);
qemu_mutex_unlock_iothread();
rcu_unregister_thread();
return NULL;
}
static void *qemu_dummy_cpu_thread_fn(void *arg)
{
#ifdef _WIN32
error_report("qtest is not supported under Windows");
exit(1);
#else
CPUState *cpu = arg;
sigset_t waitset;
int r;
rcu_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->can_do_io = 1;
current_cpu = cpu;
sigemptyset(&waitset);
sigaddset(&waitset, SIG_IPI);
/* signal CPU creation */
cpu->created = true;
qemu_cond_signal(&qemu_cpu_cond);
do {
qemu_mutex_unlock_iothread();
do {
int sig;
r = sigwait(&waitset, &sig);
} while (r == -1 && (errno == EAGAIN || errno == EINTR));
if (r == -1) {
perror("sigwait");
exit(1);
}
qemu_mutex_lock_iothread();
qemu_wait_io_event(cpu);
} while (!cpu->unplug);
qemu_mutex_unlock_iothread();
rcu_unregister_thread();
return NULL;
#endif
}
static int64_t tcg_get_icount_limit(void)
{
int64_t deadline;
if (replay_mode != REPLAY_MODE_PLAY) {
deadline = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
/* Maintain prior (possibly buggy) behaviour where if no deadline
* was set (as there is no QEMU_CLOCK_VIRTUAL timer) or it is more than
* INT32_MAX nanoseconds ahead, we still use INT32_MAX
* nanoseconds.
*/
if ((deadline < 0) || (deadline > INT32_MAX)) {
deadline = INT32_MAX;
}
return qemu_icount_round(deadline);
} else {
return replay_get_instructions();
}
}
static void handle_icount_deadline(void)
{
assert(qemu_in_vcpu_thread());
if (use_icount) {
int64_t deadline =
qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);
if (deadline == 0) {
/* Wake up other AioContexts. */
qemu_clock_notify(QEMU_CLOCK_VIRTUAL);
qemu_clock_run_timers(QEMU_CLOCK_VIRTUAL);
}
}
}
static void prepare_icount_for_run(CPUState *cpu)
{
if (use_icount) {
int insns_left;
/* These should always be cleared by process_icount_data after
* each vCPU execution. However u16.high can be raised
* asynchronously by cpu_exit/cpu_interrupt/tcg_handle_interrupt
*/
g_assert(cpu->icount_decr.u16.low == 0);
g_assert(cpu->icount_extra == 0);
cpu->icount_budget = tcg_get_icount_limit();
insns_left = MIN(0xffff, cpu->icount_budget);
cpu->icount_decr.u16.low = insns_left;
cpu->icount_extra = cpu->icount_budget - insns_left;
replay_mutex_lock();
}
}
static void process_icount_data(CPUState *cpu)
{
if (use_icount) {
/* Account for executed instructions */
cpu_update_icount(cpu);
/* Reset the counters */
cpu->icount_decr.u16.low = 0;
cpu->icount_extra = 0;
cpu->icount_budget = 0;
replay_account_executed_instructions();
replay_mutex_unlock();
}
}
static int tcg_cpu_exec(CPUState *cpu)
{
int ret;
#ifdef CONFIG_PROFILER
int64_t ti;
#endif
assert(tcg_enabled());
#ifdef CONFIG_PROFILER
ti = profile_getclock();
#endif
cpu_exec_start(cpu);
ret = cpu_exec(cpu);
cpu_exec_end(cpu);
#ifdef CONFIG_PROFILER
atomic_set(&tcg_ctx->prof.cpu_exec_time,
tcg_ctx->prof.cpu_exec_time + profile_getclock() - ti);
#endif
return ret;
}
/* Destroy any remaining vCPUs which have been unplugged and have
* finished running
*/
static void deal_with_unplugged_cpus(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
if (cpu->unplug && !cpu_can_run(cpu)) {
qemu_tcg_destroy_vcpu(cpu);
cpu->created = false;
qemu_cond_signal(&qemu_cpu_cond);
break;
}
}
}
/* Single-threaded TCG
*
* In the single-threaded case each vCPU is simulated in turn. If
* there is more than a single vCPU we create a simple timer to kick
* the vCPU and ensure we don't get stuck in a tight loop in one vCPU.
* This is done explicitly rather than relying on side-effects
* elsewhere.
*/
static void *qemu_tcg_rr_cpu_thread_fn(void *arg)
{
CPUState *cpu = arg;
assert(tcg_enabled());
rcu_register_thread();
tcg_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->created = true;
cpu->can_do_io = 1;
qemu_cond_signal(&qemu_cpu_cond);
/* wait for initial kick-off after machine start */
while (first_cpu->stopped) {
qemu_cond_wait(first_cpu->halt_cond, &qemu_global_mutex);
/* process any pending work */
CPU_FOREACH(cpu) {
current_cpu = cpu;
qemu_wait_io_event_common(cpu);
}
}
start_tcg_kick_timer();
cpu = first_cpu;
/* process any pending work */
cpu->exit_request = 1;
while (1) {
qemu_mutex_unlock_iothread();
replay_mutex_lock();
qemu_mutex_lock_iothread();
/* Account partial waits to QEMU_CLOCK_VIRTUAL. */
qemu_account_warp_timer();
/* Run the timers here. This is much more efficient than
* waking up the I/O thread and waiting for completion.
*/
handle_icount_deadline();
replay_mutex_unlock();
if (!cpu) {
cpu = first_cpu;
}
while (cpu && !cpu->queued_work_first && !cpu->exit_request) {
atomic_mb_set(&tcg_current_rr_cpu, cpu);
current_cpu = cpu;
qemu_clock_enable(QEMU_CLOCK_VIRTUAL,
(cpu->singlestep_enabled & SSTEP_NOTIMER) == 0);
if (cpu_can_run(cpu)) {
int r;
qemu_mutex_unlock_iothread();
prepare_icount_for_run(cpu);
r = tcg_cpu_exec(cpu);
process_icount_data(cpu);
qemu_mutex_lock_iothread();
if (r == EXCP_DEBUG) {
cpu_handle_guest_debug(cpu);
break;
} else if (r == EXCP_ATOMIC) {
qemu_mutex_unlock_iothread();
cpu_exec_step_atomic(cpu);
qemu_mutex_lock_iothread();
break;
}
} else if (cpu->stop) {
if (cpu->unplug) {
cpu = CPU_NEXT(cpu);
}
break;
}
cpu = CPU_NEXT(cpu);
} /* while (cpu && !cpu->exit_request).. */
/* Does not need atomic_mb_set because a spurious wakeup is okay. */
atomic_set(&tcg_current_rr_cpu, NULL);
if (cpu && cpu->exit_request) {
atomic_mb_set(&cpu->exit_request, 0);
}
if (use_icount && all_cpu_threads_idle()) {
/*
* When all cpus are sleeping (e.g in WFI), to avoid a deadlock
* in the main_loop, wake it up in order to start the warp timer.
*/
qemu_notify_event();
}
qemu_tcg_rr_wait_io_event();
deal_with_unplugged_cpus();
}
rcu_unregister_thread();
return NULL;
}
static void *qemu_hax_cpu_thread_fn(void *arg)
{
CPUState *cpu = arg;
int r;
rcu_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->created = true;
cpu->halted = 0;
current_cpu = cpu;
hax_init_vcpu(cpu);
qemu_cond_signal(&qemu_cpu_cond);
do {
if (cpu_can_run(cpu)) {
r = hax_smp_cpu_exec(cpu);
if (r == EXCP_DEBUG) {
cpu_handle_guest_debug(cpu);
}
}
qemu_wait_io_event(cpu);
} while (!cpu->unplug || cpu_can_run(cpu));
rcu_unregister_thread();
return NULL;
}
/* The HVF-specific vCPU thread function. This one should only run when the host
* CPU supports the VMX "unrestricted guest" feature. */
static void *qemu_hvf_cpu_thread_fn(void *arg)
{
CPUState *cpu = arg;
int r;
assert(hvf_enabled());
rcu_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->can_do_io = 1;
current_cpu = cpu;
hvf_init_vcpu(cpu);
/* signal CPU creation */
cpu->created = true;
qemu_cond_signal(&qemu_cpu_cond);
do {
if (cpu_can_run(cpu)) {
r = hvf_vcpu_exec(cpu);
if (r == EXCP_DEBUG) {
cpu_handle_guest_debug(cpu);
}
}
qemu_wait_io_event(cpu);
} while (!cpu->unplug || cpu_can_run(cpu));
hvf_vcpu_destroy(cpu);
cpu->created = false;
qemu_cond_signal(&qemu_cpu_cond);
qemu_mutex_unlock_iothread();
rcu_unregister_thread();
return NULL;
}
static void *qemu_whpx_cpu_thread_fn(void *arg)
{
CPUState *cpu = arg;
int r;
rcu_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
current_cpu = cpu;
r = whpx_init_vcpu(cpu);
if (r < 0) {
fprintf(stderr, "whpx_init_vcpu failed: %s\n", strerror(-r));
exit(1);
}
/* signal CPU creation */
cpu->created = true;
qemu_cond_signal(&qemu_cpu_cond);
do {
if (cpu_can_run(cpu)) {
r = whpx_vcpu_exec(cpu);
if (r == EXCP_DEBUG) {
cpu_handle_guest_debug(cpu);
}
}
while (cpu_thread_is_idle(cpu)) {
qemu_cond_wait(cpu->halt_cond, &qemu_global_mutex);
}
qemu_wait_io_event_common(cpu);
} while (!cpu->unplug || cpu_can_run(cpu));
whpx_destroy_vcpu(cpu);
cpu->created = false;
qemu_cond_signal(&qemu_cpu_cond);
qemu_mutex_unlock_iothread();
rcu_unregister_thread();
return NULL;
}
#ifdef _WIN32
static void CALLBACK dummy_apc_func(ULONG_PTR unused)
{
}
#endif
/* Multi-threaded TCG
*
* In the multi-threaded case each vCPU has its own thread. The TLS
* variable current_cpu can be used deep in the code to find the
* current CPUState for a given thread.
*/
static void *qemu_tcg_cpu_thread_fn(void *arg)
{
CPUState *cpu = arg;
assert(tcg_enabled());
g_assert(!use_icount);
rcu_register_thread();
tcg_register_thread();
qemu_mutex_lock_iothread();
qemu_thread_get_self(cpu->thread);
cpu->thread_id = qemu_get_thread_id();
cpu->created = true;
cpu->can_do_io = 1;
current_cpu = cpu;
qemu_cond_signal(&qemu_cpu_cond);
/* process any pending work */
cpu->exit_request = 1;
do {
if (cpu_can_run(cpu)) {
int r;
qemu_mutex_unlock_iothread();
r = tcg_cpu_exec(cpu);
qemu_mutex_lock_iothread();
switch (r) {
case EXCP_DEBUG:
cpu_handle_guest_debug(cpu);
break;
case EXCP_HALTED:
/* during start-up the vCPU is reset and the thread is
* kicked several times. If we don't ensure we go back
* to sleep in the halted state we won't cleanly
* start-up when the vCPU is enabled.
*
* cpu->halted should ensure we sleep in wait_io_event
*/
g_assert(cpu->halted);
break;
case EXCP_ATOMIC:
qemu_mutex_unlock_iothread();
cpu_exec_step_atomic(cpu);
qemu_mutex_lock_iothread();
default:
/* Ignore everything else? */
break;
}
}
atomic_mb_set(&cpu->exit_request, 0);
qemu_wait_io_event(cpu);
} while (!cpu->unplug || cpu_can_run(cpu));
qemu_tcg_destroy_vcpu(cpu);
cpu->created = false;
qemu_cond_signal(&qemu_cpu_cond);
qemu_mutex_unlock_iothread();
rcu_unregister_thread();
return NULL;
}
static void qemu_cpu_kick_thread(CPUState *cpu)
{
#ifndef _WIN32
int err;
if (cpu->thread_kicked) {
return;
}
cpu->thread_kicked = true;
err = pthread_kill(cpu->thread->thread, SIG_IPI);
if (err && err != ESRCH) {
fprintf(stderr, "qemu:%s: %s", __func__, strerror(err));
exit(1);
}
#else /* _WIN32 */
if (!qemu_cpu_is_self(cpu)) {
if (whpx_enabled()) {
whpx_vcpu_kick(cpu);
} else if (!QueueUserAPC(dummy_apc_func, cpu->hThread, 0)) {
fprintf(stderr, "%s: QueueUserAPC failed with error %lu\n",
__func__, GetLastError());
exit(1);
}
}
#endif
}
void qemu_cpu_kick(CPUState *cpu)
{
qemu_cond_broadcast(cpu->halt_cond);
if (tcg_enabled()) {
cpu_exit(cpu);
/* NOP unless doing single-thread RR */
qemu_cpu_kick_rr_cpu();
} else {
if (hax_enabled()) {
/*
* FIXME: race condition with the exit_request check in
* hax_vcpu_hax_exec
*/
cpu->exit_request = 1;
}
qemu_cpu_kick_thread(cpu);
}
}
void qemu_cpu_kick_self(void)
{
assert(current_cpu);
qemu_cpu_kick_thread(current_cpu);
}
bool qemu_cpu_is_self(CPUState *cpu)
{
return qemu_thread_is_self(cpu->thread);
}
bool qemu_in_vcpu_thread(void)
{
return current_cpu && qemu_cpu_is_self(current_cpu);
}
static __thread bool iothread_locked = false;
bool qemu_mutex_iothread_locked(void)
{
return iothread_locked;
}
/*
* The BQL is taken from so many places that it is worth profiling the
* callers directly, instead of funneling them all through a single function.
*/
void qemu_mutex_lock_iothread_impl(const char *file, int line)
{
QemuMutexLockFunc bql_lock = atomic_read(&qemu_bql_mutex_lock_func);
g_assert(!qemu_mutex_iothread_locked());
bql_lock(&qemu_global_mutex, file, line);
iothread_locked = true;
}
void qemu_mutex_unlock_iothread(void)
{
g_assert(qemu_mutex_iothread_locked());
iothread_locked = false;
qemu_mutex_unlock(&qemu_global_mutex);
}
static bool all_vcpus_paused(void)
{
CPUState *cpu;
CPU_FOREACH(cpu) {
if (!cpu->stopped) {
return false;
}
}
return true;
}
void pause_all_vcpus(void)
{
CPUState *cpu;
qemu_clock_enable(QEMU_CLOCK_VIRTUAL, false);
CPU_FOREACH(cpu) {
if (qemu_cpu_is_self(cpu)) {
qemu_cpu_stop(cpu, true);
} else {
cpu->stop = true;
qemu_cpu_kick(cpu);
}
}
/* We need to drop the replay_lock so any vCPU threads woken up
* can finish their replay tasks
*/
replay_mutex_unlock();
while (!all_vcpus_paused()) {
qemu_cond_wait(&qemu_pause_cond, &qemu_global_mutex);
CPU_FOREACH(cpu) {
qemu_cpu_kick(cpu);
}
}
qemu_mutex_unlock_iothread();
replay_mutex_lock();
qemu_mutex_lock_iothread();
}
void cpu_resume(CPUState *cpu)
{
cpu->stop = false;
cpu->stopped = false;
qemu_cpu_kick(cpu);
}
void resume_all_vcpus(void)
{
CPUState *cpu;
qemu_clock_enable(QEMU_CLOCK_VIRTUAL, true);
CPU_FOREACH(cpu) {
cpu_resume(cpu);
}
}
void cpu_remove_sync(CPUState *cpu)
{
cpu->stop = true;
cpu->unplug = true;
qemu_cpu_kick(cpu);
qemu_mutex_unlock_iothread();
qemu_thread_join(cpu->thread);
qemu_mutex_lock_iothread();
}
/* For temporary buffers for forming a name */
#define VCPU_THREAD_NAME_SIZE 16
static void qemu_tcg_init_vcpu(CPUState *cpu)
{
char thread_name[VCPU_THREAD_NAME_SIZE];
static QemuCond *single_tcg_halt_cond;
static QemuThread *single_tcg_cpu_thread;
static int tcg_region_inited;
assert(tcg_enabled());
/*
* Initialize TCG regions--once. Now is a good time, because:
* (1) TCG's init context, prologue and target globals have been set up.
* (2) qemu_tcg_mttcg_enabled() works now (TCG init code runs before the
* -accel flag is processed, so the check doesn't work then).
*/
if (!tcg_region_inited) {
tcg_region_inited = 1;
tcg_region_init();
}
if (qemu_tcg_mttcg_enabled() || !single_tcg_cpu_thread) {
cpu->thread = g_malloc0(sizeof(QemuThread));
cpu->halt_cond = g_malloc0(sizeof(QemuCond));
qemu_cond_init(cpu->halt_cond);
if (qemu_tcg_mttcg_enabled()) {
/* create a thread per vCPU with TCG (MTTCG) */
parallel_cpus = true;
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/TCG",
cpu->cpu_index);
qemu_thread_create(cpu->thread, thread_name, qemu_tcg_cpu_thread_fn,
cpu, QEMU_THREAD_JOINABLE);
} else {
/* share a single thread for all cpus with TCG */
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "ALL CPUs/TCG");
qemu_thread_create(cpu->thread, thread_name,
qemu_tcg_rr_cpu_thread_fn,
cpu, QEMU_THREAD_JOINABLE);
single_tcg_halt_cond = cpu->halt_cond;
single_tcg_cpu_thread = cpu->thread;
}
#ifdef _WIN32
cpu->hThread = qemu_thread_get_handle(cpu->thread);
#endif
} else {
/* For non-MTTCG cases we share the thread */
cpu->thread = single_tcg_cpu_thread;
cpu->halt_cond = single_tcg_halt_cond;
cpu->thread_id = first_cpu->thread_id;
cpu->can_do_io = 1;
cpu->created = true;
}
}
static void qemu_hax_start_vcpu(CPUState *cpu)
{
char thread_name[VCPU_THREAD_NAME_SIZE];
cpu->thread = g_malloc0(sizeof(QemuThread));
cpu->halt_cond = g_malloc0(sizeof(QemuCond));
qemu_cond_init(cpu->halt_cond);
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/HAX",
cpu->cpu_index);
qemu_thread_create(cpu->thread, thread_name, qemu_hax_cpu_thread_fn,
cpu, QEMU_THREAD_JOINABLE);
#ifdef _WIN32
cpu->hThread = qemu_thread_get_handle(cpu->thread);
#endif
}
static void qemu_kvm_start_vcpu(CPUState *cpu)
{
char thread_name[VCPU_THREAD_NAME_SIZE];
cpu->thread = g_malloc0(sizeof(QemuThread));
cpu->halt_cond = g_malloc0(sizeof(QemuCond));
qemu_cond_init(cpu->halt_cond);
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/KVM",
cpu->cpu_index);
qemu_thread_create(cpu->thread, thread_name, qemu_kvm_cpu_thread_fn,
cpu, QEMU_THREAD_JOINABLE);
}
static void qemu_hvf_start_vcpu(CPUState *cpu)
{
char thread_name[VCPU_THREAD_NAME_SIZE];
/* HVF currently does not support TCG, and only runs in
* unrestricted-guest mode. */
assert(hvf_enabled());
cpu->thread = g_malloc0(sizeof(QemuThread));
cpu->halt_cond = g_malloc0(sizeof(QemuCond));
qemu_cond_init(cpu->halt_cond);
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/HVF",
cpu->cpu_index);
qemu_thread_create(cpu->thread, thread_name, qemu_hvf_cpu_thread_fn,
cpu, QEMU_THREAD_JOINABLE);
}
static void qemu_whpx_start_vcpu(CPUState *cpu)
{
char thread_name[VCPU_THREAD_NAME_SIZE];
cpu->thread = g_malloc0(sizeof(QemuThread));
cpu->halt_cond = g_malloc0(sizeof(QemuCond));
qemu_cond_init(cpu->halt_cond);
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/WHPX",
cpu->cpu_index);
qemu_thread_create(cpu->thread, thread_name, qemu_whpx_cpu_thread_fn,
cpu, QEMU_THREAD_JOINABLE);
#ifdef _WIN32
cpu->hThread = qemu_thread_get_handle(cpu->thread);
#endif
}
static void qemu_dummy_start_vcpu(CPUState *cpu)
{
char thread_name[VCPU_THREAD_NAME_SIZE];
cpu->thread = g_malloc0(sizeof(QemuThread));
cpu->halt_cond = g_malloc0(sizeof(QemuCond));
qemu_cond_init(cpu->halt_cond);
snprintf(thread_name, VCPU_THREAD_NAME_SIZE, "CPU %d/DUMMY",
cpu->cpu_index);
qemu_thread_create(cpu->thread, thread_name, qemu_dummy_cpu_thread_fn, cpu,
QEMU_THREAD_JOINABLE);
}
void qemu_init_vcpu(CPUState *cpu)
{
cpu->nr_cores = smp_cores;
cpu->nr_threads = smp_threads;
cpu->stopped = true;
if (!cpu->as) {
/* If the target cpu hasn't set up any address spaces itself,
* give it the default one.
*/
cpu->num_ases = 1;
cpu_address_space_init(cpu, 0, "cpu-memory", cpu->memory);
}
if (kvm_enabled()) {
qemu_kvm_start_vcpu(cpu);
} else if (hax_enabled()) {
qemu_hax_start_vcpu(cpu);
} else if (hvf_enabled()) {
qemu_hvf_start_vcpu(cpu);
} else if (tcg_enabled()) {
qemu_tcg_init_vcpu(cpu);
} else if (whpx_enabled()) {
qemu_whpx_start_vcpu(cpu);
} else {
qemu_dummy_start_vcpu(cpu);
}
while (!cpu->created) {
qemu_cond_wait(&qemu_cpu_cond, &qemu_global_mutex);
}
}
void cpu_stop_current(void)
{
if (current_cpu) {
current_cpu->stop = true;
cpu_exit(current_cpu);
}
}
int vm_stop(RunState state)
{
if (qemu_in_vcpu_thread()) {
qemu_system_vmstop_request_prepare();
qemu_system_vmstop_request(state);
/*
* FIXME: should not return to device code in case
* vm_stop() has been requested.
*/
cpu_stop_current();
return 0;
}
return do_vm_stop(state, true);
}
/**
* Prepare for (re)starting the VM.
* Returns -1 if the vCPUs are not to be restarted (e.g. if they are already
* running or in case of an error condition), 0 otherwise.
*/
int vm_prepare_start(void)
{
RunState requested;
qemu_vmstop_requested(&requested);
if (runstate_is_running() && requested == RUN_STATE__MAX) {
return -1;
}
/* Ensure that a STOP/RESUME pair of events is emitted if a
* vmstop request was pending. The BLOCK_IO_ERROR event, for
* example, according to documentation is always followed by
* the STOP event.
*/
if (runstate_is_running()) {
qapi_event_send_stop();
qapi_event_send_resume();
return -1;
}
/* We are sending this now, but the CPUs will be resumed shortly later */
qapi_event_send_resume();
replay_enable_events();
cpu_enable_ticks();
runstate_set(RUN_STATE_RUNNING);
vm_state_notify(1, RUN_STATE_RUNNING);
return 0;
}
void vm_start(void)
{
if (!vm_prepare_start()) {
resume_all_vcpus();
}
}
/* does a state transition even if the VM is already stopped,
current state is forgotten forever */
int vm_stop_force_state(RunState state)
{
if (runstate_is_running()) {
return vm_stop(state);
} else {
runstate_set(state);
bdrv_drain_all();
/* Make sure to return an error if the flush in a previous vm_stop()
* failed. */
return bdrv_flush_all();
}
}
void list_cpus(FILE *f, fprintf_function cpu_fprintf, const char *optarg)
{
/* XXX: implement xxx_cpu_list for targets that still miss it */
#if defined(cpu_list)
cpu_list(f, cpu_fprintf);
#endif
}
CpuInfoList *qmp_query_cpus(Error **errp)
{
MachineState *ms = MACHINE(qdev_get_machine());
MachineClass *mc = MACHINE_GET_CLASS(ms);
CpuInfoList *head = NULL, *cur_item = NULL;
CPUState *cpu;
CPU_FOREACH(cpu) {
CpuInfoList *info;
#if defined(TARGET_I386)
X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env;
#elif defined(TARGET_PPC)
PowerPCCPU *ppc_cpu = POWERPC_CPU(cpu);
CPUPPCState *env = &ppc_cpu->env;
#elif defined(TARGET_SPARC)
SPARCCPU *sparc_cpu = SPARC_CPU(cpu);
CPUSPARCState *env = &sparc_cpu->env;
#elif defined(TARGET_RISCV)
RISCVCPU *riscv_cpu = RISCV_CPU(cpu);
CPURISCVState *env = &riscv_cpu->env;
#elif defined(TARGET_MIPS)
MIPSCPU *mips_cpu = MIPS_CPU(cpu);
CPUMIPSState *env = &mips_cpu->env;
#elif defined(TARGET_TRICORE)
TriCoreCPU *tricore_cpu = TRICORE_CPU(cpu);
CPUTriCoreState *env = &tricore_cpu->env;
#elif defined(TARGET_S390X)
S390CPU *s390_cpu = S390_CPU(cpu);
CPUS390XState *env = &s390_cpu->env;
#endif
cpu_synchronize_state(cpu);
info = g_malloc0(sizeof(*info));
info->value = g_malloc0(sizeof(*info->value));
info->value->CPU = cpu->cpu_index;
info->value->current = (cpu == first_cpu);
info->value->halted = cpu->halted;
info->value->qom_path = object_get_canonical_path(OBJECT(cpu));
info->value->thread_id = cpu->thread_id;
#if defined(TARGET_I386)
info->value->arch = CPU_INFO_ARCH_X86;
info->value->u.x86.pc = env->eip + env->segs[R_CS].base;
#elif defined(TARGET_PPC)
info->value->arch = CPU_INFO_ARCH_PPC;
info->value->u.ppc.nip = env->nip;
#elif defined(TARGET_SPARC)
info->value->arch = CPU_INFO_ARCH_SPARC;
info->value->u.q_sparc.pc = env->pc;
info->value->u.q_sparc.npc = env->npc;
#elif defined(TARGET_MIPS)
info->value->arch = CPU_INFO_ARCH_MIPS;
info->value->u.q_mips.PC = env->active_tc.PC;
#elif defined(TARGET_TRICORE)
info->value->arch = CPU_INFO_ARCH_TRICORE;
info->value->u.tricore.PC = env->PC;
#elif defined(TARGET_S390X)
info->value->arch = CPU_INFO_ARCH_S390;
info->value->u.s390.cpu_state = env->cpu_state;
#elif defined(TARGET_RISCV)
info->value->arch = CPU_INFO_ARCH_RISCV;
info->value->u.riscv.pc = env->pc;
#else
info->value->arch = CPU_INFO_ARCH_OTHER;
#endif
info->value->has_props = !!mc->cpu_index_to_instance_props;
if (info->value->has_props) {
CpuInstanceProperties *props;
props = g_malloc0(sizeof(*props));
*props = mc->cpu_index_to_instance_props(ms, cpu->cpu_index);
info->value->props = props;
}
/* XXX: waiting for the qapi to support GSList */
if (!cur_item) {
head = cur_item = info;
} else {
cur_item->next = info;
cur_item = info;
}
}
return head;
}
static CpuInfoArch sysemu_target_to_cpuinfo_arch(SysEmuTarget target)
{
/*
* The @SysEmuTarget -> @CpuInfoArch mapping below is based on the
* TARGET_ARCH -> TARGET_BASE_ARCH mapping in the "configure" script.
*/
switch (target) {
case SYS_EMU_TARGET_I386:
case SYS_EMU_TARGET_X86_64:
return CPU_INFO_ARCH_X86;
case SYS_EMU_TARGET_PPC:
case SYS_EMU_TARGET_PPC64:
return CPU_INFO_ARCH_PPC;
case SYS_EMU_TARGET_SPARC:
case SYS_EMU_TARGET_SPARC64:
return CPU_INFO_ARCH_SPARC;
case SYS_EMU_TARGET_MIPS:
case SYS_EMU_TARGET_MIPSEL:
case SYS_EMU_TARGET_MIPS64:
case SYS_EMU_TARGET_MIPS64EL:
return CPU_INFO_ARCH_MIPS;
case SYS_EMU_TARGET_TRICORE:
return CPU_INFO_ARCH_TRICORE;
case SYS_EMU_TARGET_S390X:
return CPU_INFO_ARCH_S390;
case SYS_EMU_TARGET_RISCV32:
case SYS_EMU_TARGET_RISCV64:
return CPU_INFO_ARCH_RISCV;
default:
return CPU_INFO_ARCH_OTHER;
}
}
static void cpustate_to_cpuinfo_s390(CpuInfoS390 *info, const CPUState *cpu)
{
#ifdef TARGET_S390X
S390CPU *s390_cpu = S390_CPU(cpu);
CPUS390XState *env = &s390_cpu->env;
info->cpu_state = env->cpu_state;
#else
abort();
#endif
}
/*
* fast means: we NEVER interrupt vCPU threads to retrieve
* information from KVM.
*/
CpuInfoFastList *qmp_query_cpus_fast(Error **errp)
{
MachineState *ms = MACHINE(qdev_get_machine());
MachineClass *mc = MACHINE_GET_CLASS(ms);
CpuInfoFastList *head = NULL, *cur_item = NULL;
SysEmuTarget target = qapi_enum_parse(&SysEmuTarget_lookup, TARGET_NAME,
-1, &error_abort);
CPUState *cpu;
CPU_FOREACH(cpu) {
CpuInfoFastList *info = g_malloc0(sizeof(*info));
info->value = g_malloc0(sizeof(*info->value));
info->value->cpu_index = cpu->cpu_index;
info->value->qom_path = object_get_canonical_path(OBJECT(cpu));
info->value->thread_id = cpu->thread_id;
info->value->has_props = !!mc->cpu_index_to_instance_props;
if (info->value->has_props) {
CpuInstanceProperties *props;
props = g_malloc0(sizeof(*props));
*props = mc->cpu_index_to_instance_props(ms, cpu->cpu_index);
info->value->props = props;
}
info->value->arch = sysemu_target_to_cpuinfo_arch(target);
info->value->target = target;
if (target == SYS_EMU_TARGET_S390X) {
cpustate_to_cpuinfo_s390(&info->value->u.s390x, cpu);
}
if (!cur_item) {
head = cur_item = info;
} else {
cur_item->next = info;
cur_item = info;
}
}
return head;
}
void qmp_memsave(int64_t addr, int64_t size, const char *filename,
bool has_cpu, int64_t cpu_index, Error **errp)
{
FILE *f;
uint32_t l;
CPUState *cpu;
uint8_t buf[1024];
int64_t orig_addr = addr, orig_size = size;
if (!has_cpu) {
cpu_index = 0;
}
cpu = qemu_get_cpu(cpu_index);
if (cpu == NULL) {
error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cpu-index",
"a CPU number");
return;
}
f = fopen(filename, "wb");
if (!f) {
error_setg_file_open(errp, errno, filename);
return;
}
while (size != 0) {
l = sizeof(buf);
if (l > size)
l = size;
if (cpu_memory_rw_debug(cpu, addr, buf, l, 0) != 0) {
error_setg(errp, "Invalid addr 0x%016" PRIx64 "/size %" PRId64
" specified", orig_addr, orig_size);
goto exit;
}
if (fwrite(buf, 1, l, f) != l) {
error_setg(errp, QERR_IO_ERROR);
goto exit;
}
addr += l;
size -= l;
}
exit:
fclose(f);
}
void qmp_pmemsave(int64_t addr, int64_t size, const char *filename,
Error **errp)
{
FILE *f;
uint32_t l;
uint8_t buf[1024];
f = fopen(filename, "wb");
if (!f) {
error_setg_file_open(errp, errno, filename);
return;
}
while (size != 0) {
l = sizeof(buf);
if (l > size)
l = size;
cpu_physical_memory_read(addr, buf, l);
if (fwrite(buf, 1, l, f) != l) {
error_setg(errp, QERR_IO_ERROR);
goto exit;
}
addr += l;
size -= l;
}
exit:
fclose(f);
}
void qmp_inject_nmi(Error **errp)
{
nmi_monitor_handle(monitor_get_cpu_index(), errp);
}
void dump_drift_info(FILE *f, fprintf_function cpu_fprintf)
{
if (!use_icount) {
return;
}
cpu_fprintf(f, "Host - Guest clock %"PRIi64" ms\n",
(cpu_get_clock() - cpu_get_icount())/SCALE_MS);
if (icount_align_option) {
cpu_fprintf(f, "Max guest delay %"PRIi64" ms\n", -max_delay/SCALE_MS);
cpu_fprintf(f, "Max guest advance %"PRIi64" ms\n", max_advance/SCALE_MS);
} else {
cpu_fprintf(f, "Max guest delay NA\n");
cpu_fprintf(f, "Max guest advance NA\n");
}
}
| {
"pile_set_name": "Github"
} |
//===--------------------- Support.cpp --------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file implements a few helper functions used by various pipeline
/// components.
///
//===----------------------------------------------------------------------===//
#include "Support.h"
#include "llvm/MC/MCSchedule.h"
namespace mca {
using namespace llvm;
void computeProcResourceMasks(const MCSchedModel &SM,
SmallVectorImpl<uint64_t> &Masks) {
unsigned ProcResourceID = 0;
// Create a unique bitmask for every processor resource unit.
// Skip resource at index 0, since it always references 'InvalidUnit'.
Masks.resize(SM.getNumProcResourceKinds());
for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
const MCProcResourceDesc &Desc = *SM.getProcResource(I);
if (Desc.SubUnitsIdxBegin)
continue;
Masks[I] = 1ULL << ProcResourceID;
ProcResourceID++;
}
// Create a unique bitmask for every processor resource group.
for (unsigned I = 1, E = SM.getNumProcResourceKinds(); I < E; ++I) {
const MCProcResourceDesc &Desc = *SM.getProcResource(I);
if (!Desc.SubUnitsIdxBegin)
continue;
Masks[I] = 1ULL << ProcResourceID;
for (unsigned U = 0; U < Desc.NumUnits; ++U) {
uint64_t OtherMask = Masks[Desc.SubUnitsIdxBegin[U]];
Masks[I] |= OtherMask;
}
ProcResourceID++;
}
}
double computeBlockRThroughput(const MCSchedModel &SM, unsigned DispatchWidth,
unsigned NumMicroOps,
ArrayRef<unsigned> ProcResourceUsage) {
// The block throughput is bounded from above by the hardware dispatch
// throughput. That is because the DispatchWidth is an upper bound on the
// number of opcodes that can be part of a single dispatch group.
double Max = static_cast<double>(NumMicroOps) / DispatchWidth;
// The block throughput is also limited by the amount of hardware parallelism.
// The number of available resource units affects the resource pressure
// distribution, as well as how many blocks can be executed every cycle.
for (unsigned I = 0, E = SM.getNumProcResourceKinds(); I < E; ++I) {
unsigned ResourceCycles = ProcResourceUsage[I];
if (!ResourceCycles)
continue;
const MCProcResourceDesc &MCDesc = *SM.getProcResource(I);
double Throughput = static_cast<double>(ResourceCycles) / MCDesc.NumUnits;
Max = std::max(Max, Throughput);
}
// The block reciprocal throughput is computed as the MAX of:
// - (NumMicroOps / DispatchWidth)
// - (NumUnits / ResourceCycles) for every consumed processor resource.
return Max;
}
} // namespace mca
| {
"pile_set_name": "Github"
} |
/*
* (C) Copyright 2013
* Reinhard Pfau, Guntermann & Drunck GmbH, [email protected]
*
* SPDX-License-Identifier: GPL-2.0+
*/
#include <common.h>
#include <malloc.h>
#include <fs.h>
#include <i2c.h>
#include <mmc.h>
#include <tpm.h>
#include <u-boot/sha1.h>
#include <asm/byteorder.h>
#include <asm/unaligned.h>
#include <pca9698.h>
#include "hre.h"
/* other constants */
enum {
ESDHC_BOOT_IMAGE_SIG_OFS = 0x40,
ESDHC_BOOT_IMAGE_SIZE_OFS = 0x48,
ESDHC_BOOT_IMAGE_ADDR_OFS = 0x50,
ESDHC_BOOT_IMAGE_TARGET_OFS = 0x58,
ESDHC_BOOT_IMAGE_ENTRY_OFS = 0x60,
};
enum {
I2C_SOC_0 = 0,
I2C_SOC_1 = 1,
};
enum access_mode {
HREG_NONE = 0,
HREG_RD = 1,
HREG_WR = 2,
HREG_RDWR = 3,
};
/* register constants */
enum {
FIX_HREG_DEVICE_ID_HASH = 0,
FIX_HREG_UNUSED1 = 1,
FIX_HREG_UNUSED2 = 2,
FIX_HREG_VENDOR = 3,
COUNT_FIX_HREGS
};
static struct h_reg pcr_hregs[24];
static struct h_reg fix_hregs[COUNT_FIX_HREGS];
static struct h_reg var_hregs[8];
/* hre opcodes */
enum {
/* opcodes w/o data */
HRE_NOP = 0x00,
HRE_SYNC = HRE_NOP,
HRE_CHECK0 = 0x01,
/* opcodes w/o data, w/ sync dst */
/* opcodes w/ data */
HRE_LOAD = 0x81,
/* opcodes w/data, w/sync dst */
HRE_XOR = 0xC1,
HRE_AND = 0xC2,
HRE_OR = 0xC3,
HRE_EXTEND = 0xC4,
HRE_LOADKEY = 0xC5,
};
/* hre errors */
enum {
HRE_E_OK = 0,
HRE_E_TPM_FAILURE,
HRE_E_INVALID_HREG,
};
static uint64_t device_id;
static uint64_t device_cl;
static uint64_t device_type;
static uint32_t platform_key_handle;
static uint32_t hre_tpm_err;
static int hre_err = HRE_E_OK;
#define IS_PCR_HREG(spec) ((spec) & 0x20)
#define IS_FIX_HREG(spec) (((spec) & 0x38) == 0x08)
#define IS_VAR_HREG(spec) (((spec) & 0x38) == 0x10)
#define HREG_IDX(spec) ((spec) & (IS_PCR_HREG(spec) ? 0x1f : 0x7))
static const uint8_t vendor[] = "Guntermann & Drunck";
/**
* @brief get the size of a given (TPM) NV area
* @param index NV index of the area to get size for
* @param size pointer to the size
* @return 0 on success, != 0 on error
*/
static int get_tpm_nv_size(uint32_t index, uint32_t *size)
{
uint32_t err;
uint8_t info[72];
uint8_t *ptr;
uint16_t v16;
err = tpm_get_capability(TPM_CAP_NV_INDEX, index,
info, sizeof(info));
if (err) {
printf("tpm_get_capability(CAP_NV_INDEX, %08x) failed: %u\n",
index, err);
return 1;
}
/* skip tag and nvIndex */
ptr = info + 6;
/* skip 2 pcr info fields */
v16 = get_unaligned_be16(ptr);
ptr += 2 + v16 + 1 + 20;
v16 = get_unaligned_be16(ptr);
ptr += 2 + v16 + 1 + 20;
/* skip permission and flags */
ptr += 6 + 3;
*size = get_unaligned_be32(ptr);
return 0;
}
/**
* @brief search for a key by usage auth and pub key hash.
* @param auth usage auth of the key to search for
* @param pubkey_digest (SHA1) hash of the pub key structure of the key
* @param[out] handle the handle of the key iff found
* @return 0 if key was found in TPM; != 0 if not.
*/
static int find_key(const uint8_t auth[20], const uint8_t pubkey_digest[20],
uint32_t *handle)
{
uint16_t key_count;
uint32_t key_handles[10];
uint8_t buf[288];
uint8_t *ptr;
uint32_t err;
uint8_t digest[20];
size_t buf_len;
unsigned int i;
/* fetch list of already loaded keys in the TPM */
err = tpm_get_capability(TPM_CAP_HANDLE, TPM_RT_KEY, buf, sizeof(buf));
if (err)
return -1;
key_count = get_unaligned_be16(buf);
ptr = buf + 2;
for (i = 0; i < key_count; ++i, ptr += 4)
key_handles[i] = get_unaligned_be32(ptr);
/* now search a(/ the) key which we can access with the given auth */
for (i = 0; i < key_count; ++i) {
buf_len = sizeof(buf);
err = tpm_get_pub_key_oiap(key_handles[i], auth, buf, &buf_len);
if (err && err != TPM_AUTHFAIL)
return -1;
if (err)
continue;
sha1_csum(buf, buf_len, digest);
if (!memcmp(digest, pubkey_digest, 20)) {
*handle = key_handles[i];
return 0;
}
}
return 1;
}
/**
* @brief read CCDM common data from TPM NV
* @return 0 if CCDM common data was found and read, !=0 if something failed.
*/
static int read_common_data(void)
{
uint32_t size = 0;
uint32_t err;
uint8_t buf[256];
sha1_context ctx;
if (get_tpm_nv_size(NV_COMMON_DATA_INDEX, &size) ||
size < NV_COMMON_DATA_MIN_SIZE)
return 1;
err = tpm_nv_read_value(NV_COMMON_DATA_INDEX,
buf, min(sizeof(buf), size));
if (err) {
printf("tpm_nv_read_value() failed: %u\n", err);
return 1;
}
device_id = get_unaligned_be64(buf);
device_cl = get_unaligned_be64(buf + 8);
device_type = get_unaligned_be64(buf + 16);
sha1_starts(&ctx);
sha1_update(&ctx, buf, 24);
sha1_finish(&ctx, fix_hregs[FIX_HREG_DEVICE_ID_HASH].digest);
fix_hregs[FIX_HREG_DEVICE_ID_HASH].valid = true;
platform_key_handle = get_unaligned_be32(buf + 24);
return 0;
}
/**
* @brief get pointer to hash register by specification
* @param spec specification of a hash register
* @return pointer to hash register or NULL if @a spec does not qualify a
* valid hash register; NULL else.
*/
static struct h_reg *get_hreg(uint8_t spec)
{
uint8_t idx;
idx = HREG_IDX(spec);
if (IS_FIX_HREG(spec)) {
if (idx < ARRAY_SIZE(fix_hregs))
return fix_hregs + idx;
hre_err = HRE_E_INVALID_HREG;
} else if (IS_PCR_HREG(spec)) {
if (idx < ARRAY_SIZE(pcr_hregs))
return pcr_hregs + idx;
hre_err = HRE_E_INVALID_HREG;
} else if (IS_VAR_HREG(spec)) {
if (idx < ARRAY_SIZE(var_hregs))
return var_hregs + idx;
hre_err = HRE_E_INVALID_HREG;
}
return NULL;
}
/**
* @brief get pointer of a hash register by specification and usage.
* @param spec specification of a hash register
* @param mode access mode (read or write or read/write)
* @return pointer to hash register if found and valid; NULL else.
*
* This func uses @a get_reg() to determine the hash register for a given spec.
* If a register is found it is validated according to the desired access mode.
* The value of automatic registers (PCR register and fixed registers) is
* loaded or computed on read access.
*/
static struct h_reg *access_hreg(uint8_t spec, enum access_mode mode)
{
struct h_reg *result;
result = get_hreg(spec);
if (!result)
return NULL;
if (mode & HREG_WR) {
if (IS_FIX_HREG(spec)) {
hre_err = HRE_E_INVALID_HREG;
return NULL;
}
}
if (mode & HREG_RD) {
if (!result->valid) {
if (IS_PCR_HREG(spec)) {
hre_tpm_err = tpm_pcr_read(HREG_IDX(spec),
result->digest, 20);
result->valid = (hre_tpm_err == TPM_SUCCESS);
} else if (IS_FIX_HREG(spec)) {
switch (HREG_IDX(spec)) {
case FIX_HREG_DEVICE_ID_HASH:
read_common_data();
break;
case FIX_HREG_VENDOR:
memcpy(result->digest, vendor, 20);
result->valid = true;
break;
}
} else {
result->valid = true;
}
}
if (!result->valid) {
hre_err = HRE_E_INVALID_HREG;
return NULL;
}
}
return result;
}
static void *compute_and(void *_dst, const void *_src, size_t n)
{
uint8_t *dst = _dst;
const uint8_t *src = _src;
size_t i;
for (i = n; i-- > 0; )
*dst++ &= *src++;
return _dst;
}
static void *compute_or(void *_dst, const void *_src, size_t n)
{
uint8_t *dst = _dst;
const uint8_t *src = _src;
size_t i;
for (i = n; i-- > 0; )
*dst++ |= *src++;
return _dst;
}
static void *compute_xor(void *_dst, const void *_src, size_t n)
{
uint8_t *dst = _dst;
const uint8_t *src = _src;
size_t i;
for (i = n; i-- > 0; )
*dst++ ^= *src++;
return _dst;
}
static void *compute_extend(void *_dst, const void *_src, size_t n)
{
uint8_t digest[20];
sha1_context ctx;
sha1_starts(&ctx);
sha1_update(&ctx, _dst, n);
sha1_update(&ctx, _src, n);
sha1_finish(&ctx, digest);
memcpy(_dst, digest, min(n, sizeof(digest)));
return _dst;
}
static int hre_op_loadkey(struct h_reg *src_reg, struct h_reg *dst_reg,
const void *key, size_t key_size)
{
uint32_t parent_handle;
uint32_t key_handle;
if (!src_reg || !dst_reg || !src_reg->valid || !dst_reg->valid)
return -1;
if (find_key(src_reg->digest, dst_reg->digest, &parent_handle))
return -1;
hre_tpm_err = tpm_load_key2_oiap(parent_handle, key, key_size,
src_reg->digest, &key_handle);
if (hre_tpm_err) {
hre_err = HRE_E_TPM_FAILURE;
return -1;
}
return 0;
}
/**
* @brief executes the next opcode on the hash register engine.
* @param[in,out] ip pointer to the opcode (instruction pointer)
* @param[in,out] code_size (remaining) size of the code
* @return new instruction pointer on success, NULL on error.
*/
static const uint8_t *hre_execute_op(const uint8_t **ip, size_t *code_size)
{
bool dst_modified = false;
uint32_t ins;
uint8_t opcode;
uint8_t src_spec;
uint8_t dst_spec;
uint16_t data_size;
struct h_reg *src_reg, *dst_reg;
uint8_t buf[20];
const uint8_t *src_buf, *data;
uint8_t *ptr;
int i;
void * (*bin_func)(void *, const void *, size_t);
if (*code_size < 4)
return NULL;
ins = get_unaligned_be32(*ip);
opcode = **ip;
data = *ip + 4;
src_spec = (ins >> 18) & 0x3f;
dst_spec = (ins >> 12) & 0x3f;
data_size = (ins & 0x7ff);
debug("HRE: ins=%08x (op=%02x, s=%02x, d=%02x, L=%d)\n", ins,
opcode, src_spec, dst_spec, data_size);
if ((opcode & 0x80) && (data_size + 4) > *code_size)
return NULL;
src_reg = access_hreg(src_spec, HREG_RD);
if (hre_err || hre_tpm_err)
return NULL;
dst_reg = access_hreg(dst_spec, (opcode & 0x40) ? HREG_RDWR : HREG_WR);
if (hre_err || hre_tpm_err)
return NULL;
switch (opcode) {
case HRE_NOP:
goto end;
case HRE_CHECK0:
if (src_reg) {
for (i = 0; i < 20; ++i) {
if (src_reg->digest[i])
return NULL;
}
}
break;
case HRE_LOAD:
bin_func = memcpy;
goto do_bin_func;
case HRE_XOR:
bin_func = compute_xor;
goto do_bin_func;
case HRE_AND:
bin_func = compute_and;
goto do_bin_func;
case HRE_OR:
bin_func = compute_or;
goto do_bin_func;
case HRE_EXTEND:
bin_func = compute_extend;
do_bin_func:
if (!dst_reg)
return NULL;
if (src_reg) {
src_buf = src_reg->digest;
} else {
if (!data_size) {
memset(buf, 0, 20);
src_buf = buf;
} else if (data_size == 1) {
memset(buf, *data, 20);
src_buf = buf;
} else if (data_size >= 20) {
src_buf = data;
} else {
src_buf = buf;
for (ptr = (uint8_t *)src_buf, i = 20; i > 0;
i -= data_size, ptr += data_size)
memcpy(ptr, data,
min_t(size_t, i, data_size));
}
}
bin_func(dst_reg->digest, src_buf, 20);
dst_reg->valid = true;
dst_modified = true;
break;
case HRE_LOADKEY:
if (hre_op_loadkey(src_reg, dst_reg, data, data_size))
return NULL;
break;
default:
return NULL;
}
if (dst_reg && dst_modified && IS_PCR_HREG(dst_spec)) {
hre_tpm_err = tpm_extend(HREG_IDX(dst_spec), dst_reg->digest,
dst_reg->digest);
if (hre_tpm_err) {
hre_err = HRE_E_TPM_FAILURE;
return NULL;
}
}
end:
*ip += 4;
*code_size -= 4;
if (opcode & 0x80) {
*ip += data_size;
*code_size -= data_size;
}
return *ip;
}
/**
* @brief runs a program on the hash register engine.
* @param code pointer to the (HRE) code.
* @param code_size size of the code (in bytes).
* @return 0 on success, != 0 on failure.
*/
int hre_run_program(const uint8_t *code, size_t code_size)
{
size_t code_left;
const uint8_t *ip = code;
code_left = code_size;
hre_tpm_err = 0;
hre_err = HRE_E_OK;
while (code_left > 0)
if (!hre_execute_op(&ip, &code_left))
return -1;
return hre_err;
}
int hre_verify_program(struct key_program *prg)
{
uint32_t crc;
crc = crc32(0, prg->code, prg->code_size);
if (crc != prg->code_crc) {
printf("HRC crc mismatch: %08x != %08x\n",
crc, prg->code_crc);
return 1;
}
return 0;
}
| {
"pile_set_name": "Github"
} |
Parameters for H-O
# R0 = 0.965347
# Ks = 838.193670889
# De = 0.673179557559
# beta= 2.4951216877
| {
"pile_set_name": "Github"
} |
// run-pass
#![feature(const_int_pow)]
#![feature(wrapping_next_power_of_two)]
const IS_POWER_OF_TWO_A: bool = 0u32.is_power_of_two();
const IS_POWER_OF_TWO_B: bool = 32u32.is_power_of_two();
const IS_POWER_OF_TWO_C: bool = 33u32.is_power_of_two();
const POW: u8 = 3u8.pow(5);
const CHECKED_POW_OK: Option<u8> = 3u8.checked_pow(5);
const CHECKED_POW_OVERFLOW: Option<u8> = 3u8.checked_pow(6);
const WRAPPING_POW: u8 = 3u8.wrapping_pow(6);
const OVERFLOWING_POW: (u8, bool) = 3u8.overflowing_pow(6);
const SATURATING_POW: u8 = 3u8.saturating_pow(6);
const NEXT_POWER_OF_TWO: u32 = 3u32.next_power_of_two();
const CHECKED_NEXT_POWER_OF_TWO_OK: Option<u32> = 3u32.checked_next_power_of_two();
const CHECKED_NEXT_POWER_OF_TWO_OVERFLOW: Option<u32> =
u32::MAX.checked_next_power_of_two();
const WRAPPING_NEXT_POWER_OF_TWO: u32 =
u32::MAX.wrapping_next_power_of_two();
fn main() {
assert!(!IS_POWER_OF_TWO_A);
assert!(IS_POWER_OF_TWO_B);
assert!(!IS_POWER_OF_TWO_C);
assert_eq!(POW, 243);
assert_eq!(CHECKED_POW_OK, Some(243));
assert_eq!(CHECKED_POW_OVERFLOW, None);
assert_eq!(WRAPPING_POW, 217);
assert_eq!(OVERFLOWING_POW, (217, true));
assert_eq!(SATURATING_POW, u8::MAX);
assert_eq!(NEXT_POWER_OF_TWO, 4);
assert_eq!(CHECKED_NEXT_POWER_OF_TWO_OK, Some(4));
assert_eq!(CHECKED_NEXT_POWER_OF_TWO_OVERFLOW, None);
assert_eq!(WRAPPING_NEXT_POWER_OF_TWO, 0);
}
| {
"pile_set_name": "Github"
} |
AM_CPPFLAGS = -I${top_srcdir} -I${top_builddir}
this_includedir=${includedir}/${subdir}
this_include_HEADERS = \
all.hpp \
fdm2dblackscholesop.hpp \
fdmbatesop.hpp \
fdmblackscholesop.hpp \
fdmg2op.hpp \
fdmhestonhullwhiteop.hpp \
fdmhestonop.hpp \
fdmhullwhiteop.hpp \
fdmlinearopcomposite.hpp \
fdmlinearop.hpp \
fdmlinearopiterator.hpp \
fdmlinearoplayout.hpp \
firstderivativeop.hpp \
ninepointlinearop.hpp \
secondderivativeop.hpp \
secondordermixedderivativeop.hpp \
triplebandlinearop.hpp
libFdmOperators_la_SOURCES = \
fdm2dblackscholesop.cpp \
fdmbatesop.cpp \
fdmblackscholesop.cpp \
fdmg2op.cpp \
fdmhestonhullwhiteop.cpp \
fdmhestonop.cpp \
fdmhullwhiteop.cpp \
fdmlinearoplayout.cpp \
firstderivativeop.cpp \
ninepointlinearop.cpp \
secondderivativeop.cpp \
secondordermixedderivativeop.cpp \
triplebandlinearop.cpp
noinst_LTLIBRARIES = libFdmOperators.la
all.hpp: Makefile.am
echo "/* This file is automatically generated; do not edit. */" > $@
echo "/* Add the files to be included into Makefile.am instead. */" >> $@
echo >> $@
for i in $(filter-out all.hpp, $(this_include_HEADERS)); do \
echo "#include <${subdir}/$$i>" >> $@; \
done
echo >> $@
subdirs='$(SUBDIRS)'; for i in $$subdirs; do \
echo "#include <${subdir}/$$i/all.hpp>" >> $@; \
done
| {
"pile_set_name": "Github"
} |
{
"action": [
{ "name": "loadingScreen.setProgress", "progress": 10 },
{ "name": "resource.add", "id": "level", "ignorePrevious": true },
{ "name": "loadingScreen.setProgress", "progress": 15 },
{ "name": "load", "file": "level/variables.json" },
{ "name": "load", "file": "res/level/actions.json" },
{ "name": "loadingScreen.setProgress", "progress": 20 },
{ "name": "load", "file": "res/level/fonts.json" },
{ "name": "loadingScreen.setProgress", "progress": 25 },
{ "name": "load", "file": "res/level/sounds.json" },
{ "name": "loadingScreen.setProgress", "progress": 30 },
{ "name": "load", "file": "res/level/textures.json" },
{ "name": "loadingScreen.setProgress", "progress": 35 },
{ "name": "load", "file": "level/loadBaseLevel.json" },
{ "name": "load", "file": "level/automap/loadAll.json" },
{ "name": "loadingScreen.setProgress", "progress": 45 },
{ "name": "load", "file": "level/spell/classes.json" },
{ "name": "load", "file": "level/item/classes.json" },
{ "name": "load", "file": "level/levelObject/classes.json" },
{ "name": "load", "file": "level/monster/classifiers.json" },
{ "name": "load", "file": "level/monster/defaultClass.json" },
{ "name": "load", "file": "level/player/classifiers.json" },
{ "name": "load", "file": "level/player/defaultClass.json" },
{ "name": "loadingScreen.setProgress", "progress": 50 },
{ "name": "load", "file": "res/player/sounds.json" },
{ "name": "loadingScreen.setProgress", "progress": 60 },
{ "name": "load", "file": "level/player/loadClass.json" },
{ "name": "loadingScreen.setProgress", "progress": 70 },
{ "name": "resource.add", "id": "currentLevel" },
{ "name": "load", "file": "level/map/{1}/sounds.json" },
{ "name": "loadingScreen.setProgress", "progress": 80 },
{ "name": "load", "file": "level/map/{1}/level.json" },
{ "name": "load", "file": "res/level/actions/colorCycling.json" },
{ "name": "loadingScreen.setProgress", "progress": 95 },
"loadLevelMusic",
{ "name": "load", "file": "level/showMap.json" },
{ "name": "load", "file": "level/afterLevelLoad.json" }
]
} | {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.