repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Akhenoth/Factorian | concrete/src/Updater/Migrations/Migrations/Version20150713000000.php | 451 | <?php
namespace Concrete\Core\Updater\Migrations\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
class Version20150713000000 extends AbstractMigration
{
public function up(Schema $schema)
{
$db = \Database::connection();
$db->Execute("update UserPointActions set upaHasCustomClass = 1 where upaHandle = 'won_badge'");
}
public function down(Schema $schema)
{
}
}
| mit |
aristanetworks/telegraf | plugins/inputs/logparser/logparser_test.go | 4183 | package logparser
import (
"io/ioutil"
"os"
"runtime"
"strings"
"testing"
"github.com/influxdata/telegraf/testutil"
"github.com/influxdata/telegraf/plugins/inputs/logparser/grok"
"github.com/stretchr/testify/assert"
)
func TestStartNoParsers(t *testing.T) {
logparser := &LogParserPlugin{
FromBeginning: true,
Files: []string{"grok/testdata/*.log"},
}
acc := testutil.Accumulator{}
assert.Error(t, logparser.Start(&acc))
}
func TestGrokParseLogFilesNonExistPattern(t *testing.T) {
thisdir := getCurrentDir()
p := &grok.Parser{
Patterns: []string{"%{FOOBAR}"},
CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
}
logparser := &LogParserPlugin{
FromBeginning: true,
Files: []string{thisdir + "grok/testdata/*.log"},
GrokParser: p,
}
acc := testutil.Accumulator{}
err := logparser.Start(&acc)
assert.Error(t, err)
}
func TestGrokParseLogFiles(t *testing.T) {
thisdir := getCurrentDir()
p := &grok.Parser{
Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}"},
CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
}
logparser := &LogParserPlugin{
FromBeginning: true,
Files: []string{thisdir + "grok/testdata/*.log"},
GrokParser: p,
}
acc := testutil.Accumulator{}
assert.NoError(t, logparser.Start(&acc))
acc.Wait(2)
logparser.Stop()
acc.AssertContainsTaggedFields(t, "logparser_grok",
map[string]interface{}{
"clientip": "192.168.1.1",
"myfloat": float64(1.25),
"response_time": int64(5432),
"myint": int64(101),
},
map[string]string{
"response_code": "200",
"path": thisdir + "grok/testdata/test_a.log",
})
acc.AssertContainsTaggedFields(t, "logparser_grok",
map[string]interface{}{
"myfloat": 1.25,
"mystring": "mystring",
"nomodifier": "nomodifier",
},
map[string]string{
"path": thisdir + "grok/testdata/test_b.log",
})
}
func TestGrokParseLogFilesAppearLater(t *testing.T) {
emptydir, err := ioutil.TempDir("", "TestGrokParseLogFilesAppearLater")
defer os.RemoveAll(emptydir)
assert.NoError(t, err)
thisdir := getCurrentDir()
p := &grok.Parser{
Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_B}"},
CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
}
logparser := &LogParserPlugin{
FromBeginning: true,
Files: []string{emptydir + "/*.log"},
GrokParser: p,
}
acc := testutil.Accumulator{}
assert.NoError(t, logparser.Start(&acc))
assert.Equal(t, acc.NFields(), 0)
_ = os.Symlink(thisdir+"grok/testdata/test_a.log", emptydir+"/test_a.log")
assert.NoError(t, acc.GatherError(logparser.Gather))
acc.Wait(1)
logparser.Stop()
acc.AssertContainsTaggedFields(t, "logparser_grok",
map[string]interface{}{
"clientip": "192.168.1.1",
"myfloat": float64(1.25),
"response_time": int64(5432),
"myint": int64(101),
},
map[string]string{
"response_code": "200",
"path": emptydir + "/test_a.log",
})
}
// Test that test_a.log line gets parsed even though we don't have the correct
// pattern available for test_b.log
func TestGrokParseLogFilesOneBad(t *testing.T) {
thisdir := getCurrentDir()
p := &grok.Parser{
Patterns: []string{"%{TEST_LOG_A}", "%{TEST_LOG_BAD}"},
CustomPatternFiles: []string{thisdir + "grok/testdata/test-patterns"},
}
assert.NoError(t, p.Compile())
logparser := &LogParserPlugin{
FromBeginning: true,
Files: []string{thisdir + "grok/testdata/test_a.log"},
GrokParser: p,
}
acc := testutil.Accumulator{}
acc.SetDebug(true)
assert.NoError(t, logparser.Start(&acc))
acc.Wait(1)
logparser.Stop()
acc.AssertContainsTaggedFields(t, "logparser_grok",
map[string]interface{}{
"clientip": "192.168.1.1",
"myfloat": float64(1.25),
"response_time": int64(5432),
"myint": int64(101),
},
map[string]string{
"response_code": "200",
"path": thisdir + "grok/testdata/test_a.log",
})
}
func getCurrentDir() string {
_, filename, _, _ := runtime.Caller(1)
return strings.Replace(filename, "logparser_test.go", "", 1)
}
| mit |
modulexcite/spritesmith | docs/alt-diagonal.js | 543 | // Load in dependencies
var fs = require('fs');
var spritesmith = require('../');
// Generate our spritesheet
spritesmith({
src: [
__dirname + '/fork.png',
__dirname + '/github.png',
__dirname + '/twitter.png'
],
algorithm: 'alt-diagonal'
}, function handleResult (err, result) {
// If there was an error, throw it
if (err) {
throw err;
}
// Output the image
fs.writeFileSync(__dirname + '/alt-diagonal.png', result.image, 'binary');
result.coordinates, result.properties; // Coordinates and properties
});
| mit |
jpoeng/jpoeng.github.io | node_modules/webpack/lib/web/JsonpMainTemplatePlugin.js | 19334 | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncWaterfallHook } = require("tapable");
const Template = require("../Template");
class JsonpMainTemplatePlugin {
apply(mainTemplate) {
const needChunkOnDemandLoadingCode = chunk => {
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup.getNumberOfChildren() > 0) return true;
}
return false;
};
const needChunkLoadingCode = chunk => {
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup.chunks.length > 1) return true;
if (chunkGroup.getNumberOfChildren() > 0) return true;
}
return false;
};
const needEntryDeferringCode = chunk => {
for (const chunkGroup of chunk.groupsIterable) {
if (chunkGroup.chunks.length > 1) return true;
}
return false;
};
const needPrefetchingCode = chunk => {
const allPrefetchChunks = chunk.getChildIdsByOrdersMap(true).prefetch;
return allPrefetchChunks && Object.keys(allPrefetchChunks).length;
};
// TODO webpack 5, no adding to .hooks, use WeakMap and static methods
["jsonpScript", "linkPreload", "linkPrefetch"].forEach(hook => {
if (!mainTemplate.hooks[hook]) {
mainTemplate.hooks[hook] = new SyncWaterfallHook([
"source",
"chunk",
"hash"
]);
}
});
const getScriptSrcPath = (hash, chunk, chunkIdExpression) => {
const chunkFilename = mainTemplate.outputOptions.chunkFilename;
const chunkMaps = chunk.getChunkMaps();
return mainTemplate.getAssetPath(JSON.stringify(chunkFilename), {
hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
hashWithLength: length =>
`" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
chunk: {
id: `" + ${chunkIdExpression} + "`,
hash: `" + ${JSON.stringify(
chunkMaps.hash
)}[${chunkIdExpression}] + "`,
hashWithLength(length) {
const shortChunkHashMap = Object.create(null);
for (const chunkId of Object.keys(chunkMaps.hash)) {
if (typeof chunkMaps.hash[chunkId] === "string") {
shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(
0,
length
);
}
}
return `" + ${JSON.stringify(
shortChunkHashMap
)}[${chunkIdExpression}] + "`;
},
name: `" + (${JSON.stringify(
chunkMaps.name
)}[${chunkIdExpression}]||${chunkIdExpression}) + "`,
contentHash: {
javascript: `" + ${JSON.stringify(
chunkMaps.contentHash.javascript
)}[${chunkIdExpression}] + "`
},
contentHashWithLength: {
javascript: length => {
const shortContentHashMap = {};
const contentHash = chunkMaps.contentHash.javascript;
for (const chunkId of Object.keys(contentHash)) {
if (typeof contentHash[chunkId] === "string") {
shortContentHashMap[chunkId] = contentHash[chunkId].substr(
0,
length
);
}
}
return `" + ${JSON.stringify(
shortContentHashMap
)}[${chunkIdExpression}] + "`;
}
}
},
contentHashType: "javascript"
});
};
mainTemplate.hooks.localVars.tap(
"JsonpMainTemplatePlugin",
(source, chunk, hash) => {
const extraCode = [];
if (needChunkLoadingCode(chunk)) {
extraCode.push(
"",
"// object to store loaded and loading chunks",
"// undefined = chunk not loaded, null = chunk preloaded/prefetched",
"// Promise = chunk loading, 0 = chunk loaded",
"var installedChunks = {",
Template.indent(
chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n")
),
"};",
"",
needEntryDeferringCode(chunk)
? needPrefetchingCode(chunk)
? "var deferredModules = [], deferredPrefetch = [];"
: "var deferredModules = [];"
: ""
);
}
if (needChunkOnDemandLoadingCode(chunk)) {
extraCode.push(
"",
"// script path function",
"function jsonpScriptSrc(chunkId) {",
Template.indent([
`return ${mainTemplate.requireFn}.p + ${getScriptSrcPath(
hash,
chunk,
"chunkId"
)}`
]),
"}"
);
}
if (extraCode.length === 0) return source;
return Template.asString([source, ...extraCode]);
}
);
mainTemplate.hooks.jsonpScript.tap(
"JsonpMainTemplatePlugin",
(_, chunk, hash) => {
const crossOriginLoading =
mainTemplate.outputOptions.crossOriginLoading;
const chunkLoadTimeout = mainTemplate.outputOptions.chunkLoadTimeout;
const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType;
return Template.asString([
"var script = document.createElement('script');",
"var onScriptComplete;",
jsonpScriptType
? `script.type = ${JSON.stringify(jsonpScriptType)};`
: "",
"script.charset = 'utf-8';",
`script.timeout = ${chunkLoadTimeout / 1000};`,
`if (${mainTemplate.requireFn}.nc) {`,
Template.indent(
`script.setAttribute("nonce", ${mainTemplate.requireFn}.nc);`
),
"}",
"script.src = jsonpScriptSrc(chunkId);",
crossOriginLoading
? Template.asString([
"if (script.src.indexOf(window.location.origin + '/') !== 0) {",
Template.indent(
`script.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
),
"}"
])
: "",
"// create error before stack unwound to get useful stacktrace later",
"var error = new Error();",
"onScriptComplete = function (event) {",
Template.indent([
"// avoid mem leaks in IE.",
"script.onerror = script.onload = null;",
"clearTimeout(timeout);",
"var chunk = installedChunks[chunkId];",
"if(chunk !== 0) {",
Template.indent([
"if(chunk) {",
Template.indent([
"var errorType = event && (event.type === 'load' ? 'missing' : event.type);",
"var realSrc = event && event.target && event.target.src;",
"error.message = 'Loading chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realSrc + ')';",
"error.name = 'ChunkLoadError';",
"error.type = errorType;",
"error.request = realSrc;",
"chunk[1](error);"
]),
"}",
"installedChunks[chunkId] = undefined;"
]),
"}"
]),
"};",
"var timeout = setTimeout(function(){",
Template.indent([
"onScriptComplete({ type: 'timeout', target: script });"
]),
`}, ${chunkLoadTimeout});`,
"script.onerror = script.onload = onScriptComplete;"
]);
}
);
mainTemplate.hooks.linkPreload.tap(
"JsonpMainTemplatePlugin",
(_, chunk, hash) => {
const crossOriginLoading =
mainTemplate.outputOptions.crossOriginLoading;
const jsonpScriptType = mainTemplate.outputOptions.jsonpScriptType;
return Template.asString([
"var link = document.createElement('link');",
jsonpScriptType
? `link.type = ${JSON.stringify(jsonpScriptType)};`
: "",
"link.charset = 'utf-8';",
`if (${mainTemplate.requireFn}.nc) {`,
Template.indent(
`link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);`
),
"}",
'link.rel = "preload";',
'link.as = "script";',
"link.href = jsonpScriptSrc(chunkId);",
crossOriginLoading
? Template.asString([
"if (link.href.indexOf(window.location.origin + '/') !== 0) {",
Template.indent(
`link.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
),
"}"
])
: ""
]);
}
);
mainTemplate.hooks.linkPrefetch.tap(
"JsonpMainTemplatePlugin",
(_, chunk, hash) => {
const crossOriginLoading =
mainTemplate.outputOptions.crossOriginLoading;
return Template.asString([
"var link = document.createElement('link');",
crossOriginLoading
? `link.crossOrigin = ${JSON.stringify(crossOriginLoading)};`
: "",
`if (${mainTemplate.requireFn}.nc) {`,
Template.indent(
`link.setAttribute("nonce", ${mainTemplate.requireFn}.nc);`
),
"}",
'link.rel = "prefetch";',
'link.as = "script";',
"link.href = jsonpScriptSrc(chunkId);"
]);
}
);
mainTemplate.hooks.requireEnsure.tap(
"JsonpMainTemplatePlugin load",
(source, chunk, hash) => {
return Template.asString([
source,
"",
"// JSONP chunk loading for javascript",
"",
"var installedChunkData = installedChunks[chunkId];",
'if(installedChunkData !== 0) { // 0 means "already installed".',
Template.indent([
"",
'// a Promise means "currently loading".',
"if(installedChunkData) {",
Template.indent(["promises.push(installedChunkData[2]);"]),
"} else {",
Template.indent([
"// setup Promise in chunk cache",
"var promise = new Promise(function(resolve, reject) {",
Template.indent([
"installedChunkData = installedChunks[chunkId] = [resolve, reject];"
]),
"});",
"promises.push(installedChunkData[2] = promise);",
"",
"// start chunk loading",
mainTemplate.hooks.jsonpScript.call("", chunk, hash),
"document.head.appendChild(script);"
]),
"}"
]),
"}"
]);
}
);
mainTemplate.hooks.requireEnsure.tap(
{
name: "JsonpMainTemplatePlugin preload",
stage: 10
},
(source, chunk, hash) => {
const chunkMap = chunk.getChildIdsByOrdersMap().preload;
if (!chunkMap || Object.keys(chunkMap).length === 0) return source;
return Template.asString([
source,
"",
"// chunk preloadng for javascript",
"",
`var chunkPreloadMap = ${JSON.stringify(chunkMap, null, "\t")};`,
"",
"var chunkPreloadData = chunkPreloadMap[chunkId];",
"if(chunkPreloadData) {",
Template.indent([
"chunkPreloadData.forEach(function(chunkId) {",
Template.indent([
"if(installedChunks[chunkId] === undefined) {",
Template.indent([
"installedChunks[chunkId] = null;",
mainTemplate.hooks.linkPreload.call("", chunk, hash),
"document.head.appendChild(link);"
]),
"}"
]),
"});"
]),
"}"
]);
}
);
mainTemplate.hooks.requireExtensions.tap(
"JsonpMainTemplatePlugin",
(source, chunk) => {
if (!needChunkOnDemandLoadingCode(chunk)) return source;
return Template.asString([
source,
"",
"// on error function for async loading",
`${mainTemplate.requireFn}.oe = function(err) { console.error(err); throw err; };`
]);
}
);
mainTemplate.hooks.bootstrap.tap(
"JsonpMainTemplatePlugin",
(source, chunk, hash) => {
if (needChunkLoadingCode(chunk)) {
const withDefer = needEntryDeferringCode(chunk);
const withPrefetch = needPrefetchingCode(chunk);
return Template.asString([
source,
"",
"// install a JSONP callback for chunk loading",
"function webpackJsonpCallback(data) {",
Template.indent([
"var chunkIds = data[0];",
"var moreModules = data[1];",
withDefer ? "var executeModules = data[2];" : "",
withPrefetch ? "var prefetchChunks = data[3] || [];" : "",
'// add "moreModules" to the modules object,',
'// then flag all "chunkIds" as loaded and fire callback',
"var moduleId, chunkId, i = 0, resolves = [];",
"for(;i < chunkIds.length; i++) {",
Template.indent([
"chunkId = chunkIds[i];",
"if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {",
Template.indent("resolves.push(installedChunks[chunkId][0]);"),
"}",
"installedChunks[chunkId] = 0;"
]),
"}",
"for(moduleId in moreModules) {",
Template.indent([
"if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {",
Template.indent(
mainTemplate.renderAddModule(
hash,
chunk,
"moduleId",
"moreModules[moduleId]"
)
),
"}"
]),
"}",
"if(parentJsonpFunction) parentJsonpFunction(data);",
withPrefetch
? withDefer
? "deferredPrefetch.push.apply(deferredPrefetch, prefetchChunks);"
: Template.asString([
"// chunk prefetching for javascript",
"prefetchChunks.forEach(function(chunkId) {",
Template.indent([
"if(installedChunks[chunkId] === undefined) {",
Template.indent([
"installedChunks[chunkId] = null;",
mainTemplate.hooks.linkPrefetch.call("", chunk, hash),
"document.head.appendChild(link);"
]),
"}"
]),
"});"
])
: "",
"while(resolves.length) {",
Template.indent("resolves.shift()();"),
"}",
withDefer
? Template.asString([
"",
"// add entry modules from loaded chunk to deferred list",
"deferredModules.push.apply(deferredModules, executeModules || []);",
"",
"// run deferred modules when all chunks ready",
"return checkDeferredModules();"
])
: ""
]),
"};",
withDefer
? Template.asString([
"function checkDeferredModules() {",
Template.indent([
"var result;",
"for(var i = 0; i < deferredModules.length; i++) {",
Template.indent([
"var deferredModule = deferredModules[i];",
"var fulfilled = true;",
"for(var j = 1; j < deferredModule.length; j++) {",
Template.indent([
"var depId = deferredModule[j];",
"if(installedChunks[depId] !== 0) fulfilled = false;"
]),
"}",
"if(fulfilled) {",
Template.indent([
"deferredModules.splice(i--, 1);",
"result = " +
mainTemplate.requireFn +
"(" +
mainTemplate.requireFn +
".s = deferredModule[0]);"
]),
"}"
]),
"}",
withPrefetch
? Template.asString([
"if(deferredModules.length === 0) {",
Template.indent([
"// chunk prefetching for javascript",
"deferredPrefetch.forEach(function(chunkId) {",
Template.indent([
"if(installedChunks[chunkId] === undefined) {",
Template.indent([
"installedChunks[chunkId] = null;",
mainTemplate.hooks.linkPrefetch.call(
"",
chunk,
hash
),
"document.head.appendChild(link);"
]),
"}"
]),
"});",
"deferredPrefetch.length = 0;"
]),
"}"
])
: "",
"return result;"
]),
"}"
])
: ""
]);
}
return source;
}
);
mainTemplate.hooks.beforeStartup.tap(
"JsonpMainTemplatePlugin",
(source, chunk, hash) => {
if (needChunkLoadingCode(chunk)) {
var jsonpFunction = mainTemplate.outputOptions.jsonpFunction;
var globalObject = mainTemplate.outputOptions.globalObject;
return Template.asString([
`var jsonpArray = ${globalObject}[${JSON.stringify(
jsonpFunction
)}] = ${globalObject}[${JSON.stringify(jsonpFunction)}] || [];`,
"var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);",
"jsonpArray.push = webpackJsonpCallback;",
"jsonpArray = jsonpArray.slice();",
"for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);",
"var parentJsonpFunction = oldJsonpFunction;",
"",
source
]);
}
return source;
}
);
mainTemplate.hooks.afterStartup.tap(
"JsonpMainTemplatePlugin",
(source, chunk, hash) => {
const prefetchChunks = chunk.getChildIdsByOrders().prefetch;
if (
needChunkLoadingCode(chunk) &&
prefetchChunks &&
prefetchChunks.length
) {
return Template.asString([
source,
`webpackJsonpCallback([[], {}, 0, ${JSON.stringify(
prefetchChunks
)}]);`
]);
}
return source;
}
);
mainTemplate.hooks.startup.tap(
"JsonpMainTemplatePlugin",
(source, chunk, hash) => {
if (needEntryDeferringCode(chunk)) {
if (chunk.hasEntryModule()) {
const entries = [chunk.entryModule].filter(Boolean).map(m =>
[m.id].concat(
Array.from(chunk.groupsIterable)[0]
.chunks.filter(c => c !== chunk)
.map(c => c.id)
)
);
return Template.asString([
"// add entry module to deferred list",
`deferredModules.push(${entries
.map(e => JSON.stringify(e))
.join(", ")});`,
"// run deferred modules when ready",
"return checkDeferredModules();"
]);
} else {
return Template.asString([
"// run deferred modules from other chunks",
"checkDeferredModules();"
]);
}
}
return source;
}
);
mainTemplate.hooks.hotBootstrap.tap(
"JsonpMainTemplatePlugin",
(source, chunk, hash) => {
const globalObject = mainTemplate.outputOptions.globalObject;
const hotUpdateChunkFilename =
mainTemplate.outputOptions.hotUpdateChunkFilename;
const hotUpdateMainFilename =
mainTemplate.outputOptions.hotUpdateMainFilename;
const crossOriginLoading =
mainTemplate.outputOptions.crossOriginLoading;
const hotUpdateFunction = mainTemplate.outputOptions.hotUpdateFunction;
const currentHotUpdateChunkFilename = mainTemplate.getAssetPath(
JSON.stringify(hotUpdateChunkFilename),
{
hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
hashWithLength: length =>
`" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
chunk: {
id: '" + chunkId + "'
}
}
);
const currentHotUpdateMainFilename = mainTemplate.getAssetPath(
JSON.stringify(hotUpdateMainFilename),
{
hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
hashWithLength: length =>
`" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`
}
);
const runtimeSource = Template.getFunctionContent(
require("./JsonpMainTemplate.runtime")
)
.replace(/\/\/\$semicolon/g, ";")
.replace(/\$require\$/g, mainTemplate.requireFn)
.replace(
/\$crossOriginLoading\$/g,
crossOriginLoading ? JSON.stringify(crossOriginLoading) : "null"
)
.replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
.replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
.replace(/\$hash\$/g, JSON.stringify(hash));
return `${source}
function hotDisposeChunk(chunkId) {
delete installedChunks[chunkId];
}
var parentHotUpdateCallback = ${globalObject}[${JSON.stringify(
hotUpdateFunction
)}];
${globalObject}[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`;
}
);
mainTemplate.hooks.hash.tap("JsonpMainTemplatePlugin", hash => {
hash.update("jsonp");
hash.update("6");
});
}
}
module.exports = JsonpMainTemplatePlugin;
| mit |
quzzimi/ElectronicObserver | ElectronicObserver/Window/Dialog/DialogShipGroupColumnFilter.Designer.cs | 9138 | namespace ElectronicObserver.Window.Dialog {
partial class DialogShipGroupColumnFilter {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose( bool disposing ) {
if ( disposing && ( components != null ) ) {
components.Dispose();
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.ButtonOK = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.ColumnView = new System.Windows.Forms.DataGridView();
this.ColumnView_Name = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnView_Visible = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.ColumnView_AutoSize = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.ColumnView_Width = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnView_Up = new System.Windows.Forms.DataGridViewButtonColumn();
this.ColumnView_Down = new System.Windows.Forms.DataGridViewButtonColumn();
this.label1 = new System.Windows.Forms.Label();
this.ScrLkColumnCount = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.ColumnView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ScrLkColumnCount)).BeginInit();
this.SuspendLayout();
//
// ButtonOK
//
this.ButtonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonOK.Location = new System.Drawing.Point(296, 327);
this.ButtonOK.Name = "ButtonOK";
this.ButtonOK.Size = new System.Drawing.Size(75, 23);
this.ButtonOK.TabIndex = 2;
this.ButtonOK.Text = "OK";
this.ButtonOK.UseVisualStyleBackColor = true;
this.ButtonOK.Click += new System.EventHandler(this.ButtonOK_Click);
//
// ButtonCancel
//
this.ButtonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ButtonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.ButtonCancel.Location = new System.Drawing.Point(377, 327);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(75, 23);
this.ButtonCancel.TabIndex = 3;
this.ButtonCancel.Text = "キャンセル";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// ColumnView
//
this.ColumnView.AllowUserToAddRows = false;
this.ColumnView.AllowUserToDeleteRows = false;
this.ColumnView.AllowUserToResizeColumns = false;
this.ColumnView.AllowUserToResizeRows = false;
this.ColumnView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ColumnView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.ColumnView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnView_Name,
this.ColumnView_Visible,
this.ColumnView_AutoSize,
this.ColumnView_Width,
this.ColumnView_Up,
this.ColumnView_Down});
this.ColumnView.Location = new System.Drawing.Point(12, 12);
this.ColumnView.MultiSelect = false;
this.ColumnView.Name = "ColumnView";
this.ColumnView.RowHeadersVisible = false;
this.ColumnView.RowTemplate.Height = 21;
this.ColumnView.Size = new System.Drawing.Size(440, 309);
this.ColumnView.TabIndex = 4;
this.ColumnView.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.ColumnView_CellContentClick);
this.ColumnView.CellValidating += new System.Windows.Forms.DataGridViewCellValidatingEventHandler(this.ColumnView_CellValidating);
this.ColumnView.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.ColumnView_CellValueChanged);
this.ColumnView.CurrentCellDirtyStateChanged += new System.EventHandler(this.ColumnView_CurrentCellDirtyStateChanged);
this.ColumnView.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.ColumnView_DataError);
//
// ColumnView_Name
//
this.ColumnView_Name.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ColumnView_Name.HeaderText = "列名";
this.ColumnView_Name.Name = "ColumnView_Name";
this.ColumnView_Name.ReadOnly = true;
this.ColumnView_Name.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// ColumnView_Visible
//
this.ColumnView_Visible.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.ColumnView_Visible.HeaderText = "表示";
this.ColumnView_Visible.Name = "ColumnView_Visible";
this.ColumnView_Visible.Width = 37;
//
// ColumnView_AutoSize
//
this.ColumnView_AutoSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
this.ColumnView_AutoSize.HeaderText = "自動サイズ";
this.ColumnView_AutoSize.Name = "ColumnView_AutoSize";
this.ColumnView_AutoSize.Width = 66;
//
// ColumnView_Width
//
this.ColumnView_Width.HeaderText = "幅";
this.ColumnView_Width.Name = "ColumnView_Width";
this.ColumnView_Width.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable;
//
// ColumnView_Up
//
this.ColumnView_Up.HeaderText = "↑";
this.ColumnView_Up.Name = "ColumnView_Up";
this.ColumnView_Up.Width = 20;
//
// ColumnView_Down
//
this.ColumnView_Down.HeaderText = "↓";
this.ColumnView_Down.Name = "ColumnView_Down";
this.ColumnView_Down.Width = 20;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 331);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(62, 15);
this.label1.TabIndex = 5;
this.label1.Text = "列の固定: ";
//
// ScrLkColumnCount
//
this.ScrLkColumnCount.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ScrLkColumnCount.Location = new System.Drawing.Point(80, 327);
this.ScrLkColumnCount.Name = "ScrLkColumnCount";
this.ScrLkColumnCount.Size = new System.Drawing.Size(60, 23);
this.ScrLkColumnCount.TabIndex = 6;
this.ScrLkColumnCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
//
// DialogShipGroupColumnFilter
//
this.AcceptButton = this.ButtonOK;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.CancelButton = this.ButtonCancel;
this.ClientSize = new System.Drawing.Size(464, 362);
this.Controls.Add(this.ScrLkColumnCount);
this.Controls.Add(this.label1);
this.Controls.Add(this.ColumnView);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.ButtonOK);
this.Font = new System.Drawing.Font("Meiryo UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "DialogShipGroupColumnFilter";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "列の表示設定";
this.Load += new System.EventHandler(this.DialogShipGroupColumnFilter_Load);
((System.ComponentModel.ISupportInitialize)(this.ColumnView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ScrLkColumnCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button ButtonOK;
private System.Windows.Forms.Button ButtonCancel;
private System.Windows.Forms.DataGridView ColumnView;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnView_Name;
private System.Windows.Forms.DataGridViewCheckBoxColumn ColumnView_Visible;
private System.Windows.Forms.DataGridViewCheckBoxColumn ColumnView_AutoSize;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnView_Width;
private System.Windows.Forms.DataGridViewButtonColumn ColumnView_Up;
private System.Windows.Forms.DataGridViewButtonColumn ColumnView_Down;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown ScrLkColumnCount;
}
} | mit |
ericfennis/RUNCMD | app/system/languages/ar_EG/messages.php | 16044 | <?php return array (
25 => '25',
'Invalid Password.' => '',
'Permissions' => 'الأوامر',
'Add Folder' => 'اضافة مجلد',
'Rename' => 'اعادة تسمية',
'Changelog' => '',
'Removed selected.' => 'تم مسح الملف المطلوب',
'Whoops, looks like something went wrong.' => '',
'Enable' => '',
'Manage media files' => 'إدارة ملفات الموقع',
'Update' => 'تحديث',
'Next' => '',
'SMTP User' => '',
'Hide in menu' => '',
'User Settings' => '',
'Modified' => 'معُدلة',
'Last registered' => '',
'Welcome to %site%!' => '',
'Check Connection' => '',
'Invalid type.' => '',
'Poster Image' => 'صورة الملصق',
'Path' => '',
'Unable to upload.' => 'لم نتمكن من الرفع',
'Value' => '',
'Username' => '',
'Is your language not available? Please help out by translating Pagekit into your own language on %link%.' => '',
'No Limit' => '',
'Code' => '',
'Positions' => '',
'Your user account has been created and is pending approval by the site administrator.' => '',
'Invalid url.' => '',
'Remember Me' => '',
'Info' => '',
'Permission' => '',
'Database name cannot be blank.' => '',
7 => '7',
'System' => '',
'Unable to remove.' => 'لم نتمكن من المسح',
'Latest registered Users' => '',
'Approve an account at %site%.' => '',
'Developer' => 'مطور',
'Logo' => '',
'Cannot connect to the server. Please try again later.' => '',
'Install' => '',
'Don\'t show' => 'لا تظُهر',
'Missing order data.' => '',
'Warning: Give to trusted roles only; this permission has security implications.' => 'تحذير : قم بإصدار تلك الصلاحيات لمن تثق بهم فقط , هذا التصريح يمكن ان يُحدث مشاكل في نظام الحماية',
'Removing package folder.' => '',
'Offline' => '',
'Add %type%' => '',
'User Login' => '',
'Confirm' => '',
'Setup your site' => '',
'Apply system updates' => 'تحديث النظام',
'Extensions' => '',
'Uploaded file invalid. (%s)' => 'الملف المرفوع لا يمكن رفعة (%s)',
'Forgot Password' => '',
'Unable to send verification link.' => '',
'Sub Items' => '',
'Your database is up to date.' => '',
'User Registration' => '',
'TLS' => '',
'Invalid key.' => '',
'Favicon' => '',
'Name cannot be blank.' => '',
'Roles' => 'الصلاحيات',
'Connection not established! (%s)' => '',
'Reset password' => '',
'Database' => '',
'Imperial' => 'ملكي',
'Activate Account' => '',
'Menu' => '',
'Message' => '',
'Add Widget' => '',
'None' => '',
'Visit Site' => '',
'Testemail' => '',
'URL' => 'رابط',
'Depth' => '',
'Invalid name.' => '',
'Selected' => '',
'Request password' => '',
'Thank you for signing up for %site%. Just one more step! Please click the button below to activate your account.' => '',
'Site Locale' => '',
'Session expired. Please log in again.' => '',
'"%title%" enabled.' => '',
'"%name%" has not been loaded.' => '',
4 => '4',
'Type' => '',
'Manage extensions' => 'إدارة الإضافات',
'Your account has been activated.' => '',
'Disable cache' => 'ايقاف ذاكرة المتصفح',
'Can\'t load json file from package.' => '',
'Manage widgets' => 'إدارة البلوكات',
'Hi %name%!' => '',
'Menu Title' => '',
'Total Users' => '',
'Email address is invalid.' => '',
'Logout Redirect' => '',
9 => '9',
'No pages found.' => '',
'Cache' => 'ذاكرة المتصفح',
'Pagekit %version% is available.' => '',
'Choose a title and create the administrator account.' => '',
'Database Name' => '',
'Number of Posts' => 'عدد المنشورات',
'All' => '',
'Already have an account?' => '',
'Please enable the SQLite database extension.' => '',
'Enabled, but approval is required.' => '',
'Description' => '',
'Logged in' => '',
'Unknown' => '',
'You have the latest version of Pagekit. You do not need to update. However, if you want to re-install version %version%, you can download the package and re-install manually.' => '',
'Reset' => '',
'Height' => 'طول',
'Pagekit Version' => '',
'A new user signed up for %site% with the username %username%. Please click the button below to approve the account.' => '',
'Dashboard' => 'لوحة التحكم',
'Widget deleted.' => 'تم مسح البلوك',
'Access admin area' => 'الوصول الي ادارة الموقع',
'New Password' => '',
'Unable to rename.' => 'لم نتمكن من اعادة التسمية',
'Change password' => '',
'password' => '',
'PHP Mailer' => '',
3 => '3',
'There is an update available for the package.' => '',
'Select Cache to Clear' => 'اختار ذاكرة المتصفح ليتم مسحها',
'Add User' => '',
'(Currently set to: %menu%)' => '',
'Pages' => '',
'%d TB' => '%d تيرابايت',
'Mail' => '',
'{0} %count% Users|{1} %count% User|]1,Inf[ %count% Users' => '',
'Invalid id.' => '',
'Upload' => 'رفع',
'Logout' => '',
'- Menu -' => '',
'Storage' => '',
'{1} %count% Widget moved|]1,Inf[ %count% Widgets moved' => '',
'User Logout' => '',
1 => '1',
'Reset Password' => '',
'Duplicate Menu Id.' => '',
'Email:' => '',
'Enable debug mode' => '',
'Invalid file name.' => 'اسم ملف غير موجوجد',
'Your account has not been activated.' => '',
'Hide' => '',
'No theme found.' => '',
'There is an update available.' => '',
'Installing %title% %version%' => '',
'Connection established!' => '',
'Settings' => 'الاعدادات',
'Image' => 'صورة',
'Request Password' => '',
'Slug' => '',
'Renamed.' => 'تمت اعداة التسمية',
'Url' => 'رابط',
'No Pagekit %type%' => '',
'Hidden' => '',
'Select Link' => '',
'Display' => '',
'Show all' => '',
'Title cannot be blank.' => '',
'User cannot be blank.' => '',
'No Frontpage assigned.' => '',
'Name required.' => '',
'Select Image' => 'إختر الصورة',
'Password must be 6 characters or longer.' => '',
'Table Prefix' => '',
'Node not found.' => '',
'Send Test Email' => '',
'Driver' => '',
'Muted' => 'صامتة',
'Last login' => '',
'Choose language' => '',
'We got a request to reset your %site% password for %username%. If you ignore this message, your password won\'t be changed.' => '',
'Invalid slug.' => '',
'Setting' => '',
'No file uploaded.' => '',
'Prefix must start with a letter and can only contain alphanumeric characters (A-Z, 0-9) and underscore (_)' => '',
'Close' => 'اغلاق',
'Latest logged in Users' => '',
'List' => '',
'Invalid token. Please try again.' => '',
'Homepage:' => '',
'Login Now' => '',
'Connect database' => '',
'Show on all posts' => 'إظهار في جميع المنشورات',
'You may not call this step directly.' => '',
'Folder already exists.' => 'المجلد موجود بالفعل',
'Use the site in maintenance mode' => 'إستخدام الموقع في وضع الصيانة',
'Successfully removed.' => '',
'Access' => 'الوصول',
'{0} Registered Users|{1} Registered User|]1,Inf[ Registered Users' => '',
'Version %version%' => '',
'Client' => '',
'Enter a valid email address.' => '',
'Folder Name' => 'اسم المجلد',
'Enter password.' => '',
'Unassigned' => '',
'Password' => '',
'Loop' => 'التقلب',
'Installed' => '',
'_subset' => '',
'Your account has not been activated or is blocked.' => '',
'Cannot obtain versions. Please try again later.' => '',
100 => '100',
'Invalid path.' => 'رابط غير صحيح',
'Your account is blocked.' => '',
'Thumbnail' => '',
'Your Pagekit database has been updated successfully.' => '',
'Whoops, something went wrong.' => '',
'Widgets reordered.' => 'تمت اعادة ترتيب البلوكات',
'Password required.' => '',
'Manage themes' => 'إدارة القوالب',
'Enable Markdown' => '',
'%d MB' => '%d ميجابايت',
'Temporary Files' => 'الملفات المؤقتة',
'Mail delivery failed! (%s)' => '',
'Username cannot be blank and may only contain alphanumeric characters (A-Z, 0-9) and some special characters ("._-")' => '',
'Error' => '',
'Please enter your email address. You will receive a link to create a new password via email.' => '',
40 => '40',
'%d PB' => '',
'Web Server' => '',
'Hello!' => '',
'Link' => '',
'Restrict Access' => '',
'Trash' => '',
'Password Confirmation' => '',
33 => '33',
'Email is invalid.' => '',
'SMTP Mailer' => '',
'Unit' => 'وحدة',
'Disabled' => '',
'Email not available.' => '',
'%d KB' => '%d كيلوبايت',
'No account yet?' => '',
'Account activation' => '',
'Add Page' => '',
'Host cannot be blank.' => '',
'Test email!' => '',
'Manage user permissions' => 'إدارة صلاحيات المستخدم',
'Database error: %error%' => '',
'SMTP Encryption' => '',
'{1} %count% User selected|]1,Inf[ %count% Users selected' => '',
'Field must be a valid email address.' => '',
'Approve Account' => '',
'Complete your registration by clicking the link provided in the mail that has been sent to you.' => '',
'Order saved.' => '',
'Download %version%' => '',
'Unwritable' => '',
'Title' => 'عنوان',
'Sign in to your account' => '',
'Create an account' => '',
'User' => '',
'Password cannot be blank.' => '',
'Autoplay' => 'تشغيل تلقائي',
'Position' => '',
'Start Level' => '',
'SMTP Host' => '',
'Retry' => '',
'n/a' => 'n/a',
'SMTP Port' => '',
'Login' => '',
'Home' => 'الرئيسية',
'Reset Confirm' => '',
'Enabled' => '',
'Unable to find "%name%".' => '',
'No widgets found.' => '',
'Themes' => '',
'%d Bytes' => '%d بايت',
'Unable to block yourself.' => '',
'You do not have access to the administration area of this site.' => '',
'{0} %count% Files|{1} %count% File|]1,Inf[ %count% Files' => '',
'No location found.' => 'لم يتم العثور علي الموقع',
'No URL given.' => 'لم يتم وضع رابط',
5 => '5',
'Access system settings' => 'الوصول الي إعدادات الموقع',
'Folder' => '',
'Check your email for the confirmation link.' => '',
'Enable debug toolbar' => '',
'Save' => 'حفظ',
'We\'ll be back soon.' => '',
'Menus' => 'القوائم',
'Cancel' => 'إالغاء',
15 => '15',
'Select Video' => 'إختر فيديو',
'Version' => '',
'Database connection failed!' => '',
'Current Password' => '',
'Number of Users' => '',
'Directory created.' => 'تم تجهيز الوجهة',
'Alt' => 'مماثل',
'Enter your database connection details.' => '',
'Writable' => '',
'Active' => '',
'Add Role' => '',
'Support' => '',
'Registered since' => '',
'Manage menus' => 'إدارة القوائم',
'Successfully installed.' => '',
'Admin Locale' => '',
'Removing %title% %version%' => '',
'Menu Positions' => '',
'The user\'s account has been activated and the user has been notified about it.' => '',
'Marketplace' => '',
'%d GB' => '%d جيجابايت',
'{1} %count% Widget selected|]1,Inf[ %count% Widgets selected' => '',
'Invalid password.' => '',
'Edit %type%' => '',
'From Email' => '',
'Put the site offline and show the offline message.' => '',
'Cannot connect to the marketplace. Please try again later.' => '',
'Insufficient User Rights.' => '',
'Copy' => '',
'Upload complete.' => 'تم الرفع',
'Clear' => 'مسح',
'Documentation' => '',
'Invalid Email.' => '',
'Extension' => '',
'Widgets' => 'البلوكات',
'Pages moved to %menu%.' => '',
'Database access denied!' => '',
'Controls' => 'تحكم',
'Slow down a bit.' => '',
'Require e-mail verification when a guest creates an account.' => '',
'%d ZB' => '',
'Manage users' => 'ادارة المستخدمين',
'Pagekit Installer' => '',
'%d YB' => '',
'Login!' => '',
'\'composer.json\' is missing.' => '',
'Clear Cache' => 'تنظيف ذاكرة المتصفح',
'PHP' => '',
'Show' => '',
'SMTP Password' => '',
'No extension found.' => '',
'Invalid username or password.' => '',
'Location' => 'الموقع',
'Header' => '',
'Sign up now' => '',
'Users' => 'المستخدمين',
'Hi %username%' => '',
'URL Alias' => '',
50 => '50',
'Filter by' => '',
'Username not available.' => '',
'Add Video' => 'اضافة فيديو',
'Existing Pagekit installation detected. Choose different table prefix?' => '',
'View' => '',
'Login Redirect' => '',
'General' => '',
'Pagekit has been updated! Before we send you on your way, we have to update your database to the newest version.' => '',
'%d EB' => '',
6 => '6',
'- Assign -' => '',
'Hostname' => '',
'Unable to enable "%name%".' => '',
'Mailer' => '',
'User not found.' => '',
'Unable to retrieve feed data.' => 'لا يمكن الوصول الي مغذي البيانات',
'Permission denied.' => 'الامر مرفوض',
'Username is invalid.' => '',
'We\'re really happy to have you, %name%! Just login with the username %username%.' => '',
'Your email has been verified. Once an administrator approves your account, you will be notified by email.' => '',
20 => '20',
'Package path is missing.' => '',
'No files uploaded.' => 'لم تم رفع اي ملفات ',
'User Type' => '',
'Unable to delete yourself.' => '',
'User Agent' => '',
8 => '8',
'Ok' => 'OK',
'No files found.' => 'لم يتم العثور علي الملفات ',
'Activate your %site% account.' => '',
'Size' => 'الحجم',
'"composer.json" file not valid.' => '',
'License:' => '',
'Unable to create directory.' => 'لم نتمكن من انشاء الوجهة',
'Blocked' => '',
'Add Link' => 'اضافة وصلة',
'Metric' => 'مقياس',
'Only show on first post.' => 'إظهار فقط في المنشور الاول',
'Sign up' => '',
'"%title%" disabled.' => '',
'Reset password for %site%.' => '',
10 => '10',
'Add Image' => 'إضافة صورة',
'Post Content' => 'نشر محتوي',
'Unknown email address.' => '',
'Site Title' => '',
'Registration' => '',
'Mail successfully sent!' => '',
'Status' => '',
'Maintenance' => '',
'Built On' => '',
'User Password Reset' => '',
'Meta' => '',
'username' => '',
'Localization' => '',
'Unable to activate "%name%".<br>A fatal error occured.' => '',
'Invalid node type.' => '',
'{1} %count% File selected|]1,Inf[ %count% Files selected' => '',
'Demo' => '',
'Select' => 'أختر',
'Sign in' => '',
'Installation failed!' => '',
'%type% saved.' => '',
'Unable to send confirmation link.' => '',
'Footer' => '',
'Update Pagekit' => '',
'From Name' => '',
'You have the latest version of Pagekit.' => '',
'Your password has been reset.' => '',
'No database connection.' => '',
'Your user account has been created.' => '',
'Appicon' => '',
'Your Profile' => '',
'File' => '',
'SSL' => '',
'User Profile' => '',
'Select your site language.' => '',
'Can\'t write config.' => '',
'Insert code in the header and footer of your theme. This is useful for tracking codes and meta tags.' => '',
'Width' => 'عرض',
'Site title cannot be blank.' => '',
'{0} Logged in Users|{1} Logged in User|]1,Inf[ Logged in Users' => '',
'Show only for active item' => '',
'Verification' => '',
'Handler' => '',
'Unauthorized' => '',
'Email' => '',
'New' => '',
'Forgot Password?' => '',
'No user found.' => '',
'Mail delivery failed!' => '',
'Add Menu' => '',
30 => '30',
2 => '2',
'Redirect' => '',
'Nothing found.' => '',
'System Cache' => 'ذاكرة النظام',
'Edit User' => '',
'Role not found.' => '',
'Edit Widget' => '',
'Name' => 'الاسم',
'Page not found.' => '',
'Please enable the PHP Open SSL extension.' => '',
); | mit |
Mozerskial/enigmos | Enigmas/Components/Clou/Player.cs | 1502 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cpln.Enigmos.Enigmas.Components.Clou
{
/// <summary>
/// Classe représentant un joueur du jeu du clou
/// </summary>
class Player
{
/// <summary>
/// Propriété indiquant le nombre de manches gagnés du joueur
/// </summary>
public int WinnedRound { get; set; }
/// <summary>
/// Propriété indiquant la puissance de frappe du dernier tour.
/// </summary>
public int LastTurnPower { get; set; }
/// <summary>
/// Propriété indiquant si c'est le tour du joueur courant ou pas.
/// </summary>
public bool IsTurn { get; set; }
/// <summary>
/// Constructeur : Définition/instanciation des valeurs par défaut.
/// </summary>
public Player()
{
//Par défaut, c'est toujours le joueur humain qui commence.
IsTurn = true;
}
#region Méthodes
/// <summary>
/// Donne un coup sur le clou, enregistre dans la propriété LastTurnPower la puissance du coup.
/// </summary>
/// <param name="nail">Le clou de la partie</param>
/// <param name="power">La puissanc du coup</param>
public void Blow(Nail nail, int power)
{
nail.Down(power);
LastTurnPower = power;
}
#endregion
}
}
| mit |
fengzhyuan/Halide | python_bindings/python/Argument.cpp | 4779 | #include "Argument.h"
// to avoid compiler confusion, python.hpp must be include before Halide headers
#include <boost/python.hpp>
#include "no_compare_indexing_suite.h"
#include "../../src/Argument.h"
#include <string>
namespace h = Halide;
//std::string argument_name(h::Argument &that)
//{
// return that.name;
//}
//h::Argument::Kind argument_kind(h::Argument &that)
//{
// return that.kind;
//}
void defineArgument()
{
using Halide::Argument;
namespace p = boost::python;
auto argument_class =
p::class_<Argument>("Argument",
"A struct representing an argument to a halide-generated function. "
"Used for specifying the function signature of generated code.",
p::init<>(p::arg("self")));
argument_class
.def(p::init<std::string, Argument::Kind, h::Type, uint8_t, h::Expr, h::Expr, h::Expr>(
(p::arg("self"), p::arg("name"), p::arg("kind"), p::arg("type"), p::arg("dimensions"),
p::arg("default"), p::arg("min"), p::arg("max"))))
.def(p::init<std::string, Argument::Kind, h::Type, uint8_t, h::Expr>(
(p::arg("self"), p::arg("name"), p::arg("kind"), p::arg("type"), p::arg("dimensions"),
p::arg("default"))))
.def(p::init<std::string, Argument::Kind, h::Type, uint8_t>(
(p::arg("self"), p::arg("name"), p::arg("kind"), p::arg("type"), p::arg("dimensions"))))
;
argument_class
.def_readonly("name", &Argument::name, "The name of the argument.");
//.property("name", &Argument::name, "The name of the argument.")
//.def("name",
// &argument_name, // getter instead of property to be consistent with other parts of the API
// "The name of the argument.");
p::enum_<Argument::Kind>("ArgumentKind")
.value("InputScalar", Argument::Kind::InputScalar)
.value("InputBuffer", Argument::Kind::InputBuffer)
.value("OutputBuffer", Argument::Kind::OutputBuffer)
.export_values()
;
argument_class
//.def("kind", &argument_kind,
.def_readonly("kind", &Argument::kind,
//.def("kind", [](Argument &that) -> Argument::Kind { return that.kind; },
//.def("kind", std::function<Argument::Kind(Argument &)>( [](Argument &that) { return that.kind; } ),
"An argument is either a primitive type (for parameters), or a buffer pointer.\n"
"If kind == InputScalar, then type fully encodes the expected type of the scalar argument."
"If kind == InputBuffer|OutputBuffer, then type.bytes() should be used "
"to determine* elem_size of the buffer; additionally, type.code *should* "
"reflect the expected interpretation of the buffer data (e.g. float vs int), "
"but there is no runtime enforcement of this at present.");
argument_class
.def_readonly("dimensions", &Argument::dimensions,
"If kind == InputBuffer|OutputBuffer, this is the dimensionality of the buffer. "
"If kind == InputScalar, this value is ignored (and should always be set to zero)");
argument_class
.def_readonly("type", &Argument::type,
"If this is a scalar parameter, then this is its type. "
" If this is a buffer parameter, this is used to determine elem_size of the buffer_t. "
"Note that type.width should always be 1 here.");
argument_class
.def_readonly("default", &Argument::def,
"If this is a scalar parameter, then these are its default, min, max values. "
"By default, they are left unset, implying \"no default, no min, no max\". ")
.def_readonly("min", &Argument::min)
.def_readonly("max", &Argument::max);
argument_class
.def("is_buffer", &Argument::is_buffer, p::arg("self"),
"An argument is either a primitive type (for parameters), or a buffer pointer. "
"If 'is_buffer' is true, then 'type' should be ignored.")
.def("is_scalar", &Argument::is_scalar, p::arg("self"))
.def("is_input", &Argument::is_input, p::arg("self"))
.def("is_output", &Argument::is_output, p::arg("self"));
p::class_< std::vector<h::Argument> >("ArgumentsVector")
.def( no_compare_indexing_suite< std::vector<h::Argument> >() );
return;
}
| mit |
JohnONolan/Ghost | core/server/api/v2/tags-public.js | 1574 | const Promise = require('bluebird');
const {i18n} = require('../../lib/common');
const errors = require('@tryghost/errors');
const models = require('../../models');
const ALLOWED_INCLUDES = ['count.posts'];
module.exports = {
docName: 'tags',
browse: {
options: [
'include',
'filter',
'fields',
'limit',
'order',
'page',
'debug'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
}
}
},
permissions: true,
query(frame) {
return models.TagPublic.findPage(frame.options);
}
},
read: {
options: [
'include',
'filter',
'fields',
'debug'
],
data: [
'id',
'slug',
'visibility'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
}
}
},
permissions: true,
query(frame) {
return models.TagPublic.findOne(frame.data, frame.options)
.then((model) => {
if (!model) {
return Promise.reject(new errors.NotFoundError({
message: i18n.t('errors.api.tags.tagNotFound')
}));
}
return model;
});
}
}
};
| mit |
rohanraizada1/httpfoxakamai | defaults/preferences/HttpFox.js | 317 | pref("extensions.httpfox.StartAtBrowserStart", false);
pref("extensions.httpfox.AlwaysOpenDetached", false);
pref("extensions.httpfox.ShowHttpFoxHelperRequests", false);
pref("extensions.httpfox.ColorRequests", true);
pref("extensions.httpfox.ShowDebugTab", false);
pref("extensions.httpfox.ForceCaching", true); | gpl-2.0 |
ForAEdesWeb/AEW9 | components/com_webgallery/models/categories.php | 13921 | <?php
/**
* @package Joomla.Site
* @subpackage com_webgallery
*
* @copyright Copyright (C) 2012 Asikart. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Generated by AKHelper - http://asikart.com
*/
// no direct access
defined('_JEXEC') or die;
include_once AKPATH_COMPONENT.'/modellist.php' ;
/**
* Methods supporting a list of Webgallery records.
*
* @package Joomla.Site
* @subpackage com_webgallery
*/
class WebgalleryModelCategories extends AKModelList
{
/**
* @var string The prefix to use with controller messages.
* @since 1.6
*/
protected $text_prefix = 'COM_WEBGALLERY';
/**
* The Component name.
*
* @var string
*/
protected $component = 'webgallery' ;
/**
* The URL view item variable.
*
* @var string
*/
protected $item_name = 'category' ;
/**
* The URL view list variable.
*
* @var string
*/
protected $list_name = 'categories' ;
/**
* The URL view list to request remote data (only use in API system).
*
* @var string
*/
public $request_item = '';
/**
* The URL view item to request remote data (only use in API system).
*
* @var string
*/
public $request_list = '';
/**
* The default method to call. (only use in API system).
*
* @var string
*/
public $default_method = 'getItems';
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
// Set query tables
// ========================================================================
$config['tables'] = array(
'a' => '#__categories',
// 'b' => '#__categories',
'c' => '#__users',
'd' => '#__viewlevels',
'e' => '#__languages'
);
// Set filter fields
// ========================================================================
if (empty($config['filter_fields'])) {
$config['filter_fields'] = array(
'filter_order_Dir', 'filter_order',
'search' , 'filter'
);
$config['filter_fields'] = WebgalleryHelper::_('db.mergeFilterFields', $config['filter_fields'] , $config['tables'] );
}
$this->config = $config ;
parent::__construct($config);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*/
protected function populateState($ordering = null, $direction = null)
{
// Initialise variables.
$app = JFactory::getApplication();
$user = JFactory::getUser() ;
$pk = JRequest::getInt('id');
$this->setState('category.id', $pk);
// Load the parameters. Merge Global and Menu Item params into new object
// =====================================================================================
$comParams = $app->getParams();
$menuParams = new JRegistry;
if ($menu = $app->getMenu()->getActive()) {
$menuParams->loadString($menu->params);
}
$mergedParams = clone $menuParams;
$mergedParams->merge($comParams);
$this->setState('params', $mergedParams);
$params = $mergedParams ;
// Set ViewLevel and user groups
$groups = implode(',', $user->getAuthorisedViewLevels());
$this->setState('access.group', $groups);
// List state information.
// =====================================================================================
$itemid = JRequest::getInt('id', 0) . ':' . JRequest::getInt('Itemid', 0);
$this->setState('layout', JRequest::getCmd('layout'));
// Order
// =====================================================================================
$orderCol = $params->get('orderby', 'a.id');
$this->setState('list.ordering', $orderCol);
// Order Dir
// =====================================================================================
$listOrder = $params->get('order_dir', 'asc');
$this->setState('list.direction', $listOrder);
// Limitstart
// =====================================================================================
$this->setState('list.start', JRequest::getUInt('limitstart', 0));
// Limit
// =====================================================================================
$num_leading = $params->get('num_leading_articles', 1) ;
$num_intro = $params->get('num_intro_articles', 4) ;
$num_links = $params->get('num_links', 4);
$limit = $num_leading + $num_intro + $num_links ;
$this->setState('list.num_leading', $num_leading);
$this->setState('list.num_intro', $num_intro);
$this->setState('list.num_links', $num_links);
$this->setState('list.links', $num_links);
$this->setState('list.limit', $limit);
// Max Level
// =====================================================================================
$maxLevel = $params->get('maxLevel');
if ($maxLevel) {
$this->setState('filter.max_category_levels', $maxLevel);
}
// Edit Access
// =====================================================================================
if (($user->authorise('core.edit.state', 'com_webgallery')) || ($user->authorise('core.edit', 'com_webgallery'))){
// filter on published for those who do not have edit or edit.state rights.
$this->setState('filter.unpublished', 1);
}
// View Level
// =====================================================================================
if (!$params->get('show_noauth')) {
$this->setState('filter.access', true);
}
else {
$this->setState('filter.access', false);
}
// Language
// =====================================================================================
$this->setState('filter.language', $app->getLanguageFilter());
}
/**
* Build an SQL query to load the list data.
*
* @return JDatabaseQuery
* @since 1.6
*/
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$q = $db->getQuery(true);
$order = $this->getState('list.ordering' , 'a.id');
$dir = $this->getState('list.direction', 'asc');
$date = JFactory::getDate( 'now' , JFactory::getConfig()->get('offset') ) ;
$user = JFactory::getUser() ;
// Filter and Search
$filter = $this->getState('filter', array()) ;
$search = $this->getState('search', array()) ;
$wheres = $this->getState('query.where', array()) ;
$having = $this->getState('query.having', array()) ;
// Category
// =====================================================================================
$category = $this->getCategory() ;
if( in_array('b.lft', $this->filter_fields) && in_array('b.rgt', $this->filter_fields) ){
$q->where("( b.lft >= {$category->lft} AND b.rgt <= {$category->rgt} )") ;
}
// Max Level
// =====================================================================================
$maxLevel = $this->getState('filter.max_category_levels', -1);
if($maxLevel > 0){
$q->where("b.level <= {$maxLevel}");
}
// Edit Access
// =====================================================================================
if($this->getState('filter.unpublished')){
$q->where('a.published >= 0') ;
}else{
$q->where('a.published > 0') ;
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote($date->toSQL(true));
if( in_array('a.publish_up', $this->filter_fields) && in_array('a.publish_down', $this->filter_fields) ){
// $q->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
// $q->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
}
}
// View Level
// =====================================================================================
if ($access = $this->getState('filter.access') && in_array('a.access', $this->filter_fields)) {
$groups = implode(',', $user->getAuthorisedViewLevels());
$q->where('a.access IN ('.$groups.')');
}
// Language
// =====================================================================================
if ($this->getState('filter.language') && in_array('a.language', $this->filter_fields)) {
$lang_code = $db->quote( JFactory::getLanguage()->getTag() ) ;
$q->where("a.language IN ('{$lang_code}', '*')");
}
// Filter
// ========================================================================
foreach($filter as $k => $v ){
if($v !== '' && $v != '*' && in_array($k, $this->filter_fields)){
$k = $db->qn($k);
$q->where("{$k}='{$v}'") ;
}
}
// Search
// ========================================================================
$searc_where = array();
foreach($search as $k => $v ){
if(in_array($k, $this->filter_fields)){
$k = $db->qn($k);
$searc_where[] = "{$k} LIKE '{$v}'" ;
}
}
if(count($searc_where)){
$q->where( ' ( ' .implode(' OR ', $searc_where) . ' ) ');
}
// Custom Where
// ========================================================================
foreach($wheres as $k => $v ){
$q->where($v) ;
}
// Custom Having
// ========================================================================
foreach($having as $k => $v ){
$q->having($v) ;
}
// get select columns
$select = WebgalleryHelper::_( 'db.getSelectList', $this->config['tables'] );
//build query
$q->select($select)
->from('#__categories AS a')
// ->leftJoin('#__categories AS b ON a.catid = b.id')
->leftJoin('#__users AS c ON a.created_user_id = c.id')
->leftJoin('#__viewlevels AS d ON a.access = d.id')
->leftJoin('#__languages AS e ON a.language = e.lang_code')
->where("a.extension = 'com_webgallery'")
->order( " {$order} {$dir}" ) ;
return $q;
}
/**
* Returns a reference to the a Table object, always creating it.
*
* @param type The table type to instantiate
* @param string A prefix for the table class name. Optional.
* @param array Configuration array for model. Optional.
* @return JTable A database object
* @since 1.6
*/
public function getTable($type = null, $prefix = null, $config = array())
{
return parent::getTable( $type , $prefix , $config );
}
/**
* Method to get a store id based on model configuration state.
*
* This is necessary because the model is used by the component and
* different modules that might need different sets of data or different
* ordering requirements.
*
* @param string $id A prefix for the store id.
* @return string A store id.
* @since 1.6
*/
protected function getStoreId($id = '')
{
// Compile the store id.
$id.= ':' . json_encode($this->getState());
return parent::getStoreId($id);
}
/**
* Method to get list page filter form.
*
* @return object JForm object.
* @since 2.5
*/
public function getFilter()
{
//$filter = parent::getFilter();
//return $filter ;
}
public function getItemsCount($catid = 0)
{
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select('COUNT(id)')
->from('#__webgallery_items')
->where('catid = '.$catid);
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$result = $db->loadResult();
return $result;
}
}
| gpl-2.0 |
viniciusfbarbosa/DC-UFSCar-ES2-201601-Grupo-AMTV- | src/test/java/net/sf/jabref/testutils/AssertUtil.java | 454 | package net.sf.jabref.testutils;
import org.junit.Assert;
public class AssertUtil {
/**
* Will check if two paths are the same.
*/
public static void assertEqualPaths(String path1, String path2) {
Assert.assertNotNull("first path must not be null", path1);
Assert.assertNotNull("second path must not be null", path2);
Assert.assertEquals(path1.replaceAll("\\\\", "/"), path2.replaceAll("\\\\", "/"));
}
}
| gpl-2.0 |
nejads/MqttMoped | squawk/cldc/src/com/sun/squawk/platform/windows/natives/NetDB.java | 4932 | //if[!AUTOGEN_JNA_NATIVES]
/*
* Copyright 2004-2008 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* only, as published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details (a copy is
* included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU General Public License
* version 2 along with this work; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* Please contact Sun Microsystems, Inc., 16 Network Circle, Menlo
* Park, CA 94025 or visit www.sun.com if you need additional
* information or have any questions.
*/
/* **** GENERATED FILE -- DO NOT EDIT ****
* This is a CLDC/JNA Interface class definition
* generated by com.sun.cldc.jna.JNAGen
* from the CLDC/JNA Interface class declaration in ./cldc-native-declarations/src/com/sun/squawk/platform/posix/natives/NetDB.java
*/
package com.sun.squawk.platform.windows.natives;
import com.sun.cldc.jna.*;
/**
*
* java wrapper around #include <netdb.h>
*/
/*@Includes("<netdb.h>")*/
public interface NetDB extends Library {
NetDB INSTANCE = (NetDB)
Native.loadLibrary("RTLD",
NetDB.class);
/**
* The gethostbyname() function returns a HostEnt structure describing an internet host referenced by name.
*
* @param name the host name
* @return the address of struct hostent, or null on error
*/
hostent gethostbyname(String name);
/** Authoritative Answer Host not found.
* @see #h_errno() */
int HOST_NOT_FOUND = NetDBImpl.HOST_NOT_FOUND;
/** Non-Authoritative Host not found, or SERVERFAIL.
* @see #h_errno() */
int TRY_AGAIN = NetDBImpl.TRY_AGAIN;
/** Non recoverable errors, FORMERR, REFUSED, NOTIMP.
* @see #h_errno() */
int NO_RECOVERY = NetDBImpl.NO_RECOVERY;
/** Valid name, no data record of requested type.
* @see #h_errno() */
int NO_DATA = NetDBImpl.NO_DATA;
/** Return error code for last call to gethostbyname() or gethostbyaddr().
* @return one of the error codes defined in this class.
*/
/*@GlobalVar*/
int h_errno();
/** C STRUCTURE HostEnt
struct hostent {
char *h_name; official name of host
char **h_aliases; alias list
int h_addrtype; host address type
int h_length; length of address
char **h_addr_list; list of addresses from name server
};
#define h_addr h_addr_list[0] address, for backward compatibility
*/
public static class hostent extends NetDBImpl.hostentImpl {
public String h_name; /* official name of host */
public int h_addrtype; /* host address type */
public int h_length; /* length of address */
public int[] h_addr_list; /* list of addresses from name server */
public void read() {
final int MAX_ADDRS = 16;
Pointer p = getPointer();
h_name = p.getPointer(0, 1024).getString(0);
h_addrtype = p.getInt(8);
h_length = p.getInt(12);
if (h_length != 4) {
System.err.println("WARNING: Unexpected h_length value");
}
Pointer adrlist = p.getPointer(16, MAX_ADDRS * 4);
System.out.println("in read(). Buffer: " + p);
System.out.println(" name: " + h_name);
System.out.println(" h_addrtype: " + h_addrtype);
System.out.println(" adrlist: " + adrlist);
Pointer[] addrPtrs = new Pointer[MAX_ADDRS];
int count = 0;
for (int i = 0; i < MAX_ADDRS; i++) {
Pointer addrPtr = adrlist.getPointer(i * 4, h_length);
if (addrPtr == null) {
break;
}
addrPtrs[i] = addrPtr;
count++;
}
System.out.println(" adrlist count: " + count);
h_addr_list = new int[count];
for (int i = 0; i < count; i++) {
int addr = addrPtrs[i].getInt(0);
System.err.println(" addr " + addr);
h_addr_list[i] = addr;
}
}
public void write() {
}
} /* HostEnt */
}
| gpl-2.0 |
gaoxianglong/oceanbase | oceanbase_0.4/tools/olapdrive/ob_campaign_impression.cpp | 2868 | /**
* (C) 2010-2011 Taobao Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* ob_campaign_impression.cpp for define campaign impression
* query classs.
*
* Authors:
* huating <huating.zmq@taobao.com>
*
*/
#include "ob_campaign_impression.h"
namespace oceanbase
{
namespace olapdrive
{
using namespace tbsys;
using namespace common;
using namespace client;
ObCampaignImpression::ObCampaignImpression(
ObClient& client, ObOlapdriveMeta& meta,
ObOlapdriveSchema& schema, ObOlapdriveParam& param,
ObOlapdriveStat& stat)
: ObLzQuery(client, meta, schema, param, stat)
{
}
ObCampaignImpression::~ObCampaignImpression()
{
}
const char* ObCampaignImpression::get_test_name()
{
return "CAMPAIGN_IMPRESSION";
}
int ObCampaignImpression::check(
const ObScanner &scanner, const int64_t time)
{
int ret = OB_SUCCESS;
ObScanInfo scan_info;
ret = get_scan_info(scan_info);
if (OB_SUCCESS == ret)
{
ObCampaign& campaign = scan_info.campaign_;
int64_t org_row_cnt =
(campaign.end_id_ - campaign.start_id_) * 2 * scan_info.day_count_;
print_brief_result(get_test_name(), scanner, scan_info,
time, org_row_cnt);
ret = check_row_and_cell_num(scanner, 1, 1);
if (OB_SUCCESS == ret)
{
FOREACH_CELL(scanner)
{
GET_CELL();
ret = check_one_cell(*cell_info, 1, column_index,
campaign.campaign_id_, 0);
}
}
}
return ret;
}
int ObCampaignImpression::prepare(ObScanParam &scan_param)
{
int ret = OB_SUCCESS;
ObGroupByParam& groupby_param = scan_param.get_group_by_param();
ret = reset_extra_info();
if (OB_SUCCESS == ret)
{
ret = add_scan_range(scan_param);
}
if (OB_SUCCESS == ret)
{
set_read_param(scan_param);
ret = scan_param.add_column(campaign_id);
}
if (OB_SUCCESS == ret)
{
ret = scan_param.add_column(impression);
}
if (OB_SUCCESS == ret)
{
ret = groupby_param.add_groupby_column(campaign_id);
}
if (OB_SUCCESS == ret)
{
ret = groupby_param.add_aggregate_column(impression, impression, SUM, false);
}
if (OB_SUCCESS == ret)
{
ret = groupby_param.add_having_cond(impression_filter_expr);
}
return ret;
}
} // end namespace olapdrive
} // end namespace oceanbase
| gpl-2.0 |
DevGroup-ru/dotplant2 | application/views/default/auto-complete-item-template.php | 394 | <?php
/**
* @var \yii\web\View $this
* @var \app\modules\shop\models\Product $product
*/
if (!is_object($product->getMainCategory())) {
return;
}
$url = \yii\helpers\Url::to(
[
'/shop/product/show',
'model' => $product,
'category_group_id' => $product->getMainCategory()->category_group_id,
]
);
?>
<li><a href="<?= $url ?>"><?= $product->name ?></a></li> | gpl-3.0 |
dickeyf/darkstar | scripts/zones/Ordelles_Caves/npcs/qm5.lua | 1418 | -----------------------------------
-- Area: Ordelles Caves
-- NPC: ??? (qm5)
-- Involved In Quest: Dark Puppet
-- @pos -92 -28 -70 193
-----------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("darkPuppetCS") >= 3 and player:hasItem(16940) == false) then
if (trade:hasItemQty(16681,1) and trade:getItemCount() == 1) then -- Trade Gerwitz's Axe
player:tradeComplete();
player:messageSpecial(GERWITZS_SWORD_DIALOG);
SpawnMob(17568136,180):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
montimaj/ShaktiT_LLVM | llvm/tools/clang/test/CodeGenCXX/copy-constructor-elim.cpp | 1159 | // RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -triple %ms_abi_triple -emit-llvm -o - %s | FileCheck %s -check-prefix MS
// CHECK-NOT: _ZN1CC1ERK1C
// CHECK-NOT: _ZN1SC1ERK1S
// MS-NOT: ?0C@@QAE@ABV0
// MS-NOT: ?0S@@QAE@ABV0
extern "C" int printf(...);
struct C {
C() : iC(6) {printf("C()\n"); }
C(const C& c) { printf("C(const C& c)\n"); }
int iC;
};
C foo() {
return C();
};
class X { // ...
public:
X(int) {}
X(const X&, int i = 1, int j = 2, C c = foo()) {
printf("X(const X&, %d, %d, %d)\n", i, j, c.iC);
}
};
struct S {
S();
};
S::S() { printf("S()\n"); }
void Call(S) {};
int main() {
X a(1);
X b(a, 2);
X c = b;
X d(a, 5, 6);
S s;
Call(s);
}
struct V {
int x;
};
typedef V V_over_aligned __attribute((aligned(8)));
extern const V_over_aligned gv1 = {};
extern "C" V f() { return gv1; }
// Make sure that we obey the destination's alignment requirements when emitting
// the copy.
// CHECK-LABEL: define {{.*}} @f(
// CHECK: call void @llvm.memcpy.p0i8.p0i8.{{i64|i32}}({{.*}}, i8* bitcast (%struct.V* @gv1 to i8*), {{i64|i32}} 4, i32 4, i1 false)
| gpl-3.0 |
ludwiktrammer/odoo | addons/web_editor/static/src/js/summernote.js | 82260 | odoo.define('web_editor.summernote', function (require) {
'use strict';
var core = require('web.core');
require('summernote/summernote'); // wait that summernote is loaded
var _t = core._t;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Summernote Lib (neek hack to make accessible: method and object) */
var agent = $.summernote.core.agent;
var dom = $.summernote.core.dom;
var range = $.summernote.core.range;
var list = $.summernote.core.list;
var key = $.summernote.core.key;
var eventHandler = $.summernote.eventHandler;
var editor = eventHandler.modules.editor;
var renderer = $.summernote.renderer;
var options = $.summernote.options;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Add method to Summernote*/
dom.hasContentAfter = function (node) {
var next;
if(dom.isEditable(node)) return;
while (node.nextSibling) {
next = node.nextSibling;
if (next.tagName || dom.isVisibleText(next) || dom.isBR(next)) return next;
node = next;
}
};
dom.hasContentBefore = function (node) {
var prev;
if(dom.isEditable(node)) return;
while (node.previousSibling) {
prev = node.previousSibling;
if (prev.tagName || dom.isVisibleText(prev) || dom.isBR(prev)) return prev;
node = prev;
}
};
dom.ancestorHaveNextSibling = function (node, pred) {
pred = pred || dom.hasContentAfter;
while (!dom.isEditable(node) && (!node.nextSibling || !pred(node))) { node = node.parentNode; }
return node;
};
dom.ancestorHavePreviousSibling = function (node, pred) {
pred = pred || dom.hasContentBefore;
while (!dom.isEditable(node) && (!node.previousSibling || !pred(node))) { node = node.parentNode; }
return node;
};
dom.nextElementSibling = function (node) {
while (node) {
node = node.nextSibling;
if (node && node.tagName) {
break;
}
}
return node;
};
dom.previousElementSibling = function (node) {
while (node) {
node = node.previousSibling;
if (node && node.tagName) {
break;
}
}
return node;
};
dom.lastChild = function (node) {
while (node.lastChild) { node = node.lastChild; }
return node;
};
dom.firstChild = function (node) {
while (node.firstChild) { node = node.firstChild; }
return node;
};
dom.lastElementChild = function (node, deep) {
node = deep ? dom.lastChild(node) : node.lastChild;
return !node || node.tagName ? node : dom.previousElementSibling(node);
};
dom.firstElementChild = function (node, deep) {
node = deep ? dom.firstChild(node) : node.firstChild;
return !node || node.tagName ? node : dom.nextElementSibling(node);
};
dom.isEqual = function (prev, cur) {
if (prev.tagName !== cur.tagName) {
return false;
}
if ((prev.attributes ? prev.attributes.length : 0) !== (cur.attributes ? cur.attributes.length : 0)) {
return false;
}
function strip(text) {
return text && text.replace(/^\s+|\s+$/g, '').replace(/\s+/g, ' ');
}
var att, att2;
loop_prev:
for(var a in prev.attributes) {
att = prev.attributes[a];
for(var b in cur.attributes) {
att2 = cur.attributes[b];
if (att.name === att2.name) {
if (strip(att.value) != strip(att2.value)) return false;
continue loop_prev;
}
}
return false;
}
return true;
};
/**
* Checks that the node only has a @style, not e.g. @class or whatever
*/
dom.hasOnlyStyle = function (node) {
for (var i = 0; i < node.attributes.length; i++) {
var attr = node.attributes[i];
if (attr.attributeName !== 'style') {
return false;
}
}
return true;
};
dom.hasProgrammaticStyle = function (node) {
var styles = ["float", "display", "position", "top", "left", "right", "bottom"];
for (var i = 0; i < node.style.length; i++) {
var style = node.style[i];
if (styles.indexOf(style) !== -1) {
return true;
}
}
return false;
};
dom.mergeFilter = function (prev, cur, parent) {
// merge text nodes
if (prev && (dom.isText(prev) || ("H1 H2 H3 H4 H5 H6 LI P".indexOf(prev.tagName) !== -1 && prev !== cur.parentNode)) && dom.isText(cur)) {
return true;
}
if (prev && prev.tagName === "P" && dom.isText(cur)) {
return true;
}
if (prev && dom.isText(cur) && !dom.isVisibleText(cur) && (dom.isText(prev) || dom.isVisibleText(prev))) {
return true;
}
if (prev && !dom.isBR(prev) && dom.isEqual(prev, cur) &&
((prev.tagName && dom.getComputedStyle(prev).display === "inline" &&
cur.tagName && dom.getComputedStyle(cur).display === "inline"))) {
return true;
}
if (dom.isEqual(parent, cur) &&
((parent.tagName && dom.getComputedStyle(parent).display === "inline" &&
cur.tagName && dom.getComputedStyle(cur).display === "inline"))) {
return true;
}
if (parent && cur.tagName === "FONT" && (!cur.firstChild || (!cur.attributes.getNamedItem('style') && !cur.className.length))) {
return true;
}
// On backspace, webkit browsers create a <span> with a bunch of
// inline styles "remembering" where they come from.
// chances are we had e.g.
// <p>foo</p>
// <p>bar</p>
// merged the lines getting this in webkit
// <p>foo<span>bar</span></p>
if (parent && cur.tagName === "SPAN" && dom.hasOnlyStyle(cur) && !dom.hasProgrammaticStyle(cur)) {
return true;
}
};
dom.doMerge = function (prev, cur) {
if (prev.tagName) {
if (prev.childNodes.length && !prev.textContent.match(/\S/) && dom.firstElementChild(prev) && dom.isBR(dom.firstElementChild(prev))) {
prev.removeChild(dom.firstElementChild(prev));
}
if (cur.tagName) {
while (cur.firstChild) {
prev.appendChild(cur.firstChild);
}
cur.parentNode.removeChild(cur);
} else {
prev.appendChild(cur);
}
} else {
if (cur.tagName) {
var deep = cur;
while (deep.tagName && deep.firstChild) {deep = deep.firstChild;}
prev.appendData(deep.textContent);
cur.parentNode.removeChild(cur);
} else {
prev.appendData(cur.textContent);
cur.parentNode.removeChild(cur);
}
}
};
dom.merge = function (node, begin, so, end, eo, mergeFilter, all) {
mergeFilter = mergeFilter || dom.mergeFilter;
var _merged = false;
var add = all || false;
if (!begin) {
begin = node;
while(begin.firstChild) {begin = begin.firstChild;}
so = 0;
} else if (begin.tagName && begin.childNodes[so]) {
begin = begin.childNodes[so];
so = 0;
}
if (!end) {
end = node;
while(end.lastChild) {end = end.lastChild;}
eo = end.textContent.length-1;
} else if (end.tagName) {
} else if (end.tagName && end.childNodes[so]) {
end = end.childNodes[so];
so = 0;
}
begin = dom.firstChild(begin);
if (dom.isText(begin) && so > begin.textContent.length) {
so = 0;
}
end = dom.firstChild(end);
if (dom.isText(end) && eo > end.textContent.length) {
eo = 0;
}
function __merge (node) {
var merged = false;
var prev;
for (var k=0; k<node.childNodes.length; k++) {
var cur = node.childNodes[k];
if (cur === begin) {
if (!all) add = true;
}
__merge(cur);
dom.orderClass(dom.node(cur));
if (!add || !cur) continue;
if (cur === end) {
if (!all) add = false;
}
// create the first prev value
if (!prev) {
if (mergeFilter.call(dom, prev, cur, node)) {
prev = prev || cur.previousSibling;
dom.moveTo(cur, cur.parentNode, cur);
k--;
} else {
prev = cur;
}
continue;
} else if (mergeFilter.call(dom, null, cur, node)) { // merge with parent
prev = prev || cur.previousSibling;
dom.moveTo(cur, cur.parentNode, cur);
k--;
continue;
}
// merge nodes
if (mergeFilter.call(dom, prev, cur, node)) {
var p = prev;
var c = cur;
// compute prev/end and offset
if (prev.tagName) {
if (cur.tagName) {
if (cur === begin) begin = prev;
if (cur === end) end = prev;
}
} else {
if (cur.tagName) {
var deep = cur;
while (deep.tagName && deep.lastChild) {deep = deep.lastChild;}
if (deep === begin) {
so += prev.textContent.length;
begin = prev;
}
if (deep === end) {
eo += prev.textContent.length;
end = prev;
}
} else {
// merge text nodes
if (cur === begin) {
so += prev.textContent.length;
begin = prev;
}
if (cur === end) {
eo += prev.textContent.length;
end = prev;
}
}
}
dom.doMerge(p, c);
merged = true;
k--;
continue;
}
prev = cur;
}
// an other loop to merge the new shibbing nodes
if (merged) {
_merged = true;
__merge(node);
}
}
if (node) {
__merge(node);
}
return {
merged: _merged,
sc: begin,
ec: end,
so: so,
eo: eo
};
};
dom.autoMerge = function (target, previous) {
var node = dom.lastChild(target);
var nodes = [];
var temp;
while (node) {
nodes.push(node);
if (temp = (previous ? dom.hasContentBefore(node) : dom.hasContentAfter(node))) {
if (!dom.isText(node) && !dom.isMergable(node) && temp.tagName !== node.tagName) {
nodes = [];
}
break;
}
node = node.parentNode;
}
while (nodes.length) {
node = nodes.pop();
if (node && (temp = (previous ? dom.hasContentBefore(node) : dom.hasContentAfter(node))) &&
temp.tagName === node.tagName &&
!dom.isText(node) &&
dom.isMergable(node) &&
!dom.isNotBreakable(node) && !dom.isNotBreakable(previous ? dom.previousElementSibling(node) : dom.nextElementSibling(node))) {
if (previous) {
dom.doMerge(temp, node);
} else {
dom.doMerge(node, temp);
}
}
}
};
dom.removeSpace = function (node, begin, so, end, eo) {
var removed = false;
var add = node === begin;
if (node === begin && begin === end && dom.isBR(node)) {
return {
removed: removed,
sc: begin,
ec: end,
so: so,
eo: eo
};
}
(function __remove_space (node) {
if (!node) return;
var t_begin, t_end;
for (var k=0; k<node.childNodes.length; k++) {
var cur = node.childNodes[k];
if (cur === begin) add = true;
if (cur.tagName && cur.tagName !== "SCRIPT" && cur.tagName !== "STYLE" && dom.getComputedStyle(cur).whiteSpace !== "pre") {
__remove_space(cur);
}
if (!add) continue;
if (cur === end) add = false;
// remove begin empty text node
if (node.childNodes.length > 1 && dom.isText(cur) && !dom.isVisibleText(cur)) {
removed = true;
if (cur === begin) {
t_begin = dom.hasContentBefore(dom.ancestorHavePreviousSibling(cur));
if(t_begin) {
so = 0;
begin = dom.lastChild(t_begin);
}
}
if (cur === end) {
t_end = dom.hasContentAfter(dom.ancestorHaveNextSibling(cur));
if(t_end) {
eo = 1;
end = dom.firstChild(t_end);
if (dom.isText(end)) {
eo = end.textContent.length;
}
}
}
cur.parentNode.removeChild(cur);
begin = dom.lastChild(begin);
end = dom.lastChild(end);
k--;
continue;
}
// convert HTML space
if (dom.isText(cur)) {
var text;
var exp1 = /[\t\n\r ]+/g;
var exp2 = /(?!([ ]|\u00A0)|^)\u00A0(?!([ ]|\u00A0)|$)/g;
if (cur === begin) {
var temp = cur.textContent.substr(0, so);
var _temp = temp.replace(exp1, ' ').replace(exp2, ' ');
so -= temp.length - _temp.length;
}
if (cur === end) {
var temp = cur.textContent.substr(0, eo);
var _temp = temp.replace(exp1, ' ').replace(exp2, ' ');
eo -= temp.length - _temp.length;
}
var text = cur.textContent.replace(exp1, ' ').replace(exp2, ' ');
removed = removed || cur.textContent.length !== text.length;
cur.textContent = text;
}
}
})(node);
return {
removed: removed,
sc: begin,
ec: end,
so: !dom.isBR(begin) && so > 0 ? so : 0,
eo: dom.isBR(end) ? 0 : eo
};
};
dom.node = function (node) {
return node.tagName ? node : node.parentNode;
};
dom.removeBetween = function (sc, so, ec, eo, towrite) {
if (ec.tagName) {
if (ec.childNodes[eo]) {
ec = ec.childNodes[eo];
eo = 0;
} else {
ec = dom.lastChild(ec);
eo = dom.nodeLength(ec);
}
}
if (sc.tagName) {
sc = sc.childNodes[so] || dom.firstChild(ec);
so = 0;
if (!dom.hasContentBefore(sc) && towrite) {
sc.parentNode.insertBefore(document.createTextNode('\u00A0'), sc);
}
}
if (!eo && sc !== ec) {
ec = dom.lastChild(dom.hasContentBefore(dom.ancestorHavePreviousSibling(ec)) || ec);
eo = ec.textContent.length;
}
var ancestor = dom.commonAncestor(sc.tagName ? sc.parentNode : sc, ec.tagName ? ec.parentNode : ec) || dom.ancestor(sc, dom.isEditable);
if (!dom.isContentEditable(ancestor)) {
return {
sc: sc,
so: so,
ec: sc,
eo: eo
};
}
if (ancestor.tagName) {
var ancestor_sc = sc;
var ancestor_ec = ec;
while (ancestor !== ancestor_sc && ancestor !== ancestor_sc.parentNode) { ancestor_sc = ancestor_sc.parentNode; }
while (ancestor !== ancestor_ec && ancestor !== ancestor_ec.parentNode) { ancestor_ec = ancestor_ec.parentNode; }
var node = dom.node(sc);
if (!dom.isNotBreakable(node) && !dom.isVoid(sc)) {
sc = dom.splitTree(ancestor_sc, {'node': sc, 'offset': so});
}
var before = dom.hasContentBefore(dom.ancestorHavePreviousSibling(sc));
var after;
if (ec.textContent.slice(eo, Infinity).match(/\S|\u00A0/)) {
after = dom.splitTree(ancestor_ec, {'node': ec, 'offset': eo});
} else {
after = dom.hasContentAfter(dom.ancestorHaveNextSibling(ec));
}
var nodes = dom.listBetween(sc, ec);
var ancestor_first_last = function (node) {
return node === before || node === after;
};
for (var i=0; i<nodes.length; i++) {
if (!dom.ancestor(nodes[i], ancestor_first_last) && !$.contains(nodes[i], before) && !$.contains(nodes[i], after)) {
nodes[i].parentNode.removeChild(nodes[i]);
}
}
if (dom.listAncestor(after).length <= dom.listAncestor(before).length) {
sc = dom.lastChild(before || ancestor);
so = dom.nodeLength(sc);
} else {
sc = dom.firstChild(after);
so = 0;
}
if (dom.isVoid(node)) {
// we don't need to append a br
} else if (towrite && !node.firstChild && node.parentNode && !dom.isNotBreakable(node)) {
var br = $("<br/>")[0];
node.appendChild(sc);
sc = br;
so = 0;
} else if (!ancestor.children.length && !ancestor.textContent.match(/\S|\u00A0/)) {
sc = $("<br/>")[0];
so = 0;
$(ancestor).prepend(sc);
} else if (dom.isText(sc)) {
var text = sc.textContent.replace(/[ \t\n\r]+$/, '\u00A0');
so = Math.min(so, text.length);
sc.textContent = text;
}
} else {
var text = ancestor.textContent;
ancestor.textContent = text.slice(0, so) + text.slice(eo, Infinity).replace(/^[ \t\n\r]+/, '\u00A0');
}
eo = so;
if(!dom.isBR(sc) && !dom.isVisibleText(sc) && !dom.isText(dom.hasContentBefore(sc)) && !dom.isText(dom.hasContentAfter(sc))) {
ancestor = dom.node(sc);
var text = document.createTextNode('\u00A0');
$(sc).before(text);
sc = text;
so = 0;
eo = 1;
}
return {
sc: sc,
so: so,
ec: sc,
eo: eo
};
};
dom.indent = function (node) {
var style = dom.isCell(node) ? 'paddingLeft' : 'marginLeft';
var margin = parseFloat(node.style[style] || 0)+1.5;
node.style[style] = margin + "em";
return margin;
};
dom.outdent = function (node) {
var style = dom.isCell(node) ? 'paddingLeft' : 'marginLeft';
var margin = parseFloat(node.style[style] || 0)-1.5;
node.style[style] = margin > 0 ? margin + "em" : "";
return margin;
};
dom.scrollIntoViewIfNeeded = function (node) {
var node = dom.node(node);
var $span;
if (dom.isBR(node)) {
$span = $('<span/>').text('\u00A0');
$(node).after($span);
node = $span[0];
}
if (node.scrollIntoViewIfNeeded) {
node.scrollIntoViewIfNeeded(false);
} else {
var offsetParent = node.offsetParent;
while (offsetParent) {
var elY = 0;
var elH = node.offsetHeight;
var parent = node;
while (offsetParent && parent) {
elY += node.offsetTop;
// get if a parent have a scrollbar
parent = node.parentNode;
while (parent != offsetParent &&
(parent.tagName === "BODY" || ["auto", "scroll"].indexOf(dom.getComputedStyle(parent).overflowY) === -1)) {
parent = parent.parentNode;
}
node = parent;
if (parent !== offsetParent) {
elY -= parent.offsetTop;
parent = null;
}
offsetParent = node.offsetParent;
}
if ((node.tagName === "BODY" || ["auto", "scroll"].indexOf(dom.getComputedStyle(node).overflowY) !== -1) &&
(node.scrollTop + node.clientHeight) < (elY + elH)) {
node.scrollTop = (elY + elH) - node.clientHeight;
}
}
}
if ($span) {
$span.remove();
}
return;
};
dom.moveTo = function (node, target, before) {
var nodes = [];
while (node.firstChild) {
nodes.push(node.firstChild);
if (before) {
target.insertBefore(node.firstChild, before);
} else {
target.appendChild(node.firstChild);
}
}
node.parentNode.removeChild(node);
return nodes;
};
dom.isMergable = function (node) {
return node.tagName && "h1 h2 h3 h4 h5 h6 p b bold i u code sup strong small li a ul ol font".indexOf(node.tagName.toLowerCase()) !== -1;
};
dom.isSplitable = function (node) {
return node.tagName && "h1 h2 h3 h4 h5 h6 p b bold i u code sup strong small li a font".indexOf(node.tagName.toLowerCase()) !== -1;
};
dom.isRemovableEmptyNode = function (node) {
return "h1 h2 h3 h4 h5 h6 p b bold i u code sup strong small li a ul ol font span br".indexOf(node.tagName.toLowerCase()) !== -1;
};
dom.isForbiddenNode = function (node) {
return node.tagName === "BR" || $(node).is(".fa, img");
};
dom.listBetween = function (sc, ec) {
var nodes = [];
var ancestor = dom.commonAncestor(sc, ec);
dom.walkPoint({'node': sc, 'offset': 0}, {'node': ec, 'offset': 0}, function (point) {
if (ancestor !== point.node || ancestor === sc || ancestor === ec) {
nodes.push(point.node);
}
});
return list.unique(nodes);
};
dom.isNotBreakable = function (node) {
// avoid triple click => crappy dom
return !dom.isText(node) && !dom.isBR(dom.firstChild(node)) && dom.isVoid(dom.firstChild(node));
};
dom.isContentEditable = function (node) {
return $(node).closest('[contenteditable]').is('[contenteditable="true"]');
};
dom.isPre = function (node) {
return node.tagName === "PRE";
};
dom.isFont = function (node) {
var nodeName = node && node.nodeName.toUpperCase();
return node && (nodeName === "FONT" ||
(nodeName === "SPAN" && (
node.className.match(/(^|\s)fa(\s|$)/i) ||
node.className.match(/(^|\s)(text|bg)-/i) ||
(node.attributes.style && node.attributes.style.value.match(/(^|\s)(color|background-color|font-size):/i)))) );
};
dom.isVisibleText = function (textNode) {
return !!textNode.textContent.match(/\S|\u00A0/);
};
/* avoid thinking HTML comment are visible */
var old_isVisiblePoint = dom.isVisiblePoint;
dom.isVisiblePoint = function (point) {
return point.node.nodeType !== 8 && old_isVisiblePoint.apply(this, arguments);
};
/**
* order the style of the node to compare 2 nodes and remove attribute if empty
*
* @param {Node} node
* @return {String} className
*/
dom.orderStyle = function (node) {
var style = node.getAttribute('style');
if (!style) return null;
style = style.replace(/[\s\n\r]+/, ' ').replace(/^ ?;? ?| ?;? ?$/g, '').replace(/ ?; ?/g, ';');
if (!style.length) {
node.removeAttribute("style");
return null;
}
style = style.split(";");
style.sort();
style = style.join("; ")+";";
node.setAttribute('style', style);
return style;
};
/**
* order the class of the node to compare 2 nodes and remove attribute if empty
*
* @param {Node} node
* @return {String} className
*/
dom.orderClass = function (node) {
var className = node.getAttribute && node.getAttribute('class');
if (!className) return null;
className = className.replace(/[\s\n\r]+/, ' ').replace(/^ | $/g, '').replace(/ +/g, ' ');
if (!className.length) {
node.removeAttribute("class");
return null;
}
className = className.split(" ");
className.sort();
className = className.join(" ");
node.setAttribute('class', className);
return className;
};
/**
* return the current node (if text node, return parentNode)
*
* @param {Node} node
* @return {Node} node
*/
dom.node = function (node) {
return dom.isText(node) ? node.parentNode : node;
};
/**
* move all childNode to an other node
*
* @param {Node} from
* @param {Node} to
*/
dom.moveContent = function (from, to) {
if (from === to) {
return;
}
if (from.parentNode === to) {
while (from.lastChild) {
dom.insertAfter(from.lastChild, from);
}
} else {
while (from.firstChild && from.firstChild != to) {
to.appendChild(from.firstChild);
}
}
};
dom.getComputedStyle = function (node) {
return node.nodeType == Node.COMMENT_NODE ? {} : window.getComputedStyle(node);
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
range.WrappedRange.prototype.reRange = function (keep_end, isNotBreakable) {
var sc = this.sc;
var so = this.so;
var ec = this.ec;
var eo = this.eo;
isNotBreakable = isNotBreakable || dom.isNotBreakable;
// search the first snippet editable node
var start = keep_end ? ec : sc;
while (start) {
if (isNotBreakable(start, sc, so, ec, eo)) {
break;
}
start = start.parentNode;
}
// check if the end caret have the same node
var lastFilterEnd;
var end = keep_end ? sc : ec;
while (end) {
if (start === end) {
break;
}
if (isNotBreakable(end, sc, so, ec, eo)) {
lastFilterEnd = end;
}
end = end.parentNode;
}
if (lastFilterEnd) {
end = lastFilterEnd;
}
if (!end) {
end = document.getElementsByTagName('body')[0];
}
// if same node, keep range
if (start === end || !start) {
return this;
}
// reduce or extend the range to don't break a isNotBreakable area
if ($.contains(start, end)) {
if (keep_end) {
sc = dom.lastChild(dom.hasContentBefore(dom.ancestorHavePreviousSibling(end)) || sc);
so = sc.textContent.length;
} else if (!eo) {
ec = dom.lastChild(dom.hasContentBefore(dom.ancestorHavePreviousSibling(end)) || ec);
eo = ec.textContent.length;
} else {
ec = dom.firstChild(dom.hasContentAfter(dom.ancestorHaveNextSibling(end)) || ec);
eo = 0;
}
} else {
if (keep_end) {
sc = dom.firstChild(start);
so = 0;
} else {
ec = dom.lastChild(start);
eo = ec.textContent.length;
}
}
return new range.WrappedRange(sc, so, ec, eo);
};
// isOnImg: judge whether range is an image node or not
range.WrappedRange.prototype.isOnImg = function () {
var nb = 0;
var image;
var startPoint = {node: this.sc.childNodes.length && this.sc.childNodes[this.so] || this.sc};
startPoint.offset = startPoint.node === this.sc ? this.so : 0;
var endPoint = {node: this.ec.childNodes.length && this.ec.childNodes[this.eo] || this.ec};
endPoint.offset = endPoint.node === this.ec ? this.eo : 0;
if (dom.isImg(startPoint.node)) {
nb ++;
image = startPoint.node;
}
dom.walkPoint(startPoint, endPoint, function (point) {
if (!dom.isText(endPoint.node) && point.node === endPoint.node && point.offset === endPoint.offset) {
return;
}
var node = point.node.childNodes.length && point.node.childNodes[point.offset] || point.node;
var offset = node === point.node ? point.offset : 0;
var isImg = dom.ancestor(node, dom.isImg);
if (!isImg && ((!dom.isBR(node) && !dom.isText(node)) || (offset && node.textContent.length !== offset && node.textContent.match(/\S|\u00A0/)))) {
nb++;
}
if (isImg && image !== isImg) {
image = isImg;
nb ++;
}
});
return nb === 1 && image;
};
range.WrappedRange.prototype.deleteContents = function (towrite) {
var prevBP = dom.removeBetween(this.sc, this.so, this.ec, this.eo, towrite);
$(dom.node(prevBP.sc)).trigger("click"); // trigger click to disable and reanable editor and image handler
return new range.WrappedRange(
prevBP.sc,
prevBP.so,
prevBP.ec,
prevBP.eo
);
};
range.WrappedRange.prototype.clean = function (mergeFilter, all) {
var node = dom.node(this.sc === this.ec ? this.sc : this.commonAncestor());
node = node || $(this.sc).closest('[contenteditable]')[0];
if (node.childNodes.length <=1) {
return this;
}
var merge = dom.merge(node, this.sc, this.so, this.ec, this.eo, mergeFilter, all);
var rem = dom.removeSpace(node.parentNode, merge.sc, merge.so, merge.ec, merge.eo);
if (merge.merged || rem.removed) {
return range.create(rem.sc, rem.so, rem.ec, rem.eo);
}
return this;
};
range.WrappedRange.prototype.remove = function (mergeFilter) {
};
range.WrappedRange.prototype.isOnCellFirst = function () {
var node = dom.ancestor(this.sc, function (node) {return ["LI", "DIV", "TD","TH"].indexOf(node.tagName) !== -1;});
return node && ["TD","TH"].indexOf(node.tagName) !== -1;
};
range.WrappedRange.prototype.isContentEditable = function () {
return dom.isContentEditable(this.sc) && (this.sc === this.ec || dom.isContentEditable(this.ec));
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
renderer.tplButtonInfo.fontsize = function (lang, options) {
var items = options.fontSizes.reduce(function (memo, v) {
return memo + '<li><a data-event="fontSize" href="#" data-value="' + v + '">' +
'<i class="fa fa-check"></i> ' + v +
'</a></li>';
}, '');
var sLabel = '<span class="note-current-fontsize">11</span>';
return renderer.getTemplate().button(sLabel, {
title: lang.font.size,
dropdown: '<ul class="dropdown-menu">' + items + '</ul>'
});
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* add some text commands */
key.nameFromCode[46] = 'DELETE';
key.nameFromCode[27] = 'ESCAPE';
options.keyMap.pc['BACKSPACE'] = 'backspace';
options.keyMap.pc['DELETE'] = 'delete';
options.keyMap.pc['ENTER'] = 'enter';
options.keyMap.pc['ESCAPE'] = 'cancel';
options.keyMap.mac['SHIFT+TAB'] = 'untab';
options.keyMap.pc['UP'] = 'up';
options.keyMap.pc['DOWN'] = 'down';
options.keyMap.mac['BACKSPACE'] = 'backspace';
options.keyMap.mac['DELETE'] = 'delete';
options.keyMap.mac['ENTER'] = 'enter';
options.keyMap.mac['ESCAPE'] = 'cancel';
options.keyMap.mac['UP'] = 'up';
options.keyMap.mac['DOWN'] = 'down';
$.summernote.pluginEvents.insertTable = function (event, editor, layoutInfo, sDim) {
var $editable = layoutInfo.editable();
var dimension = sDim.split('x');
var r = range.create();
if (!r) return;
r = r.deleteContents();
var isBodyContainer = dom.isBodyContainer;
dom.isBodyContainer = dom.isNotBreakable;
r.insertNode(editor.table.createTable(dimension[0], dimension[1]));
dom.isBodyContainer = isBodyContainer;
editor.afterCommand($editable);
event.preventDefault();
return false;
};
$.summernote.pluginEvents.tab = function (event, editor, layoutInfo, outdent) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable, 'tab');
var r = range.create();
var outdent = outdent || false;
event.preventDefault();
if (r && (dom.ancestor(r.sc, dom.isCell) || dom.ancestor(r.ec, dom.isCell))) {
if (r.isCollapsed() && r.isOnCell() && r.isOnCellFirst()) {
var td = dom.ancestor(r.sc, dom.isCell);
if (!outdent && !dom.nextElementSibling(td) && !dom.nextElementSibling(td.parentNode)) {
var last = dom.lastChild(td);
range.create(last, dom.nodeLength(last), last, dom.nodeLength(last)).select();
$.summernote.pluginEvents.enter(event, editor, layoutInfo);
} else if (outdent && !dom.previousElementSibling(td) && !$(td.parentNode).text().match(/\S/)) {
$.summernote.pluginEvents.backspace(event, editor, layoutInfo);
} else {
editor.table.tab(r, outdent);
}
} else {
$.summernote.pluginEvents.indent(event, editor, layoutInfo, outdent);
}
} else if (r && r.isCollapsed()) {
if (!r.sc.textContent.slice(0,r.so).match(/\S/) && r.isOnList()) {
if (outdent) {
$.summernote.pluginEvents.outdent(event, editor, layoutInfo);
} else {
$.summernote.pluginEvents.indent(event, editor, layoutInfo);
}
} else {
if (!outdent){
if(dom.isText(r.sc)) {
var next = r.sc.splitText(r.so);
} else {
var next = document.createTextNode('')
$(r.sc.childNodes[r.so]).before(next);
}
editor.typing.insertTab($editable, r, options.tabsize);
r = range.create(next, 0, next, 0);
r = dom.merge(r.sc.parentNode, r.sc, r.so, r.ec, r.eo, null, true);
range.create(r.sc, r.so, r.ec, r.eo).select();
} else {
r = dom.merge(r.sc.parentNode, r.sc, r.so, r.ec, r.eo, null, true);
r = range.create(r.sc, r.so, r.ec, r.eo);
var next = r.sc.splitText(r.so);
r.sc.textContent = r.sc.textContent.replace(/(\u00A0)+$/g, '');
next.textContent = next.textContent.replace(/^(\u00A0)+/g, '');
range.create(r.sc, r.sc.textContent.length, r.sc, r.sc.textContent.length).select();
}
}
}
return false;
};
$.summernote.pluginEvents.untab = function (event, editor, layoutInfo) {
return $.summernote.pluginEvents.tab(event, editor, layoutInfo, true);
};
$.summernote.pluginEvents.up = function (event, editor, layoutInfo) {
var r = range.create();
var node = dom.firstChild(r.sc.childNodes[r.so] || r.sc);
if (!r.isOnCell() || (!dom.isCell(node) && dom.hasContentBefore(node) && (!dom.isBR(dom.hasContentBefore(node)) || !dom.isText(node) || dom.isVisibleText(node) || dom.hasContentBefore(dom.hasContentBefore(node))))) {
return;
}
event.preventDefault();
var td = dom.ancestor(r.sc, dom.isCell);
var tr = td.parentNode;
var target = tr.previousElementSibling && tr.previousElementSibling.children[_.indexOf(tr.children, td)];
if (!target) {
target = (dom.ancestorHavePreviousSibling(tr) || tr).previousSibling;
}
if (target) {
range.create(dom.lastChild(target), dom.lastChild(target).textContent.length).select();
}
};
$.summernote.pluginEvents.down = function (event, editor, layoutInfo) {
var r = range.create();
var node = dom.firstChild(r.sc.childNodes[r.so] || r.sc);
if (!r.isOnCell() || (!dom.isCell(node) && dom.hasContentAfter(node) && (!dom.isBR(dom.hasContentAfter(node)) || !dom.isText(node) || dom.isVisibleText(node) || dom.hasContentAfter(dom.hasContentAfter(node))))) {
return;
}
event.preventDefault();
var td = dom.ancestor(r.sc, dom.isCell);
var tr = td.parentNode;
var target = tr.nextElementSibling && tr.nextElementSibling.children[_.indexOf(tr.children, td)];
if (!target) {
target = (dom.ancestorHaveNextSibling(tr) || tr).nextSibling;
}
if (target) {
range.create(dom.firstChild(target), 0).select();
}
};
$.summernote.pluginEvents.enter = function (event, editor, layoutInfo) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable, 'enter');
var r = range.create();
if (!r.isContentEditable()) {
event.preventDefault();
return false;
}
if (!r.isCollapsed()) {
r = r.deleteContents();
r.select();
}
var br = $("<br/>")[0];
var contentBefore = r.sc.textContent.slice(0,r.so).match(/\S|\u00A0/);
if (!contentBefore && dom.isText(r.sc)) {
var node = r.sc.previousSibling;
while (!contentBefore && node && dom.isText(node)) {
contentBefore = dom.isVisibleText(node);
node = node.previousSibling;
}
}
var node = dom.node(r.sc);
var exist = r.sc.childNodes[r.so] || r.sc;
exist = dom.isVisibleText(exist) || dom.isBR(exist) ? exist : dom.hasContentAfter(exist) || (dom.hasContentBefore(exist) || exist);
// table: add a tr
var td = dom.ancestor(node, dom.isCell);
if (td && !dom.nextElementSibling(node) && !dom.nextElementSibling(td) && !dom.nextElementSibling(td.parentNode) && (!dom.isText(r.sc) || !r.sc.textContent.slice(r.so).match(/\S|\u00A0/))) {
var $node = $(td.parentNode);
var $clone = $node.clone();
$clone.children().html(dom.blank);
$node.after($clone);
var node = dom.firstElementChild($clone[0]) || $clone[0];
range.create(node, 0, node, 0).select();
dom.scrollIntoViewIfNeeded(br);
event.preventDefault();
return false;
}
var last = node;
while (node && dom.isSplitable(node) && !dom.isList(node)) {
last = node;
node = node.parentNode;
}
if (last === node && !dom.isBR(node)) {
node = r.insertNode(br, true);
if (isFormatNode(last.firstChild) && $(last).closest(options.styleTags.join(',')).length) {
dom.moveContent(last.firstChild, last);
last.removeChild(last.firstChild);
}
do {
node = dom.hasContentAfter(node);
} while (node && dom.isBR(node));
// create an other br because the user can't see the new line with only br in a block
if (!node && (!br.nextElementSibling || !dom.isBR(br.nextElementSibling))) {
$(br).before($("<br/>")[0]);
}
node = br.nextSibling || br;
} else if (last === node && dom.isBR(node)) {
$(node).after(br);
node = br;
} else if (!r.so && r.isOnList() && !r.sc.textContent.length && !dom.ancestor(r.sc, dom.isLi).nextElementSibling) {
// double enter on the end of a list = new line out of the list
$('<p></p>').append(br).insertAfter(dom.ancestor(r.sc, dom.isList));
node = br;
} else if (dom.isBR(exist) && $(r.sc).closest('blockquote, pre').length && !dom.hasContentAfter($(exist.parentNode).closest('blockquote *, pre *').length ? exist.parentNode : exist)) {
// double enter on the end of a blockquote & pre = new line out of the list
$('<p></p>').append(br).insertAfter($(r.sc).closest('blockquote, pre'));
node = br;
} else if (last === r.sc) {
if (dom.isBR(last)) {
last = last.parentNode;
}
var $node = $(last);
var $clone = $node.clone().text("");
$node.after($clone);
node = dom.node(dom.firstElementChild($clone[0]) || $clone[0]);
$(node).html(br);
node = br;
} else {
node = dom.splitTree(last, {'node': r.sc, 'offset': r.so}) || r.sc;
if (!contentBefore) {
var cur = dom.node(dom.lastChild(node.previousSibling));
if (!dom.isBR(cur)) {
$(cur).html(br);
}
}
if (!dom.isVisibleText(node)) {
node = dom.firstChild(node);
$(dom.node( dom.isBR(node) ? node.parentNode : node )).html(br);
node = br;
}
}
if (node) {
node = dom.firstChild(node);
if (dom.isBR(node)) {
range.createFromNode(node).select();
} else {
range.create(node,0).select();
}
dom.scrollIntoViewIfNeeded(node);
}
event.preventDefault();
return false;
};
$.summernote.pluginEvents.visible = function (event, editor, layoutInfo) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable, "visible");
var r = range.create();
if (!r) return;
if (!r.isCollapsed()) {
if (dom.isCell(dom.node(r.sc)) || dom.isCell(dom.node(r.ec))) {
remove_table_content(r);
r = range.create(r.ec, 0).select();
} else {
r = r.deleteContents(true);
}
r.select();
}
// don't write in forbidden tag (like span for font awsome)
var node = dom.firstChild(r.sc.tagName && r.so ? r.sc.childNodes[r.so] || r.sc : r.sc);
while (node.parentNode) {
if (dom.isForbiddenNode(node)) {
var text = node.previousSibling;
if (text && dom.isText(text) && dom.isVisibleText(text)) {
range.create(text, text.textContent.length, text, text.textContent.length).select();
} else {
text = node.parentNode.insertBefore(document.createTextNode( "." ), node);
range.create(text, 1, text, 1).select();
setTimeout(function () {
var text = range.create().sc;
text.textContent = text.textContent.replace(/^./, '');
range.create(text, text.textContent.length, text, text.textContent.length).select();
},0);
}
break;
}
node = node.parentNode;
}
return true;
};
function summernote_keydown_clean (field) {
setTimeout(function () {
var r = range.create();
if (!r) return;
var node = r[field];
while (dom.isText(node)) {node = node.parentNode;}
node = node.parentNode;
var data = dom.merge(node, r.sc, r.so, r.ec, r.eo, null, true);
data = dom.removeSpace(node.parentNode, data.sc, data.so, data.sc, data.so);
range.create(data.sc, data.so, data.sc, data.so).select();
},0);
}
function remove_table_content(r) {
var ancestor = r.commonAncestor();
var nodes = dom.listBetween(r.sc, r.ec);
if (dom.isText(r.sc)) {
r.sc.textContent = r.sc.textContent.slice(0, r.so);
}
if (dom.isText(r.ec)) {
r.ec.textContent = r.ec.textContent.slice(r.eo);
}
for (var i in nodes) {
var node = nodes[i];
if (node === r.sc || node === r.ec || $.contains(node, r.sc) || $.contains(node, r.ec)) {
continue;
} else if (dom.isCell(node)) {
$(node).html("<br/>");
} else if(node.parentNode) {
do {
var parent = node.parentNode;
parent.removeChild(node);
node = parent;
} while(!dom.isVisibleText(node) && !dom.firstElementChild(node) &&
!dom.isCell(node) &&
node.parentNode && !$(node.parentNode).hasClass('o_editable'));
}
}
return false;
}
$.summernote.pluginEvents.delete = function (event, editor, layoutInfo) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable, "delete");
var r = range.create();
if (!r) return;
if (!r.isContentEditable()) {
event.preventDefault();
return false;
}
if (!r.isCollapsed()) {
if (dom.isCell(dom.node(r.sc)) || dom.isCell(dom.node(r.ec))) {
remove_table_content(r);
range.create(r.ec, 0).select();
} else {
r = r.deleteContents();
r.select();
}
event.preventDefault();
return false;
}
var target = r.ec;
var offset = r.eo;
if (target.tagName && target.childNodes[offset]) {
target = target.childNodes[offset];
offset = 0;
}
var node = dom.node(target);
var data = dom.merge(node, target, offset, target, offset, null, true);
data = dom.removeSpace(node.parentNode, data.sc, data.so, data.ec, data.eo);
r = range.create(data.sc, data.so);
r.select();
target = r.sc;
offset = r.so;
while (!dom.hasContentAfter(node) && !dom.hasContentBefore(node) && !dom.isImg(node)) {node = node.parentNode;}
var contentAfter = target.textContent.slice(offset,Infinity).match(/\S|\u00A0/);
var content = target.textContent.replace(/[ \t\r\n]+$/, '');
var temp;
var temp2;
// media
if (dom.isImg(node) || (!contentAfter && dom.isImg(dom.hasContentAfter(node)))) {
var parent;
var index;
var r;
if (!dom.isImg(node)) {
node = dom.hasContentAfter(node);
}
while (dom.isImg(node)) {
parent = node.parentNode;
index = dom.position(node);
if (index>0) {
var next = node.previousSibling;
r = range.create(next, next.textContent.length);
} else {
r = range.create(parent, 0);
}
if (!dom.hasContentAfter(node) && !dom.hasContentBefore(node)) {
parent.appendChild($('<br/>')[0]);
}
parent.removeChild(node);
node = parent;
r.select();
}
}
// empty tag
else if (!content.length && target.tagName && dom.isRemovableEmptyNode(dom.isBR(target) ? target.parentNode : target)) {
if (node === $editable[0] || $.contains(node, $editable[0])) {
event.preventDefault();
return false;
}
var before = false;
var next = dom.hasContentAfter(dom.ancestorHaveNextSibling(node));
if (!dom.isContentEditable(next)) {
before = true;
next = dom.hasContentBefore(dom.ancestorHavePreviousSibling(node));
}
dom.removeSpace(next.parentNode, next, 0, next, 0); // clean before jump for not select invisible space between 2 tag
next = dom.firstChild(next);
node.parentNode.removeChild(node);
range.create(next, before ? next.textContent.length : 0).select();
}
// normal feature if same tag and not the end
else if (contentAfter) {
return true;
}
// merge with the next text node
else if (dom.isText(target) && (temp = dom.hasContentAfter(target)) && dom.isText(temp)) {
return true;
}
//merge with the next block
else if ((temp = dom.ancestorHaveNextSibling(target)) &&
!r.isOnCell() &&
dom.isMergable(temp) &&
dom.isMergable(temp2 = dom.hasContentAfter(temp)) &&
temp.tagName === temp2.tagName &&
(temp.tagName !== "LI" || !$('ul,ol', temp).length) && (temp2.tagName !== "LI" || !$('ul,ol', temp2).length) && // protect li
!dom.isNotBreakable(temp) &&
!dom.isNotBreakable(temp2)) {
dom.autoMerge(target, false);
var next = dom.firstChild(dom.hasContentAfter(dom.ancestorHaveNextSibling(target)));
if (dom.isBR(next)) {
if(dom.position(next) == 0) {
range.create(next.parentNode, 0).select();
}
else {
range.create(next.previousSibling, next.previousSibling.textContent.length).select();
}
next.parentNode.removeChild(next);
} else {
range.create(next, 0).select();
}
}
// jump to next node for delete
else if ((temp = dom.ancestorHaveNextSibling(target)) && (temp2 = dom.hasContentAfter(temp)) && dom.isContentEditable(temp2)) {
dom.removeSpace(temp2.parentNode, temp2, 0, temp, 0); // clean before jump for not select invisible space between 2 tag
temp2 = dom.firstChild(temp2);
r = range.create(temp2, 0);
r.select();
if ((dom.isText(temp) || dom.getComputedStyle(temp).display === "inline") && (dom.isText(temp2) || dom.getComputedStyle(temp2).display === "inline")) {
if (dom.isText(temp2)) {
temp2.textContent = temp2.textContent.replace(/^\s*\S/, '');
} else {
$.summernote.pluginEvents.delete(event, editor, layoutInfo);
}
}
}
$(dom.node(r.sc)).trigger("click"); // trigger click to disable and reanable editor and image handler
event.preventDefault();
return false;
};
$.summernote.pluginEvents.backspace = function (event, editor, layoutInfo) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable, "backspace");
var r = range.create();
if (!r) return;
if (!r.isContentEditable()) {
event.preventDefault();
return false;
}
if (!r.isCollapsed()) {
if (dom.isCell(dom.node(r.sc)) || dom.isCell(dom.node(r.ec))) {
remove_table_content(r);
range.create(r.sc, dom.nodeLength(r.sc)).select();
} else {
r = r.deleteContents();
r.select();
}
event.preventDefault();
return false;
}
var target = r.sc;
var offset = r.so;
if (target.tagName && target.childNodes[offset]) {
target = target.childNodes[offset];
offset = 0;
}
var node = dom.node(target);
var data = dom.merge(node, target, offset, target, offset, null, true);
data = dom.removeSpace(node.parentNode, data.sc, data.so, data.ec, data.eo);
r = dom.isVoid(data.sc) ? range.createFromNode(data.sc) : range.create(data.sc, data.so);
r.select();
target = r.sc;
offset = r.so;
if (target.tagName && target.childNodes[offset]) {
target = target.childNodes[offset];
offset = 0;
node = dom.node(target);
}
while (node.parentNode && !dom.hasContentAfter(node) && !dom.hasContentBefore(node) && !dom.isImg(node)) {node = node.parentNode;}
var contentBefore = target.textContent.slice(0,offset).match(/\S|\u00A0/);
var content = target.textContent.replace(/[ \t\r\n]+$/, '');
var temp;
var temp2;
// delete media
if (dom.isImg(node) || (!contentBefore && dom.isImg(dom.hasContentBefore(node)))) {
if (!dom.isImg(node)) {
node = dom.hasContentBefore(node);
}
range.createFromNode(node).select();
$.summernote.pluginEvents.delete(event, editor, layoutInfo);
}
// table tr td
else if (r.isOnCell() && !offset && (target === (temp = dom.ancestor(target, dom.isCell)) || target === temp.firstChild || (dom.isText(temp.firstChild) && !dom.isVisibleText(temp.firstChild) && target === temp.firstChild.nextSibling))) {
if (dom.previousElementSibling(temp)) {
var td = dom.previousElementSibling(temp);
node = td.lastChild || td;
} else {
var tr = temp.parentNode;
var prevTr = dom.previousElementSibling(tr);
if (!$(temp.parentNode).text().match(/\S|\u00A0/)) {
if (prevTr) {
node = dom.lastChild(dom.lastElementChild(prevTr));
} else {
node = dom.lastChild(dom.hasContentBefore(dom.ancestorHavePreviousSibling(tr)) || $editable.get(0));
}
$(tr).empty();
if(!$(tr).closest('table').has('td, th').length) {
$(tr).closest('table').remove();
}
$(tr).remove();
range.create(node, node.textContent.length, node, node.textContent.length).select();
} else {
node = dom.lastElementChild(prevTr).lastChild || dom.lastElementChild(prevTr);
}
}
if (dom.isBR(node)) {
range.createFromNode(node).select();
} else {
range.create(node, dom.nodeLength(node)).select();
}
}
// empty tag
else if (!content.length && target.tagName && dom.isRemovableEmptyNode(target)) {
if (node === $editable[0] || $.contains(node, $editable[0])) {
event.preventDefault();
return false;
}
var before = true;
var prev = dom.hasContentBefore(dom.ancestorHavePreviousSibling(node));
if (!dom.isContentEditable(prev)) {
before = false;
prev = dom.hasContentAfter(dom.ancestorHaveNextSibling(node));
}
dom.removeSpace(prev.parentNode, prev, 0, prev, 0); // clean before jump for not select invisible space between 2 tag
prev = dom.lastChild(prev);
node.parentNode.removeChild(node);
range.createFromNode(prev).select();
range.create(prev, before ? prev.textContent.length : 0).select();
}
// normal feature if same tag and not the begin
else if (contentBefore) {
return true;
}
// merge with the previous text node
else if (dom.isText(target) && (temp = dom.hasContentBefore(target)) && (dom.isText(temp) || dom.isBR(temp))) {
return true;
}
//merge with the previous block
else if ((temp = dom.ancestorHavePreviousSibling(target)) &&
dom.isMergable(temp) &&
dom.isMergable(temp2 = dom.hasContentBefore(temp)) &&
temp.tagName === temp2.tagName &&
(temp.tagName !== "LI" || !$('ul,ol', temp).length) && (temp2.tagName !== "LI" || !$('ul,ol', temp2).length) && // protect li
!dom.isNotBreakable(temp) &&
!dom.isNotBreakable(temp2)) {
var prev = dom.firstChild(target);
dom.autoMerge(target, true);
range.create(prev, 0).select();
}
// jump to previous node for delete
else if ((temp = dom.ancestorHavePreviousSibling(target)) && (temp2 = dom.hasContentBefore(temp)) && dom.isContentEditable(temp2)) {
dom.removeSpace(temp2.parentNode, temp2, 0, temp, 0); // clean before jump for not select invisible space between 2 tag
temp2 = dom.lastChild(temp2);
r = range.create(temp2, temp2.textContent.length, temp2, temp2.textContent.length);
r.select();
if ((dom.isText(temp) || dom.getComputedStyle(temp).display === "inline") && (dom.isText(temp2) || dom.getComputedStyle(temp2).display === "inline")) {
if (dom.isText(temp2)) {
temp2.textContent = temp2.textContent.replace(/\S\s*$/, '');
} else {
$.summernote.pluginEvents.backspace(event, editor, layoutInfo);
}
}
}
var r = range.create();
if (r) {
$(dom.node(r.sc)).trigger("click"); // trigger click to disable and reanable editor and image handler
dom.scrollIntoViewIfNeeded(r.sc.parentNode.previousElementSibling || r.sc);
}
event.preventDefault();
return false;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* add list command (create a uggly dom for chrome) */
function isFormatNode(node) {
return node.tagName && options.styleTags.indexOf(node.tagName.toLowerCase()) !== -1;
}
$.summernote.pluginEvents.insertUnorderedList = function (event, editor, layoutInfo, sorted) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable);
var parent;
var r = range.create();
if (!r) return;
var node = r.sc;
while (node && node !== $editable[0]) {
parent = node.parentNode;
if (node.tagName === (sorted ? "UL" : "OL")) {
var ul = document.createElement(sorted ? "ol" : "ul");
ul.className = node.className;
parent.insertBefore(ul, node);
while (node.firstChild) {
ul.appendChild(node.firstChild);
}
parent.removeChild(node);
r.select();
return;
} else if (node.tagName === (sorted ? "OL" : "UL")) {
var lis = [];
for (var i=0; i<node.children.length; i++) {
lis.push(node.children[i]);
}
if (parent.tagName === "LI") {
node = parent;
parent = node.parentNode;
_.each(lis, function (li) {
parent.insertBefore(li, node);
});
} else {
_.each(lis, function (li) {
while (li.firstChild) {
parent.insertBefore(li.firstChild, node);
}
});
}
parent.removeChild(node);
r.select();
return;
}
node = parent;
}
var p0 = r.sc;
while (p0 && p0.parentNode && p0.parentNode !== $editable[0] && !isFormatNode(p0)) {
p0 = p0.parentNode;
}
if (!p0) return;
var p1 = r.ec;
while (p1 && p1.parentNode && p1.parentNode !== $editable[0] && !isFormatNode(p1)) {
p1 = p1.parentNode;
}
if (!p0.parentNode || p0.parentNode !== p1.parentNode) {
return;
}
var parent = p0.parentNode;
var ul = document.createElement(sorted ? "ol" : "ul");
parent.insertBefore(ul, p0);
var childNodes = parent.childNodes;
var brs = [];
var begin = false;
for (var i=0; i<childNodes.length; i++) {
if (begin && dom.isBR(childNodes[i])) {
parent.removeChild(childNodes[i]);
i--;
}
if ((!dom.isText(childNodes[i]) && !isFormatNode(childNodes[i])) || (!ul.firstChild && childNodes[i] !== p0) ||
$.contains(ul, childNodes[i]) || (dom.isText(childNodes[i]) && !childNodes[i].textContent.match(/\S|u00A0/))) {
continue;
}
begin = true;
var li = document.createElement('li');
ul.appendChild(li);
li.appendChild(childNodes[i]);
if (li.firstChild === p1) {
break;
}
i--;
}
if (dom.isBR(childNodes[i])) {
parent.removeChild(childNodes[i]);
}
for (var i=0; i<brs.length; i++) {
parent.removeChild(brs[i]);
}
r.clean().select();
event.preventDefault();
return false;
};
$.summernote.pluginEvents.insertOrderedList = function (event, editor, layoutInfo) {
return $.summernote.pluginEvents.insertUnorderedList(event, editor, layoutInfo, true);
};
$.summernote.pluginEvents.indent = function (event, editor, layoutInfo, outdent) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable);
var r = range.create();
if (!r) return;
var flag = false;
function indentUL (UL, start, end) {
var next;
var tagName = UL.tagName;
var node = UL.firstChild;
var parent = UL.parentNode;
var ul = document.createElement(tagName);
var li = document.createElement("li");
li.style.listStyle = "none";
li.appendChild(ul);
if (flag) {
flag = 1;
}
// create and fill ul into a li
while (node) {
if (flag === 1 || node === start || $.contains(node, start)) {
flag = true;
node.parentNode.insertBefore(li, node);
}
next = dom.nextElementSibling(node);
if (flag) {
ul.appendChild(node);
}
if (node === end || $.contains(node, end)) {
flag = false;
break;
}
node = next;
}
var temp;
var prev = dom.previousElementSibling(li);
if (prev && prev.tagName === "LI" && (temp = dom.firstElementChild(prev)) && temp.tagName === tagName && ((dom.firstElementChild(prev) || prev.firstChild) !== ul)) {
dom.doMerge(dom.firstElementChild(prev) || prev.firstChild, ul);
li = prev;
li.parentNode.removeChild(dom.nextElementSibling(li));
}
var next = dom.nextElementSibling(li);
if (next && next.tagName === "LI" && (temp = dom.firstElementChild(next)) && temp.tagName === tagName && (dom.firstElementChild(li) !== dom.firstElementChild(next))) {
dom.doMerge(dom.firstElementChild(li), dom.firstElementChild(next));
li.parentNode.removeChild(dom.nextElementSibling(li));
}
}
function outdenttUL (UL, start, end) {
var next;
var tagName = UL.tagName;
var node = UL.firstChild;
var parent = UL.parentNode;
var li = UL.parentNode.tagName === "LI" ? UL.parentNode : UL;
var ul = UL.parentNode.tagName === "LI" ? UL.parentNode.parentNode : UL.parentNode;
start = dom.ancestor(start, dom.isLi);
end = dom.ancestor(end, dom.isLi);
if (ul.tagName !== "UL" && ul.tagName !== "OL") return;
// create and fill ul into a li
while (node) {
if (node === start || $.contains(node, start)) {
flag = true;
if (dom.previousElementSibling(node) && li.tagName === "LI") {
li = dom.splitTree(li, dom.prevPoint({'node': node, 'offset': 0}));
}
}
next = dom.nextElementSibling(node);
if (flag) {
ul = node.parentNode;
li.parentNode.insertBefore(node, li);
if (!ul.children.length) {
if (ul.parentNode.tagName === "LI") {
ul = ul.parentNode;
}
ul.parentNode.removeChild(ul);
}
}
if (node === end || $.contains(node, end)) {
flag = false;
break;
}
node = next;
}
dom.merge(parent, start, 0, end, 1, null, true);
}
function indentOther (p, start, end) {
if (p === start || $.contains(p, start) || $.contains(start, p)) {
flag = true;
}
if (flag) {
if (outdent) {
dom.outdent(p);
} else {
dom.indent(p);
}
}
if (p === end || $.contains(p, end) || $.contains(end, p)) {
flag = false;
}
}
var ancestor = r.commonAncestor();
var $dom = $(ancestor);
if (!dom.isList(ancestor)) {
$dom = $(dom.node(ancestor)).children();
}
if (!$dom.length) {
$dom = $(dom.ancestor(r.sc, dom.isList) || dom.ancestor(r.sc, dom.isCell));
if (!$dom.length) {
$dom = $(r.sc).closest(options.styleTags.join(','));
}
}
// if select tr, take the first td
$dom = $dom.map(function () { return this.tagName === "TR" ? dom.firstElementChild(this) : this; });
$dom.each(function () {
if (flag || $.contains(this, r.sc)) {
if (dom.isList(this)) {
if (outdent) {
outdenttUL(this, r.sc, r.ec);
} else {
indentUL(this, r.sc, r.ec);
}
} else if (isFormatNode(this) || dom.ancestor(this, dom.isCell)) {
indentOther(this, r.sc, r.ec);
}
}
});
if ($dom.length) {
var $parent = $dom.parent();
// remove text nodes between lists
var $ul = $parent.find('ul, ol');
if (!$ul.length) {
$ul = $(dom.ancestor(r.sc, dom.isList));
}
$ul.each(function () {
if (this.previousSibling &&
this.previousSibling !== dom.previousElementSibling(this) &&
!this.previousSibling.textContent.match(/\S/)) {
this.parentNode.removeChild(this.previousSibling);
}
if (this.nextSibling &&
this.nextSibling !== dom.nextElementSibling(this) &&
!this.nextSibling.textContent.match(/\S/)) {
this.parentNode.removeChild(this.nextSibling);
}
});
// merge same ul or ol
r = dom.merge($parent[0], r.sc, r.so, r.ec, r.eo, function (prev, cur) {
if (prev && dom.isList(prev) && dom.isEqual(prev, cur)) {
return true;
}
}, true);
range.create(r.sc, r.so, r.ec, r.eo).select();
}
event.preventDefault();
return false;
};
$.summernote.pluginEvents.outdent = function (event, editor, layoutInfo) {
return $.summernote.pluginEvents.indent(event, editor, layoutInfo, true);
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
$.summernote.pluginEvents.formatBlock = function (event, editor, layoutInfo, sTagName) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable);
event.preventDefault();
var r = range.create();
if (!r) {
return;
}
r.reRange().select();
if (sTagName === "blockquote" || sTagName === "pre") {
sTagName = $.summernote.core.agent.isMSIE ? '<' + sTagName + '>' : sTagName;
document.execCommand('FormatBlock', false, sTagName);
return;
}
// fix by odoo because if you select a style in a li with no p tag all the ul is wrapped by the style tag
var nodes = dom.listBetween(r.sc, r.ec);
for (var i=0; i<nodes.length; i++) {
if (dom.isBR(nodes[i]) || (dom.isText(nodes[i]) && dom.isVisibleText(nodes[i])) || dom.isB(nodes[i]) || dom.isU(nodes[i]) || dom.isS(nodes[i]) || dom.isI(nodes[i]) || dom.isFont(nodes[i])) {
var ancestor = dom.ancestor(nodes[i], isFormatNode);
if (!ancestor) {
dom.wrap(nodes[i], sTagName);
} else if (ancestor.tagName.toLowerCase() !== sTagName) {
var tag = document.createElement(sTagName);
ancestor.parentNode.insertBefore(tag, ancestor);
dom.moveContent(ancestor, tag);
if (ancestor.className) {
tag.className = ancestor.className;
}
ancestor.parentNode.removeChild(ancestor);
}
}
}
r.select();
};
$.summernote.pluginEvents.removeFormat = function (event, editor, layoutInfo, value) {
var $editable = layoutInfo.editable();
$editable.data('NoteHistory').recordUndo($editable);
var r = range.create();
if(!r) return;
var node = range.create().sc.parentNode;
document.execCommand('removeFormat');
document.execCommand('removeFormat');
var r = range.create();
if (!r) return;
r = dom.merge(node, r.sc, r.so, r.ec, r.eo, null, true);
range.create(r.sc, r.so, r.ec, r.eo).select();
event.preventDefault();
return false;
};
var fn_boutton_updateRecentColor = eventHandler.modules.toolbar.button.updateRecentColor;
eventHandler.modules.toolbar.button.updateRecentColor = function (elBtn, sEvent, sValue) {
fn_boutton_updateRecentColor.call(this, elBtn, sEvent, sValue);
var font = $(elBtn).closest('.note-color').find('.note-recent-color i')[0];
if (sEvent === "foreColor") {
if (sValue.indexOf('text-') !== -1) {
font.className += ' ' + sValue;
font.style.color = '';
} else {
font.className = font.className.replace(/(^|\s+)text-\S+/);
font.style.color = sValue !== 'inherit' ? sValue : "";
}
} else {
if (sValue.indexOf('bg-') !== -1) {
font.className += ' ' + sValue;
font.style.backgroundColor = "";
} else {
font.className = font.className.replace(/(^|\s+)bg-\S+/);
font.style.backgroundColor = sValue !== 'inherit' ? sValue : "";
}
}
return false;
};
$(document).on('click keyup', function () {
var $popover = $((range.create()||{}).sc).closest('[contenteditable]');
var popover_history = ($popover.data()||{}).NoteHistory;
if(!popover_history || popover_history == history) return;
var editor = $popover.parent('.note-editor');
$('button[data-event="undo"]', editor).attr('disabled', !popover_history.hasUndo());
$('button[data-event="redo"]', editor).attr('disabled', !popover_history.hasRedo());
});
eventHandler.modules.editor.undo = function ($popover) {
if(!$popover.attr('disabled')) $popover.data('NoteHistory').undo();
};
eventHandler.modules.editor.redo = function ($popover) {
if(!$popover.attr('disabled')) $popover.data('NoteHistory').redo();
};
// use image toolbar if current range is on image
var fn_editor_currentstyle = eventHandler.modules.editor.currentStyle;
eventHandler.modules.editor.currentStyle = function(target) {
var styleInfo = fn_editor_currentstyle.apply(this, arguments);
// with our changes for inline editor, the targeted element could be a button of the editor
if(!styleInfo.image || !dom.isEditable(styleInfo.image)) {
styleInfo.image = undefined;
var r = range.create();
if(r)
styleInfo.image = r.isOnImg();
}
return styleInfo;
}
options.fontSizes = [_t('Default'), 8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 62];
$.summernote.pluginEvents.applyFont = function (event, editor, layoutInfo, color, bgcolor, size) {
var r = range.create();
if(!r) return;
var startPoint = r.getStartPoint();
var endPoint = r.getEndPoint();
if (r.isCollapsed() && !dom.isFont(r.sc)) {
return {
sc: startPoint.node,
so: startPoint.offset,
ec: endPoint.node,
offset: endPoint.offset
};
}
if (startPoint.node.tagName && startPoint.node.childNodes[startPoint.offset]) {
startPoint.node = startPoint.node.childNodes[startPoint.offset];
startPoint.offset = 0;
}
if (endPoint.node.tagName && endPoint.node.childNodes[endPoint.offset]) {
endPoint.node = endPoint.node.childNodes[endPoint.offset];
endPoint.offset = 0;
}
// get first and last point
if (endPoint.offset && endPoint.offset != dom.nodeLength(endPoint.node)) {
var ancestor = dom.ancestor(endPoint.node, dom.isFont) || endPoint.node;
dom.splitTree(ancestor, endPoint);
}
if (startPoint.offset && startPoint.offset != dom.nodeLength(startPoint.node)) {
var ancestor = dom.ancestor(startPoint.node, dom.isFont) || startPoint.node;
var node = dom.splitTree(ancestor, startPoint);
if (endPoint.node === startPoint.node) {
endPoint.node = node;
endPoint.offset = dom.nodeLength(node);
}
startPoint.node = node;
startPoint.offset = 0;
}
// get list of nodes to change
var nodes = [];
dom.walkPoint(startPoint, endPoint, function (point) {
var node = point.node;
if (((dom.isText(node) && dom.isVisibleText(node)) ||
(dom.isFont(node) && !dom.isVisibleText(node))) &&
(node != endPoint.node || endPoint.offset)) {
nodes.push(point.node);
}
});
nodes = list.unique(nodes);
// If ico fa
if (r.isCollapsed()) {
nodes.push(startPoint.node);
}
// apply font: foreColor, backColor, size (the color can be use a class text-... or bg-...)
var node, font, $font, fonts = [], className;
if (color || bgcolor || size) {
for (var i=0; i<nodes.length; i++) {
node = nodes[i];
font = dom.ancestor(node, dom.isFont);
if (!font) {
if (node.textContent.match(/^[ ]|[ ]$/)) {
node.textContent = node.textContent.replace(/^[ ]|[ ]$/g, '\u00A0');
}
font = dom.create("font");
node.parentNode.insertBefore(font, node);
font.appendChild(node);
}
fonts.push(font);
className = font.className.split(/\s+/);
if (color) {
for (var k=0; k<className.length; k++) {
if (className[k].length && className[k].slice(0,5) === "text-") {
className.splice(k,1);
k--;
}
}
if (color.indexOf('text-') !== -1) {
font.className = className.join(" ") + " " + color;
font.style.color = "inherit";
} else {
font.className = className.join(" ");
font.style.color = color;
}
}
if (bgcolor) {
for (var k=0; k<className.length; k++) {
if (className[k].length && className[k].slice(0,3) === "bg-") {
className.splice(k,1);
k--;
}
}
if (bgcolor.indexOf('bg-') !== -1) {
font.className = className.join(" ") + " " + bgcolor;
font.style.backgroundColor = "inherit";
} else {
font.className = className.join(" ");
font.style.backgroundColor = bgcolor;
}
}
if (size) {
font.style.fontSize = "inherit";
if (!isNaN(size) && Math.abs(parseInt(dom.getComputedStyle(font).fontSize, 10)-size)/size > 0.05) {
font.style.fontSize = size + "px";
}
}
}
}
// remove empty values
// we must remove the value in 2 steps (applay inherit then remove) because some
// browser like chrome have some time an error for the rendering and/or keep inherit
for (var i=0; i<fonts.length; i++) {
font = fonts[i];
if (font.style.backgroundColor === "inherit") {
font.style.backgroundColor = "";
}
if (font.style.color === "inherit") {
font.style.color = "";
}
if (font.style.fontSize === "inherit") {
font.style.fontSize = "";
}
$font = $(font);
if (!$font.css("color") && !$font.css("background-color") && !$font.css("font-size")) {
$font.removeAttr("style");
}
if (!font.className.length) {
$font.removeAttr("class");
}
}
// select nodes to clean (to remove empty font and merge same nodes)
var nodes = [];
dom.walkPoint(startPoint, endPoint, function (point) {
nodes.push(point.node);
});
nodes = list.unique(nodes);
function remove (node, to) {
if (node === endPoint.node) {
endPoint = dom.prevPoint(endPoint);
}
if (to) {
dom.moveContent(node, to);
}
dom.remove(node);
}
// remove node without attributes (move content), and merge the same nodes
var className2, style, style2, $prev;
for (var i=0; i<nodes.length; i++) {
node = nodes[i];
if ((dom.isText(node) || dom.isBR(node)) && !dom.isVisibleText(node)) {
remove(node);
nodes.splice(i,1);
i--;
continue;
}
font = dom.ancestor(node, dom.isFont);
node = font || dom.ancestor(node, dom.isSpan);
if (!node) {
continue;
}
$font = $(node);
className = dom.orderClass(node);
style = dom.orderStyle(node);
if (!className && !style) {
remove(node, node.parentNode);
nodes.splice(i,1);
i--;
continue;
}
if (i>0 && (font = dom.ancestor(nodes[i-1], dom.isFont))) {
className2 = font.getAttribute('class');
style2 = font.getAttribute('style');
if (node !== font && className == className2 && style == style2) {
remove(node, font);
nodes.splice(i,1);
i--;
continue;
}
}
}
range.create(startPoint.node, startPoint.offset, endPoint.node, endPoint.offset).select();
};
$.summernote.pluginEvents.fontSize = function (event, editor, layoutInfo, value) {
var $editable = layoutInfo.editable();
event.preventDefault();
$.summernote.pluginEvents.applyFont(event, editor, layoutInfo, null, null, value);
editor.afterCommand($editable);
};
$.summernote.pluginEvents.color = function (event, editor, layoutInfo, sObjColor) {
var $editable = layoutInfo.editable();
var oColor = JSON.parse(sObjColor);
var foreColor = oColor.foreColor, backColor = oColor.backColor;
if (foreColor) { $.summernote.pluginEvents.foreColor(event, editor, layoutInfo, foreColor); }
if (backColor) { $.summernote.pluginEvents.backColor(event, editor, layoutInfo, backColor); }
};
$.summernote.pluginEvents.foreColor = function (event, editor, layoutInfo, foreColor) {
var $editable = layoutInfo.editable();
$.summernote.pluginEvents.applyFont(event, editor, layoutInfo, foreColor, null, null);
editor.afterCommand($editable);
};
$.summernote.pluginEvents.backColor = function (event, editor, layoutInfo, backColor) {
var $editable = layoutInfo.editable();
var r = range.create();
if (!r) return;
if (r.isCollapsed() && r.isOnCell()) {
var cell = dom.ancestor(r.sc, dom.isCell);
cell.className = cell.className.replace(new RegExp('(^|\\s+)bg-[^\\s]+(\\s+|$)', 'gi'), '');
cell.style.backgroundColor = "";
if (backColor.indexOf('bg-') !== -1) {
cell.className += ' ' + backColor;
} else if (backColor !== 'inherit') {
cell.style.backgroundColor = backColor;
}
return;
}
$.summernote.pluginEvents.applyFont(event, editor, layoutInfo, null, backColor, null);
editor.afterCommand($editable);
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
options.onCreateLink = function (sLinkUrl) {
if (sLinkUrl.indexOf('mailto:') === 0) {
// pass
} else if (sLinkUrl.indexOf('@') !== -1 && sLinkUrl.indexOf(':') === -1) {
sLinkUrl = 'mailto:' + sLinkUrl;
} else if (sLinkUrl.indexOf('://') === -1 && sLinkUrl.indexOf('/') !== 0 && sLinkUrl.indexOf('#') !== 0) {
sLinkUrl = 'http://' + sLinkUrl;
}
return sLinkUrl;
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* table */
function summernote_table_scroll (event) {
var r = range.create();
if (r && r.isOnCell()) {
$('.o_table_handler').remove();
}
}
function summernote_table_update (oStyle) {
var r = range.create();
if (!oStyle.range || !r || !r.isOnCell() || !r.isOnCellFirst()) {
$('.o_table_handler').remove();
return;
}
var table = dom.ancestor(oStyle.range.sc, dom.isTable);
if (!table) { // if the editable tag is inside the table
return;
}
var $editable = $(table).closest('.o_editable');
$('.o_table_handler').remove();
var $dels = $();
var $adds = $();
var $tds = $('tr:first', table).children();
$tds.each(function () {
var $td = $(this);
var pos = $td.offset();
var $del = $('<span class="o_table_handler fa fa-minus-square"/>').appendTo('body');
$del.data('td', this);
$dels = $dels.add($del);
$del.css({
left: ((pos.left + $td.outerWidth()/2)-6) + "px",
top: (pos.top-6) + "px"
});
var $add = $('<span class="o_table_handler fa fa-plus-square"/>').appendTo('body');
$add.data('td', this);
$adds = $adds.add($add);
$add.css({
left: (pos.left-6) + "px",
top: (pos.top-6) + "px"
});
});
var $last = $tds.last();
var pos = $last.offset();
var $add = $('<span class="o_table_handler fa fa-plus-square"/>').appendTo('body');
$adds = $adds.add($add);
$add.css({
left: (pos.left+$last.outerWidth()-6) + "px",
top: (pos.top-6) + "px"
});
var $table = $(table);
$dels.data('table', table).on('mousedown', function (event) {
var td = $(this).data('td');
$editable.data('NoteHistory').recordUndo($editable);
var newTd;
if ($(td).siblings().length) {
var eq = $(td).index();
$table.find('tr').each(function () {
$('> td:eq('+eq+')', this).remove();
});
newTd = $table.find('tr:first > td:eq('+eq+'), tr:first > td:last').first();
} else {
var prev = dom.lastChild(dom.hasContentBefore(dom.ancestorHavePreviousSibling($table[0])));
$table.remove();
$('.o_table_handler').remove();
r = range.create(prev, prev.textContent.length);
r.select();
$(r.sc).trigger('mouseup');
return;
}
$('.o_table_handler').remove();
range.create(newTd[0], 0, newTd[0], 0).select();
newTd.trigger('mouseup');
});
$adds.data('table', table).on('mousedown', function (event) {
var td = $(this).data('td');
$editable.data('NoteHistory').recordUndo($editable);
var newTd;
if (td) {
var eq = $(td).index();
$table.find('tr').each(function () {
$('td:eq('+eq+')', this).before('<td>'+dom.blank+'</td>');
});
newTd = $table.find('tr:first td:eq('+eq+')');
} else {
$table.find('tr').each(function () {
$(this).append('<td>'+dom.blank+'</td>');
});
newTd = $table.find('tr:first td:last');
}
$('.o_table_handler').remove();
range.create(newTd[0], 0, newTd[0], 0).select();
newTd.trigger('mouseup');
});
$dels.css({
'position': 'absolute',
'cursor': 'pointer',
'background-color': '#fff',
'color': '#ff0000'
});
$adds.css({
'position': 'absolute',
'cursor': 'pointer',
'background-color': '#fff',
'color': '#00ff00'
});
}
var fn_popover_update = eventHandler.modules.popover.update;
eventHandler.modules.popover.update = function ($popover, oStyle, isAirMode) {
fn_popover_update.call(this, $popover, oStyle, isAirMode);
if(!!(isAirMode ? $popover : $popover.parent()).find('.note-table').length) {
summernote_table_update(oStyle);
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////
var fn_attach = eventHandler.attach;
eventHandler.attach = function (oLayoutInfo, options) {
var $editable = oLayoutInfo.editor().hasClass('note-editable') ? oLayoutInfo.editor() : oLayoutInfo.editor().find('.note-editable');
fn_attach.call(this, oLayoutInfo, options);
$editable.on("scroll", summernote_table_scroll);
};
var fn_detach = eventHandler.detach;
eventHandler.detach = function (oLayoutInfo, options) {
var $editable = oLayoutInfo.editor().hasClass('note-editable') ? oLayoutInfo.editor() : oLayoutInfo.editor().find('.note-editable');
fn_detach.call(this, oLayoutInfo, options);
$editable.off("scroll", summernote_table_scroll);
$('.o_table_handler').remove();
};
return $.summernote;
});
| agpl-3.0 |
lue/dealii | tests/bits/compressed_sparsity_pattern_07.cc | 1538 | // ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
// check CompressedSparsityPattern::exists. since we create quite some
// output here, choose smaller number of rows and entries than in the other
// tests
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/lac/compressed_sparsity_pattern.h>
#include <iomanip>
#include <fstream>
void test ()
{
const unsigned int N = 100;
CompressedSparsityPattern csp (N,N);
for (unsigned int i=0; i<N; ++i)
for (unsigned int j=0; j<10; ++j)
csp.add (i, (i+(i+1)*(j*j+i))%N);
csp.symmetrize ();
for (unsigned int i=0; i<N; ++i)
{
deallog << i << ' ';
for (unsigned int j=0; j<N; ++j)
deallog << (csp.exists(i,j) ? 'x' : ' ');
deallog << std::endl;
}
}
int main ()
{
std::ofstream logfile("output");
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test ();
return 0;
}
| lgpl-2.1 |
Philippe2201/vraptor4 | vraptor-core/src/main/java/br/com/caelum/vraptor/core/AbstractResult.java | 2724 | /***
* Copyright (c) 2009 Caelum - www.caelum.com.br/opensource 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 br.com.caelum.vraptor.core;
import static br.com.caelum.vraptor.proxy.CDIProxies.extractRawTypeIfPossible;
import static br.com.caelum.vraptor.view.Results.logic;
import static br.com.caelum.vraptor.view.Results.page;
import static br.com.caelum.vraptor.view.Results.status;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.view.Results;
/**
* An abstract result that implements all shortcut methods in the
* recommended way
*
* @author Lucas Cavalcanti
* @since 3.1.2
*/
public abstract class AbstractResult implements Result {
@Override
public void forwardTo(String uri) {
use(page()).forwardTo(uri);
}
@Override
public void redirectTo(String uri) {
use(page()).redirectTo(uri);
}
@Override
public <T> T forwardTo(Class<T> controller) {
return use(logic()).forwardTo(controller);
}
@Override
public <T> T redirectTo(Class<T> controller) {
return use(logic()).redirectTo(controller);
}
@Override
public <T> T of(Class<T> controller) {
return use(page()).of(controller);
}
@Override
@SuppressWarnings("unchecked")
public <T> T redirectTo(T controller) {
return (T) redirectTo((Class<T>) extractRawTypeIfPossible(controller.getClass()));
}
@Override
@SuppressWarnings("unchecked")
public <T> T forwardTo(T controller) {
return (T) forwardTo((Class<T>) extractRawTypeIfPossible(controller.getClass()));
}
@Override
@SuppressWarnings("unchecked")
public <T> T of(T controller) {
return (T) of((Class<T>) extractRawTypeIfPossible(controller.getClass()));
}
@Override
public void nothing() {
use(Results.nothing());
}
@Override
public void notFound() {
use(status()).notFound();
}
@Override
public void permanentlyRedirectTo(String uri) {
use(status()).movedPermanentlyTo(uri);
}
@Override
public <T> T permanentlyRedirectTo(Class<T> controller) {
return use(status()).movedPermanentlyTo(controller);
}
@Override
@SuppressWarnings("unchecked")
public <T> T permanentlyRedirectTo(T controller) {
return (T) use(status()).movedPermanentlyTo(controller.getClass());
}
} | apache-2.0 |
isaksky/selenium | java/server/src/org/openqa/grid/web/servlet/beta/WebProxyHtmlRendererBeta.java | 6852 | /*
Copyright 2012 Selenium committers
Copyright 2012 Software Freedom Conservancy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.grid.web.servlet.beta;
import org.json.JSONObject;
import org.openqa.grid.common.SeleniumProtocol;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.RemoteProxy;
import org.openqa.grid.internal.TestSession;
import org.openqa.grid.internal.TestSlot;
import org.openqa.grid.internal.utils.HtmlRenderer;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.CapabilityType;
import java.util.Map;
public class WebProxyHtmlRendererBeta implements HtmlRenderer {
private RemoteProxy proxy;
@SuppressWarnings("unused")
private WebProxyHtmlRendererBeta() {}
public WebProxyHtmlRendererBeta(RemoteProxy proxy) {
this.proxy = proxy;
}
public String renderSummary() {
StringBuilder builder = new StringBuilder();
builder.append("<div class='proxy'>");
builder.append("<p class='proxyname'>");
builder.append(proxy.getClass().getSimpleName());
// TODO freynaud
builder.append(getHtmlNodeVersion());
String platform = getPlatform(proxy);
builder.append("<p class='proxyid'>id : ");
builder.append(proxy.getId());
builder.append(", OS : " + platform + "</p>");
builder.append(nodeTabs());
builder.append("<div class='content'>");
builder.append(tabBrowsers());
builder.append(tabConfig());
builder.append("</div>");
builder.append("</div>");
return builder.toString();
}
private String getHtmlNodeVersion() {
try {
JSONObject object = proxy.getStatus();
String version = object.getJSONObject("value").getJSONObject("build").getString("version");
return " (version : "+version+ ")";
}catch (Exception e) {
return " unknown version,"+e.getMessage();
}
}
// content of the config tab.
private String tabConfig() {
StringBuilder builder = new StringBuilder();
builder.append("<div type='config' class='content_detail'>");
Map<String, Object> config = proxy.getConfig();
for (String key : config.keySet()) {
builder.append("<p>");
builder.append(key);
builder.append(":");
builder.append(config.get(key));
builder.append("</p>");
}
builder.append("</div>");
return builder.toString();
}
// content of the browsers tab
private String tabBrowsers() {
StringBuilder builder = new StringBuilder();
builder.append("<div type='browsers' class='content_detail'>");
SlotsLines rcLines = new SlotsLines();
SlotsLines wdLines = new SlotsLines();
for (TestSlot slot : proxy.getTestSlots()) {
if (slot.getProtocol() == SeleniumProtocol.Selenium) {
rcLines.add(slot);
} else {
wdLines.add(slot);
}
}
if (rcLines.getLinesType().size() != 0) {
builder.append("<p class='protocol' >Remote Control (legacy)</p>");
builder.append(getLines(rcLines));
}
if (wdLines.getLinesType().size() != 0) {
builder.append("<p class='protocol' >WebDriver</p>");
builder.append(getLines(wdLines));
}
builder.append("</div>");
return builder.toString();
}
// the lines of icon representing the possible slots
private String getLines(SlotsLines lines) {
StringBuilder builder = new StringBuilder();
for (MiniCapability cap : lines.getLinesType()) {
String icon = cap.getIcon();
String version = cap.getVersion();
builder.append("<p>");
if (version != null) {
builder.append("v:" + version);
}
for (TestSlot s : lines.getLine(cap)) {
builder.append(getSingleSlotHtml(s, icon));
}
builder.append("</p>");
}
return builder.toString();
}
// icon ( or generic html if icon not available )
private String getSingleSlotHtml(TestSlot s, String icon) {
StringBuilder builder = new StringBuilder();
TestSession session = s.getSession();
if (icon != null) {
builder.append("<img ");
builder.append("src='").append(icon).append("' width='16' height='16'");
} else {
builder.append("<a href='#' ");
}
if (session != null) {
builder.append(" class='busy' ");
builder.append(" title='").append(session.get("lastCommand")).append("' ");
} else {
builder.append(" title='").append(s.getCapabilities()).append("'");
}
if (icon != null) {
builder.append(" />\n");
} else {
builder.append(">");
builder.append(s.getCapabilities().get(CapabilityType.BROWSER_NAME));
builder.append("</a>");
}
return builder.toString();
}
// the tabs header.
private String nodeTabs() {
StringBuilder builder = new StringBuilder();
builder.append("<div class='tabs'>");
builder.append("<ul>");
builder
.append("<li class='tab' type='browsers'><a title='test slots' href='#'>Browsers</a></li>");
builder
.append("<li class='tab' type='config'><a title='node configuration' href='#'>Configuration</a></li>");
builder.append("</ul>");
builder.append("</div>");
return builder.toString();
}
/**
* return the platform for the proxy. It should be the same for all slots of the proxy, so checking that.
* @return Either the platform name, "Unknown", "mixed OS", or "not specified".
*/
public static String getPlatform(RemoteProxy proxy) {
Platform res = null;
if (proxy.getTestSlots().size() == 0) {
return "Unknown";
} else {
res = getPlatform(proxy.getTestSlots().get(0));
}
for (TestSlot slot : proxy.getTestSlots()) {
Platform tmp = getPlatform(slot);
if (tmp != res) {
return "mixed OS";
} else {
res = tmp;
}
}
if (res == null) {
return "not specified";
} else {
return res.toString();
}
}
private static Platform getPlatform(TestSlot slot) {
Object o = slot.getCapabilities().get(CapabilityType.PLATFORM);
if (o == null) {
return Platform.ANY;
} else {
if (o instanceof String) {
return Platform.valueOf((String) o);
} else if (o instanceof Platform) {
return (Platform) o;
} else {
throw new GridException("Cannot cast " + o + " to org.openqa.selenium.Platform");
}
}
}
}
| apache-2.0 |
mdaniel/intellij-community | python/src/com/jetbrains/python/run/PyRemoteProcessStarterManager.java | 2568 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.run;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.jetbrains.python.remote.PyRemotePathMapper;
import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* For anything but plain code execution consider introducing a separate
* extension point with implementations for different
* {@link com.intellij.remote.CredentialsType} using
* {@link PyRemoteSdkAdditionalDataBase#switchOnConnectionType(com.intellij.remote.ext.CredentialsCase[])}.
*
* @see PyRemoteProcessStarterManagerUtil
*/
public interface PyRemoteProcessStarterManager {
ExtensionPointName<PyRemoteProcessStarterManager> EP_NAME = ExtensionPointName.create("Pythonid.remoteProcessStarterManager");
boolean supports(@NotNull PyRemoteSdkAdditionalDataBase sdkAdditionalData);
@NotNull
ProcessHandler startRemoteProcess(@Nullable Project project,
@NotNull GeneralCommandLine commandLine,
@NotNull PyRemoteSdkAdditionalDataBase sdkAdditionalData,
@NotNull PyRemotePathMapper pathMapper) throws ExecutionException, InterruptedException;
@NotNull
ProcessOutput executeRemoteProcess(@Nullable Project project,
String @NotNull [] command,
@Nullable String workingDir,
@NotNull PyRemoteSdkAdditionalDataBase sdkAdditionalData,
@NotNull PyRemotePathMapper pathMapper) throws ExecutionException, InterruptedException;
}
| apache-2.0 |
graben1437/titan1.0.1.kafka | titan-core/src/main/java/com/thinkaurelius/titan/graphdb/types/indextype/MixedIndexTypeWrapper.java | 2017 | package com.thinkaurelius.titan.graphdb.types.indextype;
import com.google.common.collect.Iterables;
import com.thinkaurelius.titan.core.schema.Parameter;
import com.thinkaurelius.titan.core.PropertyKey;
import com.thinkaurelius.titan.graphdb.types.*;
import org.apache.tinkerpop.gremlin.structure.Direction;
/**
* @author Matthias Broecheler (me@matthiasb.com)
*/
public class MixedIndexTypeWrapper extends IndexTypeWrapper implements MixedIndexType {
public static final String NAME_PREFIX = "extindex";
public MixedIndexTypeWrapper(SchemaSource base) {
super(base);
}
@Override
public boolean isCompositeIndex() {
return false;
}
@Override
public boolean isMixedIndex() {
return true;
}
ParameterIndexField[] fields = null;
@Override
public ParameterIndexField[] getFieldKeys() {
ParameterIndexField[] result = fields;
if (result==null) {
Iterable<SchemaSource.Entry> entries = base.getRelated(TypeDefinitionCategory.INDEX_FIELD,Direction.OUT);
int numFields = Iterables.size(entries);
result = new ParameterIndexField[numFields];
int pos = 0;
for (SchemaSource.Entry entry : entries) {
assert entry.getSchemaType() instanceof PropertyKey;
assert entry.getModifier() instanceof Parameter[];
result[pos++]=ParameterIndexField.of((PropertyKey)entry.getSchemaType(),(Parameter[])entry.getModifier());
}
fields = result;
}
assert result!=null;
return result;
}
@Override
public ParameterIndexField getField(PropertyKey key) {
return (ParameterIndexField)super.getField(key);
}
@Override
public void resetCache() {
super.resetCache();
fields = null;
}
@Override
public String getStoreName() {
return base.getDefinition().getValue(TypeDefinitionCategory.INDEXSTORE_NAME,String.class);
}
}
| apache-2.0 |
reiaaoyama/contrail-controller | src/api-lib/java/test/net/juniper/contrail/api/ObjectReferenceTest.java | 4367 | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
package net.juniper.contrail.api;
import java.util.List;
import java.util.UUID;
import net.juniper.contrail.api.types.NetworkIpam;
import net.juniper.contrail.api.types.Project;
import net.juniper.contrail.api.types.SubnetType;
import net.juniper.contrail.api.types.VirtualMachineInterface;
import net.juniper.contrail.api.types.VirtualNetwork;
import net.juniper.contrail.api.types.VnSubnetsType;
import net.juniper.contrail.api.types.VnSubnetsType.IpamSubnetType;
import junit.framework.TestCase;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class ObjectReferenceTest extends TestCase {
/**
* API server requires the attr element in an ObjectReference to be present, even when null.
*/
@Test
public void testNullAttr() {
VirtualMachineInterface vmi = new VirtualMachineInterface();
VirtualNetwork vn = new VirtualNetwork();
vn.setName("testnet");
vn.setUuid(UUID.randomUUID().toString());
vmi.setName("x-0");
vmi.setVirtualNetwork(vn);
String jsdata = ApiSerializer.serializeObject("virtual-machine-interface", vmi);
assertNotSame(jsdata, -1, jsdata.indexOf("\"attr\":null"));
}
@Test
public void testAttr() {
VirtualNetwork vn = new VirtualNetwork();
vn.setName("testnet");
NetworkIpam ipam = new NetworkIpam();
ipam.setName("testipam");
VnSubnetsType subnets = new VnSubnetsType();
subnets.addIpamSubnets(new VnSubnetsType.IpamSubnetType(new SubnetType("192.168.0.0", 24), "192.168.0.254", null, UUID.randomUUID().toString(), false, null, null, false, null, null, vn.getName() + "-subnet"));
vn.setNetworkIpam(ipam, subnets);
String jsdata = ApiSerializer.serializeObject("virtual-network", vn);
assertNotSame(jsdata, -1, jsdata.indexOf("192.168.0.0"));
final JsonParser parser = new JsonParser();
final JsonObject js_obj = parser.parse(jsdata).getAsJsonObject();
final JsonElement element = js_obj.get("virtual-network");
VirtualNetwork result = (VirtualNetwork) ApiSerializer.deserialize(element.toString(), VirtualNetwork.class);
List<IpamSubnetType> iplist = result.getNetworkIpam().get(0).attr.getIpamSubnets();
assertSame(1, iplist.size());
assertEquals("192.168.0.0", iplist.get(0).getSubnet().getIpPrefix());
}
@Test
public void testVoidReference() {
String voidref = "{\"network_policys\": [{\"to\": [\"default-domain\", \"testProject\", \"testPolicy\"], \"href\": \"http://localhost:53730/network-policy/4e4b0486-e56f-4bfe-8716-afc1a76ad106\", \"uuid\": \"4e4b0486-e56f-4bfe-8716-afc1a76ad106\"}]}";
final JsonParser parser = new JsonParser();
final JsonObject js_obj = parser.parse(voidref).getAsJsonObject();
final JsonElement element = js_obj.get("network_policys");
JsonArray items = element.getAsJsonArray();
JsonElement item = items.get(0);
Gson json = ApiSerializer.getDeserializer();
ObjectReference<?> result = json.fromJson(item.toString(), ObjectReference.class);
assertNotNull(result);
assertEquals("testPolicy", result.to.get(2));
}
@Test
/**
* API generator adds an "s" at the end of the children name. Thus "network-policy" becomes "network-policys".
*/
public void testVoidAttrType() {
String content = "{\"project\": {\"network_policys\": [{\"to\": [\"default-domain\", \"testProject\", \"testPolicy\"], \"href\": \"http://localhost:53730/network-policy/4e4b0486-e56f-4bfe-8716-afc1a76ad106\", \"uuid\": \"4e4b0486-e56f-4bfe-8716-afc1a76ad106\"}], \"fq_name\": [\"default-domain\", \"testProject\"], \"uuid\": \"7a6580ac-d7dc-4363-a342-47a473a32884\"}}";
final JsonParser parser = new JsonParser();
final JsonObject js_obj = parser.parse(content).getAsJsonObject();
final JsonElement element = js_obj.get("project");
Project result = (Project) ApiSerializer.deserialize(element.toString(), Project.class);
assertEquals("testProject", result.getName());
assertNotNull(result.getNetworkPolicys());
}
}
| apache-2.0 |
aldian/tensorflow | tensorflow/core/distributed_runtime/rpc/grpc_master_service.cc | 12840 | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// GrpcMasterService implements the RPC service MasterService.
//
// A GrpcMasterService maintains the state of live graph computation
// sessions, each session orchestrates both local and remote devices
// to carry out the graph computation.
//
// A GrpcMasterService knows ahead of time local devices available as
// client devices.
//
// A GrpcMasterService discovers remote devices in the background and
// keeps track of statistics of those remote devices.
//
// Each session analyzes the graph, places nodes across available
// devices, and ultimately drives the graph computation by initiating
// RunGraph on workers.
#include "tensorflow/core/distributed_runtime/rpc/grpc_master_service.h"
#include "grpcpp/alarm.h"
#include "grpcpp/server_builder.h"
#include "tensorflow/core/distributed_runtime/master.h"
#include "tensorflow/core/distributed_runtime/rpc/async_service_interface.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_call.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_master_service_impl.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/tracing.h"
#include "tensorflow/core/profiler/lib/traceme.h"
#include "tensorflow/core/protobuf/master.pb.h"
namespace tensorflow {
class GrpcMasterService : public AsyncServiceInterface {
public:
GrpcMasterService(Master* master, const ConfigProto& default_session_config,
::grpc::ServerBuilder* builder)
: master_impl_(master),
is_shutdown_(false),
default_session_config_(default_session_config) {
builder->RegisterService(&master_service_);
cq_ = builder->AddCompletionQueue();
}
~GrpcMasterService() override { delete shutdown_alarm_; }
void Shutdown() override {
bool did_shutdown = false;
{
mutex_lock l(mu_);
if (!is_shutdown_) {
LOG(INFO) << "Shutting down GrpcMasterService.";
is_shutdown_ = true;
did_shutdown = true;
}
}
if (did_shutdown) {
// NOTE(mrry): This enqueues a special event (with a null tag)
// that causes the completion queue to be shut down on the
// polling thread.
shutdown_alarm_ =
new ::grpc::Alarm(cq_.get(), gpr_now(GPR_CLOCK_MONOTONIC), nullptr);
}
}
// This macro creates a new request for the given RPC method name
// (e.g., `ENQUEUE_REQUEST(RunStep);`), and enqueues it on
// `this->cq_`.
//
// This macro is invoked one or more times for each RPC method to
// ensure that there are sufficient completion queue entries to
// handle incoming requests without blocking.
//
// The implementation of the request handler for each RPC method
// must ensure that it calls ENQUEUE_REQUEST() for that RPC method,
// to keep accepting new requests.
#define ENQUEUE_REQUEST(method, supports_cancel) \
do { \
mutex_lock l(mu_); \
if (!is_shutdown_) { \
Call<GrpcMasterService, grpc::MasterService::AsyncService, \
method##Request, method##Response>:: \
EnqueueRequest(&master_service_, cq_.get(), \
&grpc::MasterService::AsyncService::Request##method, \
&GrpcMasterService::method##Handler, \
(supports_cancel)); \
} \
} while (0)
void HandleRPCsLoop() override {
ENQUEUE_REQUEST(CreateSession, true);
ENQUEUE_REQUEST(ExtendSession, false);
for (int i = 0; i < 100; ++i) {
ENQUEUE_REQUEST(PartialRunSetup, false);
ENQUEUE_REQUEST(RunStep, true);
}
ENQUEUE_REQUEST(CloseSession, false);
ENQUEUE_REQUEST(ListDevices, false);
ENQUEUE_REQUEST(Reset, false);
ENQUEUE_REQUEST(MakeCallable, false);
for (int i = 0; i < 100; ++i) {
ENQUEUE_REQUEST(RunCallable, true);
}
ENQUEUE_REQUEST(ReleaseCallable, false);
void* tag;
bool ok;
while (cq_->Next(&tag, &ok)) {
UntypedCall<GrpcMasterService>::Tag* callback_tag =
static_cast<UntypedCall<GrpcMasterService>::Tag*>(tag);
if (callback_tag) {
callback_tag->OnCompleted(this, ok);
} else {
// NOTE(mrry): A null `callback_tag` indicates that this is
// the shutdown alarm.
cq_->Shutdown();
}
}
}
private:
Master* master_impl_ = nullptr; // Not owned.
std::unique_ptr<::grpc::ServerCompletionQueue> cq_;
grpc::MasterService::AsyncService master_service_;
mutex mu_;
bool is_shutdown_ TF_GUARDED_BY(mu_);
const ConfigProto default_session_config_;
::grpc::Alarm* shutdown_alarm_ = nullptr;
template <class RequestMessage, class ResponseMessage>
using MasterCall = Call<GrpcMasterService, grpc::MasterService::AsyncService,
RequestMessage, ResponseMessage>;
// RPC handler for creating a session.
void CreateSessionHandler(
MasterCall<CreateSessionRequest, CreateSessionResponse>* call) {
CreateSessionRequest* rewritten_req = new CreateSessionRequest;
rewritten_req->mutable_config()->MergeFrom(default_session_config_);
rewritten_req->MergeFrom(call->request);
master_impl_->CreateSession(rewritten_req, &call->response,
[call, rewritten_req](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
delete rewritten_req;
});
ENQUEUE_REQUEST(CreateSession, true);
}
// RPC handler for extending a session.
void ExtendSessionHandler(
MasterCall<ExtendSessionRequest, ExtendSessionResponse>* call) {
master_impl_->ExtendSession(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(ExtendSession, false);
}
// RPC handler for setting up a partial run call.
void PartialRunSetupHandler(
MasterCall<PartialRunSetupRequest, PartialRunSetupResponse>* call) {
master_impl_->PartialRunSetup(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(PartialRunSetup, false);
}
// RPC handler for running one step in a session.
void RunStepHandler(MasterCall<RunStepRequest, RunStepResponse>* call) {
auto* trace = TraceRpc("RunStep/Server", call->client_metadata());
CallOptions* call_opts = new CallOptions;
if (call->request.options().timeout_in_ms() > 0) {
call_opts->SetTimeout(call->request.options().timeout_in_ms());
} else {
call_opts->SetTimeout(default_session_config_.operation_timeout_in_ms());
}
RunStepRequestWrapper* wrapped_request =
new ProtoRunStepRequest(&call->request);
MutableRunStepResponseWrapper* wrapped_response =
new NonOwnedProtoRunStepResponse(&call->response);
call->SetCancelCallback([call_opts]() { call_opts->StartCancel(); });
master_impl_->RunStep(
call_opts, wrapped_request, wrapped_response,
[call, call_opts, wrapped_request, trace](const Status& status) {
call->ClearCancelCallback();
delete call_opts;
delete wrapped_request;
delete trace;
if (call->request.store_errors_in_response_body() && !status.ok()) {
call->response.set_status_code(status.code());
call->response.set_status_error_message(status.error_message());
call->SendResponse(ToGrpcStatus(Status::OK()));
} else {
call->SendResponse(ToGrpcStatus(status));
}
});
ENQUEUE_REQUEST(RunStep, true);
}
// RPC handler for deleting a session.
void CloseSessionHandler(
MasterCall<CloseSessionRequest, CloseSessionResponse>* call) {
master_impl_->CloseSession(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(CloseSession, false);
}
// RPC handler for listing devices.
void ListDevicesHandler(
MasterCall<ListDevicesRequest, ListDevicesResponse>* call) {
master_impl_->ListDevices(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(ListDevices, false);
}
// RPC handler for resetting all sessions.
void ResetHandler(MasterCall<ResetRequest, ResetResponse>* call) {
master_impl_->Reset(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(Reset, false);
}
// RPC handler for making a callable.
void MakeCallableHandler(
MasterCall<MakeCallableRequest, MakeCallableResponse>* call) {
master_impl_->MakeCallable(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(MakeCallable, false);
}
// RPC handler for running a callable.
void RunCallableHandler(
MasterCall<RunCallableRequest, RunCallableResponse>* call) {
auto* trace = TraceRpc("RunCallable/Server", call->client_metadata());
CallOptions* call_opts = new CallOptions;
// The timeout may be overridden by a non-zero timeout in the
// callable's `RunOptions`; this overriding will happen inside the
// `MasterSession` implementation.
call_opts->SetTimeout(default_session_config_.operation_timeout_in_ms());
call->SetCancelCallback([call_opts]() { call_opts->StartCancel(); });
master_impl_->RunCallable(call_opts, &call->request, &call->response,
[call, call_opts, trace](const Status& status) {
call->ClearCancelCallback();
delete call_opts;
delete trace;
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(RunCallable, false);
}
// RPC handler for making a callable.
void ReleaseCallableHandler(
MasterCall<ReleaseCallableRequest, ReleaseCallableResponse>* call) {
master_impl_->ReleaseCallable(&call->request, &call->response,
[call](const Status& status) {
call->SendResponse(ToGrpcStatus(status));
});
ENQUEUE_REQUEST(ReleaseCallable, false);
}
#undef ENQUEUE_REQUEST
// Start tracing, including the ID attached to the RPC.
profiler::TraceMe* TraceRpc(
StringPiece name,
const std::multimap<::grpc::string_ref, ::grpc::string_ref>& metadata) {
StringPiece id;
auto it = metadata.find(GrpcIdKey());
if (it != metadata.end()) {
id = StringPiece(it->second.data(), it->second.size());
}
return new profiler::TraceMe([&] { return strings::StrCat(name, ":", id); },
profiler::TraceMeLevel::kInfo);
}
TF_DISALLOW_COPY_AND_ASSIGN(GrpcMasterService);
};
AsyncServiceInterface* NewGrpcMasterService(
Master* master, const ConfigProto& default_session_config,
::grpc::ServerBuilder* builder) {
return new GrpcMasterService(master, default_session_config, builder);
}
} // end namespace tensorflow
| apache-2.0 |
haikuowuya/api_demos | src/com/example/android/apis/app/PresentationActivity.java | 18444 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.apis.app;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Presentation;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.hardware.display.DisplayManager;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.Creator;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/**
* <h3>Presentation Activity</h3>
*
* <p>
* This demonstrates how to create an activity that shows some content
* on a secondary display using a {@link Presentation}.
* </p><p>
* The activity uses the {@link DisplayManager} API to enumerate displays.
* When the user selects a display, the activity opens a {@link Presentation}
* on that display. We show a different photograph in each presentation
* on a unique background along with a label describing the display.
* We also write information about displays and display-related events to
* the Android log which you can read using <code>adb logcat</code>.
* </p><p>
* You can try this out using an HDMI or Wifi display or by using the
* "Simulate secondary displays" feature in Development Settings to create a few
* simulated secondary displays. Each display will appear in the list along with a
* checkbox to show a presentation on that display.
* </p><p>
* See also the {@link PresentationWithMediaRouterActivity} sample which
* uses the media router to automatically select a secondary display
* on which to show content based on the currently selected route.
* </p>
*/
public class PresentationActivity extends Activity
implements OnCheckedChangeListener, OnClickListener {
private final String TAG = "PresentationActivity";
// Key for storing saved instance state.
private static final String PRESENTATION_KEY = "presentation";
// The content that we want to show on the presentation.
private static final int[] PHOTOS = new int[] {
R.drawable.frantic,
R.drawable.photo1, R.drawable.photo2, R.drawable.photo3,
R.drawable.photo4, R.drawable.photo5, R.drawable.photo6,
R.drawable.sample_4,
};
private DisplayManager mDisplayManager;
private DisplayListAdapter mDisplayListAdapter;
private CheckBox mShowAllDisplaysCheckbox;
private ListView mListView;
private int mNextImageNumber;
// List of presentation contents indexed by displayId.
// This state persists so that we can restore the old presentation
// contents when the activity is paused or resumed.
private SparseArray<PresentationContents> mSavedPresentationContents;
// List of all currently visible presentations indexed by display id.
private final SparseArray<DemoPresentation> mActivePresentations =
new SparseArray<DemoPresentation>();
/**
* Initialization of the Activity after it is first created. Must at least
* call {@link android.app.Activity#setContentView setContentView()} to
* describe what is to be displayed in the screen.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// Restore saved instance state.
if (savedInstanceState != null) {
mSavedPresentationContents =
savedInstanceState.getSparseParcelableArray(PRESENTATION_KEY);
} else {
mSavedPresentationContents = new SparseArray<PresentationContents>();
}
// Get the display manager service.
mDisplayManager = (DisplayManager)getSystemService(Context.DISPLAY_SERVICE);
// See assets/res/any/layout/presentation_activity.xml for this
// view layout definition, which is being set here as
// the content of our screen.
setContentView(R.layout.presentation_activity);
// Set up checkbox to toggle between showing all displays or only presentation displays.
mShowAllDisplaysCheckbox = (CheckBox)findViewById(R.id.show_all_displays);
mShowAllDisplaysCheckbox.setOnCheckedChangeListener(this);
// Set up the list of displays.
mDisplayListAdapter = new DisplayListAdapter(this);
mListView = (ListView)findViewById(R.id.display_list);
mListView.setAdapter(mDisplayListAdapter);
}
@Override
protected void onResume() {
// Be sure to call the super class.
super.onResume();
// Update our list of displays on resume.
mDisplayListAdapter.updateContents();
// Restore presentations from before the activity was paused.
final int numDisplays = mDisplayListAdapter.getCount();
for (int i = 0; i < numDisplays; i++) {
final Display display = mDisplayListAdapter.getItem(i);
final PresentationContents contents =
mSavedPresentationContents.get(display.getDisplayId());
if (contents != null) {
showPresentation(display, contents);
}
}
mSavedPresentationContents.clear();
// Register to receive events from the display manager.
mDisplayManager.registerDisplayListener(mDisplayListener, null);
}
@Override
protected void onPause() {
// Be sure to call the super class.
super.onPause();
// Unregister from the display manager.
mDisplayManager.unregisterDisplayListener(mDisplayListener);
// Dismiss all of our presentations but remember their contents.
Log.d(TAG, "Activity is being paused. Dismissing all active presentation.");
for (int i = 0; i < mActivePresentations.size(); i++) {
DemoPresentation presentation = mActivePresentations.valueAt(i);
int displayId = mActivePresentations.keyAt(i);
mSavedPresentationContents.put(displayId, presentation.mContents);
presentation.dismiss();
}
mActivePresentations.clear();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// Be sure to call the super class.
super.onSaveInstanceState(outState);
outState.putSparseParcelableArray(PRESENTATION_KEY, mSavedPresentationContents);
}
/**
* Shows a {@link Presentation} on the specified display.
*/
private void showPresentation(Display display, PresentationContents contents) {
final int displayId = display.getDisplayId();
if (mActivePresentations.get(displayId) != null) {
return;
}
Log.d(TAG, "Showing presentation photo #" + contents.photo
+ " on display #" + displayId + ".");
DemoPresentation presentation = new DemoPresentation(this, display, contents);
presentation.show();
presentation.setOnDismissListener(mOnDismissListener);
mActivePresentations.put(displayId, presentation);
}
/**
* Hides a {@link Presentation} on the specified display.
*/
private void hidePresentation(Display display) {
final int displayId = display.getDisplayId();
DemoPresentation presentation = mActivePresentations.get(displayId);
if (presentation == null) {
return;
}
Log.d(TAG, "Dismissing presentation on display #" + displayId + ".");
presentation.dismiss();
mActivePresentations.delete(displayId);
}
private int getNextPhoto() {
final int photo = mNextImageNumber;
mNextImageNumber = (mNextImageNumber + 1) % PHOTOS.length;
return photo;
}
/**
* Called when the show all displays checkbox is toggled or when
* an item in the list of displays is checked or unchecked.
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView == mShowAllDisplaysCheckbox) {
// Show all displays checkbox was toggled.
mDisplayListAdapter.updateContents();
} else {
// Display item checkbox was toggled.
final Display display = (Display)buttonView.getTag();
if (isChecked) {
PresentationContents contents = new PresentationContents(getNextPhoto());
showPresentation(display, contents);
} else {
hidePresentation(display);
}
}
}
/**
* Called when the Info button next to a display is clicked to show information
* about the display.
*/
@Override
public void onClick(View v) {
Context context = v.getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final Display display = (Display)v.getTag();
Resources r = context.getResources();
AlertDialog alert = builder
.setTitle(r.getString(
R.string.presentation_alert_info_text, display.getDisplayId()))
.setMessage(display.toString())
.setNeutralButton(R.string.presentation_alert_dismiss_text,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create();
alert.show();
}
/**
* Listens for displays to be added, changed or removed.
* We use it to update the list and show a new {@link Presentation} when a
* display is connected.
*
* Note that we don't bother dismissing the {@link Presentation} when a
* display is removed, although we could. The presentation API takes care
* of doing that automatically for us.
*/
private final DisplayManager.DisplayListener mDisplayListener =
new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {
Log.d(TAG, "Display #" + displayId + " added.");
mDisplayListAdapter.updateContents();
}
@Override
public void onDisplayChanged(int displayId) {
Log.d(TAG, "Display #" + displayId + " changed.");
mDisplayListAdapter.updateContents();
}
@Override
public void onDisplayRemoved(int displayId) {
Log.d(TAG, "Display #" + displayId + " removed.");
mDisplayListAdapter.updateContents();
}
};
/**
* Listens for when presentations are dismissed.
*/
private final DialogInterface.OnDismissListener mOnDismissListener =
new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
DemoPresentation presentation = (DemoPresentation)dialog;
int displayId = presentation.getDisplay().getDisplayId();
Log.d(TAG, "Presentation on display #" + displayId + " was dismissed.");
mActivePresentations.delete(displayId);
mDisplayListAdapter.notifyDataSetChanged();
}
};
/**
* List adapter.
* Shows information about all displays.
*/
private final class DisplayListAdapter extends ArrayAdapter<Display> {
final Context mContext;
public DisplayListAdapter(Context context) {
super(context, R.layout.presentation_list_item);
mContext = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final View v;
if (convertView == null) {
v = ((Activity) mContext).getLayoutInflater().inflate(
R.layout.presentation_list_item, null);
} else {
v = convertView;
}
final Display display = getItem(position);
final int displayId = display.getDisplayId();
CheckBox cb = (CheckBox)v.findViewById(R.id.checkbox_presentation);
cb.setTag(display);
cb.setOnCheckedChangeListener(PresentationActivity.this);
cb.setChecked(mActivePresentations.indexOfKey(displayId) >= 0
|| mSavedPresentationContents.indexOfKey(displayId) >= 0);
TextView tv = (TextView)v.findViewById(R.id.display_id);
tv.setText(v.getContext().getResources().getString(
R.string.presentation_display_id_text, displayId, display.getName()));
Button b = (Button)v.findViewById(R.id.info);
b.setTag(display);
b.setOnClickListener(PresentationActivity.this);
return v;
}
/**
* Update the contents of the display list adapter to show
* information about all current displays.
*/
public void updateContents() {
clear();
String displayCategory = getDisplayCategory();
Display[] displays = mDisplayManager.getDisplays(displayCategory);
addAll(displays);
Log.d(TAG, "There are currently " + displays.length + " displays connected.");
for (Display display : displays) {
Log.d(TAG, " " + display);
}
}
private String getDisplayCategory() {
return mShowAllDisplaysCheckbox.isChecked() ? null :
DisplayManager.DISPLAY_CATEGORY_PRESENTATION;
}
}
/**
* The presentation to show on the secondary display.
*
* Note that the presentation display may have different metrics from the display on which
* the main activity is showing so we must be careful to use the presentation's
* own {@link Context} whenever we load resources.
*/
private final class DemoPresentation extends Presentation {
final PresentationContents mContents;
public DemoPresentation(Context context, Display display, PresentationContents contents) {
super(context, display);
mContents = contents;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
// Get the resources for the context of the presentation.
// Notice that we are getting the resources from the context of the presentation.
Resources r = getContext().getResources();
// Inflate the layout.
setContentView(R.layout.presentation_content);
final Display display = getDisplay();
final int displayId = display.getDisplayId();
final int photo = mContents.photo;
// Show a caption to describe what's going on.
TextView text = (TextView)findViewById(R.id.text);
text.setText(r.getString(R.string.presentation_photo_text,
photo, displayId, display.getName()));
// Show a n image for visual interest.
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(r.getDrawable(PHOTOS[photo]));
GradientDrawable drawable = new GradientDrawable();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setGradientType(GradientDrawable.RADIAL_GRADIENT);
// Set the background to a random gradient.
Point p = new Point();
getDisplay().getSize(p);
drawable.setGradientRadius(Math.max(p.x, p.y) / 2);
drawable.setColors(mContents.colors);
findViewById(android.R.id.content).setBackground(drawable);
}
}
/**
* Information about the content we want to show in a presentation.
*/
private final static class PresentationContents implements Parcelable {
final int photo;
final int[] colors;
public static final Creator<PresentationContents> CREATOR =
new Creator<PresentationContents>() {
@Override
public PresentationContents createFromParcel(Parcel in) {
return new PresentationContents(in);
}
@Override
public PresentationContents[] newArray(int size) {
return new PresentationContents[size];
}
};
public PresentationContents(int photo) {
this.photo = photo;
colors = new int[] {
((int) (Math.random() * Integer.MAX_VALUE)) | 0xFF000000,
((int) (Math.random() * Integer.MAX_VALUE)) | 0xFF000000 };
}
private PresentationContents(Parcel in) {
photo = in.readInt();
colors = new int[] { in.readInt(), in.readInt() };
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(photo);
dest.writeInt(colors[0]);
dest.writeInt(colors[1]);
}
}
}
| apache-2.0 |
baifendian/sqoop | src/java/org/apache/sqoop/mapreduce/db/DBConfiguration.java | 16264 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sqoop.mapreduce.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrTokenizer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.sqoop.mapreduce.DBWritable;
import com.cloudera.sqoop.mapreduce.db.DBInputFormat.NullDBWritable;
/**
* A container for configuration property names for jobs with DB input/output.
*
* The job can be configured using the static methods in this class,
* {@link DBInputFormat}, and {@link DBOutputFormat}.
* Alternatively, the properties can be set in the configuration with proper
* values.
*
* @see DBConfiguration#configureDB(Configuration, String, String, String,
* String)
* @see DBInputFormat#setInput(Job, Class, String, String)
* @see DBInputFormat#setInput(Job, Class, String, String, String, String...)
* @see DBOutputFormat#setOutput(Job, String, String...)
*/
public class DBConfiguration {
public static final Log LOG =
LogFactory.getLog(DBConfiguration.class.getName());
/** The JDBC Driver class name. */
public static final String DRIVER_CLASS_PROPERTY =
"mapreduce.jdbc.driver.class";
/** JDBC Database access URL. */
public static final String URL_PROPERTY = "mapreduce.jdbc.url";
/** User name to access the database. */
public static final String USERNAME_PROPERTY = "mapreduce.jdbc.username";
/** Password to access the database. */
public static final String PASSWORD_PROPERTY = "mapreduce.jdbc.password";
private static final Text PASSWORD_SECRET_KEY =
new Text(DBConfiguration.PASSWORD_PROPERTY);
/** JDBC connection parameters. */
public static final String CONNECTION_PARAMS_PROPERTY =
"mapreduce.jdbc.params";
/** Fetch size. */
public static final String FETCH_SIZE = "mapreduce.jdbc.fetchsize";
/** Input table name. */
public static final String INPUT_TABLE_NAME_PROPERTY =
"mapreduce.jdbc.input.table.name";
/** Field names in the Input table. */
public static final String INPUT_FIELD_NAMES_PROPERTY =
"mapreduce.jdbc.input.field.names";
/** WHERE clause in the input SELECT statement. */
public static final String INPUT_CONDITIONS_PROPERTY =
"mapreduce.jdbc.input.conditions";
/** ORDER BY clause in the input SELECT statement. */
public static final String INPUT_ORDER_BY_PROPERTY =
"mapreduce.jdbc.input.orderby";
/** Whole input query, exluding LIMIT...OFFSET. */
public static final String INPUT_QUERY = "mapreduce.jdbc.input.query";
/** Input query to get the count of records. */
public static final String INPUT_COUNT_QUERY =
"mapreduce.jdbc.input.count.query";
/** Input query to get the max and min values of the jdbc.input.query. */
public static final String INPUT_BOUNDING_QUERY =
"mapred.jdbc.input.bounding.query";
/** Class name implementing DBWritable which will hold input tuples. */
public static final String INPUT_CLASS_PROPERTY =
"mapreduce.jdbc.input.class";
/** Output table name. */
public static final String OUTPUT_TABLE_NAME_PROPERTY =
"mapreduce.jdbc.output.table.name";
/** Field names in the Output table. */
public static final String OUTPUT_FIELD_NAMES_PROPERTY =
"mapreduce.jdbc.output.field.names";
/** Number of fields in the Output table. */
public static final String OUTPUT_FIELD_COUNT_PROPERTY =
"mapreduce.jdbc.output.field.count";
/**
* The name of the parameter to use for making Isolation level to be
* read uncommitted by default for connections.
*/
public static final String PROP_RELAXED_ISOLATION =
"org.apache.sqoop.db.relaxedisolation";
/**
* Sets the DB access related fields in the {@link Configuration}.
* @param conf the configuration
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL
* @param userName DB access username
* @param passwd DB access passwd
* @param fetchSize DB fetch size
* @param connectionParams JDBC connection parameters
*/
public static void configureDB(Configuration conf, String driverClass,
String dbUrl, String userName, String passwd, Integer fetchSize,
Properties connectionParams) {
conf.set(DRIVER_CLASS_PROPERTY, driverClass);
conf.set(URL_PROPERTY, dbUrl);
if (userName != null) {
conf.set(USERNAME_PROPERTY, userName);
}
if (passwd != null) {
setPassword((JobConf) conf, passwd);
}
if (fetchSize != null) {
conf.setInt(FETCH_SIZE, fetchSize);
}
if (connectionParams != null) {
conf.set(CONNECTION_PARAMS_PROPERTY,
propertiesToString(connectionParams));
}
}
// set the password in the secure credentials object
private static void setPassword(JobConf configuration, String password) {
LOG.debug("Securing password into job credentials store");
configuration.getCredentials().addSecretKey(
PASSWORD_SECRET_KEY, password.getBytes());
}
/**
* Sets the DB access related fields in the JobConf.
* @param job the job
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL
* @param fetchSize DB fetch size
* @param connectionParams JDBC connection parameters
*/
public static void configureDB(Configuration job, String driverClass,
String dbUrl, Integer fetchSize, Properties connectionParams) {
configureDB(job, driverClass, dbUrl, null, null, fetchSize,
connectionParams);
}
/**
* Sets the DB access related fields in the {@link Configuration}.
* @param conf the configuration
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL
* @param userName DB access username
* @param passwd DB access passwd
* @param connectionParams JDBC connection parameters
*/
public static void configureDB(Configuration conf, String driverClass,
String dbUrl, String userName, String passwd,
Properties connectionParams) {
configureDB(conf, driverClass, dbUrl, userName, passwd, null,
connectionParams);
}
/**
* Sets the DB access related fields in the JobConf.
* @param job the job
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL.
* @param connectionParams JDBC connection parameters
*/
public static void configureDB(Configuration job, String driverClass,
String dbUrl, Properties connectionParams) {
configureDB(job, driverClass, dbUrl, null, connectionParams);
}
/**
* Sets the DB access related fields in the {@link Configuration}.
* @param conf the configuration
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL
* @param userName DB access username
* @param passwd DB access passwd
* @param fetchSize DB fetch size
*/
public static void configureDB(Configuration conf, String driverClass,
String dbUrl, String userName, String passwd, Integer fetchSize) {
configureDB(conf, driverClass, dbUrl, userName, passwd, fetchSize,
(Properties) null);
}
/**
* Sets the DB access related fields in the JobConf.
* @param job the job
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL
* @param fetchSize DB fetch size
*/
public static void configureDB(Configuration job, String driverClass,
String dbUrl, Integer fetchSize) {
configureDB(job, driverClass, dbUrl, fetchSize, (Properties) null);
}
/**
* Sets the DB access related fields in the {@link Configuration}.
* @param conf the configuration
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL
* @param userName DB access username
* @param passwd DB access passwd
*/
public static void configureDB(Configuration conf, String driverClass,
String dbUrl, String userName, String passwd) {
configureDB(conf, driverClass, dbUrl, userName, passwd, (Properties) null);
}
/**
* Sets the DB access related fields in the JobConf.
* @param job the job
* @param driverClass JDBC Driver class name
* @param dbUrl JDBC DB access URL.
*/
public static void configureDB(Configuration job, String driverClass,
String dbUrl) {
configureDB(job, driverClass, dbUrl, (Properties) null);
}
private Configuration conf;
public DBConfiguration(Configuration job) {
this.conf = job;
}
/** Returns a connection object to the DB.
* @throws ClassNotFoundException
* @throws SQLException */
public Connection getConnection()
throws ClassNotFoundException, SQLException {
Connection connection;
Class.forName(conf.get(DBConfiguration.DRIVER_CLASS_PROPERTY));
String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
String password = getPassword((JobConf) conf);
String connectString = conf.get(DBConfiguration.URL_PROPERTY);
String connectionParamsStr =
conf.get(DBConfiguration.CONNECTION_PARAMS_PROPERTY);
Properties connectionParams = propertiesFromString(connectionParamsStr);
if (connectionParams != null && connectionParams.size() > 0) {
Properties props = new Properties();
if (username != null) {
props.put("user", username);
}
if (password != null) {
props.put("password", password);
}
props.putAll(connectionParams);
connection = DriverManager.getConnection(connectString, props);
} else {
if (username == null) {
connection = DriverManager.getConnection(connectString);
} else {
connection = DriverManager.getConnection(
connectString, username, password);
}
}
return connection;
}
// retrieve the password from the credentials object
public static String getPassword(JobConf configuration) {
LOG.debug("Fetching password from job credentials store");
byte[] secret = configuration.getCredentials().getSecretKey(
PASSWORD_SECRET_KEY);
return secret != null ? new String(secret) : null;
}
public Configuration getConf() {
return conf;
}
public Integer getFetchSize() {
if (conf.get(DBConfiguration.FETCH_SIZE) == null) {
return null;
}
return conf.getInt(DBConfiguration.FETCH_SIZE, 0);
}
public void setFetchSize(Integer fetchSize) {
if (fetchSize != null) {
conf.setInt(DBConfiguration.FETCH_SIZE, fetchSize);
} else {
conf.set(FETCH_SIZE, null);
}
}
public String getInputTableName() {
return conf.get(DBConfiguration.INPUT_TABLE_NAME_PROPERTY);
}
public void setInputTableName(String tableName) {
conf.set(DBConfiguration.INPUT_TABLE_NAME_PROPERTY, tableName);
}
public String[] getInputFieldNames() {
return conf.getStrings(DBConfiguration.INPUT_FIELD_NAMES_PROPERTY);
}
public void setInputFieldNames(String... fieldNames) {
conf.setStrings(DBConfiguration.INPUT_FIELD_NAMES_PROPERTY, fieldNames);
}
public String getInputConditions() {
return conf.get(DBConfiguration.INPUT_CONDITIONS_PROPERTY);
}
public void setInputConditions(String conditions) {
if (conditions != null && conditions.length() > 0) {
conf.set(DBConfiguration.INPUT_CONDITIONS_PROPERTY, conditions);
}
}
public String getInputOrderBy() {
return conf.get(DBConfiguration.INPUT_ORDER_BY_PROPERTY);
}
public void setInputOrderBy(String orderby) {
if (orderby != null && orderby.length() >0) {
conf.set(DBConfiguration.INPUT_ORDER_BY_PROPERTY, orderby);
}
}
public String getInputQuery() {
return conf.get(DBConfiguration.INPUT_QUERY);
}
public void setInputQuery(String query) {
if (query != null && query.length() >0) {
conf.set(DBConfiguration.INPUT_QUERY, query);
}
}
public String getInputCountQuery() {
return conf.get(DBConfiguration.INPUT_COUNT_QUERY);
}
public void setInputCountQuery(String query) {
if (query != null && query.length() > 0) {
conf.set(DBConfiguration.INPUT_COUNT_QUERY, query);
}
}
public void setInputBoundingQuery(String query) {
if (query != null && query.length() > 0) {
conf.set(DBConfiguration.INPUT_BOUNDING_QUERY, query);
}
}
public String getInputBoundingQuery() {
return conf.get(DBConfiguration.INPUT_BOUNDING_QUERY);
}
public Class<?> getInputClass() {
return conf.getClass(DBConfiguration.INPUT_CLASS_PROPERTY,
NullDBWritable.class);
}
public void setInputClass(Class<? extends DBWritable> inputClass) {
conf.setClass(DBConfiguration.INPUT_CLASS_PROPERTY, inputClass,
DBWritable.class);
}
public String getOutputTableName() {
return conf.get(DBConfiguration.OUTPUT_TABLE_NAME_PROPERTY);
}
public void setOutputTableName(String tableName) {
conf.set(DBConfiguration.OUTPUT_TABLE_NAME_PROPERTY, tableName);
}
public String[] getOutputFieldNames() {
return conf.getStrings(DBConfiguration.OUTPUT_FIELD_NAMES_PROPERTY);
}
public void setOutputFieldNames(String... fieldNames) {
conf.setStrings(DBConfiguration.OUTPUT_FIELD_NAMES_PROPERTY, fieldNames);
}
public void setOutputFieldCount(int fieldCount) {
conf.setInt(DBConfiguration.OUTPUT_FIELD_COUNT_PROPERTY, fieldCount);
}
public int getOutputFieldCount() {
return conf.getInt(OUTPUT_FIELD_COUNT_PROPERTY, 0);
}
/**
* Converts connection properties to a String to be passed to the mappers.
* @param properties JDBC connection parameters
* @return String to be passed to configuration
*/
protected static String propertiesToString(Properties properties) {
List<String> propertiesList = new ArrayList<String>(properties.size());
for(Entry<Object, Object> property : properties.entrySet()) {
String key = StringEscapeUtils.escapeCsv(property.getKey().toString());
if (key.equals(property.getKey().toString()) && key.contains("=")) {
key = "\"" + key + "\"";
}
String val = StringEscapeUtils.escapeCsv(property.getValue().toString());
if (val.equals(property.getValue().toString()) && val.contains("=")) {
val = "\"" + val + "\"";
}
propertiesList.add(StringEscapeUtils.escapeCsv(key + "=" + val));
}
return StringUtils.join(propertiesList, ',');
}
/**
* Converts a String back to connection parameters.
* @param input String from configuration
* @return JDBC connection parameters
*/
protected static Properties propertiesFromString(String input) {
if (input != null && !input.isEmpty()) {
Properties result = new Properties();
StrTokenizer propertyTokenizer = StrTokenizer.getCSVInstance(input);
StrTokenizer valueTokenizer = StrTokenizer.getCSVInstance();
valueTokenizer.setDelimiterChar('=');
while (propertyTokenizer.hasNext()){
valueTokenizer.reset(propertyTokenizer.nextToken());
String[] values = valueTokenizer.getTokenArray();
if (values.length==2) {
result.put(values[0], values[1]);
}
}
return result;
} else {
return null;
}
}
}
| apache-2.0 |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaEditorTextFieldBorder.java | 4369 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.laf.darcula.ui;
import com.intellij.ide.ui.laf.VisualPaddingsProvider;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.FocusChangeListener;
import com.intellij.ui.ComponentUtil;
import com.intellij.ui.EditorTextField;
import com.intellij.util.ui.JBInsets;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.MacUIUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import static com.intellij.ide.ui.laf.darcula.DarculaUIUtil.*;
/**
* @author Konstantin Bulenkov
*/
public class DarculaEditorTextFieldBorder extends DarculaTextBorder implements VisualPaddingsProvider {
public DarculaEditorTextFieldBorder() {
this(null, null);
}
public DarculaEditorTextFieldBorder(EditorTextField editorTextField, EditorEx editor) {
if (editorTextField != null && editor != null) {
editor.addFocusListener(new FocusChangeListener() {
@Override
public void focusGained(@NotNull Editor editor) {
editorTextField.repaint();
}
@Override
public void focusLost(@NotNull Editor editor) {
editorTextField.repaint();
}
});
}
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
if (isComboBoxEditor(c)) {
g.setColor(c.getBackground());
g.fillRect(x, y, width, height);
return;
}
EditorTextField editorTextField = ComponentUtil.getParentOfType((Class<? extends EditorTextField>)EditorTextField.class, c);
if (editorTextField == null) return;
boolean hasFocus = editorTextField.getFocusTarget().hasFocus();
Rectangle r = new Rectangle(x, y, width, height);
if (isTableCellEditor(c)) {
paintCellEditorBorder((Graphics2D)g, c, r, hasFocus);
}
else {
Graphics2D g2 = (Graphics2D)g.create();
try {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
MacUIUtil.USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE);
if (c.isOpaque()) {
g2.setColor(UIUtil.getPanelBackground());
g2.fill(r);
}
JBInsets.removeFrom(r, JBUI.insets(1));
g2.translate(r.x, r.y);
float lw = lw(g2);
float bw = bw();
Shape outer = new Rectangle2D.Float(bw, bw, r.width - bw * 2, r.height - bw * 2);
g2.setColor(c.getBackground());
g2.fill(outer);
Object op = editorTextField.getClientProperty("JComponent.outline");
if (editorTextField.isEnabled() && op != null) {
paintOutlineBorder(g2, r.width, r.height, 0, true, hasFocus, Outline.valueOf(op.toString()));
}
else if (editorTextField.isEnabled() && editorTextField.isVisible()) {
if (hasFocus) {
paintOutlineBorder(g2, r.width, r.height, 0, true, true, Outline.focus);
}
Path2D border = new Path2D.Float(Path2D.WIND_EVEN_ODD);
border.append(outer, false);
border.append(new Rectangle2D.Float(bw + lw, bw + lw, r.width - (bw + lw) * 2, r.height - (bw + lw) * 2), false);
g2.setColor(getOutlineColor(editorTextField.isEnabled(), hasFocus));
g2.fill(border);
}
}
finally {
g2.dispose();
}
}
}
@Override
public Insets getBorderInsets(Component c) {
return isTableCellEditor(c) || isCompact(c) || isComboBoxEditor(c) ?
JBInsets.create(2, 3).asUIResource() : JBInsets.create(6, 8).asUIResource();
}
@Override
public boolean isBorderOpaque() {
return true;
}
public static boolean isComboBoxEditor(Component c) {
return ComponentUtil.getParentOfType((Class<? extends JComboBox>)JComboBox.class, c) != null;
}
@Nullable
@Override
public Insets getVisualPaddings(@NotNull Component component) {
return JBUI.insets(3);
}
}
| apache-2.0 |
sdmcraft/sling | bundles/api/src/main/java/org/apache/sling/api/request/RequestParameter.java | 4583 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.api.request;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import aQute.bnd.annotation.ProviderType;
/**
* The <code>RequestParameter</code> class represents a single parameter sent
* with the client request. Instances of this class are returned by the
* {@link org.apache.sling.api.SlingHttpServletRequest#getRequestParameter(String)},
* {@link org.apache.sling.api.SlingHttpServletRequest#getRequestParameters(String)} and
* {@link org.apache.sling.api.SlingHttpServletRequest#getRequestParameterMap()} method.
*
* @see org.apache.sling.api.SlingHttpServletRequest#getRequestParameter(String)
* @see org.apache.sling.api.SlingHttpServletRequest#getRequestParameters(String)
* @see org.apache.sling.api.SlingHttpServletRequest#getRequestParameterMap()
*/
@ProviderType
public interface RequestParameter {
/**
* @return the name of this {@code RequestParameter}
* @since 2.4 (Sling API Bundle 2.6)
*/
@Nonnull String getName();
/**
* Determines whether or not this instance represents a simple form field or
* an uploaded file.
*
* @return <code>true</code> if the instance represents a simple form
* field; <code>false</code> if it represents an uploaded file.
*/
boolean isFormField();
/**
* Returns the content type passed by the browser or <code>null</code> if
* not defined.
*
* @return The content type passed by the browser or <code>null</code> if
* not defined.
*/
@CheckForNull String getContentType();
/**
* Returns the size in bytes of the parameter.
*
* @return The size in bytes of the parameter.
*/
long getSize();
/**
* Returns the contents of the parameter as an array of bytes.
*
* @return The contents of the parameter as an array of bytes.
*/
byte[] get();
/**
* Returns an InputStream that can be used to retrieve the contents of the
* file.
* <p>
* Each call to this method returns a new {@code InputStream} to the
* request parameter data. Make sure to close the stream to prevent
* leaking resources.
*
* @return An InputStream that can be used to retrieve the contents of the
* file.
* @throws IOException if an error occurs.
*/
@CheckForNull InputStream getInputStream() throws IOException;
/**
* Returns the original filename in the client's filesystem, as provided by
* the browser (or other client software). In most cases, this will be the
* base file name, without path information. However, some clients, such as
* the Opera browser, do include path information.
*
* @return The original filename in the client's filesystem.
*/
@CheckForNull String getFileName();
/**
* Returns the contents of the parameter as a String, using the default
* character encoding. This method uses {@link #get()} to retrieve the
* contents of the item.
*
* @return The contents of the parameter, as a string.
*/
@Nonnull String getString();
/**
* Returns the contents of the parameter as a String, using the specified
* encoding. This method uses link {@link #get()} to retrieve the contents
* of the item.
*
* @param encoding The character encoding to use.
* @return The contents of the parameter, as a string.
* @throws UnsupportedEncodingException if the requested character encoding
* is not available.
*/
@Nonnull String getString(@Nonnull String encoding) throws UnsupportedEncodingException;
}
| apache-2.0 |
freebsd/phabricator | src/applications/phame/storage/PhameBlogTransaction.php | 1374 | <?php
final class PhameBlogTransaction
extends PhabricatorModularTransaction {
const MAILTAG_DETAILS = 'phame-blog-details';
const MAILTAG_SUBSCRIBERS = 'phame-blog-subscribers';
const MAILTAG_OTHER = 'phame-blog-other';
public function getApplicationName() {
return 'phame';
}
public function getApplicationTransactionType() {
return PhabricatorPhameBlogPHIDType::TYPECONST;
}
public function getBaseTransactionClass() {
return 'PhameBlogTransactionType';
}
public function getMailTags() {
$tags = parent::getMailTags();
switch ($this->getTransactionType()) {
case PhabricatorTransactions::TYPE_SUBSCRIBERS:
$tags[] = self::MAILTAG_SUBSCRIBERS;
break;
case PhameBlogNameTransaction::TRANSACTIONTYPE:
case PhameBlogSubtitleTransaction::TRANSACTIONTYPE:
case PhameBlogDescriptionTransaction::TRANSACTIONTYPE:
case PhameBlogFullDomainTransaction::TRANSACTIONTYPE:
case PhameBlogParentSiteTransaction::TRANSACTIONTYPE:
case PhameBlogParentDomainTransaction::TRANSACTIONTYPE:
case PhameBlogProfileImageTransaction::TRANSACTIONTYPE:
case PhameBlogHeaderImageTransaction::TRANSACTIONTYPE:
$tags[] = self::MAILTAG_DETAILS;
break;
default:
$tags[] = self::MAILTAG_OTHER;
break;
}
return $tags;
}
}
| apache-2.0 |
pvorb/spring-boot | spring-boot/src/main/java/org/springframework/boot/origin/SystemEnvironmentOrigin.java | 1780 | /*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.origin;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
/**
* {@link Origin} for an item loaded from the system environment. Provides access to the
* original property name.
*
* @author Madhura Bhave
* @since 2.0.0
*/
public class SystemEnvironmentOrigin implements Origin {
private final String property;
public SystemEnvironmentOrigin(String property) {
Assert.notNull(property, "Property name must not be null");
Assert.hasText(property, "Property name must not be empty");
this.property = property;
}
public String getProperty() {
return this.property;
}
@Override
public String toString() {
return "System Environment Property \"" + this.property + "\"";
}
@Override
public int hashCode() {
return ObjectUtils.nullSafeHashCode(this.property);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SystemEnvironmentOrigin other = (SystemEnvironmentOrigin) obj;
return ObjectUtils.nullSafeEquals(this.property, other.property);
}
}
| apache-2.0 |
heejaechang/roslyn | src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/ReturnStatementHighlighter.cs | 2552 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp)]
internal class ReturnStatementHighlighter : AbstractKeywordHighlighter<ReturnStatementSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ReturnStatementHighlighter()
{
}
protected override void AddHighlights(
ReturnStatementSyntax returnStatement, List<TextSpan> spans, CancellationToken cancellationToken)
{
var parent = returnStatement
.GetAncestorsOrThis<SyntaxNode>()
.FirstOrDefault(n => n.IsReturnableConstruct());
if (parent == null)
{
return;
}
HighlightRelatedKeywords(parent, spans);
}
/// <summary>
/// Finds all returns that are children of this node, and adds the appropriate spans to the spans list.
/// </summary>
private void HighlightRelatedKeywords(SyntaxNode node, List<TextSpan> spans)
{
switch (node)
{
case ReturnStatementSyntax statement:
spans.Add(statement.ReturnKeyword.Span);
spans.Add(EmptySpan(statement.SemicolonToken.Span.End));
break;
default:
foreach (var child in node.ChildNodesAndTokens())
{
if (child.IsToken)
continue;
// Only recurse if we have anything to do
if (!child.AsNode().IsReturnableConstruct())
HighlightRelatedKeywords(child.AsNode(), spans);
}
break;
}
}
}
}
| apache-2.0 |
alvinkwekel/camel | components/camel-cm-sms/src/main/java/org/apache/camel/component/cm/CMMessage.java | 4992 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.cm;
/**
* Valid message to be serialized and sent to CM Endpoints. If the message only uses GSM 7-bit characters, then 160
* characters will fit in 1 SMS part, and 153*n characters will fit in n SMS parts for n>1. If the message contains
* other characters, then only 70 characters will fit in 1 SMS part, and 67*n characters will fit in n SMS parts for
* n>1. <br>
* <br>
* {@link https://dashboard.onlinesmsgateway.com/docs} <br>
* {@link http://support.telerivet.com/customer/portal/articles/1957426-multipart-unicode-sms-messages}
*/
public class CMMessage {
/**
* Restrictions: 1 - 32 alphanumeric characters and reference will not work for demo accounts
*/
// TODO: use a ID generator?
private String idAsString;
private String phoneNumber;
private String message;
private String sender;
private boolean unicode;
private int multipart = 1;
public CMMessage(final String phoneNumber, final String message) {
this.message = message;
this.phoneNumber = phoneNumber;
}
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getSender() {
return sender;
}
public void setSender(final String sender) {
this.sender = sender;
}
public String getIdAsString() {
return idAsString;
}
public void setIdAsString(final String idAsString) {
this.idAsString = idAsString;
}
public boolean isUnicode() {
return unicode;
}
public void setUnicode(final boolean unicode) {
this.unicode = unicode;
}
public boolean isMultipart() {
return multipart > 1;
}
/**
* For a CMMessage instance
*
* @param defaultMaxNumberOfParts
*/
public void setUnicodeAndMultipart(int defaultMaxNumberOfParts) {
// Set UNICODE and MULTIPART
final String msg = getMessage();
if (CMUtils.isGsm0338Encodeable(msg)) {
// Not Unicode is Multipart?
if (msg.length() > CMConstants.MAX_GSM_MESSAGE_LENGTH) {
// Multiparts. 153 caracteres max per part
int parts = msg.length() / CMConstants.MAX_GSM_MESSAGE_LENGTH_PER_PART_IF_MULTIPART;
if (msg.length() % CMConstants.MAX_GSM_MESSAGE_LENGTH_PER_PART_IF_MULTIPART != 0) {
parts++;
}
setMultiparts((parts > defaultMaxNumberOfParts) ? defaultMaxNumberOfParts : parts);
} else { // Otherwise multipart = 1
setMultiparts(1);
}
} else {
// Unicode Message
setUnicode(true);
if (msg.length() > CMConstants.MAX_UNICODE_MESSAGE_LENGTH) {
// Multiparts. 67 caracteres max per part
int parts = msg.length() / CMConstants.MAX_UNICODE_MESSAGE_LENGTH_PER_PART_IF_MULTIPART;
if (msg.length() % CMConstants.MAX_UNICODE_MESSAGE_LENGTH_PER_PART_IF_MULTIPART != 0) {
parts++;
}
setMultiparts((parts > defaultMaxNumberOfParts) ? defaultMaxNumberOfParts : parts);
} else { // Otherwise multipart = 1
setMultiparts(1);
}
}
}
public void setMultiparts(final int multipart) {
this.multipart = multipart;
}
public int getMultiparts() {
return multipart;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(
" {phoneNumber: " + phoneNumber + ", message: " + message + ", sender=" + sender + ", unicode: " + unicode
+ ", multipart: " + multipart);
if (idAsString != null && !idAsString.isEmpty()) {
sb.append(", idAsString=" + idAsString);
}
sb.append(" }");
return sb.toString();
}
}
| apache-2.0 |
ErikSchierboom/roslyn | src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/ContainsGraphQuery.cs | 2908 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.Schemas;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
internal sealed class ContainsGraphQuery : IGraphQuery
{
public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken)
{
var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false);
var nodesToProcess = context.InputNodes;
for (var depth = 0; depth < context.LinkDepth; depth++)
{
// This is the list of nodes we created and will process
var newNodes = new HashSet<GraphNode>();
foreach (var node in nodesToProcess)
{
cancellationToken.ThrowIfCancellationRequested();
var symbol = graphBuilder.GetSymbol(node);
if (symbol != null)
{
foreach (var newSymbol in SymbolContainment.GetContainedSymbols(symbol))
{
cancellationToken.ThrowIfCancellationRequested();
var newNode = await graphBuilder.AddNodeAsync(newSymbol, relatedNode: node).ConfigureAwait(false);
graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode);
}
}
else if (node.HasCategory(CodeNodeCategories.File))
{
var document = graphBuilder.GetContextDocument(node);
if (document != null)
{
foreach (var newSymbol in await SymbolContainment.GetContainedSymbolsAsync(document, cancellationToken).ConfigureAwait(false))
{
cancellationToken.ThrowIfCancellationRequested();
var newNode = await graphBuilder.AddNodeAsync(newSymbol, relatedNode: node).ConfigureAwait(false);
graphBuilder.AddLink(node, GraphCommonSchema.Contains, newNode);
}
}
}
}
nodesToProcess = newNodes;
}
return graphBuilder;
}
}
}
| apache-2.0 |
jcouv/roslyn | src/Workspaces/Core/Portable/Shared/Extensions/INamespaceSymbolExtensions.cs | 7248 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static partial class INamespaceSymbolExtensions
{
private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap =
new ConditionalWeakTable<INamespaceSymbol, List<string>>();
private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>>.CreateValueCallback s_getNameParts = GetNameParts;
public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo;
public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer();
private static List<string> GetNameParts(INamespaceSymbol namespaceSymbol)
{
var result = new List<string>();
GetNameParts(namespaceSymbol, result);
return result;
}
private static void GetNameParts(INamespaceSymbol namespaceSymbol, List<string> result)
{
if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace)
{
return;
}
GetNameParts(namespaceSymbol.ContainingNamespace, result);
result.Add(namespaceSymbol.Name);
}
public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2)
{
var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts);
var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts);
for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++)
{
var comp = names1[i].CompareTo(names2[i]);
if (comp != 0)
{
return comp;
}
}
return names1.Count - names2.Count;
}
public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes(
this INamespaceSymbol namespaceSymbol,
CancellationToken cancellationToken)
{
var stack = new Stack<INamespaceOrTypeSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
if (current is INamespaceSymbol childNamespace)
{
stack.Push(childNamespace.GetMembers().AsEnumerable());
yield return childNamespace;
}
else
{
var child = (INamedTypeSymbol)current;
stack.Push(child.GetTypeMembers());
yield return child;
}
}
}
public static IEnumerable<INamedTypeSymbol> GetAllTypes(
this IEnumerable<INamespaceSymbol> namespaceSymbols,
CancellationToken cancellationToken)
{
return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken));
}
/// <summary>
/// Searches the namespace for namespaces with the provided name.
/// </summary>
public static IEnumerable<INamespaceSymbol> FindNamespaces(
this INamespaceSymbol namespaceSymbol,
string namespaceName,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var stack = new Stack<INamespaceSymbol>();
stack.Push(namespaceSymbol);
while (stack.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = stack.Pop();
var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>();
foreach (var child in matchingChildren)
{
yield return child;
}
stack.Push(current.GetNamespaceMembers());
}
}
public static bool ContainsAccessibleTypesOrNamespaces(
this INamespaceSymbol namespaceSymbol,
IAssemblySymbol assembly)
{
using (var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject())
{
return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object);
}
}
public static INamespaceSymbol GetQualifiedNamespace(
this INamespaceSymbol globalNamespace,
string namespaceName)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Count() == 1
? members.First() as INamespaceSymbol
: null;
if ((object)namespaceSymbol == null)
{
break;
}
}
return namespaceSymbol;
}
private static bool ContainsAccessibleTypesOrNamespacesWorker(
this INamespaceSymbol namespaceSymbol,
IAssemblySymbol assembly,
Queue<INamespaceOrTypeSymbol> namespaceQueue)
{
// Note: we only store INamespaceSymbols in here, even though we type it as
// INamespaceOrTypeSymbol. This is because when we call GetMembers below we
// want it to return an ImmutableArray so we don't incur any costs to iterate
// over it.
foreach (var constituent in namespaceSymbol.ConstituentNamespaces)
{
// Assume that any namespace in our own assembly is accessible to us. This saves a
// lot of cpu time checking namespaces.
if (constituent.ContainingAssembly == assembly)
{
return true;
}
namespaceQueue.Enqueue(constituent);
}
while (namespaceQueue.Count > 0)
{
var ns = namespaceQueue.Dequeue();
// Upcast so we call the 'GetMembers' method that returns an ImmutableArray.
ImmutableArray<ISymbol> members = ns.GetMembers();
foreach (var namespaceOrType in members)
{
if (namespaceOrType.Kind == SymbolKind.NamedType)
{
if (namespaceOrType.IsAccessibleWithin(assembly))
{
return true;
}
}
else
{
namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType);
}
}
}
return false;
}
}
}
| apache-2.0 |
praveev/druid | processing/src/main/java/io/druid/query/topn/InvertedTopNMetricSpec.java | 4315 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.query.topn;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.druid.java.util.common.guava.Comparators;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.PostAggregator;
import io.druid.query.dimension.DimensionSpec;
import org.joda.time.DateTime;
import java.nio.ByteBuffer;
import java.util.Comparator;
import java.util.List;
/**
*/
public class InvertedTopNMetricSpec implements TopNMetricSpec
{
private static final byte CACHE_TYPE_ID = 0x3;
private final TopNMetricSpec delegate;
@JsonCreator
public InvertedTopNMetricSpec(
@JsonProperty("metric") TopNMetricSpec delegate
)
{
this.delegate = delegate;
}
@Override
public void verifyPreconditions(
List<AggregatorFactory> aggregatorSpecs,
List<PostAggregator> postAggregatorSpecs
)
{
delegate.verifyPreconditions(aggregatorSpecs, postAggregatorSpecs);
}
@JsonProperty("metric")
public TopNMetricSpec getDelegate()
{
return delegate;
}
@Override
public Comparator getComparator(
final List<AggregatorFactory> aggregatorSpecs,
final List<PostAggregator> postAggregatorSpecs
)
{
return Comparators.inverse(
new Comparator()
{
@Override
public int compare(Object o1, Object o2)
{
// nulls last
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
return delegate.getComparator(aggregatorSpecs, postAggregatorSpecs).compare(o1, o2);
}
}
);
}
@Override
public TopNResultBuilder getResultBuilder(
DateTime timestamp,
DimensionSpec dimSpec,
int threshold,
Comparator comparator,
List<AggregatorFactory> aggFactories,
List<PostAggregator> postAggs
)
{
return delegate.getResultBuilder(
timestamp,
dimSpec,
threshold,
comparator,
aggFactories,
postAggs
);
}
@Override
public byte[] getCacheKey()
{
final byte[] cacheKey = delegate.getCacheKey();
return ByteBuffer.allocate(1 + cacheKey.length).put(CACHE_TYPE_ID).put(cacheKey).array();
}
@Override
public <T> TopNMetricSpecBuilder<T> configureOptimizer(TopNMetricSpecBuilder<T> builder)
{
if (!canBeOptimizedUnordered()) {
return builder;
}
return delegate.configureOptimizer(builder);
}
@Override
public void initTopNAlgorithmSelector(TopNAlgorithmSelector selector)
{
delegate.initTopNAlgorithmSelector(selector);
}
@Override
public String getMetricName(DimensionSpec dimSpec)
{
return delegate.getMetricName(dimSpec);
}
@Override
public boolean canBeOptimizedUnordered()
{
return delegate.canBeOptimizedUnordered();
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InvertedTopNMetricSpec that = (InvertedTopNMetricSpec) o;
if (delegate != null ? !delegate.equals(that.delegate) : that.delegate != null) {
return false;
}
return true;
}
@Override
public int hashCode()
{
return delegate != null ? delegate.hashCode() : 0;
}
@Override
public String toString()
{
return "InvertedTopNMetricSpec{" +
"delegate=" + delegate +
'}';
}
}
| apache-2.0 |
uschindler/elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/StartRollupJobAction.java | 4557 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.rollup.action;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.tasks.BaseTasksRequest;
import org.elasticsearch.action.support.tasks.BaseTasksResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.rollup.RollupField;
import java.io.IOException;
import java.util.Collections;
import java.util.Objects;
public class StartRollupJobAction extends ActionType<StartRollupJobAction.Response> {
public static final StartRollupJobAction INSTANCE = new StartRollupJobAction();
public static final String NAME = "cluster:admin/xpack/rollup/start";
private StartRollupJobAction() {
super(NAME, StartRollupJobAction.Response::new);
}
public static class Request extends BaseTasksRequest<Request> implements ToXContentObject {
private String id;
public Request(String id) {
this.id = ExceptionsHelper.requireNonNull(id, RollupField.ID.getPreferredName());
}
public Request() {}
public Request(StreamInput in) throws IOException {
super(in);
id = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(id);
}
public String getId() {
return id;
}
@Override
public ActionRequestValidationException validate() {
return null;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(RollupField.ID.getPreferredName(), id);
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Request other = (Request) obj;
return Objects.equals(id, other.id);
}
}
public static class RequestBuilder extends ActionRequestBuilder<Request, Response> {
protected RequestBuilder(ElasticsearchClient client, StartRollupJobAction action) {
super(client, action, new Request());
}
}
public static class Response extends BaseTasksResponse implements Writeable, ToXContentObject {
private final boolean started;
public Response(boolean started) {
super(Collections.emptyList(), Collections.emptyList());
this.started = started;
}
public Response(StreamInput in) throws IOException {
super(in);
started = in.readBoolean();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeBoolean(started);
}
public boolean isStarted() {
return started;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("started", started);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Response response = (Response) o;
return started == response.started;
}
@Override
public int hashCode() {
return Objects.hash(started);
}
}
}
| apache-2.0 |
kaushik94/react | fixtures/packaging/systemjs-builder/prod/config.js | 275 | System.config({
paths: {
react: '../../../../build/node_modules/react/umd/react.production.min.js',
'react-dom':
'../../../../build/node_modules/react-dom/umd/react-dom.production.min.js',
schedule: '../../../../build/dist/schedule.development',
},
});
| bsd-3-clause |
was4444/chromium.src | net/quic/congestion_control/rtt_stats_test.cc | 12025 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/quic/congestion_control/rtt_stats.h"
#include <vector>
#include "base/logging.h"
#include "base/test/mock_log.h"
#include "net/quic/test_tools/rtt_stats_peer.h"
#include "testing/gtest/include/gtest/gtest.h"
using logging::LOG_WARNING;
using std::vector;
using testing::HasSubstr;
using testing::Message;
using testing::_;
namespace net {
namespace test {
class RttStatsTest : public ::testing::Test {
protected:
RttStats rtt_stats_;
};
TEST_F(RttStatsTest, DefaultsBeforeUpdate) {
EXPECT_LT(0u, rtt_stats_.initial_rtt_us());
EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.smoothed_rtt());
}
TEST_F(RttStatsTest, SmoothedRtt) {
// Verify that ack_delay is corrected for in Smoothed RTT.
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
QuicTime::Delta::FromMilliseconds(100),
QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt());
// Verify that effective RTT of zero does not change Smoothed RTT.
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200),
QuicTime::Delta::FromMilliseconds(200),
QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt());
// Verify that large erroneous ack_delay does not change Smoothed RTT.
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200),
QuicTime::Delta::FromMilliseconds(300),
QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt());
}
TEST_F(RttStatsTest, MinRtt) {
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(200),
QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200),
rtt_stats_.recent_min_rtt());
rtt_stats_.UpdateRtt(
QuicTime::Delta::FromMilliseconds(10), QuicTime::Delta::Zero(),
QuicTime::Zero().Add(QuicTime::Delta::FromMilliseconds(10)));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.recent_min_rtt());
rtt_stats_.UpdateRtt(
QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(),
QuicTime::Zero().Add(QuicTime::Delta::FromMilliseconds(20)));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.recent_min_rtt());
rtt_stats_.UpdateRtt(
QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(),
QuicTime::Zero().Add(QuicTime::Delta::FromMilliseconds(30)));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.recent_min_rtt());
rtt_stats_.UpdateRtt(
QuicTime::Delta::FromMilliseconds(50), QuicTime::Delta::Zero(),
QuicTime::Zero().Add(QuicTime::Delta::FromMilliseconds(40)));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.recent_min_rtt());
// Verify that ack_delay does not go into recording of min_rtt_.
rtt_stats_.UpdateRtt(
QuicTime::Delta::FromMilliseconds(7),
QuicTime::Delta::FromMilliseconds(2),
QuicTime::Zero().Add(QuicTime::Delta::FromMilliseconds(50)));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(7), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(7), rtt_stats_.recent_min_rtt());
}
TEST_F(RttStatsTest, RecentMinRtt) {
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(10),
QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.recent_min_rtt());
rtt_stats_.SampleNewRecentMinRtt(4);
for (int i = 0; i < 3; ++i) {
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(50),
QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10),
rtt_stats_.recent_min_rtt());
}
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(50),
QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(50), rtt_stats_.recent_min_rtt());
}
TEST_F(RttStatsTest, WindowedRecentMinRtt) {
// Set the window to 99ms, so 25ms is more than a quarter rtt.
rtt_stats_.set_recent_min_rtt_window(QuicTime::Delta::FromMilliseconds(99));
QuicTime now = QuicTime::Zero();
QuicTime::Delta rtt_sample = QuicTime::Delta::FromMilliseconds(10);
rtt_stats_.UpdateRtt(rtt_sample, QuicTime::Delta::Zero(), now);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.recent_min_rtt());
// Gradually increase the rtt samples and ensure the recent_min_rtt starts
// rising.
for (int i = 0; i < 8; ++i) {
now = now.Add(QuicTime::Delta::FromMilliseconds(25));
rtt_sample = rtt_sample.Add(QuicTime::Delta::FromMilliseconds(10));
rtt_stats_.UpdateRtt(rtt_sample, QuicTime::Delta::Zero(), now);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(rtt_sample, RttStatsPeer::GetQuarterWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample.Subtract(QuicTime::Delta::FromMilliseconds(10)),
RttStatsPeer::GetHalfWindowRtt(&rtt_stats_));
if (i < 3) {
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10),
rtt_stats_.recent_min_rtt());
} else if (i < 5) {
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(30),
rtt_stats_.recent_min_rtt());
} else if (i < 7) {
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(50),
rtt_stats_.recent_min_rtt());
} else {
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(70),
rtt_stats_.recent_min_rtt());
}
}
// A new quarter rtt low sets that, but nothing else.
rtt_sample = rtt_sample.Subtract(QuicTime::Delta::FromMilliseconds(5));
rtt_stats_.UpdateRtt(rtt_sample, QuicTime::Delta::Zero(), now);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(rtt_sample, RttStatsPeer::GetQuarterWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample.Subtract(QuicTime::Delta::FromMilliseconds(5)),
RttStatsPeer::GetHalfWindowRtt(&rtt_stats_));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(70), rtt_stats_.recent_min_rtt());
// A new half rtt low sets that and the quarter rtt low.
rtt_sample = rtt_sample.Subtract(QuicTime::Delta::FromMilliseconds(15));
rtt_stats_.UpdateRtt(rtt_sample, QuicTime::Delta::Zero(), now);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(rtt_sample, RttStatsPeer::GetQuarterWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample, RttStatsPeer::GetHalfWindowRtt(&rtt_stats_));
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(70), rtt_stats_.recent_min_rtt());
// A new full window loss sets the recent_min_rtt, but not min_rtt.
rtt_sample = QuicTime::Delta::FromMilliseconds(65);
rtt_stats_.UpdateRtt(rtt_sample, QuicTime::Delta::Zero(), now);
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(10), rtt_stats_.min_rtt());
EXPECT_EQ(rtt_sample, RttStatsPeer::GetQuarterWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample, RttStatsPeer::GetHalfWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample, rtt_stats_.recent_min_rtt());
// A new all time low sets both the min_rtt and the recent_min_rtt.
rtt_sample = QuicTime::Delta::FromMilliseconds(5);
rtt_stats_.UpdateRtt(rtt_sample, QuicTime::Delta::Zero(), now);
EXPECT_EQ(rtt_sample, rtt_stats_.min_rtt());
EXPECT_EQ(rtt_sample, RttStatsPeer::GetQuarterWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample, RttStatsPeer::GetHalfWindowRtt(&rtt_stats_));
EXPECT_EQ(rtt_sample, rtt_stats_.recent_min_rtt());
}
TEST_F(RttStatsTest, ExpireSmoothedMetrics) {
QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(10);
rtt_stats_.UpdateRtt(initial_rtt, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt());
EXPECT_EQ(initial_rtt, rtt_stats_.recent_min_rtt());
EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt());
EXPECT_EQ(initial_rtt.Multiply(0.5), rtt_stats_.mean_deviation());
// Update once with a 20ms RTT.
QuicTime::Delta doubled_rtt = initial_rtt.Multiply(2);
rtt_stats_.UpdateRtt(doubled_rtt, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(initial_rtt.Multiply(1.125), rtt_stats_.smoothed_rtt());
// Expire the smoothed metrics, increasing smoothed rtt and mean deviation.
rtt_stats_.ExpireSmoothedMetrics();
EXPECT_EQ(doubled_rtt, rtt_stats_.smoothed_rtt());
EXPECT_EQ(initial_rtt.Multiply(0.875), rtt_stats_.mean_deviation());
// Now go back down to 5ms and expire the smoothed metrics, and ensure the
// mean deviation increases to 15ms.
QuicTime::Delta half_rtt = initial_rtt.Multiply(0.5);
rtt_stats_.UpdateRtt(half_rtt, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_GT(doubled_rtt, rtt_stats_.smoothed_rtt());
EXPECT_LT(initial_rtt, rtt_stats_.mean_deviation());
}
TEST_F(RttStatsTest, UpdateRttWithBadSendDeltas) {
// Make sure we ignore bad RTTs.
base::test::MockLog log;
QuicTime::Delta initial_rtt = QuicTime::Delta::FromMilliseconds(10);
rtt_stats_.UpdateRtt(initial_rtt, QuicTime::Delta::Zero(), QuicTime::Zero());
EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt());
EXPECT_EQ(initial_rtt, rtt_stats_.recent_min_rtt());
EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt());
vector<QuicTime::Delta> bad_send_deltas;
bad_send_deltas.push_back(QuicTime::Delta::Zero());
bad_send_deltas.push_back(QuicTime::Delta::Infinite());
bad_send_deltas.push_back(QuicTime::Delta::FromMicroseconds(-1000));
log.StartCapturingLogs();
for (QuicTime::Delta bad_send_delta : bad_send_deltas) {
SCOPED_TRACE(Message() << "bad_send_delta = "
<< bad_send_delta.ToMicroseconds());
EXPECT_CALL(log, Log(LOG_WARNING, _, _, _, HasSubstr("Ignoring")));
rtt_stats_.UpdateRtt(bad_send_delta, QuicTime::Delta::Zero(),
QuicTime::Zero());
EXPECT_EQ(initial_rtt, rtt_stats_.min_rtt());
EXPECT_EQ(initial_rtt, rtt_stats_.recent_min_rtt());
EXPECT_EQ(initial_rtt, rtt_stats_.smoothed_rtt());
}
}
TEST_F(RttStatsTest, ResetAfterConnectionMigrations) {
rtt_stats_.UpdateRtt(QuicTime::Delta::FromMilliseconds(300),
QuicTime::Delta::FromMilliseconds(100),
QuicTime::Zero());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.latest_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(200), rtt_stats_.smoothed_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::FromMilliseconds(300),
rtt_stats_.recent_min_rtt());
// Reset rtt stats on connection migrations.
rtt_stats_.OnConnectionMigration();
EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.latest_rtt());
EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.smoothed_rtt());
EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.min_rtt());
EXPECT_EQ(QuicTime::Delta::Zero(), rtt_stats_.recent_min_rtt());
}
} // namespace test
} // namespace net
| bsd-3-clause |
cato541265/orleans | src/Orleans/SystemTargetInterfaces/IRemoteGrainDirectory.cs | 8634 | /*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Orleans.Runtime
{
internal interface IActivationInfo
{
SiloAddress SiloAddress { get; }
DateTime TimeCreated { get; }
}
internal interface IGrainInfo
{
Dictionary<ActivationId, IActivationInfo> Instances { get; }
int VersionTag { get; }
bool SingleInstance { get; }
bool AddActivation(ActivationId act, SiloAddress silo);
ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo);
bool RemoveActivation(ActivationAddress addr);
bool RemoveActivation(ActivationId act, bool force);
bool Merge(GrainId grain, IGrainInfo other);
}
/// <summary>
/// Per-silo system interface for managing the distributed, partitioned grain-silo-activation directory.
/// </summary>
internal interface IRemoteGrainDirectory : ISystemTarget
{
/// <summary>
/// Record a new grain activation by adding it to the directory.
/// </summary>
/// <param name="address">The address of the new activation.</param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns>The version associated with this directory mapping.</returns>
Task<int> Register(ActivationAddress address, int retries = 0);
/// <summary>
/// Records a bunch of new grain activations.
/// </summary>
/// <param name="silo"></param>
/// <param name="addresses"></param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns></returns>
Task RegisterMany(List<ActivationAddress> addresses, int retries = 0);
/// <summary>
/// Registers a new activation, in single activation mode, with the directory service.
/// If there is already an activation registered for this grain, then the new activation will
/// not be registered and the address of the existing activation will be returned.
/// Otherwise, the passed-in address will be returned.
/// <para>This method must be called from a scheduler thread.</para>
/// </summary>
/// <param name="silo"></param>
/// <param name="address">The address of the potential new activation.</param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns>The address registered for the grain's single activation and the version associated with it.</returns>
Task<Tuple<ActivationAddress, int>> RegisterSingleActivation(ActivationAddress address, int retries = 0);
/// <summary>
/// Registers multiple new activations, in single activation mode, with the directory service.
/// If there is already an activation registered for any of the grains, then the corresponding new activation will
/// not be registered.
/// <para>This method must be called from a scheduler thread.</para>
/// </summary>
/// <param name="silo"></param>
/// <param name="addresses"></param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns></returns>
Task RegisterManySingleActivation(List<ActivationAddress> addresses, int retries = 0);
/// <summary>
/// Remove an activation from the directory.
/// </summary>
/// <param name="address">The address of the activation to unregister.</param>
/// <param name="force">If true, then the entry is removed; if false, then the entry is removed only if it is
/// sufficiently old.</param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns>Success</returns>
Task Unregister(ActivationAddress address, bool force, int retries = 0);
/// <summary>
/// Removes all directory information about a grain.
/// </summary>
/// <param name="grain">The ID of the grain to look up.</param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns></returns>
Task DeleteGrain(GrainId grain, int retries = 0);
/// <summary>
/// Fetch the list of the current activations for a grain along with the version number of the list.
/// </summary>
/// <param name="grain">The ID of the grain.</param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns></returns>
Task<Tuple<List<Tuple<SiloAddress, ActivationId>>, int>> LookUp(GrainId grain, int retries = 0);
/// <summary>
/// Fetch the updated information on the given list of grains.
/// This method should be called only remotely to refresh directory caches.
/// </summary>
/// <param name="grainAndETagList">list of grains and generation (version) numbers. The latter denote the versions of
/// the lists of activations currently held by the invoker of this method.</param>
/// <param name="retries">Number of retries to execute the method in case the virtual ring (servers) changes.</param>
/// <returns>list of tuples holding a grain, generation number of the list of activations, and the list of activations.
/// If the generation number of the invoker matches the number of the destination, the list is null. If the destination does not
/// hold the information on the grain, generation counter -1 is returned (and the list of activations is null)</returns>
Task<List<Tuple<GrainId, int, List<Tuple<SiloAddress, ActivationId>>>>> LookUpMany(List<Tuple<GrainId, int>> grainAndETagList, int retries = 0);
/// <summary>
/// Handoffs the the directory partition from source silo to the destination silo.
/// </summary>
/// <param name="source">The address of the owner of the partition.</param>
/// <param name="partition">The (full or partial) copy of the directory partition to be Haded off.</param>
/// <param name="isFullCopy">Flag specifying whether it is a full copy of the directory partition (and thus any old copy should be just replaced) or the
/// a delta copy (and thus the old copy should be updated by delta changes) </param>
/// <returns></returns>
Task AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy);
/// <summary>
/// Removes the handed off directory partition from source silo on the destination silo.
/// </summary>
/// <param name="source">The address of the owner of the partition.</param>
/// <returns></returns>
Task RemoveHandoffPartition(SiloAddress source);
/// <summary>
/// Unregister a block of addresses at once
/// </summary>
/// <param name="activationAddresses"></param>
/// <param name="retries"></param>
/// <returns></returns>
Task UnregisterMany(List<ActivationAddress> activationAddresses, int retries);
}
}
| mit |
c72578/poedit | deps/boost/libs/hana/benchmark/fold_left/compile.cexpr.unrolled.erb.cpp | 1064 | // Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/detail/variadic/foldl1.hpp>
template <typename ...xs>
struct list { };
template <typename T>
struct basic_type { using type = T; };
template <typename T>
constexpr basic_type<T> type{};
template <typename F, typename State, typename ...Xs>
constexpr auto foldl(F f, State s, list<Xs...> xs)
{ return boost::hana::detail::variadic::foldl(f, s, type<Xs>...); }
//////////////////////////////////////////////////////////////////////////////
struct f {
template <typename ...>
struct result { };
template <typename X, typename Y>
constexpr auto operator()(X, Y) const
{ return result<X, Y>{}; }
};
template <int> struct x { };
struct state { };
int main() {
constexpr auto xs = list<
<%= (1..input_size).map { |i| "x<#{i}>" }.join(', ') %>
>{};
constexpr auto result = foldl(f{}, state{}, xs);
(void)result;
}
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/jQuery.mmenu/4.1.1/js/addons/jquery.mmenu.header.js | 129 | version https://git-lfs.github.com/spec/v1
oid sha256:d6297e3df777d8dd1bc638a89d240ce4ed259283723e95b26151365a3b230a08
size 3559
| mit |
gjack/subscribem | db/migrate/20151123025701_create_subscribem_users.rb | 213 | class CreateSubscribemUsers < ActiveRecord::Migration
def change
create_table :subscribem_users do |t|
t.string :email
t.string :password_digest
t.timestamps null: false
end
end
end
| mit |
mikeycattell/benefit-housing-rebuild | node_modules/napa/node_modules/write-json-file/index.js | 1148 | 'use strict';
var path = require('path');
var fs = require('graceful-fs');
var writeFileAtomic = require('write-file-atomic');
var sortKeys = require('sort-keys');
var objectAssign = require('object-assign');
var mkdirp = require('mkdirp');
var Promise = require('pinkie-promise');
var pify = require('pify');
function main(fn, fp, data, opts) {
if (!fp) {
throw new TypeError('Expected a filepath');
}
if (data === undefined) {
throw new TypeError('Expected data to stringify');
}
opts = objectAssign({
indent: '\t',
sortKeys: false
}, opts);
if (opts.sortKeys) {
data = sortKeys(data, {
deep: true,
compare: typeof opts.sortKeys === 'function' && opts.sortKeys
});
}
var json = JSON.stringify(data, opts.replacer, opts.indent) + '\n';
return fn(fp, json, {mode: opts.mode});
}
module.exports = function (fp, data, opts) {
return pify(mkdirp, Promise)(path.dirname(fp), {fs: fs}).then(function () {
return main(pify(writeFileAtomic, Promise), fp, data, opts);
});
};
module.exports.sync = function (fp, data, opts) {
mkdirp.sync(path.dirname(fp), {fs: fs});
main(writeFileAtomic.sync, fp, data, opts);
};
| mit |
mikrotikAhmet/mbe-cpdev | app/code/core/Mage/XmlConnect/Block/Adminhtml/Template/Preview/Form.php | 2193 | <?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_XmlConnect
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Admin form widget
*
* @category Mage
* @package Mage_XmlConnect
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_XmlConnect_Block_Adminhtml_Template_Preview_Form extends Mage_Adminhtml_Block_Widget_Form
{
/**
* Preparing from for revision page
*
* @return Mage_XmlConnect_Block_Adminhtml_Template_Preview_Form
*/
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'id' => 'preview_form',
'action' => $this->getUrl('*/*/drop', array('_current' => true)),
'method' => 'post'
));
if ($data = $this->getTemplateFormData()) {
$mapper = array('preview_store_id' => 'store_id');
foreach ($data as $key => $value) {
if (array_key_exists($key, $mapper)) {
$name = $mapper[$key];
} else {
$name = $key;
}
$form->addField($key, 'hidden', array('name' => $name));
}
$form->setValues($data);
}
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
| mit |
EMostafaAli/mathnet-numerics | src/UnitTests/LinearAlgebraTests/Single/Factorization/EvdTests.cs | 9625 | // <copyright file="EvdTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Single;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Eigenvalues factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class EvdTests
{
[Test]
public void CanFactorizeIdentityMatrix([Values(1, 10, 100)] int order)
{
var matrix = Matrix<float>.Build.DenseIdentity(order);
var factorEvd = matrix.Evd();
var eigenValues = factorEvd.EigenValues;
var eigenVectors = factorEvd.EigenVectors;
var d = factorEvd.D;
Assert.AreEqual(matrix.RowCount, eigenVectors.RowCount);
Assert.AreEqual(matrix.RowCount, eigenVectors.ColumnCount);
Assert.AreEqual(matrix.ColumnCount, d.RowCount);
Assert.AreEqual(matrix.ColumnCount, d.ColumnCount);
for (var i = 0; i < eigenValues.Count; i++)
{
Assert.AreEqual(Complex.One, eigenValues[i]);
}
}
[Test]
public void CanFactorizeRandomSquareMatrix([Values(1, 2, 5, 10, 50, 100)] int order)
{
var A = Matrix<float>.Build.Random(order, order, 1);
var factorEvd = A.Evd();
var V = factorEvd.EigenVectors;
var λ = factorEvd.D;
Assert.AreEqual(order, V.RowCount);
Assert.AreEqual(order, V.ColumnCount);
Assert.AreEqual(order, λ.RowCount);
Assert.AreEqual(order, λ.ColumnCount);
// Verify A*V = λ*V
var Av = A * V;
var Lv = V * λ;
AssertHelpers.AlmostEqual(Av, Lv, 3);
}
[Test]
public void CanFactorizeRandomSymmetricMatrix([Values(1, 2, 5, 10, 50, 100)] int order)
{
var A = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
MatrixHelpers.ForceSymmetric(A);
var factorEvd = A.Evd();
var V = factorEvd.EigenVectors;
var λ = factorEvd.D;
Assert.AreEqual(order, V.RowCount);
Assert.AreEqual(order, V.ColumnCount);
Assert.AreEqual(order, λ.RowCount);
Assert.AreEqual(order, λ.ColumnCount);
// Verify A = V*λ*VT
var matrix = V * λ * V.Transpose();
AssertHelpers.AlmostEqual(matrix, A, 2);
AssertHelpers.AlmostEqualRelative(matrix, A, 0);
}
[Test]
public void CanCheckRankSquare([Values(10, 50, 100)] int order)
{
var A = Matrix<float>.Build.Random(order, order, 1);
Assert.AreEqual(A.Evd().Rank, order);
}
[Test]
public void CanCheckRankOfSquareSingular([Values(10, 50, 100)] int order)
{
var A = new DenseMatrix(order, order);
A[0, 0] = 1;
A[order - 1, order - 1] = 1;
for (var i = 1; i < order - 1; i++)
{
A[i, i - 1] = 1;
A[i, i + 1] = 1;
A[i - 1, i] = 1;
A[i + 1, i] = 1;
}
var factorEvd = A.Evd();
Assert.AreEqual(factorEvd.Determinant, 0);
Assert.AreEqual(factorEvd.Rank, order - 1);
}
[Test]
public void IdentityDeterminantIsOne([Values(1, 10, 100)] int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorEvd = matrixI.Evd();
Assert.AreEqual(1.0, factorEvd.Determinant);
}
/// <summary>
/// Can solve a system of linear equations for a random vector and symmetric matrix (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[Test]
public void CanSolveForRandomVectorAndSymmetricMatrix([Values(1, 2, 5, 10, 50, 100)] int order)
{
var A = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
MatrixHelpers.ForceSymmetric(A);
var ACopy = A.Clone();
var evd = A.Evd();
var b = Vector<float>.Build.Random(order, 2);
var bCopy = b.Clone();
var x = evd.Solve(b);
var bReconstruct = A * x;
// Check the reconstruction.
AssertHelpers.AlmostEqual(b, bReconstruct, -1);
// Make sure A/B didn't change.
AssertHelpers.AlmostEqual(ACopy, A, 14);
AssertHelpers.AlmostEqual(bCopy, b, 14);
}
/// <summary>
/// Can solve a system of linear equations for a random matrix and symmetric matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[Test]
public void CanSolveForRandomMatrixAndSymmetricMatrix([Values(1, 2, 5, 10, 50, 100)] int order)
{
var A = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
MatrixHelpers.ForceSymmetric(A);
var ACopy = A.Clone();
var evd = A.Evd();
var B = Matrix<float>.Build.Random(order, order, 2);
var BCopy = B.Clone();
var X = evd.Solve(B);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(A.ColumnCount, X.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(B.ColumnCount, X.ColumnCount);
var BReconstruct = A * X;
// Check the reconstruction.
AssertHelpers.AlmostEqual(B, BReconstruct, -1);
// Make sure A/B didn't change.
AssertHelpers.AlmostEqual(ACopy, A, 14);
AssertHelpers.AlmostEqual(BCopy, B, 14);
}
/// <summary>
/// Can solve a system of linear equations for a random vector and symmetric matrix (Ax=b) into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[Test]
public void CanSolveForRandomVectorAndSymmetricMatrixWhenResultVectorGiven([Values(1, 2, 5, 10, 50, 100)] int order)
{
var A = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
MatrixHelpers.ForceSymmetric(A);
var ACopy = A.Clone();
var evd = A.Evd();
var b = Vector<float>.Build.Random(order, 2);
var bCopy = b.Clone();
var x = new DenseVector(order);
evd.Solve(b, x);
var bReconstruct = A * x;
// Check the reconstruction.
AssertHelpers.AlmostEqual(b, bReconstruct, -1);
// Make sure A/B didn't change.
AssertHelpers.AlmostEqual(ACopy, A, 14);
AssertHelpers.AlmostEqual(bCopy, b, 14);
}
/// <summary>
/// Can solve a system of linear equations for a random matrix and symmetric matrix (AX=B) into result matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[Test]
public void CanSolveForRandomMatrixAndSymmetricMatrixWhenResultMatrixGiven([Values(1, 2, 5, 10, 50, 100)] int order)
{
var A = Matrix<float>.Build.RandomPositiveDefinite(order, 1);
MatrixHelpers.ForceSymmetric(A);
var ACopy = A.Clone();
var evd = A.Evd();
var B = Matrix<float>.Build.Random(order, order, 2);
var BCopy = B.Clone();
var X = new DenseMatrix(order, order);
evd.Solve(B, X);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(A.ColumnCount, X.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(B.ColumnCount, X.ColumnCount);
var BReconstruct = A * X;
// Check the reconstruction.
AssertHelpers.AlmostEqual(B, BReconstruct, -1);
// Make sure A/B didn't change.
AssertHelpers.AlmostEqual(ACopy, A, 14);
AssertHelpers.AlmostEqual(BCopy, B, 14);
}
}
}
| mit |
fabianoleittes/rails | railties/test/generators/generated_attribute_test.rb | 5545 | # frozen_string_literal: true
require "generators/generators_test_helper"
require "rails/generators/generated_attribute"
class GeneratedAttributeTest < Rails::Generators::TestCase
include GeneratorsTestHelper
def setup
@old_belongs_to_required_by_default = Rails.application.config.active_record.belongs_to_required_by_default
Rails.application.config.active_record.belongs_to_required_by_default = true
end
def teardown
Rails.application.config.active_record.belongs_to_required_by_default = @old_belongs_to_required_by_default
end
def test_field_type_returns_number_field
assert_field_type :integer, :number_field
end
def test_field_type_returns_text_field
%w(float decimal string).each do |attribute_type|
assert_field_type attribute_type, :text_field
end
end
def test_field_type_returns_datetime_select
%w(datetime timestamp).each do |attribute_type|
assert_field_type attribute_type, :datetime_select
end
end
def test_field_type_returns_time_select
assert_field_type :time, :time_select
end
def test_field_type_returns_date_select
assert_field_type :date, :date_select
end
def test_field_type_returns_text_area
assert_field_type :text, :text_area
end
def test_field_type_returns_check_box
assert_field_type :boolean, :check_box
end
def test_field_type_returns_rich_text_area
assert_field_type :rich_text, :rich_text_area
end
def test_field_type_returns_file_field
%w(attachment attachments).each do |attribute_type|
assert_field_type attribute_type, :file_field
end
end
def test_field_type_with_unknown_type_returns_text_field
%w(foo bar baz).each do |attribute_type|
assert_field_type attribute_type, :text_field
end
end
def test_default_value_is_integer
assert_field_default_value :integer, 1
end
def test_default_value_is_float
assert_field_default_value :float, 1.5
end
def test_default_value_is_decimal
assert_field_default_value :decimal, "9.99"
end
def test_default_value_is_datetime
%w(datetime timestamp time).each do |attribute_type|
assert_field_default_value attribute_type, Time.now.to_s(:db)
end
end
def test_default_value_is_date
assert_field_default_value :date, Date.today.to_s(:db)
end
def test_default_value_is_string
assert_field_default_value :string, "MyString"
end
def test_default_value_for_type
att = Rails::Generators::GeneratedAttribute.parse("type:string")
assert_equal("", att.default)
end
def test_default_value_is_text
assert_field_default_value :text, "MyText"
end
def test_default_value_is_boolean
assert_field_default_value :boolean, false
end
def test_default_value_is_nil
%w(references belongs_to rich_text attachment attachments).each do |attribute_type|
assert_field_default_value attribute_type, nil
end
end
def test_default_value_is_empty_string
%w(foo bar baz).each do |attribute_type|
assert_field_default_value attribute_type, ""
end
end
def test_human_name
assert_equal(
"Full name",
create_generated_attribute(:string, "full_name").human_name
)
end
def test_reference_is_true
%w(references belongs_to).each do |attribute_type|
assert_predicate create_generated_attribute(attribute_type), :reference?
end
end
def test_reference_is_false
%w(foo bar baz).each do |attribute_type|
assert_not_predicate create_generated_attribute(attribute_type), :reference?
end
end
def test_polymorphic_reference_is_true
%w(references belongs_to).each do |attribute_type|
assert_predicate create_generated_attribute("#{attribute_type}{polymorphic}"), :polymorphic?
end
end
def test_polymorphic_reference_is_false
%w(foo bar baz).each do |attribute_type|
assert_not_predicate create_generated_attribute("#{attribute_type}{polymorphic}"), :polymorphic?
end
end
def test_blank_type_defaults_to_string_raises_exception
assert_equal :string, create_generated_attribute(nil, "title").type
assert_equal :string, create_generated_attribute("", "title").type
end
def test_handles_index_names_for_references
assert_equal "post", create_generated_attribute("string", "post").index_name
assert_equal "post_id", create_generated_attribute("references", "post").index_name
assert_equal "post_id", create_generated_attribute("belongs_to", "post").index_name
assert_equal ["post_id", "post_type"], create_generated_attribute("references{polymorphic}", "post").index_name
end
def test_handles_column_names_for_references
assert_equal "post", create_generated_attribute("string", "post").column_name
assert_equal "post_id", create_generated_attribute("references", "post").column_name
assert_equal "post_id", create_generated_attribute("belongs_to", "post").column_name
end
def test_parse_required_attribute_with_index
att = Rails::Generators::GeneratedAttribute.parse("supplier:references:index")
assert_equal "supplier", att.name
assert_equal :references, att.type
assert_predicate att, :has_index?
assert_predicate att, :required?
end
def test_parse_required_attribute_with_index_false_when_belongs_to_required_by_default_global_config_is_false
Rails.application.config.active_record.belongs_to_required_by_default = false
att = Rails::Generators::GeneratedAttribute.parse("supplier:references:index")
assert_not_predicate att, :required?
end
end
| mit |
ViktorHofer/corefx | src/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Unary/IndexedWhereQueryOperator.cs | 8258 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// IndexedWhereQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// A variant of the Where operator that supplies element index while performing the
/// filtering operation. This requires cooperation with partitioning and merging to
/// guarantee ordering is preserved.
///
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
internal sealed class IndexedWhereQueryOperator<TInputOutput> : UnaryQueryOperator<TInputOutput, TInputOutput>
{
// Predicate function. Used to filter out non-matching elements during execution.
private readonly Func<TInputOutput, int, bool> _predicate;
private bool _prematureMerge = false; // Whether to prematurely merge the input of this operator.
private bool _limitsParallelism = false; // Whether this operator limits parallelism
//---------------------------------------------------------------------------------------
// Initializes a new where operator.
//
// Arguments:
// child - the child operator or data source from which to pull data
// predicate - a delegate representing the predicate function
//
// Assumptions:
// predicate must be non null.
//
internal IndexedWhereQueryOperator(IEnumerable<TInputOutput> child,
Func<TInputOutput, int, bool> predicate)
: base(child)
{
Debug.Assert(child != null, "child data source cannot be null");
Debug.Assert(predicate != null, "need a filter function");
_predicate = predicate;
// In an indexed Select, elements must be returned in the order in which
// indices were assigned.
_outputOrdered = true;
InitOrdinalIndexState();
}
private void InitOrdinalIndexState()
{
OrdinalIndexState childIndexState = Child.OrdinalIndexState;
if (ExchangeUtilities.IsWorseThan(childIndexState, OrdinalIndexState.Correct))
{
_prematureMerge = true;
_limitsParallelism = childIndexState != OrdinalIndexState.Shuffled;
}
SetOrdinalIndexState(OrdinalIndexState.Increasing);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TInputOutput> Open(
QuerySettings settings, bool preferStriping)
{
QueryResults<TInputOutput> childQueryResults = Child.Open(settings, preferStriping);
return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings)
{
int partitionCount = inputStream.PartitionCount;
// If the index is not correct, we need to reindex.
PartitionedStream<TInputOutput, int> inputStreamInt;
if (_prematureMerge)
{
ListQueryResults<TInputOutput> listResults = ExecuteAndCollectResults(inputStream, partitionCount, Child.OutputOrdered, preferStriping, settings);
inputStreamInt = listResults.GetPartitionedStream();
}
else
{
Debug.Assert(typeof(TKey) == typeof(int));
inputStreamInt = (PartitionedStream<TInputOutput, int>)(object)inputStream;
}
// Since the index is correct, the type of the index must be int
PartitionedStream<TInputOutput, int> outputStream =
new PartitionedStream<TInputOutput, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState);
for (int i = 0; i < partitionCount; i++)
{
outputStream[i] = new IndexedWhereQueryOperatorEnumerator(inputStreamInt[i], _predicate, settings.CancellationState.MergedCancellationToken);
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
return wrappedChild.Where(_predicate);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return _limitsParallelism; }
}
//-----------------------------------------------------------------------------------
// An enumerator that implements the filtering logic.
//
private class IndexedWhereQueryOperatorEnumerator : QueryOperatorEnumerator<TInputOutput, int>
{
private readonly QueryOperatorEnumerator<TInputOutput, int> _source; // The data source to enumerate.
private readonly Func<TInputOutput, int, bool> _predicate; // The predicate used for filtering.
private readonly CancellationToken _cancellationToken;
private Shared<int> _outputLoopCount;
//-----------------------------------------------------------------------------------
// Instantiates a new enumerator.
//
internal IndexedWhereQueryOperatorEnumerator(QueryOperatorEnumerator<TInputOutput, int> source, Func<TInputOutput, int, bool> predicate,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
Debug.Assert(predicate != null);
_source = source;
_predicate = predicate;
_cancellationToken = cancellationToken;
}
//-----------------------------------------------------------------------------------
// Moves to the next matching element in the underlying data stream.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey)
{
Debug.Assert(_predicate != null, "expected a compiled operator");
// Iterate through the input until we reach the end of the sequence or find
// an element matching the predicate.
if (_outputLoopCount == null)
_outputLoopCount = new Shared<int>(0);
while (_source.MoveNext(ref currentElement, ref currentKey))
{
if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
if (_predicate(currentElement, currentKey))
{
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
}
}
| mit |
fx2003/tensorflow-study | TensorFlow实战/models/compression/entropy_coder/all_models/all_models_test.py | 2447 | # Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Basic test of all registered models."""
import tensorflow as tf
# pylint: disable=unused-import
import all_models
# pylint: enable=unused-import
from entropy_coder.model import model_factory
class AllModelsTest(tf.test.TestCase):
def testBuildModelForTraining(self):
factory = model_factory.GetModelRegistry()
model_names = factory.GetAvailableModels()
for m in model_names:
tf.reset_default_graph()
global_step = tf.Variable(tf.zeros([], dtype=tf.int64),
trainable=False,
name='global_step')
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
batch_size = 3
height = 40
width = 20
depth = 5
binary_codes = tf.placeholder(dtype=tf.float32,
shape=[batch_size, height, width, depth])
# Create a model with the default configuration.
print('Creating model: {}'.format(m))
model = factory.CreateModel(m)
model.Initialize(global_step,
optimizer,
model.GetConfigStringForUnitTest())
self.assertTrue(model.loss is None, 'model: {}'.format(m))
self.assertTrue(model.train_op is None, 'model: {}'.format(m))
self.assertTrue(model.average_code_length is None, 'model: {}'.format(m))
# Build the Tensorflow graph corresponding to the model.
model.BuildGraph(binary_codes)
self.assertTrue(model.loss is not None, 'model: {}'.format(m))
self.assertTrue(model.average_code_length is not None,
'model: {}'.format(m))
if model.train_op is None:
print('Model {} is not trainable'.format(m))
if __name__ == '__main__':
tf.test.main()
| mit |
hungys/vscode | src/vs/editor/common/model/editStack.ts | 3995 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { onUnexpectedError } from 'vs/base/common/errors';
import { ICursorStateComputer, IEditableTextModel, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon';
import { Selection } from 'vs/editor/common/core/selection';
interface IEditOperation {
operations: IIdentifiedSingleEditOperation[];
}
interface IStackElement {
beforeVersionId: number;
beforeCursorState: Selection[];
editOperations: IEditOperation[];
afterCursorState: Selection[];
afterVersionId: number;
}
export interface IUndoRedoResult {
selections: Selection[];
recordedVersionId: number;
}
export class EditStack {
private model: IEditableTextModel;
private currentOpenStackElement: IStackElement;
private past: IStackElement[];
private future: IStackElement[];
constructor(model: IEditableTextModel) {
this.model = model;
this.currentOpenStackElement = null;
this.past = [];
this.future = [];
}
public pushStackElement(): void {
if (this.currentOpenStackElement !== null) {
this.past.push(this.currentOpenStackElement);
this.currentOpenStackElement = null;
}
}
public clear(): void {
this.currentOpenStackElement = null;
this.past = [];
this.future = [];
}
public pushEditOperation(beforeCursorState: Selection[], editOperations: IIdentifiedSingleEditOperation[], cursorStateComputer: ICursorStateComputer): Selection[] {
// No support for parallel universes :(
this.future = [];
if (!this.currentOpenStackElement) {
this.currentOpenStackElement = {
beforeVersionId: this.model.getAlternativeVersionId(),
beforeCursorState: beforeCursorState,
editOperations: [],
afterCursorState: null,
afterVersionId: -1
};
}
var inverseEditOperation: IEditOperation = {
operations: this.model.applyEdits(editOperations)
};
this.currentOpenStackElement.editOperations.push(inverseEditOperation);
try {
this.currentOpenStackElement.afterCursorState = cursorStateComputer ? cursorStateComputer(inverseEditOperation.operations) : null;
} catch (e) {
onUnexpectedError(e);
this.currentOpenStackElement.afterCursorState = null;
}
this.currentOpenStackElement.afterVersionId = this.model.getVersionId();
return this.currentOpenStackElement.afterCursorState;
}
public undo(): IUndoRedoResult {
this.pushStackElement();
if (this.past.length > 0) {
var pastStackElement = this.past.pop();
try {
// Apply all operations in reverse order
for (var i = pastStackElement.editOperations.length - 1; i >= 0; i--) {
pastStackElement.editOperations[i] = {
operations: this.model.applyEdits(pastStackElement.editOperations[i].operations)
};
}
} catch (e) {
this.clear();
return null;
}
this.future.push(pastStackElement);
return {
selections: pastStackElement.beforeCursorState,
recordedVersionId: pastStackElement.beforeVersionId
};
}
return null;
}
public redo(): IUndoRedoResult {
if (this.future.length > 0) {
if (this.currentOpenStackElement) {
throw new Error('How is this possible?');
}
var futureStackElement = this.future.pop();
try {
// Apply all operations
for (var i = 0; i < futureStackElement.editOperations.length; i++) {
futureStackElement.editOperations[i] = {
operations: this.model.applyEdits(futureStackElement.editOperations[i].operations)
};
}
} catch (e) {
this.clear();
return null;
}
this.past.push(futureStackElement);
return {
selections: futureStackElement.afterCursorState,
recordedVersionId: futureStackElement.afterVersionId
};
}
return null;
}
}
| mit |
jorsi/runuo | Scripts/Items/Shields/BaseShield.cs | 3886 | using System;
using System.Collections;
using Server;
using Server.Network;
namespace Server.Items
{
public class BaseShield : BaseArmor
{
public override ArmorMaterialType MaterialType{ get{ return ArmorMaterialType.Plate; } }
public BaseShield( int itemID ) : base( itemID )
{
}
public BaseShield( Serial serial ) : base(serial)
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 1 );//version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
if ( version < 1 )
{
if ( this is Aegis )
return;
// The 15 bonus points to resistances are not applied to shields on OSI.
PhysicalBonus = 0;
FireBonus = 0;
ColdBonus = 0;
PoisonBonus = 0;
EnergyBonus = 0;
}
}
public override double ArmorRating
{
get
{
Mobile m = this.Parent as Mobile;
double ar = base.ArmorRating;
if ( m != null )
return ( ( m.Skills[SkillName.Parry].Value * ar ) / 200.0 ) + 1.0;
else
return ar;
}
}
public override int OnHit( BaseWeapon weapon, int damage )
{
if( Core.AOS )
{
if( ArmorAttributes.SelfRepair > Utility.Random( 10 ) )
{
HitPoints += 2;
}
else
{
double halfArmor = ArmorRating / 2.0;
int absorbed = (int)(halfArmor + (halfArmor*Utility.RandomDouble()));
if( absorbed < 2 )
absorbed = 2;
int wear;
if( weapon.Type == WeaponType.Bashing )
wear = (absorbed / 2);
else
wear = Utility.Random( 2 );
if( wear > 0 && MaxHitPoints > 0 )
{
if( HitPoints >= wear )
{
HitPoints -= wear;
wear = 0;
}
else
{
wear -= HitPoints;
HitPoints = 0;
}
if( wear > 0 )
{
if( MaxHitPoints > wear )
{
MaxHitPoints -= wear;
if( Parent is Mobile )
((Mobile)Parent).LocalOverheadMessage( MessageType.Regular, 0x3B2, 1061121 ); // Your equipment is severely damaged.
}
else
{
Delete();
}
}
}
}
return 0;
}
else
{
Mobile owner = this.Parent as Mobile;
if( owner == null )
return damage;
double ar = this.ArmorRating;
double chance = (owner.Skills[SkillName.Parry].Value - (ar * 2.0)) / 100.0;
if( chance < 0.01 )
chance = 0.01;
/*
FORMULA: Displayed AR = ((Parrying Skill * Base AR of Shield) ÷ 200) + 1
FORMULA: % Chance of Blocking = parry skill - (shieldAR * 2)
FORMULA: Melee Damage Absorbed = (AR of Shield) / 2 | Archery Damage Absorbed = AR of Shield
*/
if( owner.CheckSkill( SkillName.Parry, chance ) )
{
if( weapon.Skill == SkillName.Archery )
damage -= (int)ar;
else
damage -= (int)(ar / 2.0);
if( damage < 0 )
damage = 0;
owner.FixedEffect( 0x37B9, 10, 16 );
if( 25 > Utility.Random( 100 ) ) // 25% chance to lower durability
{
int wear = Utility.Random( 2 );
if( wear > 0 && MaxHitPoints > 0 )
{
if( HitPoints >= wear )
{
HitPoints -= wear;
wear = 0;
}
else
{
wear -= HitPoints;
HitPoints = 0;
}
if( wear > 0 )
{
if( MaxHitPoints > wear )
{
MaxHitPoints -= wear;
if( Parent is Mobile )
((Mobile)Parent).LocalOverheadMessage( MessageType.Regular, 0x3B2, 1061121 ); // Your equipment is severely damaged.
}
else
{
Delete();
}
}
}
}
}
return damage;
}
}
}
}
| gpl-2.0 |
emilienGallet/DrupalUnicef | vendor/drupal/console/src/Command/Cron/ReleaseCommand.php | 1097 | <?php
/**
* @file
* Contains \Drupal\Console\Command\Cron\ReleaseCommand.
*/
namespace Drupal\Console\Command\Cron;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Drupal\Console\Command\ContainerAwareCommand;
use Drupal\Console\Style\DrupalStyle;
class ReleaseCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('cron:release')
->setDescription($this->trans('commands.cron.release.description'));
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$lock = $this->getDatabaseLockBackend();
try {
$lock->release('cron');
$io->info($this->trans('commands.cron.release.messages.released'));
} catch (Exception $e) {
$io->error($e->getMessage());
}
$this->getChain()->addCommand('cache:rebuild', ['cache' => 'all']);
}
}
| gpl-2.0 |
turtlerrrrr/myapp | web/src/main/webapp/WEB-INF/app/ext/modern/modern/src/field/Number.js | 5914 | /**
* The Number field creates an HTML5 number input and is usually created inside a form. Because it creates an HTML
* number input field, most browsers will show a specialized virtual keyboard for entering numbers. The Number field
* only accepts numerical input and also provides additional spinner UI that increases or decreases the current value
* by a configured {@link #stepValue step value}. Here's how we might use one in a form:
*
* @example
* Ext.create('Ext.form.Panel', {
* fullscreen: true,
* items: [
* {
* xtype: 'fieldset',
* title: 'How old are you?',
* items: [
* {
* xtype: 'numberfield',
* label: 'Age',
* minValue: 18,
* maxValue: 150,
* name: 'age'
* }
* ]
* }
* ]
* });
*
* Or on its own, outside of a form:
*
* Ext.create('Ext.field.Number', {
* label: 'Age',
* value: '26'
* });
*
* ## minValue, maxValue and stepValue
*
* The {@link #minValue} and {@link #maxValue} configurations are self-explanatory and simply constrain the value
* entered to the range specified by the configured min and max values. The other option exposed by this component
* is {@link #stepValue}, which enables you to set how much the value changes every time the up and down spinners
* are tapped on. For example, to create a salary field that ticks up and down by $1,000 each tap we can do this:
*
* @example
* Ext.create('Ext.form.Panel', {
* fullscreen: true,
* items: [
* {
* xtype: 'fieldset',
* title: 'Are you rich yet?',
* items: [
* {
* xtype: 'numberfield',
* label: 'Salary',
* value: 30000,
* minValue: 25000,
* maxValue: 50000,
* stepValue: 1000
* }
* ]
* }
* ]
* });
*
* This creates a field that starts with a value of $30,000, steps up and down in $1,000 increments and will not go
* beneath $25,000 or above $50,000.
*
* Because number field inherits from {@link Ext.field.Text textfield} it gains all of the functionality that text
* fields provide, including getting and setting the value at runtime, validations and various events that are fired as
* the user interacts with the component. Check out the {@link Ext.field.Text} docs to see the additional functionality
* available.
*/
Ext.define('Ext.field.Number', {
extend: 'Ext.field.Text',
xtype: 'numberfield',
alternateClassName: 'Ext.form.Number',
/**
* @event change
* Fires when the value has changed.
* @param {Ext.field.Text} this This field
* @param {Number} newValue The new value
* @param {Number} oldValue The original value
*/
config: {
/**
* @cfg
* @inheritdoc
*/
component: {
type: 'number'
},
/**
* @cfg
* @inheritdoc
*/
ui: 'number'
},
proxyConfig: {
/**
* @cfg {Number} minValue The minimum value that this Number field can accept
* @accessor
*/
minValue: null,
/**
* @cfg {Number} maxValue The maximum value that this Number field can accept
* @accessor
*/
maxValue: null,
/**
* @cfg {Number} stepValue The amount by which the field is incremented or decremented each time the spinner is tapped.
* Defaults to undefined, which means that the field goes up or down by 1 each time the spinner is tapped
* @accessor
*/
stepValue: null
},
applyPlaceHolder: function(value) {
// Android 4.1 & lower require a hack for placeholder text in number fields when using the Stock Browser
// details here https://code.google.com/p/android/issues/detail?id=24626
this._enableNumericPlaceHolderHack = ((!Ext.feature.has.NumericInputPlaceHolder) && (!Ext.isEmpty(value)));
return value;
},
onFocus: function(e) {
if (this._enableNumericPlaceHolderHack) {
this.getComponent().input.dom.setAttribute("type", "number");
}
this.callParent(arguments);
},
onBlur: function(e) {
if (this._enableNumericPlaceHolderHack) {
this.getComponent().input.dom.setAttribute("type", "text");
}
this.callParent(arguments);
},
doInitValue : function() {
var value = this.getInitialConfig().value;
if (value) {
value = this.applyValue(value);
}
this.originalValue = value;
},
applyValue: function(value) {
var minValue = this.getMinValue(),
maxValue = this.getMaxValue();
if (Ext.isNumber(minValue) && Ext.isNumber(value)) {
value = Math.max(value, minValue);
}
if (Ext.isNumber(maxValue) && Ext.isNumber(value)) {
value = Math.min(value, maxValue);
}
value = parseFloat(value);
return (isNaN(value)) ? '' : value;
},
getValue: function() {
var value = parseFloat(this.callParent(), 10);
return (isNaN(value)) ? null : value;
},
doClearIconTap: function(me, e) {
me.getComponent().setValue('');
me.getValue();
me.hideClearIcon();
}
});
| gpl-2.0 |
webeindustry/discourse | spec/models/category_user_spec.rb | 5744 | # encoding: utf-8
require 'rails_helper'
require_dependency 'post_creator'
describe CategoryUser do
it 'allows batch set' do
user = Fabricate(:user)
category1 = Fabricate(:category)
category2 = Fabricate(:category)
watching = CategoryUser.where(user_id: user.id, notification_level: CategoryUser.notification_levels[:watching])
CategoryUser.batch_set(user, :watching, [category1.id, category2.id])
expect(watching.pluck(:category_id).sort).to eq [category1.id, category2.id]
CategoryUser.batch_set(user, :watching, [])
expect(watching.count).to eq 0
CategoryUser.batch_set(user, :watching, [category2.id])
expect(watching.count).to eq 1
end
context 'integration' do
before do
ActiveRecord::Base.observers.enable :all
end
it 'should operate correctly' do
watched_category = Fabricate(:category)
muted_category = Fabricate(:category)
tracked_category = Fabricate(:category)
user = Fabricate(:user)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
CategoryUser.create!(user: user, category: muted_category, notification_level: CategoryUser.notification_levels[:muted])
CategoryUser.create!(user: user, category: tracked_category, notification_level: CategoryUser.notification_levels[:tracking])
watched_post = create_post(category: watched_category)
_muted_post = create_post(category: muted_category)
tracked_post = create_post(category: tracked_category)
expect(Notification.where(user_id: user.id, topic_id: watched_post.topic_id).count).to eq 1
expect(Notification.where(user_id: user.id, topic_id: tracked_post.topic_id).count).to eq 0
tu = TopicUser.get(tracked_post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:tracking]
expect(tu.notifications_reason_id).to eq TopicUser.notification_reasons[:auto_track_category]
end
it "watches categories that have been changed" do
user = Fabricate(:user)
watched_category = Fabricate(:category)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
post = create_post
expect(TopicUser.get(post.topic, user)).to be_blank
# Now, change the topic's category
post.topic.change_category_to_id(watched_category.id)
tu = TopicUser.get(post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:watching]
end
it "unwatches categories that have been changed" do
user = Fabricate(:user)
watched_category = Fabricate(:category)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
post = create_post(category: watched_category)
tu = TopicUser.get(post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:watching]
# Now, change the topic's category
unwatched_category = Fabricate(:category)
post.topic.change_category_to_id(unwatched_category.id)
expect(TopicUser.get(post.topic, user)).to be_blank
end
it "does not delete TopicUser record when topic category is changed, and new category has same notification level" do
# this is done so as to maintain topic notification state when topic category is changed and the new category has same notification level for the user
# see: https://meta.discourse.org/t/changing-topic-from-one-watched-category-to-another-watched-category-makes-topic-new-again/36517/15
user = Fabricate(:user)
watched_category_1 = Fabricate(:category)
watched_category_2 = Fabricate(:category)
CategoryUser.create!(user: user, category: watched_category_1, notification_level: CategoryUser.notification_levels[:watching])
CategoryUser.create!(user: user, category: watched_category_2, notification_level: CategoryUser.notification_levels[:watching])
post = create_post(category: watched_category_1)
tu = TopicUser.get(post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:watching]
# Now, change the topic's category
post.topic.change_category_to_id(watched_category_2.id)
expect(TopicUser.get(post.topic, user)).to eq tu
end
it "deletes TopicUser record when topic category is changed, and new category has different notification level" do
user = Fabricate(:user)
watched_category = Fabricate(:category)
tracked_category = Fabricate(:category)
CategoryUser.create!(user: user, category: watched_category, notification_level: CategoryUser.notification_levels[:watching])
CategoryUser.create!(user: user, category: tracked_category, notification_level: CategoryUser.notification_levels[:tracking])
post = create_post(category: watched_category)
tu = TopicUser.get(post.topic, user)
expect(tu.notification_level).to eq TopicUser.notification_levels[:watching]
# Now, change the topic's category
post.topic.change_category_to_id(tracked_category.id)
expect(TopicUser.get(post.topic, user).notification_level).to eq TopicUser.notification_levels[:tracking]
end
it "is destroyed when a user is deleted" do
user = Fabricate(:user)
category = Fabricate(:category)
CategoryUser.create!(user: user, category: category, notification_level: CategoryUser.notification_levels[:watching])
expect(CategoryUser.where(user_id: user.id).count).to eq(1)
user.destroy!
expect(CategoryUser.where(user_id: user.id).count).to eq(0)
end
end
end
| gpl-2.0 |
openprivacy/.emacs.d | elpy/rpc-venv/lib/python3.8/site-packages/pip/_internal/operations/freeze.py | 10373 | from __future__ import absolute_import
import collections
import logging
import os
from pip._vendor import six
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.pkg_resources import RequirementParseError
from pip._internal.exceptions import BadCommand, InstallationError
from pip._internal.req.constructors import (
install_req_from_editable,
install_req_from_line,
)
from pip._internal.req.req_file import COMMENT_RE
from pip._internal.utils.direct_url_helpers import (
direct_url_as_pep440_direct_reference,
dist_get_direct_url,
)
from pip._internal.utils.misc import (
dist_is_editable,
get_installed_distributions,
)
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from typing import (
Iterator, Optional, List, Container, Set, Dict, Tuple, Iterable, Union
)
from pip._internal.cache import WheelCache
from pip._vendor.pkg_resources import (
Distribution, Requirement
)
RequirementInfo = Tuple[Optional[Union[str, Requirement]], bool, List[str]]
logger = logging.getLogger(__name__)
def freeze(
requirement=None, # type: Optional[List[str]]
find_links=None, # type: Optional[List[str]]
local_only=False, # type: bool
user_only=False, # type: bool
paths=None, # type: Optional[List[str]]
isolated=False, # type: bool
wheel_cache=None, # type: Optional[WheelCache]
exclude_editable=False, # type: bool
skip=() # type: Container[str]
):
# type: (...) -> Iterator[str]
find_links = find_links or []
for link in find_links:
yield '-f {}'.format(link)
installations = {} # type: Dict[str, FrozenRequirement]
for dist in get_installed_distributions(
local_only=local_only,
skip=(),
user_only=user_only,
paths=paths
):
try:
req = FrozenRequirement.from_dist(dist)
except RequirementParseError as exc:
# We include dist rather than dist.project_name because the
# dist string includes more information, like the version and
# location. We also include the exception message to aid
# troubleshooting.
logger.warning(
'Could not generate requirement for distribution %r: %s',
dist, exc
)
continue
if exclude_editable and req.editable:
continue
installations[req.canonical_name] = req
if requirement:
# the options that don't get turned into an InstallRequirement
# should only be emitted once, even if the same option is in multiple
# requirements files, so we need to keep track of what has been emitted
# so that we don't emit it again if it's seen again
emitted_options = set() # type: Set[str]
# keep track of which files a requirement is in so that we can
# give an accurate warning if a requirement appears multiple times.
req_files = collections.defaultdict(list) # type: Dict[str, List[str]]
for req_file_path in requirement:
with open(req_file_path) as req_file:
for line in req_file:
if (not line.strip() or
line.strip().startswith('#') or
line.startswith((
'-r', '--requirement',
'-f', '--find-links',
'-i', '--index-url',
'--pre',
'--trusted-host',
'--process-dependency-links',
'--extra-index-url',
'--use-feature'))):
line = line.rstrip()
if line not in emitted_options:
emitted_options.add(line)
yield line
continue
if line.startswith('-e') or line.startswith('--editable'):
if line.startswith('-e'):
line = line[2:].strip()
else:
line = line[len('--editable'):].strip().lstrip('=')
line_req = install_req_from_editable(
line,
isolated=isolated,
)
else:
line_req = install_req_from_line(
COMMENT_RE.sub('', line).strip(),
isolated=isolated,
)
if not line_req.name:
logger.info(
"Skipping line in requirement file [%s] because "
"it's not clear what it would install: %s",
req_file_path, line.strip(),
)
logger.info(
" (add #egg=PackageName to the URL to avoid"
" this warning)"
)
else:
line_req_canonical_name = canonicalize_name(
line_req.name)
if line_req_canonical_name not in installations:
# either it's not installed, or it is installed
# but has been processed already
if not req_files[line_req.name]:
logger.warning(
"Requirement file [%s] contains %s, but "
"package %r is not installed",
req_file_path,
COMMENT_RE.sub('', line).strip(),
line_req.name
)
else:
req_files[line_req.name].append(req_file_path)
else:
yield str(installations[
line_req_canonical_name]).rstrip()
del installations[line_req_canonical_name]
req_files[line_req.name].append(req_file_path)
# Warn about requirements that were included multiple times (in a
# single requirements file or in different requirements files).
for name, files in six.iteritems(req_files):
if len(files) > 1:
logger.warning("Requirement %s included multiple times [%s]",
name, ', '.join(sorted(set(files))))
yield(
'## The following requirements were added by '
'pip freeze:'
)
for installation in sorted(
installations.values(), key=lambda x: x.name.lower()):
if installation.canonical_name not in skip:
yield str(installation).rstrip()
def get_requirement_info(dist):
# type: (Distribution) -> RequirementInfo
"""
Compute and return values (req, editable, comments) for use in
FrozenRequirement.from_dist().
"""
if not dist_is_editable(dist):
return (None, False, [])
location = os.path.normcase(os.path.abspath(dist.location))
from pip._internal.vcs import vcs, RemoteNotFoundError
vcs_backend = vcs.get_backend_for_dir(location)
if vcs_backend is None:
req = dist.as_requirement()
logger.debug(
'No VCS found for editable requirement "%s" in: %r', req,
location,
)
comments = [
'# Editable install with no version control ({})'.format(req)
]
return (location, True, comments)
try:
req = vcs_backend.get_src_requirement(location, dist.project_name)
except RemoteNotFoundError:
req = dist.as_requirement()
comments = [
'# Editable {} install with no remote ({})'.format(
type(vcs_backend).__name__, req,
)
]
return (location, True, comments)
except BadCommand:
logger.warning(
'cannot determine version of editable source in %s '
'(%s command not found in path)',
location,
vcs_backend.name,
)
return (None, True, [])
except InstallationError as exc:
logger.warning(
"Error when trying to get requirement for VCS system %s, "
"falling back to uneditable format", exc
)
else:
if req is not None:
return (req, True, [])
logger.warning(
'Could not determine repository location of %s', location
)
comments = ['## !! Could not determine repository location']
return (None, False, comments)
class FrozenRequirement(object):
def __init__(self, name, req, editable, comments=()):
# type: (str, Union[str, Requirement], bool, Iterable[str]) -> None
self.name = name
self.canonical_name = canonicalize_name(name)
self.req = req
self.editable = editable
self.comments = comments
@classmethod
def from_dist(cls, dist):
# type: (Distribution) -> FrozenRequirement
# TODO `get_requirement_info` is taking care of editable requirements.
# TODO This should be refactored when we will add detection of
# editable that provide .dist-info metadata.
req, editable, comments = get_requirement_info(dist)
if req is None and not editable:
# if PEP 610 metadata is present, attempt to use it
direct_url = dist_get_direct_url(dist)
if direct_url:
req = direct_url_as_pep440_direct_reference(
direct_url, dist.project_name
)
comments = []
if req is None:
# name==version requirement
req = dist.as_requirement()
return cls(dist.project_name, req, editable, comments=comments)
def __str__(self):
# type: () -> str
req = self.req
if self.editable:
req = '-e {}'.format(req)
return '\n'.join(list(self.comments) + [str(req)]) + '\n'
| gpl-2.0 |
thanhluu/sentora-core | dryden/ws/generic.class.php | 9128 | <?php
/**
* @copyright 2014-2015 Sentora Project (http://www.sentora.org/)
* Sentora is a GPL fork of the ZPanel Project whose original header follows:
*
* Generic web services class.
* @package zpanelx
* @subpackage dryden -> webservices
* @version 1.0.0
* @author Bobby Allen (ballen@bobbyallen.me)
* @copyright ZPanel Project (http://www.zpanelcp.com/)
* @link http://www.zpanelcp.com/
* @license GPL (http://www.gnu.org/licenses/gpl.html)
*/
class ws_generic {
/**
* Provides very basic way of retrieving a result as a string from a given URL (RAW) this does not need to be a 'true' web service.
* @author Bobby Allen (ballen@bobbyallen.me)
* @param string $requestURL The URL to the resource.
* @return mixed If the request was successful it will return the contents of the requested URL otherwise will return 'false'.
*/
static function ReadURLRequestResult($requestURL) {
ob_start();
@readfile($requestURL);
$reqcontent = ob_get_contents();
ob_clean();
if ($reqcontent)
return $reqcontent;
$ws_log = new debug_logger();
$ws_log->logcode = "903";
$ws_log->detail = "Unable to connect to webservice URL (" . $requestURL . ") as requested in ws_generic::ReadURLRequestResult()";
$ws_log->writeLog();
return false;
}
/**
* Generic method to send POST data to a web service and then return its response (without the need to use cURL or another HTTP client).
* @author Bobby Allen (ballen@bobbyallen.me)
* @param string $url The URL of which to POST the data too.
* @param string $data The data content of which to send.
* @param string $optional_headers Option headers if you require to send them.
* @return string The response recieved.
*/
static function DoPostRequest($url, $data, $optional_headers = null) {
//$ws_log = new debug_logger();
//$ws_log->logcode = "904";
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
//$ws_log->detail = "Problem with " .$url. ", ".$php_errormsg."";
//$ws_log->writeLog();
}
$response = @stream_get_contents($fp);
if ($response == false) {
//$ws_log->detail = "Problem reading data from ".$url. ", ".$php_errormsg."";
//$ws_log->writeLog();
}
return $response;
}
/**
* Captures the RAW POST data passed to this script.
* @author Bobby Allen (ballen@bobbyallen.me)
* @return string The raw request data.
*/
static function ProcessRawRequest() {
$xml_raw_data = fs_filehandler::ReadFileContents('php://input');
return $xml_raw_data;
}
/**
* Returns the value of a tag from an XML string.
* @author Bobby Allen (ballen@bobbyallen.me)
* @param string $tagname The name of the tag of which to retrieve the value from.
* @param string $xml The XML string
* @return string The XML tag value.
*/
static function GetTagValue($tagname, $xml) {
$matches = array();
$pattern = "/<$tagname>(.*?)<\/$tagname>/";
preg_match($pattern, $xml, $matches);
return $matches[1];
}
/**
* Takes an XML string and converts it into a usable PHP array.
* @author Bobby Allen (ballen@bobbyallen.me)
* @param string $contents The XML content to convert to a PHP array.
* @param int $get_arrtibutes Retieve the tag attrubtes too (1 = yes, 0 =no)?
* @param string $priotiry What should take priority? tag or attributes?
* @return array Associated array of the XML tag data.
*/
static function XMLToArray($contents, $get_attributes = 1, $priority = 'tag') {
if (!function_exists('xml_parser_create')) {
return array('message' => 'xml_parser_create function does not exist on the server!');
}
$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);
if (!$xml_values)
return; //Hmm...
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();
$current = & $xml_array;
$repeated_tag_index = array();
foreach ($xml_values as $data) {
unset($attributes, $value);
extract($data);
$result = array();
$attributes_data = array();
if (isset($value)) {
if ($priority == 'tag') {
$result = $value;
} else {
$result['value'] = $value;
}
}
if (isset($attributes) and $get_attributes) {
foreach ($attributes as $attr => $val) {
if ($priority == 'tag') {
$attributes_data[$attr] = $val;
} else {
$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
}
}
}
if ($type == "open") {
$parent[$level - 1] = & $current;
if (!is_array($current) or (!in_array($tag, array_keys($current)))) {
$current[$tag] = $result;
if ($attributes_data)
$current[$tag . '_attr'] = $attributes_data;
$repeated_tag_index[$tag . '_' . $level] = 1;
$current = & $current[$tag];
}else {
if (isset($current[$tag][0])) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
$repeated_tag_index[$tag . '_' . $level]++;
} else {
$current[$tag] = array(
$current[$tag],
$result
);
$repeated_tag_index[$tag . '_' . $level] = 2;
if (isset($current[$tag . '_attr'])) {
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
}
$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
$current = & $current[$tag][$last_item_index];
}
} elseif ($type == "complete") {
if (!isset($current[$tag])) {
$current[$tag] = $result;
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $attributes_data)
$current[$tag . '_attr'] = $attributes_data;
}else {
if (isset($current[$tag][0]) and is_array($current[$tag])) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
if ($priority == 'tag' and $get_attributes and $attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level]++;
} else {
$current[$tag] = array(
$current[$tag],
$result
);
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' and $get_attributes) {
if (isset($current[$tag . '_attr'])) {
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset($current[$tag . '_attr']);
}
if ($attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
}
}
} elseif ($type == 'close') {
$current = & $parent[$level - 1];
}
}
return ($xml_array);
}
/**
* Takes an JSON string and converts it into a usable PHP array.
* @param string $content The JSON string of which to decode.
* @return array Associated array of the JSON tag data.
*/
static function JSONToArray($content) {
return json_decode($content, true);
}
}
?>
| gpl-3.0 |
msshapira/yowsup | yowsup/demos/contacts/stack.py | 2409 | from yowsup.stacks import YowStack
from .layer import SyncLayer
from yowsup.layers import YowLayerEvent
from yowsup.layers.auth import YowCryptLayer, YowAuthenticationProtocolLayer, AuthError
from yowsup.layers.coder import YowCoderLayer
from yowsup.layers.network import YowNetworkLayer
from yowsup.layers.stanzaregulator import YowStanzaRegulator
from yowsup.layers.protocol_receipts import YowReceiptProtocolLayer
from yowsup.layers.protocol_acks import YowAckProtocolLayer
from yowsup.layers.logger import YowLoggerLayer
from yowsup.layers.protocol_contacts import YowContactsIqProtocolLayer
from yowsup.layers import YowParallelLayer
class YowsupSyncStack(object):
def __init__(self, credentials, contacts, encryptionEnabled = False):
"""
:param credentials:
:param contacts: list of [jid ]
:param encryptionEnabled:
:return:
"""
if encryptionEnabled:
from yowsup.layers.axolotl import YowAxolotlLayer
layers = (
SyncLayer,
YowParallelLayer([YowAuthenticationProtocolLayer, YowContactsIqProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer]),
YowAxolotlLayer,
YowLoggerLayer,
YowCoderLayer,
YowCryptLayer,
YowStanzaRegulator,
YowNetworkLayer
)
else:
layers = (
SyncLayer,
YowParallelLayer([YowAuthenticationProtocolLayer, YowContactsIqProtocolLayer, YowReceiptProtocolLayer, YowAckProtocolLayer]),
YowLoggerLayer,
YowCoderLayer,
YowCryptLayer,
YowStanzaRegulator,
YowNetworkLayer
)
self.stack = YowStack(layers)
self.stack.setProp(SyncLayer.PROP_CONTACTS, contacts)
self.stack.setProp(YowAuthenticationProtocolLayer.PROP_PASSIVE, True)
self.stack.setCredentials(credentials)
def start(self):
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
try:
self.stack.loop()
except AuthError as e:
print("Authentication Error: %s" % e.message)
| gpl-3.0 |
SlateScience/MozillaJS | js/src/tests/test262/ch11/11.8/11.8.1/S11.8.1_A3.1_T2.3.js | 804 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* If Type(Primitive(x)) is not String or Type(Primitive(y)) is not String, then operator x < y returns ToNumber(x) < ToNumber(y)
*
* @path ch11/11.8/11.8.1/S11.8.1_A3.1_T2.3.js
* @description Type(Primitive(x)) is different from Type(Primitive(y)) and both types vary between Number (primitive or object) and Null
*/
//CHECK#1
if (1 < null !== false) {
$ERROR('#1: 1 < null === false');
}
//CHECK#2
if (null < 1 !== true) {
$ERROR('#2: null < 1 === true');
}
//CHECK#3
if (new Number(1) < null !== false) {
$ERROR('#3: new Number(1) < null === false');
}
//CHECK#4
if (null < new Number(1) !== true) {
$ERROR('#4: null < new Number(1) === true');
}
| mpl-2.0 |
arrivu/jigsaw-lms | spec/apis/v1/comm_messages_api_spec.rb | 7657 | #
# Copyright (C) 2013 Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
require File.expand_path(File.dirname(__FILE__) + '/../api_spec_helper')
describe CommMessagesApiController, :type => :integration do
describe "index" do
context "a site admin" do
context "with permission" do
before do
@test_user = user(:active_all => true)
site_admin_user
user_session(@admin)
end
it "should be able to see all messages" do
Message.create!(:user => @test_user, :body => "site admin message", :root_account_id => Account.site_admin.id)
Message.create!(:user => @test_user, :body => "account message", :root_account_id => Account.default.id)
json = api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param })
json.size.should eql 2
json.map {|m| m['body'] }.sort.should eql ['account message', 'site admin message']
end
it "should require a valid user_id parameter" do
raw_api_call(:get, "/api/v1/comm_messages", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json'})
response.code.should eql '404'
raw_api_call(:get, "/api/v1/comm_messages?user_id=0", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => '0' })
response.code.should eql '404'
end
it "should use start_time and end_time parameters to limit results" do
m = Message.new(:user => @test_user, :body => "site admin message", :root_account_id => Account.site_admin.id)
m.write_attribute(:created_at, Time.zone.now - 1.day)
m.save!
Message.create!(:user => @test_user, :body => "account message", :root_account_id => Account.default.id)
m = Message.new(:user => @test_user, :body => "account message", :root_account_id => Account.default.id)
m.write_attribute(:created_at, Time.zone.now + 1.day)
m.save!
start_time = (Time.zone.now - 1.hour).iso8601
end_time = (Time.zone.now + 1.hour).iso8601
json = api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}&start_time=#{start_time}&end_time=#{end_time}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param, :start_time => start_time, :end_time => end_time })
end
it "should paginate results" do
5.times do |v|
Message.create!(:user => @test_user, :body => "body #{v}", :root_account_id => Account.default.id)
end
json = api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}&per_page=2", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param, :per_page => '2' })
json.size.should eql 2
json = api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}&per_page=2&page=2", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param, :per_page => '2', :page => '2' })
json.size.should eql 2
json = api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}&per_page=2&page=3", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param, :per_page => '2', :page => '3' })
json.size.should eql 1
end
end
context "without permission" do
before do
@test_user = user(:active_all => true)
account_admin_user_with_role_changes(:account => Account.site_admin,
:role_changes => {:read_messages => false})
user_session(@admin)
end
it "should receive unauthorized" do
raw_api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param })
response.code.should eql '401'
end
end
end
context "an account admin" do
context "with permission" do
before do
@test_user = user(:active_all => true)
account_admin_user_with_role_changes(:account => Account.default,
:role_changes => {:view_notifications => true})
user_session(@admin)
end
it "should receive unauthorized if account setting disabled" do
Account.default.settings[:admins_can_view_notifications] = false
Account.default.save!
raw_api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param })
response.code.should eql '401'
end
it "should only be able to see associated account's messages" do
Account.default.settings[:admins_can_view_notifications] = true
Account.default.save!
Message.create!(:user => @test_user, :body => "site admin message", :root_account_id => Account.site_admin.id)
Message.create!(:user => @test_user, :body => "account message", :root_account_id => Account.default.id)
json = api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param })
json.size.should eql 1
json.map {|m| m['body'] }.sort.should eql ['account message']
end
end
context "without permission" do
before do
@test_user = user(:active_all => true)
account_admin_user_with_role_changes(:account => Account.default,
:role_changes => {:view_notifications => false})
user_session(@admin)
end
it "should receive unauthorized" do
raw_api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param })
response.code.should eql '401'
end
end
end
context "an unauthorized user" do
before do
@test_user = user(:active_all => true)
@user = user(:active_all => true)
user_session(@user)
end
it "should receive unauthorized" do
raw_api_call(:get, "/api/v1/comm_messages?user_id=#{@test_user.id}", {
:controller => 'comm_messages_api', :action => 'index', :format => 'json',
:user_id => @test_user.to_param })
response.code.should eql '401'
end
end
end
end
| agpl-3.0 |
Endika/edx-platform | openedx/core/djangoapps/bookmarks/tests/test_services.py | 3421 | """
Tests for bookmark services.
"""
from unittest import skipUnless
from django.conf import settings
from opaque_keys.edx.keys import UsageKey
from ..services import BookmarksService
from .test_models import BookmarksTestsBase
@skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Tests only valid in LMS')
class BookmarksServiceTests(BookmarksTestsBase):
"""
Tests the Bookmarks service.
"""
def setUp(self):
super(BookmarksServiceTests, self).setUp()
self.bookmark_service = BookmarksService(user=self.user)
def test_get_bookmarks(self):
"""
Verifies get_bookmarks returns data as expected.
"""
with self.assertNumQueries(1):
bookmarks_data = self.bookmark_service.bookmarks(course_key=self.course.id)
self.assertEqual(len(bookmarks_data), 2)
self.assert_bookmark_data_is_valid(self.bookmark_2, bookmarks_data[0])
self.assert_bookmark_data_is_valid(self.bookmark_1, bookmarks_data[1])
def test_is_bookmarked(self):
"""
Verifies is_bookmarked returns Bool as expected.
"""
with self.assertNumQueries(1):
self.assertTrue(self.bookmark_service.is_bookmarked(usage_key=self.sequential_1.location))
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location))
self.assertTrue(self.bookmark_service.is_bookmarked(usage_key=self.sequential_2.location))
self.bookmark_service.set_bookmarked(usage_key=self.chapter_1.location)
with self.assertNumQueries(0):
self.assertTrue(self.bookmark_service.is_bookmarked(usage_key=self.chapter_1.location))
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location))
# Removing a bookmark should result in the cache being updated on the next request
self.bookmark_service.unset_bookmarked(usage_key=self.chapter_1.location)
with self.assertNumQueries(0):
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.chapter_1.location))
self.assertFalse(self.bookmark_service.is_bookmarked(usage_key=self.vertical_2.location))
# Get bookmark that does not exist.
bookmark_service = BookmarksService(self.other_user)
with self.assertNumQueries(1):
self.assertFalse(bookmark_service.is_bookmarked(usage_key=self.sequential_1.location))
def test_set_bookmarked(self):
"""
Verifies set_bookmarked returns Bool as expected.
"""
# Assert False for item that does not exist.
with self.assertNumQueries(0):
self.assertFalse(
self.bookmark_service.set_bookmarked(usage_key=UsageKey.from_string("i4x://ed/ed/ed/interactive"))
)
with self.assertNumQueries(9):
self.assertTrue(self.bookmark_service.set_bookmarked(usage_key=self.vertical_2.location))
def test_unset_bookmarked(self):
"""
Verifies unset_bookmarked returns Bool as expected.
"""
with self.assertNumQueries(1):
self.assertFalse(
self.bookmark_service.unset_bookmarked(usage_key=UsageKey.from_string("i4x://ed/ed/ed/interactive"))
)
with self.assertNumQueries(3):
self.assertTrue(self.bookmark_service.unset_bookmarked(usage_key=self.sequential_1.location))
| agpl-3.0 |
harterj/moose | modules/phase_field/src/action/DisplacementGradientsAction.C | 3841 | //* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "DisplacementGradientsAction.h"
#include "Factory.h"
#include "FEProblem.h"
#include "libmesh/string_to_enum.h"
registerMooseAction("PhaseFieldApp", DisplacementGradientsAction, "add_kernel");
registerMooseAction("PhaseFieldApp", DisplacementGradientsAction, "add_material");
registerMooseAction("PhaseFieldApp", DisplacementGradientsAction, "add_variable");
InputParameters
DisplacementGradientsAction::validParams()
{
InputParameters params = Action::validParams();
params.addClassDescription("Set up variables, kernels, and materials for a the displacement "
"gradients and their elastic free energy derivatives for non-split "
"Cahn-Hilliard problems.");
params.addRequiredParam<std::vector<VariableName>>("displacements",
"Vector of displacement variables");
params.addRequiredParam<std::vector<VariableName>>("displacement_gradients",
"Vector of displacement gradient variables");
params.addParam<Real>(
"scaling", 1.0, "Specifies a scaling factor to apply to the displacement gradient variables");
return params;
}
DisplacementGradientsAction::DisplacementGradientsAction(const InputParameters & params)
: Action(params),
_displacements(getParam<std::vector<VariableName>>("displacements")),
_displacement_gradients(getParam<std::vector<VariableName>>("displacement_gradients"))
{
}
void
DisplacementGradientsAction::act()
{
unsigned int ngrad = _displacement_gradients.size();
if (_current_task == "add_variable")
{
// Loop through the gij variables
Real scaling = getParam<Real>("scaling");
for (unsigned int i = 0; i < ngrad; ++i)
{
auto var_params = _factory.getValidParams("MooseVariable");
var_params.set<MooseEnum>("family") = "LAGRANGE";
var_params.set<MooseEnum>("order") = "FIRST";
var_params.set<std::vector<Real>>("scaling") = {scaling};
// Create displacement gradient variables
_problem->addVariable("MooseVariable", _displacement_gradients[i], var_params);
}
}
else if (_current_task == "add_material")
{
InputParameters params = _factory.getValidParams("StrainGradDispDerivatives");
params.set<std::vector<VariableName>>("displacement_gradients") = _displacement_gradients;
params.set<std::vector<SubdomainName>>("block") = {"0"}; // TODO: add parameter for this
_problem->addMaterial("StrainGradDispDerivatives", "strain_grad_disp_derivatives", params);
}
else if (_current_task == "add_kernel")
{
unsigned int ndisp = _displacements.size();
if (ndisp * ndisp != ngrad)
paramError("displacement_gradients",
"Number of displacement gradient variables must be the square of the number of "
"displacement variables.");
// Loop through the displacements
unsigned int i = 0;
for (unsigned int j = 0; j < ndisp; ++j)
for (unsigned int k = 0; k < ndisp; ++k)
{
InputParameters params = _factory.getValidParams("GradientComponent");
params.set<NonlinearVariableName>("variable") = _displacement_gradients[i];
params.set<std::vector<VariableName>>("v") = {_displacements[j]};
params.set<unsigned int>("component") = k;
_problem->addKernel(
"GradientComponent", _displacement_gradients[i] + "_grad_kernel", params);
++i;
}
}
else
mooseError("Internal error.");
}
| lgpl-2.1 |
harterj/moose | modules/tensor_mechanics/src/kernels/CosseratStressDivergenceTensors.C | 1492 | //* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "CosseratStressDivergenceTensors.h"
#include "Material.h"
#include "RankFourTensor.h"
#include "ElasticityTensorTools.h"
#include "RankTwoTensor.h"
#include "MooseMesh.h"
registerMooseObject("TensorMechanicsApp", CosseratStressDivergenceTensors);
InputParameters
CosseratStressDivergenceTensors::validParams()
{
InputParameters params = StressDivergenceTensors::validParams();
params.addRequiredCoupledVar("Cosserat_rotations", "The 3 Cosserat rotation variables");
return params;
}
CosseratStressDivergenceTensors::CosseratStressDivergenceTensors(const InputParameters & parameters)
: StressDivergenceTensors(parameters),
_nrots(coupledComponents("Cosserat_rotations")),
_wc_var(_nrots)
{
for (unsigned i = 0; i < _nrots; ++i)
_wc_var[i] = coupled("Cosserat_rotations", i);
}
Real
CosseratStressDivergenceTensors::computeQpOffDiagJacobian(unsigned int jvar)
{
for (unsigned int v = 0; v < _nrots; ++v)
if (jvar == _wc_var[v])
return ElasticityTensorTools::elasticJacobianWC(
_Jacobian_mult[_qp], _component, v, _grad_test[_i][_qp], _phi[_j][_qp]);
return StressDivergenceTensors::computeQpOffDiagJacobian(jvar);
}
| lgpl-2.1 |
sylvainmed/simplesamlphp | modules/authgoogleOIDC/extlibinc/src/Google/Service/AdExchangeBuyer.php | 45415 | <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for AdExchangeBuyer (v1.3).
*
* <p>
* Lets you manage your Ad Exchange Buyer account.
* </p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/ad-exchange/buyer-rest" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_AdExchangeBuyer extends Google_Service
{
/** Manage your Ad Exchange buyer account configuration. */
const ADEXCHANGE_BUYER = "https://www.googleapis.com/auth/adexchange.buyer";
public $accounts;
public $creatives;
public $directDeals;
public $performanceReport;
public $pretargetingConfig;
/**
* Constructs the internal representation of the AdExchangeBuyer service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->servicePath = 'adexchangebuyer/v1.3/';
$this->version = 'v1.3';
$this->serviceName = 'adexchangebuyer';
$this->accounts = new Google_Service_AdExchangeBuyer_Accounts_Resource(
$this,
$this->serviceName,
'accounts',
array(
'methods' => array(
'get' => array(
'path' => 'accounts/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
),
),'list' => array(
'path' => 'accounts',
'httpMethod' => 'GET',
'parameters' => array(),
),'patch' => array(
'path' => 'accounts/{id}',
'httpMethod' => 'PATCH',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
),
),'update' => array(
'path' => 'accounts/{id}',
'httpMethod' => 'PUT',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
),
),
)
)
);
$this->creatives = new Google_Service_AdExchangeBuyer_Creatives_Resource(
$this,
$this->serviceName,
'creatives',
array(
'methods' => array(
'get' => array(
'path' => 'creatives/{accountId}/{buyerCreativeId}',
'httpMethod' => 'GET',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'integer',
'required' => true,
),
'buyerCreativeId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'creatives',
'httpMethod' => 'POST',
'parameters' => array(),
),'list' => array(
'path' => 'creatives',
'httpMethod' => 'GET',
'parameters' => array(
'statusFilter' => array(
'location' => 'query',
'type' => 'string',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
'buyerCreativeId' => array(
'location' => 'query',
'type' => 'string',
'repeated' => true,
),
'accountId' => array(
'location' => 'query',
'type' => 'integer',
'repeated' => true,
),
),
),
)
)
);
$this->directDeals = new Google_Service_AdExchangeBuyer_DirectDeals_Resource(
$this,
$this->serviceName,
'directDeals',
array(
'methods' => array(
'get' => array(
'path' => 'directdeals/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'directdeals',
'httpMethod' => 'GET',
'parameters' => array(),
),
)
)
);
$this->performanceReport = new Google_Service_AdExchangeBuyer_PerformanceReport_Resource(
$this,
$this->serviceName,
'performanceReport',
array(
'methods' => array(
'list' => array(
'path' => 'performancereport',
'httpMethod' => 'GET',
'parameters' => array(
'accountId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'endDateTime' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'startDateTime' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'maxResults' => array(
'location' => 'query',
'type' => 'integer',
),
),
),
)
)
);
$this->pretargetingConfig = new Google_Service_AdExchangeBuyer_PretargetingConfig_Resource(
$this,
$this->serviceName,
'pretargetingConfig',
array(
'methods' => array(
'delete' => array(
'path' => 'pretargetingconfigs/{accountId}/{configId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'configId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'pretargetingconfigs/{accountId}/{configId}',
'httpMethod' => 'GET',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'configId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'insert' => array(
'path' => 'pretargetingconfigs/{accountId}',
'httpMethod' => 'POST',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'pretargetingconfigs/{accountId}',
'httpMethod' => 'GET',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'patch' => array(
'path' => 'pretargetingconfigs/{accountId}/{configId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'configId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'update' => array(
'path' => 'pretargetingconfigs/{accountId}/{configId}',
'httpMethod' => 'PUT',
'parameters' => array(
'accountId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'configId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
}
}
/**
* The "accounts" collection of methods.
* Typical usage is:
* <code>
* $adexchangebuyerService = new Google_Service_AdExchangeBuyer(...);
* $accounts = $adexchangebuyerService->accounts;
* </code>
*/
class Google_Service_AdExchangeBuyer_Accounts_Resource extends Google_Service_Resource
{
/**
* Gets one account by ID. (accounts.get)
*
* @param int $id
* The account id
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_Account
*/
public function get($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_AdExchangeBuyer_Account");
}
/**
* Retrieves the authenticated user's list of accounts. (accounts.listAccounts)
*
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_AccountsList
*/
public function listAccounts($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AdExchangeBuyer_AccountsList");
}
/**
* Updates an existing account. This method supports patch semantics.
* (accounts.patch)
*
* @param int $id
* The account id
* @param Google_Account $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_Account
*/
public function patch($id, Google_Service_AdExchangeBuyer_Account $postBody, $optParams = array())
{
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_AdExchangeBuyer_Account");
}
/**
* Updates an existing account. (accounts.update)
*
* @param int $id
* The account id
* @param Google_Account $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_Account
*/
public function update($id, Google_Service_AdExchangeBuyer_Account $postBody, $optParams = array())
{
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_AdExchangeBuyer_Account");
}
}
/**
* The "creatives" collection of methods.
* Typical usage is:
* <code>
* $adexchangebuyerService = new Google_Service_AdExchangeBuyer(...);
* $creatives = $adexchangebuyerService->creatives;
* </code>
*/
class Google_Service_AdExchangeBuyer_Creatives_Resource extends Google_Service_Resource
{
/**
* Gets the status for a single creative. A creative will be available 30-40
* minutes after submission. (creatives.get)
*
* @param int $accountId
* The id for the account that will serve this creative.
* @param string $buyerCreativeId
* The buyer-specific id for this creative.
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_Creative
*/
public function get($accountId, $buyerCreativeId, $optParams = array())
{
$params = array('accountId' => $accountId, 'buyerCreativeId' => $buyerCreativeId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_AdExchangeBuyer_Creative");
}
/**
* Submit a new creative. (creatives.insert)
*
* @param Google_Creative $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_Creative
*/
public function insert(Google_Service_AdExchangeBuyer_Creative $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_AdExchangeBuyer_Creative");
}
/**
* Retrieves a list of the authenticated user's active creatives. A creative
* will be available 30-40 minutes after submission. (creatives.listCreatives)
*
* @param array $optParams Optional parameters.
*
* @opt_param string statusFilter
* When specified, only creatives having the given status are returned.
* @opt_param string pageToken
* A continuation token, used to page through ad clients. To retrieve the next page, set this
* parameter to the value of "nextPageToken" from the previous response. Optional.
* @opt_param string maxResults
* Maximum number of entries returned on one result page. If not set, the default is 100. Optional.
* @opt_param string buyerCreativeId
* When specified, only creatives for the given buyer creative ids are returned.
* @opt_param int accountId
* When specified, only creatives for the given account ids are returned.
* @return Google_Service_AdExchangeBuyer_CreativesList
*/
public function listCreatives($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AdExchangeBuyer_CreativesList");
}
}
/**
* The "directDeals" collection of methods.
* Typical usage is:
* <code>
* $adexchangebuyerService = new Google_Service_AdExchangeBuyer(...);
* $directDeals = $adexchangebuyerService->directDeals;
* </code>
*/
class Google_Service_AdExchangeBuyer_DirectDeals_Resource extends Google_Service_Resource
{
/**
* Gets one direct deal by ID. (directDeals.get)
*
* @param string $id
* The direct deal id
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_DirectDeal
*/
public function get($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_AdExchangeBuyer_DirectDeal");
}
/**
* Retrieves the authenticated user's list of direct deals.
* (directDeals.listDirectDeals)
*
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_DirectDealsList
*/
public function listDirectDeals($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AdExchangeBuyer_DirectDealsList");
}
}
/**
* The "performanceReport" collection of methods.
* Typical usage is:
* <code>
* $adexchangebuyerService = new Google_Service_AdExchangeBuyer(...);
* $performanceReport = $adexchangebuyerService->performanceReport;
* </code>
*/
class Google_Service_AdExchangeBuyer_PerformanceReport_Resource extends Google_Service_Resource
{
/**
* Retrieves the authenticated user's list of performance metrics.
* (performanceReport.listPerformanceReport)
*
* @param string $accountId
* The account id to get the reports.
* @param string $endDateTime
* The end time of the report in ISO 8601 timestamp format using UTC.
* @param string $startDateTime
* The start time of the report in ISO 8601 timestamp format using UTC.
* @param array $optParams Optional parameters.
*
* @opt_param string pageToken
* A continuation token, used to page through performance reports. To retrieve the next page, set
* this parameter to the value of "nextPageToken" from the previous response. Optional.
* @opt_param string maxResults
* Maximum number of entries returned on one result page. If not set, the default is 100. Optional.
* @return Google_Service_AdExchangeBuyer_PerformanceReportList
*/
public function listPerformanceReport($accountId, $endDateTime, $startDateTime, $optParams = array())
{
$params = array('accountId' => $accountId, 'endDateTime' => $endDateTime, 'startDateTime' => $startDateTime);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AdExchangeBuyer_PerformanceReportList");
}
}
/**
* The "pretargetingConfig" collection of methods.
* Typical usage is:
* <code>
* $adexchangebuyerService = new Google_Service_AdExchangeBuyer(...);
* $pretargetingConfig = $adexchangebuyerService->pretargetingConfig;
* </code>
*/
class Google_Service_AdExchangeBuyer_PretargetingConfig_Resource extends Google_Service_Resource
{
/**
* Deletes an existing pretargeting config. (pretargetingConfig.delete)
*
* @param string $accountId
* The account id to delete the pretargeting config for.
* @param string $configId
* The specific id of the configuration to delete.
* @param array $optParams Optional parameters.
*/
public function delete($accountId, $configId, $optParams = array())
{
$params = array('accountId' => $accountId, 'configId' => $configId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Gets a specific pretargeting configuration (pretargetingConfig.get)
*
* @param string $accountId
* The account id to get the pretargeting config for.
* @param string $configId
* The specific id of the configuration to retrieve.
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_PretargetingConfig
*/
public function get($accountId, $configId, $optParams = array())
{
$params = array('accountId' => $accountId, 'configId' => $configId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_AdExchangeBuyer_PretargetingConfig");
}
/**
* Inserts a new pretargeting configuration. (pretargetingConfig.insert)
*
* @param string $accountId
* The account id to insert the pretargeting config for.
* @param Google_PretargetingConfig $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_PretargetingConfig
*/
public function insert($accountId, Google_Service_AdExchangeBuyer_PretargetingConfig $postBody, $optParams = array())
{
$params = array('accountId' => $accountId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_AdExchangeBuyer_PretargetingConfig");
}
/**
* Retrieves a list of the authenticated user's pretargeting configurations.
* (pretargetingConfig.listPretargetingConfig)
*
* @param string $accountId
* The account id to get the pretargeting configs for.
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_PretargetingConfigList
*/
public function listPretargetingConfig($accountId, $optParams = array())
{
$params = array('accountId' => $accountId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_AdExchangeBuyer_PretargetingConfigList");
}
/**
* Updates an existing pretargeting config. This method supports patch
* semantics. (pretargetingConfig.patch)
*
* @param string $accountId
* The account id to update the pretargeting config for.
* @param string $configId
* The specific id of the configuration to update.
* @param Google_PretargetingConfig $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_PretargetingConfig
*/
public function patch($accountId, $configId, Google_Service_AdExchangeBuyer_PretargetingConfig $postBody, $optParams = array())
{
$params = array('accountId' => $accountId, 'configId' => $configId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_AdExchangeBuyer_PretargetingConfig");
}
/**
* Updates an existing pretargeting config. (pretargetingConfig.update)
*
* @param string $accountId
* The account id to update the pretargeting config for.
* @param string $configId
* The specific id of the configuration to update.
* @param Google_PretargetingConfig $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_AdExchangeBuyer_PretargetingConfig
*/
public function update($accountId, $configId, Google_Service_AdExchangeBuyer_PretargetingConfig $postBody, $optParams = array())
{
$params = array('accountId' => $accountId, 'configId' => $configId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_AdExchangeBuyer_PretargetingConfig");
}
}
class Google_Service_AdExchangeBuyer_Account extends Google_Collection
{
protected $bidderLocationType = 'Google_Service_AdExchangeBuyer_AccountBidderLocation';
protected $bidderLocationDataType = 'array';
public $cookieMatchingNid;
public $cookieMatchingUrl;
public $id;
public $kind;
public $maximumTotalQps;
public function setBidderLocation($bidderLocation)
{
$this->bidderLocation = $bidderLocation;
}
public function getBidderLocation()
{
return $this->bidderLocation;
}
public function setCookieMatchingNid($cookieMatchingNid)
{
$this->cookieMatchingNid = $cookieMatchingNid;
}
public function getCookieMatchingNid()
{
return $this->cookieMatchingNid;
}
public function setCookieMatchingUrl($cookieMatchingUrl)
{
$this->cookieMatchingUrl = $cookieMatchingUrl;
}
public function getCookieMatchingUrl()
{
return $this->cookieMatchingUrl;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setMaximumTotalQps($maximumTotalQps)
{
$this->maximumTotalQps = $maximumTotalQps;
}
public function getMaximumTotalQps()
{
return $this->maximumTotalQps;
}
}
class Google_Service_AdExchangeBuyer_AccountBidderLocation extends Google_Model
{
public $maximumQps;
public $region;
public $url;
public function setMaximumQps($maximumQps)
{
$this->maximumQps = $maximumQps;
}
public function getMaximumQps()
{
return $this->maximumQps;
}
public function setRegion($region)
{
$this->region = $region;
}
public function getRegion()
{
return $this->region;
}
public function setUrl($url)
{
$this->url = $url;
}
public function getUrl()
{
return $this->url;
}
}
class Google_Service_AdExchangeBuyer_AccountsList extends Google_Collection
{
protected $itemsType = 'Google_Service_AdExchangeBuyer_Account';
protected $itemsDataType = 'array';
public $kind;
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_AdExchangeBuyer_Creative extends Google_Collection
{
public $hTMLSnippet;
public $accountId;
public $advertiserId;
public $advertiserName;
public $agencyId;
public $attribute;
public $buyerCreativeId;
public $clickThroughUrl;
protected $correctionsType = 'Google_Service_AdExchangeBuyer_CreativeCorrections';
protected $correctionsDataType = 'array';
protected $disapprovalReasonsType = 'Google_Service_AdExchangeBuyer_CreativeDisapprovalReasons';
protected $disapprovalReasonsDataType = 'array';
protected $filteringReasonsType = 'Google_Service_AdExchangeBuyer_CreativeFilteringReasons';
protected $filteringReasonsDataType = '';
public $height;
public $kind;
public $productCategories;
public $restrictedCategories;
public $sensitiveCategories;
public $status;
public $vendorType;
public $videoURL;
public $width;
public function setHTMLSnippet($hTMLSnippet)
{
$this->hTMLSnippet = $hTMLSnippet;
}
public function getHTMLSnippet()
{
return $this->hTMLSnippet;
}
public function setAccountId($accountId)
{
$this->accountId = $accountId;
}
public function getAccountId()
{
return $this->accountId;
}
public function setAdvertiserId($advertiserId)
{
$this->advertiserId = $advertiserId;
}
public function getAdvertiserId()
{
return $this->advertiserId;
}
public function setAdvertiserName($advertiserName)
{
$this->advertiserName = $advertiserName;
}
public function getAdvertiserName()
{
return $this->advertiserName;
}
public function setAgencyId($agencyId)
{
$this->agencyId = $agencyId;
}
public function getAgencyId()
{
return $this->agencyId;
}
public function setAttribute($attribute)
{
$this->attribute = $attribute;
}
public function getAttribute()
{
return $this->attribute;
}
public function setBuyerCreativeId($buyerCreativeId)
{
$this->buyerCreativeId = $buyerCreativeId;
}
public function getBuyerCreativeId()
{
return $this->buyerCreativeId;
}
public function setClickThroughUrl($clickThroughUrl)
{
$this->clickThroughUrl = $clickThroughUrl;
}
public function getClickThroughUrl()
{
return $this->clickThroughUrl;
}
public function setCorrections($corrections)
{
$this->corrections = $corrections;
}
public function getCorrections()
{
return $this->corrections;
}
public function setDisapprovalReasons($disapprovalReasons)
{
$this->disapprovalReasons = $disapprovalReasons;
}
public function getDisapprovalReasons()
{
return $this->disapprovalReasons;
}
public function setFilteringReasons(Google_Service_AdExchangeBuyer_CreativeFilteringReasons $filteringReasons)
{
$this->filteringReasons = $filteringReasons;
}
public function getFilteringReasons()
{
return $this->filteringReasons;
}
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setProductCategories($productCategories)
{
$this->productCategories = $productCategories;
}
public function getProductCategories()
{
return $this->productCategories;
}
public function setRestrictedCategories($restrictedCategories)
{
$this->restrictedCategories = $restrictedCategories;
}
public function getRestrictedCategories()
{
return $this->restrictedCategories;
}
public function setSensitiveCategories($sensitiveCategories)
{
$this->sensitiveCategories = $sensitiveCategories;
}
public function getSensitiveCategories()
{
return $this->sensitiveCategories;
}
public function setStatus($status)
{
$this->status = $status;
}
public function getStatus()
{
return $this->status;
}
public function setVendorType($vendorType)
{
$this->vendorType = $vendorType;
}
public function getVendorType()
{
return $this->vendorType;
}
public function setVideoURL($videoURL)
{
$this->videoURL = $videoURL;
}
public function getVideoURL()
{
return $this->videoURL;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
}
class Google_Service_AdExchangeBuyer_CreativeCorrections extends Google_Collection
{
public $details;
public $reason;
public function setDetails($details)
{
$this->details = $details;
}
public function getDetails()
{
return $this->details;
}
public function setReason($reason)
{
$this->reason = $reason;
}
public function getReason()
{
return $this->reason;
}
}
class Google_Service_AdExchangeBuyer_CreativeDisapprovalReasons extends Google_Collection
{
public $details;
public $reason;
public function setDetails($details)
{
$this->details = $details;
}
public function getDetails()
{
return $this->details;
}
public function setReason($reason)
{
$this->reason = $reason;
}
public function getReason()
{
return $this->reason;
}
}
class Google_Service_AdExchangeBuyer_CreativeFilteringReasons extends Google_Collection
{
public $date;
protected $reasonsType = 'Google_Service_AdExchangeBuyer_CreativeFilteringReasonsReasons';
protected $reasonsDataType = 'array';
public function setDate($date)
{
$this->date = $date;
}
public function getDate()
{
return $this->date;
}
public function setReasons($reasons)
{
$this->reasons = $reasons;
}
public function getReasons()
{
return $this->reasons;
}
}
class Google_Service_AdExchangeBuyer_CreativeFilteringReasonsReasons extends Google_Model
{
public $filteringCount;
public $filteringStatus;
public function setFilteringCount($filteringCount)
{
$this->filteringCount = $filteringCount;
}
public function getFilteringCount()
{
return $this->filteringCount;
}
public function setFilteringStatus($filteringStatus)
{
$this->filteringStatus = $filteringStatus;
}
public function getFilteringStatus()
{
return $this->filteringStatus;
}
}
class Google_Service_AdExchangeBuyer_CreativesList extends Google_Collection
{
protected $itemsType = 'Google_Service_AdExchangeBuyer_Creative';
protected $itemsDataType = 'array';
public $kind;
public $nextPageToken;
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
class Google_Service_AdExchangeBuyer_DirectDeal extends Google_Model
{
public $accountId;
public $advertiser;
public $currencyCode;
public $endTime;
public $fixedCpm;
public $id;
public $kind;
public $name;
public $privateExchangeMinCpm;
public $sellerNetwork;
public $startTime;
public function setAccountId($accountId)
{
$this->accountId = $accountId;
}
public function getAccountId()
{
return $this->accountId;
}
public function setAdvertiser($advertiser)
{
$this->advertiser = $advertiser;
}
public function getAdvertiser()
{
return $this->advertiser;
}
public function setCurrencyCode($currencyCode)
{
$this->currencyCode = $currencyCode;
}
public function getCurrencyCode()
{
return $this->currencyCode;
}
public function setEndTime($endTime)
{
$this->endTime = $endTime;
}
public function getEndTime()
{
return $this->endTime;
}
public function setFixedCpm($fixedCpm)
{
$this->fixedCpm = $fixedCpm;
}
public function getFixedCpm()
{
return $this->fixedCpm;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setPrivateExchangeMinCpm($privateExchangeMinCpm)
{
$this->privateExchangeMinCpm = $privateExchangeMinCpm;
}
public function getPrivateExchangeMinCpm()
{
return $this->privateExchangeMinCpm;
}
public function setSellerNetwork($sellerNetwork)
{
$this->sellerNetwork = $sellerNetwork;
}
public function getSellerNetwork()
{
return $this->sellerNetwork;
}
public function setStartTime($startTime)
{
$this->startTime = $startTime;
}
public function getStartTime()
{
return $this->startTime;
}
}
class Google_Service_AdExchangeBuyer_DirectDealsList extends Google_Collection
{
protected $directDealsType = 'Google_Service_AdExchangeBuyer_DirectDeal';
protected $directDealsDataType = 'array';
public $kind;
public function setDirectDeals($directDeals)
{
$this->directDeals = $directDeals;
}
public function getDirectDeals()
{
return $this->directDeals;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_AdExchangeBuyer_PerformanceReport extends Google_Collection
{
public $calloutStatusRate;
public $cookieMatcherStatusRate;
public $creativeStatusRate;
public $hostedMatchStatusRate;
public $kind;
public $latency50thPercentile;
public $latency85thPercentile;
public $latency95thPercentile;
public $noQuotaInRegion;
public $outOfQuota;
public $pixelMatchRequests;
public $pixelMatchResponses;
public $quotaConfiguredLimit;
public $quotaThrottledLimit;
public $region;
public $timestamp;
public function setCalloutStatusRate($calloutStatusRate)
{
$this->calloutStatusRate = $calloutStatusRate;
}
public function getCalloutStatusRate()
{
return $this->calloutStatusRate;
}
public function setCookieMatcherStatusRate($cookieMatcherStatusRate)
{
$this->cookieMatcherStatusRate = $cookieMatcherStatusRate;
}
public function getCookieMatcherStatusRate()
{
return $this->cookieMatcherStatusRate;
}
public function setCreativeStatusRate($creativeStatusRate)
{
$this->creativeStatusRate = $creativeStatusRate;
}
public function getCreativeStatusRate()
{
return $this->creativeStatusRate;
}
public function setHostedMatchStatusRate($hostedMatchStatusRate)
{
$this->hostedMatchStatusRate = $hostedMatchStatusRate;
}
public function getHostedMatchStatusRate()
{
return $this->hostedMatchStatusRate;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setLatency50thPercentile($latency50thPercentile)
{
$this->latency50thPercentile = $latency50thPercentile;
}
public function getLatency50thPercentile()
{
return $this->latency50thPercentile;
}
public function setLatency85thPercentile($latency85thPercentile)
{
$this->latency85thPercentile = $latency85thPercentile;
}
public function getLatency85thPercentile()
{
return $this->latency85thPercentile;
}
public function setLatency95thPercentile($latency95thPercentile)
{
$this->latency95thPercentile = $latency95thPercentile;
}
public function getLatency95thPercentile()
{
return $this->latency95thPercentile;
}
public function setNoQuotaInRegion($noQuotaInRegion)
{
$this->noQuotaInRegion = $noQuotaInRegion;
}
public function getNoQuotaInRegion()
{
return $this->noQuotaInRegion;
}
public function setOutOfQuota($outOfQuota)
{
$this->outOfQuota = $outOfQuota;
}
public function getOutOfQuota()
{
return $this->outOfQuota;
}
public function setPixelMatchRequests($pixelMatchRequests)
{
$this->pixelMatchRequests = $pixelMatchRequests;
}
public function getPixelMatchRequests()
{
return $this->pixelMatchRequests;
}
public function setPixelMatchResponses($pixelMatchResponses)
{
$this->pixelMatchResponses = $pixelMatchResponses;
}
public function getPixelMatchResponses()
{
return $this->pixelMatchResponses;
}
public function setQuotaConfiguredLimit($quotaConfiguredLimit)
{
$this->quotaConfiguredLimit = $quotaConfiguredLimit;
}
public function getQuotaConfiguredLimit()
{
return $this->quotaConfiguredLimit;
}
public function setQuotaThrottledLimit($quotaThrottledLimit)
{
$this->quotaThrottledLimit = $quotaThrottledLimit;
}
public function getQuotaThrottledLimit()
{
return $this->quotaThrottledLimit;
}
public function setRegion($region)
{
$this->region = $region;
}
public function getRegion()
{
return $this->region;
}
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
}
public function getTimestamp()
{
return $this->timestamp;
}
}
class Google_Service_AdExchangeBuyer_PerformanceReportList extends Google_Collection
{
public $kind;
protected $performanceReportType = 'Google_Service_AdExchangeBuyer_PerformanceReport';
protected $performanceReportDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPerformanceReport($performanceReport)
{
$this->performanceReport = $performanceReport;
}
public function getPerformanceReport()
{
return $this->performanceReport;
}
}
class Google_Service_AdExchangeBuyer_PretargetingConfig extends Google_Collection
{
public $configId;
public $configName;
public $creativeType;
protected $dimensionsType = 'Google_Service_AdExchangeBuyer_PretargetingConfigDimensions';
protected $dimensionsDataType = 'array';
public $excludedContentLabels;
public $excludedGeoCriteriaIds;
protected $excludedPlacementsType = 'Google_Service_AdExchangeBuyer_PretargetingConfigExcludedPlacements';
protected $excludedPlacementsDataType = 'array';
public $excludedUserLists;
public $excludedVerticals;
public $geoCriteriaIds;
public $isActive;
public $kind;
public $languages;
public $mobileCarriers;
public $mobileDevices;
public $mobileOperatingSystemVersions;
protected $placementsType = 'Google_Service_AdExchangeBuyer_PretargetingConfigPlacements';
protected $placementsDataType = 'array';
public $platforms;
public $supportedCreativeAttributes;
public $userLists;
public $vendorTypes;
public $verticals;
public function setConfigId($configId)
{
$this->configId = $configId;
}
public function getConfigId()
{
return $this->configId;
}
public function setConfigName($configName)
{
$this->configName = $configName;
}
public function getConfigName()
{
return $this->configName;
}
public function setCreativeType($creativeType)
{
$this->creativeType = $creativeType;
}
public function getCreativeType()
{
return $this->creativeType;
}
public function setDimensions($dimensions)
{
$this->dimensions = $dimensions;
}
public function getDimensions()
{
return $this->dimensions;
}
public function setExcludedContentLabels($excludedContentLabels)
{
$this->excludedContentLabels = $excludedContentLabels;
}
public function getExcludedContentLabels()
{
return $this->excludedContentLabels;
}
public function setExcludedGeoCriteriaIds($excludedGeoCriteriaIds)
{
$this->excludedGeoCriteriaIds = $excludedGeoCriteriaIds;
}
public function getExcludedGeoCriteriaIds()
{
return $this->excludedGeoCriteriaIds;
}
public function setExcludedPlacements($excludedPlacements)
{
$this->excludedPlacements = $excludedPlacements;
}
public function getExcludedPlacements()
{
return $this->excludedPlacements;
}
public function setExcludedUserLists($excludedUserLists)
{
$this->excludedUserLists = $excludedUserLists;
}
public function getExcludedUserLists()
{
return $this->excludedUserLists;
}
public function setExcludedVerticals($excludedVerticals)
{
$this->excludedVerticals = $excludedVerticals;
}
public function getExcludedVerticals()
{
return $this->excludedVerticals;
}
public function setGeoCriteriaIds($geoCriteriaIds)
{
$this->geoCriteriaIds = $geoCriteriaIds;
}
public function getGeoCriteriaIds()
{
return $this->geoCriteriaIds;
}
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
public function getIsActive()
{
return $this->isActive;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setLanguages($languages)
{
$this->languages = $languages;
}
public function getLanguages()
{
return $this->languages;
}
public function setMobileCarriers($mobileCarriers)
{
$this->mobileCarriers = $mobileCarriers;
}
public function getMobileCarriers()
{
return $this->mobileCarriers;
}
public function setMobileDevices($mobileDevices)
{
$this->mobileDevices = $mobileDevices;
}
public function getMobileDevices()
{
return $this->mobileDevices;
}
public function setMobileOperatingSystemVersions($mobileOperatingSystemVersions)
{
$this->mobileOperatingSystemVersions = $mobileOperatingSystemVersions;
}
public function getMobileOperatingSystemVersions()
{
return $this->mobileOperatingSystemVersions;
}
public function setPlacements($placements)
{
$this->placements = $placements;
}
public function getPlacements()
{
return $this->placements;
}
public function setPlatforms($platforms)
{
$this->platforms = $platforms;
}
public function getPlatforms()
{
return $this->platforms;
}
public function setSupportedCreativeAttributes($supportedCreativeAttributes)
{
$this->supportedCreativeAttributes = $supportedCreativeAttributes;
}
public function getSupportedCreativeAttributes()
{
return $this->supportedCreativeAttributes;
}
public function setUserLists($userLists)
{
$this->userLists = $userLists;
}
public function getUserLists()
{
return $this->userLists;
}
public function setVendorTypes($vendorTypes)
{
$this->vendorTypes = $vendorTypes;
}
public function getVendorTypes()
{
return $this->vendorTypes;
}
public function setVerticals($verticals)
{
$this->verticals = $verticals;
}
public function getVerticals()
{
return $this->verticals;
}
}
class Google_Service_AdExchangeBuyer_PretargetingConfigDimensions extends Google_Model
{
public $height;
public $width;
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
}
class Google_Service_AdExchangeBuyer_PretargetingConfigExcludedPlacements extends Google_Model
{
public $token;
public $type;
public function setToken($token)
{
$this->token = $token;
}
public function getToken()
{
return $this->token;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
class Google_Service_AdExchangeBuyer_PretargetingConfigList extends Google_Collection
{
protected $itemsType = 'Google_Service_AdExchangeBuyer_PretargetingConfig';
protected $itemsDataType = 'array';
public $kind;
public function setItems($items)
{
$this->items = $items;
}
public function getItems()
{
return $this->items;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
}
class Google_Service_AdExchangeBuyer_PretargetingConfigPlacements extends Google_Model
{
public $token;
public $type;
public function setToken($token)
{
$this->token = $token;
}
public function getToken()
{
return $this->token;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
| lgpl-2.1 |
sfu-ireceptor/gateway | public/js/highcharts/code/es-modules/Stock/Indicators/PriceEnvelopes/PriceEnvelopesIndicator.js | 8818 | /* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import SeriesRegistry from '../../../Core/Series/SeriesRegistry.js';
var SMAIndicator = SeriesRegistry.seriesTypes.sma;
import U from '../../../Core/Utilities.js';
var extend = U.extend, isArray = U.isArray, merge = U.merge;
/**
* The Price Envelopes series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.priceenvelopes
*
* @augments Highcharts.Series
*/
var PriceEnvelopesIndicator = /** @class */ (function (_super) {
__extends(PriceEnvelopesIndicator, _super);
function PriceEnvelopesIndicator() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.data = void 0;
_this.options = void 0;
_this.points = void 0;
return _this;
}
PriceEnvelopesIndicator.prototype.init = function () {
SeriesRegistry.seriesTypes.sma.prototype.init.apply(this, arguments);
// Set default color for lines:
this.options = merge({
topLine: {
styles: {
lineColor: this.color
}
},
bottomLine: {
styles: {
lineColor: this.color
}
}
}, this.options);
};
PriceEnvelopesIndicator.prototype.toYData = function (point) {
return [point.top, point.middle, point.bottom];
};
PriceEnvelopesIndicator.prototype.translate = function () {
var indicator = this, translatedEnvelopes = ['plotTop', 'plotMiddle', 'plotBottom'];
SeriesRegistry.seriesTypes.sma.prototype.translate.apply(indicator);
indicator.points.forEach(function (point) {
[point.top, point.middle, point.bottom].forEach(function (value, i) {
if (value !== null) {
point[translatedEnvelopes[i]] =
indicator.yAxis.toPixels(value, true);
}
});
});
};
PriceEnvelopesIndicator.prototype.drawGraph = function () {
var indicator = this, middleLinePoints = indicator.points, pointsLength = middleLinePoints.length, middleLineOptions = (indicator.options), middleLinePath = indicator.graph, gappedExtend = {
options: {
gapSize: middleLineOptions.gapSize
}
}, deviations = [[], []], // top and bottom point place holders
point;
// Generate points for top and bottom lines:
while (pointsLength--) {
point = middleLinePoints[pointsLength];
deviations[0].push({
plotX: point.plotX,
plotY: point.plotTop,
isNull: point.isNull
});
deviations[1].push({
plotX: point.plotX,
plotY: point.plotBottom,
isNull: point.isNull
});
}
// Modify options and generate lines:
['topLine', 'bottomLine'].forEach(function (lineName, i) {
indicator.points = deviations[i];
indicator.options = merge(middleLineOptions[lineName].styles, gappedExtend);
indicator.graph = indicator['graph' + lineName];
SeriesRegistry.seriesTypes.sma.prototype.drawGraph.call(indicator);
// Now save lines:
indicator['graph' + lineName] = indicator.graph;
});
// Restore options and draw a middle line:
indicator.points = middleLinePoints;
indicator.options = middleLineOptions;
indicator.graph = middleLinePath;
SeriesRegistry.seriesTypes.sma.prototype.drawGraph.call(indicator);
};
PriceEnvelopesIndicator.prototype.getValues = function (series, params) {
var period = params.period, topPercent = params.topBand, botPercent = params.bottomBand, xVal = series.xData, yVal = series.yData, yValLen = yVal ? yVal.length : 0,
// 0- date, 1-top line, 2-middle line, 3-bottom line
PE = [],
// middle line, top line and bottom line
ML, TL, BL, date, xData = [], yData = [], slicedX, slicedY, point, i;
// Price envelopes requires close value
if (xVal.length < period ||
!isArray(yVal[0]) ||
yVal[0].length !== 4) {
return;
}
for (i = period; i <= yValLen; i++) {
slicedX = xVal.slice(i - period, i);
slicedY = yVal.slice(i - period, i);
point = SeriesRegistry.seriesTypes.sma.prototype.getValues.call(this, {
xData: slicedX,
yData: slicedY
}, params);
date = point.xData[0];
ML = point.yData[0];
TL = ML * (1 + topPercent);
BL = ML * (1 - botPercent);
PE.push([date, TL, ML, BL]);
xData.push(date);
yData.push([TL, ML, BL]);
}
return {
values: PE,
xData: xData,
yData: yData
};
};
/**
* Price envelopes indicator based on [SMA](#plotOptions.sma) calculations.
* This series requires the `linkedTo` option to be set and should be loaded
* after the `stock/indicators/indicators.js` file.
*
* @sample stock/indicators/price-envelopes
* Price envelopes
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/price-envelopes
* @optionparent plotOptions.priceenvelopes
*/
PriceEnvelopesIndicator.defaultOptions = merge(SMAIndicator.defaultOptions, {
marker: {
enabled: false
},
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>'
},
params: {
period: 20,
/**
* Percentage above the moving average that should be displayed.
* 0.1 means 110%. Relative to the calculated value.
*/
topBand: 0.1,
/**
* Percentage below the moving average that should be displayed.
* 0.1 means 90%. Relative to the calculated value.
*/
bottomBand: 0.1
},
/**
* Bottom line options.
*/
bottomLine: {
styles: {
/**
* Pixel width of the line.
*/
lineWidth: 1,
/**
* Color of the line. If not set, it's inherited from
* [plotOptions.priceenvelopes.color](
* #plotOptions.priceenvelopes.color).
*
* @type {Highcharts.ColorString}
*/
lineColor: void 0
}
},
/**
* Top line options.
*
* @extends plotOptions.priceenvelopes.bottomLine
*/
topLine: {
styles: {
lineWidth: 1
}
},
dataGrouping: {
approximation: 'averages'
}
});
return PriceEnvelopesIndicator;
}(SMAIndicator));
extend(PriceEnvelopesIndicator.prototype, {
nameComponents: ['period', 'topBand', 'bottomBand'],
nameBase: 'Price envelopes',
pointArrayMap: ['top', 'middle', 'bottom'],
parallelArrays: ['x', 'y', 'top', 'bottom'],
pointValKey: 'middle'
});
SeriesRegistry.registerSeriesType('priceenvelopes', PriceEnvelopesIndicator);
/* *
*
* Default Export
*
* */
export default PriceEnvelopesIndicator;
/**
* A price envelopes indicator. If the [type](#series.priceenvelopes.type)
* option is not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.priceenvelopes
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/price-envelopes
* @apioption series.priceenvelopes
*/
''; // to include the above in the js output
| lgpl-3.0 |
jzmq/pinot | pinot-core/src/main/java/com/linkedin/pinot/core/realtime/impl/invertedIndex/RealtimeInvertedIndex.java | 1001 | /**
* Copyright (C) 2014-2015 LinkedIn Corp. (pinot-core@linkedin.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linkedin.pinot.core.realtime.impl.invertedIndex;
import org.roaringbitmap.buffer.MutableRoaringBitmap;
import com.linkedin.pinot.core.segment.index.InvertedIndexReader;
public interface RealtimeInvertedIndex extends InvertedIndexReader {
public void add(Object dictId, int docId);
public MutableRoaringBitmap getDocIdSetFor(Object dicId);
}
| apache-2.0 |
mglukhikh/intellij-community | java/java-tests/testSrc/com/intellij/java/refactoring/IntroduceFieldWitSetUpInitializationTest.java | 3818 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.refactoring;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiLocalVariable;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.introduceField.BaseExpressionToFieldHandler;
import com.intellij.refactoring.introduceField.LocalToFieldHandler;
import com.intellij.util.PathUtil;
import org.jetbrains.annotations.NotNull;
import org.junit.Before;
import java.io.File;
public class IntroduceFieldWitSetUpInitializationTest extends CodeInsightTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath();
}
@NotNull
@Override
protected Module createModule(final String name) {
final Module module = super.createModule(name);
final String url = VfsUtil.getUrlForLibraryRoot(new File(PathUtil.getJarPathForClass(Before.class)));
ModuleRootModificationUtil.addModuleLibrary(module, url);
return module;
}
public void testInSetUp() throws Exception {
doTest();
}
public void testInitiallyInSetUp() throws Exception {
doTest();
}
public void testPublicBaseClassSetUp() throws Exception {
doTest();
}
public void testBeforeExist() throws Exception {
doTest();
}
public void testBeforeNotExist() throws Exception {
doTest();
}
public void testBeforeNotExist1() throws Exception {
doTest();
}
public void testOrderInSetup() throws Exception {
doTest();
}
public void testBeforeExistNonAnnotated() throws Exception {
doTest();
}
private void doTest() throws Exception {
configureByFile("/refactoring/introduceField/before" + getTestName(false) + ".java");
final PsiLocalVariable local =
PsiTreeUtil.getParentOfType(getFile().findElementAt(getEditor().getCaretModel().getOffset()), PsiLocalVariable.class);
new LocalToFieldHandler(getProject(), false) {
@Override
protected BaseExpressionToFieldHandler.Settings showRefactoringDialog(final PsiClass aClass,
final PsiLocalVariable local,
final PsiExpression[] occurences,
final boolean isStatic) {
return new BaseExpressionToFieldHandler.Settings("i", null, occurences, true, false, false,
BaseExpressionToFieldHandler.InitializationPlace.IN_SETUP_METHOD,
PsiModifier.PRIVATE, local, local.getType(), true, (BaseExpressionToFieldHandler.TargetDestination)null, false,
false);
}
}.convertLocalToField(local, myEditor);
checkResultByFile("/refactoring/introduceField/after" + getTestName(false)+ ".java");
}
}
| apache-2.0 |
tr3vr/jena | jena-arq/src/main/java/org/apache/jena/query/QueryParseException.java | 2189 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.query;
/** QueryParseException is root exception for all (intentional) exceptions
* from the various parsers where the error is to do with the syntax of a query.
*/
public class QueryParseException extends QueryException
{
private int line ;
private int column ;
public QueryParseException(int line, int column)
{ this(null, null, line, column) ; }
public QueryParseException(Throwable cause, int line, int column)
{ this(null, cause, line, column) ; }
public QueryParseException(String msg, int line, int column)
{ this(msg, null, line, column) ; }
public QueryParseException(String msg, Throwable cause, int line, int column)
{
//super(formatMessage(msg, line, column), cause) ;
super(msg, cause) ;
set(line, column) ;
}
private void set(int line, int column)
{ this.line = line ; this.column = column ; }
/** Column number where the parse exception occurred. */
public int getColumn() { return column ; }
/** Line number where the parse exception occurred. */
public int getLine() { return line ; }
public static String formatMessage(String msg, int line, int column)
{
if ( line == -1 || column == -1 )
return msg ;
return String.format("[line: %d, col: %d] "+msg, line, column) ; }
}
| apache-2.0 |
corecode/obc-peer | bddtests/steps/peer_logging_impl.py | 1945 | #
# Copyright IBM Corp. 2016 All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import os.path
import re
import time
import copy
from datetime import datetime, timedelta
from behave import *
import sys, requests, json
import bdd_test_util
@then(u'I wait up to {waitTime} seconds for an error in the logs for peer {peerName}')
def step_impl(context, waitTime, peerName):
timeout = time.time() + float(waitTime)
hasError = False
while timeout > time.time():
stdout, stderr = getPeerLogs(context, peerName)
hasError = logHasError(stdout) or logHasError(stderr)
if hasError:
break
time.sleep(1.0)
assert hasError is True
def getPeerLogs(context, peerName):
fullContainerName = bdd_test_util.fullNameFromContainerNamePart(peerName, context.compose_containers)
stdout, stderr, retcode = bdd_test_util.cli_call(context, ["docker", "logs", fullContainerName], expect_success=True)
return stdout, stderr
def logHasError(logText):
# This seems to be an acceptable heuristic for detecting errors
return logText.find("-> ERRO") >= 0
@then(u'ensure after {waitTime} seconds there are no errors in the logs for peer {peerName}')
def step_impl(context, waitTime, peerName):
time.sleep(float(waitTime))
stdout, stderr = getPeerLogs(context, peerName)
assert logHasError(stdout) is False
assert logHasError(stderr) is False | apache-2.0 |
ssilvert/keycloak | services/src/main/java/org/keycloak/services/resources/admin/permissions/GroupPermissionEvaluator.java | 1697 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.services.resources.admin.permissions;
import org.keycloak.models.GroupModel;
import java.util.Map;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
public interface GroupPermissionEvaluator {
boolean canList();
void requireList();
boolean canManage(GroupModel group);
void requireManage(GroupModel group);
boolean canView(GroupModel group);
void requireView(GroupModel group);
boolean canManage();
void requireManage();
boolean canView();
void requireView();
boolean getGroupsWithViewPermission(GroupModel group);
void requireViewMembers(GroupModel group);
boolean canManageMembers(GroupModel group);
boolean canManageMembership(GroupModel group);
void requireManageMembership(GroupModel group);
void requireManageMembers(GroupModel group);
Map<String, Boolean> getAccess(GroupModel group);
Set<String> getGroupsWithViewPermission();
}
| apache-2.0 |
blois/AndroidSDKCloneMin | sdk/sources/android-20/com/android/test/hwui/BitmapsRectActivity.java | 2799 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.test.hwui;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
@SuppressWarnings({"UnusedDeclaration"})
public class BitmapsRectActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final BitmapsView view = new BitmapsView(this);
setContentView(view);
}
static class BitmapsView extends View {
private Paint mBitmapPaint;
private final Bitmap mBitmap1;
private final Bitmap mBitmap2;
private final Rect mSrcRect;
private final RectF mDstRect;
private final RectF mDstRect2;
BitmapsView(Context c) {
super(c);
mBitmap1 = BitmapFactory.decodeResource(c.getResources(), R.drawable.sunset1);
mBitmap2 = BitmapFactory.decodeResource(c.getResources(), R.drawable.sunset2);
mBitmapPaint = new Paint();
mBitmapPaint.setFilterBitmap(true);
final float fourth = mBitmap1.getWidth() / 4.0f;
final float half = mBitmap1.getHeight() / 2.0f;
mSrcRect = new Rect((int) fourth, (int) (half - half / 2.0f),
(int) (fourth + fourth), (int) (half + half / 2.0f));
mDstRect = new RectF(fourth, half - half / 2.0f, fourth + fourth, half + half / 2.0f);
mDstRect2 = new RectF(fourth, half - half / 2.0f,
(fourth + fourth) * 3.0f, (half + half / 2.0f) * 3.0f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.translate(120.0f, 50.0f);
canvas.drawBitmap(mBitmap1, mSrcRect, mDstRect, mBitmapPaint);
canvas.translate(0.0f, mBitmap1.getHeight());
canvas.translate(-100.0f, 25.0f);
canvas.drawBitmap(mBitmap1, mSrcRect, mDstRect2, mBitmapPaint);
}
}
} | apache-2.0 |
reneploetz/keycloak | integration/client-cli/admin-cli/src/main/java/org/keycloak/client/admin/cli/config/RealmConfigData.java | 4676 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.client.admin.cli.config;
import org.keycloak.util.JsonSerialization;
import java.io.IOException;
/**
* @author <a href="mailto:mstrukel@redhat.com">Marko Strukelj</a>
*/
public class RealmConfigData {
private String serverUrl;
private String realm;
private String clientId;
private String token;
private String refreshToken;
private String signingToken;
private String secret;
private String grantTypeForAuthentication;
private Long expiresAt;
private Long refreshExpiresAt;
private Long sigExpiresAt;
public String serverUrl() {
return serverUrl;
}
public void serverUrl(String serverUrl) {
this.serverUrl = serverUrl;
}
public String realm() {
return realm;
}
public void realm(String realm) {
this.realm = realm;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getSigningToken() {
return signingToken;
}
public void setSigningToken(String signingToken) {
this.signingToken = signingToken;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getGrantTypeForAuthentication() {
return grantTypeForAuthentication;
}
public void setGrantTypeForAuthentication(String grantTypeForAuthentication) {
this.grantTypeForAuthentication = grantTypeForAuthentication;
}
public Long getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(Long expiresAt) {
this.expiresAt = expiresAt;
}
public Long getRefreshExpiresAt() {
return refreshExpiresAt;
}
public void setRefreshExpiresAt(Long refreshExpiresAt) {
this.refreshExpiresAt = refreshExpiresAt;
}
public Long getSigExpiresAt() {
return sigExpiresAt;
}
public void setSigExpiresAt(Long sigExpiresAt) {
this.sigExpiresAt = sigExpiresAt;
}
public void merge(RealmConfigData source) {
serverUrl = source.serverUrl;
realm = source.realm;
clientId = source.clientId;
token = source.token;
refreshToken = source.refreshToken;
signingToken = source.signingToken;
secret = source.secret;
grantTypeForAuthentication = source.grantTypeForAuthentication;
expiresAt = source.expiresAt;
refreshExpiresAt = source.refreshExpiresAt;
sigExpiresAt = source.sigExpiresAt;
}
public void mergeRefreshTokens(RealmConfigData source) {
token = source.token;
refreshToken = source.refreshToken;
expiresAt = source.expiresAt;
refreshExpiresAt = source.refreshExpiresAt;
}
@Override
public String toString() {
try {
return JsonSerialization.writeValueAsPrettyString(this);
} catch (IOException e) {
return super.toString() + " - Error: " + e.toString();
}
}
public RealmConfigData deepcopy() {
RealmConfigData data = new RealmConfigData();
data.serverUrl = serverUrl;
data.realm = realm;
data.clientId = clientId;
data.token = token;
data.refreshToken = refreshToken;
data.signingToken = signingToken;
data.secret = secret;
data.grantTypeForAuthentication = grantTypeForAuthentication;
data.expiresAt = expiresAt;
data.refreshExpiresAt = refreshExpiresAt;
data.sigExpiresAt = sigExpiresAt;
return data;
}
}
| apache-2.0 |
wangyum/beam | sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/ReifyTimestamps.java | 2872 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.transforms;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TimestampedValue;
import org.joda.time.Duration;
/**
* {@link PTransform PTransforms} for reifying the timestamp of values and reemitting the original
* value with the original timestamp.
*/
class ReifyTimestamps {
private ReifyTimestamps() {}
/**
* Create a {@link PTransform} that will output all input {@link KV KVs} with the timestamp inside
* the value.
*/
public static <K, V>
PTransform<PCollection<? extends KV<K, V>>, PCollection<KV<K, TimestampedValue<V>>>>
inValues() {
return ParDo.of(new ReifyValueTimestampDoFn<K, V>());
}
/**
* Create a {@link PTransform} that consumes {@link KV KVs} with a {@link TimestampedValue} as the
* value, and outputs the {@link KV} of the input key and value at the timestamp specified by the
* {@link TimestampedValue}.
*/
public static <K, V>
PTransform<PCollection<? extends KV<K, TimestampedValue<V>>>, PCollection<KV<K, V>>>
extractFromValues() {
return ParDo.of(new ExtractTimestampedValueDoFn<K, V>());
}
private static class ReifyValueTimestampDoFn<K, V>
extends DoFn<KV<K, V>, KV<K, TimestampedValue<V>>> {
@ProcessElement
public void processElement(ProcessContext context) {
context.output(
KV.of(
context.element().getKey(),
TimestampedValue.of(context.element().getValue(), context.timestamp())));
}
}
private static class ExtractTimestampedValueDoFn<K, V>
extends DoFn<KV<K, TimestampedValue<V>>, KV<K, V>> {
@Override
public Duration getAllowedTimestampSkew() {
return Duration.millis(Long.MAX_VALUE);
}
@ProcessElement
public void processElement(ProcessContext context) {
KV<K, TimestampedValue<V>> kv = context.element();
context.outputWithTimestamp(
KV.of(kv.getKey(), kv.getValue().getValue()), kv.getValue().getTimestamp());
}
}
}
| apache-2.0 |
baslr/ArangoDB | 3rdParty/boost/1.62.0/libs/hana/test/experimental/printable/map.cpp | 1505 | // Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
#include <boost/hana/assert.hpp>
#include <boost/hana/experimental/printable.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/pair.hpp>
#include <sstream>
#include <string>
namespace hana = boost::hana;
int main() {
{
std::ostringstream ss;
ss << hana::experimental::print(
hana::make_map()
);
BOOST_HANA_RUNTIME_CHECK(ss.str() == "{}");
}
{
std::ostringstream ss;
ss << hana::experimental::print(
hana::make_map(hana::make_pair(hana::int_c<1>, 'x'))
);
BOOST_HANA_RUNTIME_CHECK(ss.str() == "{1 => x}");
}
{
std::ostringstream ss;
ss << hana::experimental::print(
hana::make_map(hana::make_pair(hana::int_c<1>, 'x'),
hana::make_pair(hana::int_c<2>, 'y'))
);
BOOST_HANA_RUNTIME_CHECK(ss.str() == "{1 => x, 2 => y}");
}
{
std::ostringstream ss;
ss << hana::experimental::print(
hana::make_map(hana::make_pair(hana::int_c<1>, 'x'),
hana::make_pair(hana::int_c<2>, 'y'),
hana::make_pair(hana::int_c<3>, 'z'))
);
BOOST_HANA_RUNTIME_CHECK(ss.str() == "{1 => x, 2 => y, 3 => z}");
}
}
| apache-2.0 |
kenneyhe/docker-10.6-x86_32 | vendor/src/github.com/docker/libnetwork/drivers/bridge/setup_fixedcidrv6.go | 371 | package bridge
import (
log "github.com/Sirupsen/logrus"
)
func setupFixedCIDRv6(config *NetworkConfiguration, i *bridgeInterface) error {
log.Debugf("Using IPv6 subnet: %v", config.FixedCIDRv6)
if err := ipAllocator.RegisterSubnet(config.FixedCIDRv6, config.FixedCIDRv6); err != nil {
return &FixedCIDRv6Error{Net: config.FixedCIDRv6, Err: err}
}
return nil
}
| apache-2.0 |
msteinert/drone | drone.go | 1279 | package main
import (
"flag"
"github.com/drone/drone/engine"
"github.com/drone/drone/remote"
"github.com/drone/drone/router"
"github.com/drone/drone/router/middleware/cache"
"github.com/drone/drone/router/middleware/context"
"github.com/drone/drone/router/middleware/header"
"github.com/drone/drone/shared/envconfig"
"github.com/drone/drone/shared/server"
"github.com/drone/drone/store/datastore"
"github.com/Sirupsen/logrus"
)
// build revision number populated by the continuous
// integration server at compile time.
var build string = "custom"
var (
dotenv = flag.String("config", ".env", "")
debug = flag.Bool("debug", false, "")
)
func main() {
flag.Parse()
// debug level if requested by user
if *debug {
logrus.SetLevel(logrus.DebugLevel)
}
// Load the configuration from env file
env := envconfig.Load(*dotenv)
// Setup the database driver
store_ := datastore.Load(env)
// setup the remote driver
remote_ := remote.Load(env)
// setup the runner
engine_ := engine.Load(env, store_)
// setup the server and start the listener
server_ := server.Load(env)
server_.Run(
router.Load(
header.Version(build),
cache.Default(),
context.SetStore(store_),
context.SetRemote(remote_),
context.SetEngine(engine_),
),
)
}
| apache-2.0 |
droyad/roslyn | src/Compilers/CSharp/Test/Emit/PDB/PDBDynamicLocalsTests.cs | 82110 | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBDynamicLocalsTests : CSharpTestBase
{
[Fact]
public void EmitPDBDynamicObjectVariable1()
{
string source = @"
class Helper
{
int x;
public void foo(int y){}
public Helper(){}
public Helper(int x){}
}
struct Point
{
int x;
int y;
}
class Test
{
delegate void D(int y);
public static void Main(string[] args)
{
dynamic d1 = new Helper();
dynamic d2 = new Point();
D d4 = new D(d1.foo);
Helper d5 = new Helper(d1);
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, references: new[] { CSharpRef }, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Helper"" name=""foo"" parameterNames=""y"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""0"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Helper"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""Helper"" methodName=""foo"" parameterNames=""y"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""0"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""0"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Helper"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""Helper"" methodName=""foo"" parameterNames=""y"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""0"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""0"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Helper"" methodName=""foo"" parameterNames=""y"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d1"" />
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d2"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""43"" />
<slot kind=""0"" offset=""67"" />
<slot kind=""0"" offset=""98"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""0"" />
<entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""29"" document=""0"" />
<entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""28"" document=""0"" />
<entry offset=""0x17"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""24"" document=""0"" />
<entry offset=""0xb1"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""30"" document=""0"" />
<entry offset=""0x10f"" startLine=""24"" startColumn=""3"" endLine=""24"" endColumn=""4"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x110"">
<local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" />
<local name=""d2"" il_index=""1"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" />
<local name=""d4"" il_index=""2"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" />
<local name=""d5"" il_index=""3"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBLangConstructsLocals1()
{
string source = @"
using System;
class Test
{
public static void Main(string[] args)
{
dynamic[] arrDynamic = new dynamic[] {""1""};
foreach (dynamic d in arrDynamic)
{
//do nothing
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<dynamicLocals>
<bucket flagCount=""2"" flags=""01"" slotId=""0"" localName=""arrDynamic"" />
<bucket flagCount=""1"" flags=""1"" slotId=""3"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""6"" offset=""58"" />
<slot kind=""8"" offset=""58"" />
<slot kind=""0"" offset=""58"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""46"" document=""0"" />
<entry offset=""0x10"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""0"" />
<entry offset=""0x11"" startLine=""8"" startColumn=""31"" endLine=""8"" endColumn=""41"" document=""0"" />
<entry offset=""0x15"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""27"" document=""0"" />
<entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""0"" />
<entry offset=""0x1c"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
<entry offset=""0x1d"" hidden=""true"" document=""0"" />
<entry offset=""0x21"" startLine=""8"" startColumn=""28"" endLine=""8"" endColumn=""30"" document=""0"" />
<entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x28"">
<namespace name=""System"" />
<local name=""arrDynamic"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" />
<scope startOffset=""0x17"" endOffset=""0x1d"">
<local name=""d"" il_index=""3"" il_start=""0x17"" il_end=""0x1d"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBDynamicConstVariable()
{
string source = @"
class Test
{
public static void Main(string[] args)
{
const dynamic d = null;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""0"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""3"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<constant name=""d"" value=""null"" type=""Object"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void EmitPDBDynamicArrayVariable()
{
string source = @"
class ArrayTest
{
int x;
}
class Test
{
public static void Main(string[] args)
{
dynamic[] arr = new dynamic[10];
dynamic[,] arrdim = new string[2,3];
dynamic[] arrobj = new ArrayTest[2];
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<dynamicLocals>
<bucket flagCount=""2"" flags=""01"" slotId=""0"" localName=""arr"" />
<bucket flagCount=""2"" flags=""01"" slotId=""1"" localName=""arrdim"" />
<bucket flagCount=""2"" flags=""01"" slotId=""2"" localName=""arrobj"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""52"" />
<slot kind=""0"" offset=""91"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""4"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""35"" document=""0"" />
<entry offset=""0x9"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""39"" document=""0"" />
<entry offset=""0x11"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""39"" document=""0"" />
<entry offset=""0x18"" startLine=""13"" startColumn=""3"" endLine=""13"" endColumn=""4"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""arr"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
<local name=""arrdim"" il_index=""1"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
<local name=""arrobj"" il_index=""2"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBDynamicCollectionVariable()
{
string source = @"
using System.Collections.Generic;
class Test
{
public static void Main(string[] args)
{
dynamic l1 = new List<int>();
List<dynamic> l2 = new List<dynamic>();
dynamic l3 = new List<dynamic>();
Dictionary<dynamic,dynamic> d1 = new Dictionary<dynamic,dynamic>();
dynamic d2 = new Dictionary<int,int>();
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""l1"" />
<bucket flagCount=""2"" flags=""01"" slotId=""1"" localName=""l2"" />
<bucket flagCount=""1"" flags=""1"" slotId=""2"" localName=""l3"" />
<bucket flagCount=""3"" flags=""011"" slotId=""3"" localName=""d1"" />
<bucket flagCount=""1"" flags=""1"" slotId=""4"" localName=""d2"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""52"" />
<slot kind=""0"" offset=""89"" />
<slot kind=""0"" offset=""146"" />
<slot kind=""0"" offset=""197"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""3"" endLine=""6"" endColumn=""4"" document=""0"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""32"" document=""0"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""42"" document=""0"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""36"" document=""0"" />
<entry offset=""0x13"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""70"" document=""0"" />
<entry offset=""0x19"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""42"" document=""0"" />
<entry offset=""0x20"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""4"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x21"">
<namespace name=""System.Collections.Generic"" />
<local name=""l1"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<local name=""l2"" il_index=""1"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<local name=""l3"" il_index=""2"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<local name=""d1"" il_index=""3"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
<local name=""d2"" il_index=""4"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void EmitPDBDynamicObjectVariable2()
{
string source = @"
class Helper
{
int x;
public void foo(int y){}
public Helper(){}
public Helper(int x){}
}
struct Point
{
int x;
int y;
}
class Test
{
delegate void D(int y);
public static void Main(string[] args)
{
Helper staticObj = new Helper();
dynamic d1 = new Helper();
dynamic d3 = new D(staticObj.foo);
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Helper"" name=""foo"" parameterNames=""y"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""0"" />
<entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Helper"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""Helper"" methodName=""foo"" parameterNames=""y"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""0"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""0"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Helper"" name="".ctor"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""Helper"" methodName=""foo"" parameterNames=""y"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""0"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""0"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Helper"" methodName=""foo"" parameterNames=""y"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""d1"" />
<bucket flagCount=""1"" flags=""1"" slotId=""2"" localName=""d3"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""12"" />
<slot kind=""0"" offset=""49"" />
<slot kind=""0"" offset=""79"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""0"" />
<entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""35"" document=""0"" />
<entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""29"" document=""0"" />
<entry offset=""0xd"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""37"" document=""0"" />
<entry offset=""0x1a"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""4"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1b"">
<local name=""staticObj"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
<local name=""d1"" il_index=""1"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
<local name=""d3"" il_index=""2"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBClassConstructorDynamicLocals()
{
string source = @"
class Test
{
public Test()
{
dynamic d;
}
public static void Main(string[] args)
{
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name="".ctor"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""4"" startColumn=""2"" endLine=""4"" endColumn=""15"" document=""0"" />
<entry offset=""0x7"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""0"" />
<entry offset=""0x8"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""3"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<scope startOffset=""0x7"" endOffset=""0x8"">
<local name=""d"" il_index=""0"" il_start=""0x7"" il_end=""0x8"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Test"" methodName="".ctor"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBClassPropertyDynamicLocals()
{
string source = @"
class Test
{
string field;
public dynamic Field
{
get
{
dynamic d = field + field;
return d;
}
set
{
dynamic d = null;
//field = d; Not yet implemented in Roslyn
}
}
public static void Main(string[] args)
{
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""get_Field"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""23"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""0"" />
<entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""0"" />
<entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""set_Field"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""get_Field"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""23"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""0"" />
<entry offset=""0x3"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""get_Field"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBClassOverloadedOperatorDynamicLocals()
{
string source = @"
class Complex
{
int real;
int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
public static dynamic operator +(Complex c1, Complex c2)
{
dynamic d = new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
return d;
}
}
class Test
{
public static void Main(string[] args)
{
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Complex"" name="".ctor"" parameterNames=""real, imaginary"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""44"" document=""0"" />
<entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""0"" />
<entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""36"" document=""0"" />
<entry offset=""0x16"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Complex"" name=""op_Addition"" parameterNames=""c1, c2"">
<customDebugInfo>
<forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""81"" document=""0"" />
<entry offset=""0x21"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""0"" />
<entry offset=""0x25"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x27"">
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBClassIndexerDynamicLocal()
{
string source = @"
class Test
{
dynamic[] arr;
public dynamic this[int i]
{
get
{
dynamic d = arr[i];
return d;
}
set
{
dynamic d = (dynamic) value;
arr[i] = d;
}
}
public static void Main(string[] args)
{
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""get_Item"" parameterNames=""i"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""23"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""32"" document=""0"" />
<entry offset=""0xa"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""0"" />
<entry offset=""0xe"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x10"">
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x10"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""set_Item"" parameterNames=""i, value"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""23"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""41"" document=""0"" />
<entry offset=""0x3"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0xc"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xd"">
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBClassEventHandlerDynamicLocal()
{
string source = @"
using System;
class Sample
{
public static void Main()
{
ConsoleKeyInfo cki;
Console.Clear();
Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
}
protected static void myHandler(object sender, ConsoleCancelEventArgs args)
{
dynamic d;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Sample"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""26"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""0"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""76"" document=""0"" />
<entry offset=""0x19"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1a"">
<namespace name=""System"" />
<local name=""cki"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" />
</scope>
</method>
<method containingType=""Sample"" name=""myHandler"" parameterNames=""sender, args"">
<customDebugInfo>
<forward declaringType=""Sample"" methodName=""Main"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBStructDynamicLocals()
{
string source = @"
using System;
struct Test
{
int d;
public Test(int d)
{
dynamic d1;
this.d = d;
}
public int D
{
get
{
dynamic d2;
return d;
}
set
{
dynamic d3;
d = value;
}
}
public static Test operator +(Test t1, Test t2)
{
dynamic d4;
return new Test(t1.d + t2.d);
}
public static void Main()
{
dynamic d5;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name="".ctor"" parameterNames=""d"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d1"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""0"" />
<entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
<local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""get_D"">
<customDebugInfo>
<forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d2"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""23"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""22"" document=""0"" />
<entry offset=""0xa"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xc"">
<local name=""d2"" il_index=""0"" il_start=""0x0"" il_end=""0xc"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""set_D"" parameterNames=""value"">
<customDebugInfo>
<forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d3"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""23"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""0"" />
<entry offset=""0x1"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""23"" document=""0"" />
<entry offset=""0x8"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<local name=""d3"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""op_Addition"" parameterNames=""t1, t2"">
<customDebugInfo>
<forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d4"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""21"" offset=""0"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""38"" document=""0"" />
<entry offset=""0x16"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x18"">
<local name=""d4"" il_index=""0"" il_start=""0x0"" il_end=""0x18"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d5"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBAnonymousFunctionLocals()
{
string source = @"
using System;
class Test
{
public delegate dynamic D1(dynamic d1);
public delegate void D2(dynamic d2);
public static void Main(string[] args)
{
D1 obj1 = d3 => d3;
D2 obj2 = new D2(d4 => { dynamic d5; d5 = d4; });
D1 obj3 = (dynamic d6) => { return d6; };
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""14"" />
<slot kind=""0"" offset=""43"" />
<slot kind=""0"" offset=""102"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<lambda offset=""27"" />
<lambda offset=""63"" />
<lambda offset=""125"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""0"" />
<entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""58"" document=""0"" />
<entry offset=""0x41"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""50"" document=""0"" />
<entry offset=""0x61"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x62"">
<namespace name=""System"" />
<local name=""obj1"" il_index=""0"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" />
<local name=""obj2"" il_index=""1"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" />
<local name=""obj3"" il_index=""2"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c"" name=""<Main>b__2_0"" parameterNames=""d3"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""27"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test+<>c"" name=""<Main>b__2_1"" parameterNames=""d4"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d5"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""73"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""32"" endLine=""10"" endColumn=""33"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""46"" endLine=""10"" endColumn=""54"" document=""0"" />
<entry offset=""0x5"" startLine=""10"" startColumn=""55"" endLine=""10"" endColumn=""56"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6"">
<local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c"" name=""<Main>b__2_2"" parameterNames=""d6"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" />
<encLocalSlotMap>
<slot kind=""21"" offset=""125"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""35"" endLine=""11"" endColumn=""36"" document=""0"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""37"" endLine=""11"" endColumn=""47"" document=""0"" />
<entry offset=""0x5"" startLine=""11"" startColumn=""48"" endLine=""11"" endColumn=""49"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBLangConstructsLocals2()
{
string source = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Test
{
public static void Main(string[] args)
{
int d1 = 0;
int[] arrInt = new int[] { 1, 2, 3 };
dynamic[] scores = new dynamic[] { ""97"", ""92"", ""81"", ""60"" };
dynamic[] arrDynamic = new dynamic[] { ""1"", ""2"", ""3"" };
while (d1 < 1)
{
dynamic dInWhile;
d1++;
}
do
{
dynamic dInDoWhile;
d1++;
} while (d1 < 1);
foreach (int d in arrInt)
{
dynamic dInForEach;
}
for (int i = 0; i < 1; i++)
{
dynamic dInFor;
}
for (dynamic d = ""1""; ;)
{
//do nothing
}
if (d1 == 0)
{
dynamic dInIf;
}
else
{
dynamic dInElse;
}
try
{
dynamic dInTry;
throw new Exception();
}
catch
{
dynamic dInCatch;
}
finally
{
dynamic dInFinally;
}
IEnumerable<dynamic> scoreQuery1 =
from score in scores
select score;
dynamic scoreQuery2 =
from score in scores
select score;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""3"" />
</using>
<dynamicLocals>
<bucket flagCount=""2"" flags=""01"" slotId=""2"" localName=""scores"" />
<bucket flagCount=""2"" flags=""01"" slotId=""3"" localName=""arrDynamic"" />
<bucket flagCount=""2"" flags=""01"" slotId=""4"" localName=""scoreQuery1"" />
<bucket flagCount=""1"" flags=""1"" slotId=""5"" localName=""scoreQuery2"" />
<bucket flagCount=""1"" flags=""1"" slotId=""6"" localName=""dInWhile"" />
<bucket flagCount=""1"" flags=""1"" slotId=""9"" localName=""dInDoWhile"" />
<bucket flagCount=""1"" flags=""1"" slotId=""14"" localName=""dInForEach"" />
<bucket flagCount=""1"" flags=""1"" slotId=""16"" localName=""dInFor"" />
<bucket flagCount=""1"" flags=""1"" slotId=""18"" localName=""d"" />
<bucket flagCount=""1"" flags=""1"" slotId=""20"" localName=""dInIf"" />
<bucket flagCount=""1"" flags=""1"" slotId=""21"" localName=""dInElse"" />
<bucket flagCount=""1"" flags=""1"" slotId=""22"" localName=""dInTry"" />
<bucket flagCount=""1"" flags=""1"" slotId=""23"" localName=""dInCatch"" />
<bucket flagCount=""1"" flags=""1"" slotId=""24"" localName=""dInFinally"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
<slot kind=""0"" offset=""38"" />
<slot kind=""0"" offset=""89"" />
<slot kind=""0"" offset=""159"" />
<slot kind=""0"" offset=""1071"" />
<slot kind=""0"" offset=""1163"" />
<slot kind=""0"" offset=""261"" />
<slot kind=""temp"" />
<slot kind=""1"" offset=""214"" />
<slot kind=""0"" offset=""345"" />
<slot kind=""1"" offset=""310"" />
<slot kind=""6"" offset=""412"" />
<slot kind=""8"" offset=""412"" />
<slot kind=""0"" offset=""412"" />
<slot kind=""0"" offset=""470"" />
<slot kind=""0"" offset=""511"" />
<slot kind=""0"" offset=""562"" />
<slot kind=""1"" offset=""502"" />
<slot kind=""0"" offset=""603"" />
<slot kind=""1"" offset=""672"" />
<slot kind=""0"" offset=""717"" />
<slot kind=""0"" offset=""781"" />
<slot kind=""0"" offset=""846"" />
<slot kind=""0"" offset=""948"" />
<slot kind=""0"" offset=""1018"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""1139"" />
<lambda offset=""1231"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""0"" />
<entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""0"" />
<entry offset=""0x15"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""69"" document=""0"" />
<entry offset=""0x3c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""64"" document=""0"" />
<entry offset=""0x5b"" hidden=""true"" document=""0"" />
<entry offset=""0x5d"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""0"" />
<entry offset=""0x5e"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""0"" />
<entry offset=""0x66"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""0"" />
<entry offset=""0x67"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""0"" />
<entry offset=""0x6d"" hidden=""true"" document=""0"" />
<entry offset=""0x71"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""0"" />
<entry offset=""0x72"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""0"" />
<entry offset=""0x7a"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" />
<entry offset=""0x7b"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""0"" />
<entry offset=""0x81"" hidden=""true"" document=""0"" />
<entry offset=""0x85"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""0"" />
<entry offset=""0x86"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""0"" />
<entry offset=""0x8c"" hidden=""true"" document=""0"" />
<entry offset=""0x8e"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""0"" />
<entry offset=""0x95"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""0"" />
<entry offset=""0x96"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""0"" />
<entry offset=""0x97"" hidden=""true"" document=""0"" />
<entry offset=""0x9d"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""0"" />
<entry offset=""0xa5"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""0"" />
<entry offset=""0xa8"" hidden=""true"" document=""0"" />
<entry offset=""0xaa"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""0"" />
<entry offset=""0xab"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""0"" />
<entry offset=""0xac"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""0"" />
<entry offset=""0xb6"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""0"" />
<entry offset=""0xbd"" hidden=""true"" document=""0"" />
<entry offset=""0xc1"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""0"" />
<entry offset=""0xc8"" hidden=""true"" document=""0"" />
<entry offset=""0xca"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""0"" />
<entry offset=""0xcb"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""0"" />
<entry offset=""0xcc"" hidden=""true"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xce"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<namespace name=""System.Linq"" />
<local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0xce"" attributes=""0"" />
<local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0xce"" attributes=""0"" />
<local name=""scores"" il_index=""2"" il_start=""0x0"" il_end=""0xce"" attributes=""0"" />
<local name=""arrDynamic"" il_index=""3"" il_start=""0x0"" il_end=""0xce"" attributes=""0"" />
<local name=""scoreQuery1"" il_index=""4"" il_start=""0x0"" il_end=""0xce"" attributes=""0"" />
<local name=""scoreQuery2"" il_index=""5"" il_start=""0x0"" il_end=""0xce"" attributes=""0"" />
<scope startOffset=""0x5d"" endOffset=""0x67"">
<local name=""dInWhile"" il_index=""6"" il_start=""0x5d"" il_end=""0x67"" attributes=""0"" />
</scope>
<scope startOffset=""0x71"" endOffset=""0x7b"">
<local name=""dInDoWhile"" il_index=""9"" il_start=""0x71"" il_end=""0x7b"" attributes=""0"" />
</scope>
<scope startOffset=""0x8e"" endOffset=""0x97"">
<local name=""d"" il_index=""13"" il_start=""0x8e"" il_end=""0x97"" attributes=""0"" />
<scope startOffset=""0x95"" endOffset=""0x97"">
<local name=""dInForEach"" il_index=""14"" il_start=""0x95"" il_end=""0x97"" attributes=""0"" />
</scope>
</scope>
<scope startOffset=""0xa5"" endOffset=""0xc1"">
<local name=""i"" il_index=""15"" il_start=""0xa5"" il_end=""0xc1"" attributes=""0"" />
<scope startOffset=""0xaa"" endOffset=""0xac"">
<local name=""dInFor"" il_index=""16"" il_start=""0xaa"" il_end=""0xac"" attributes=""0"" />
</scope>
</scope>
<scope startOffset=""0xc1"" endOffset=""0xce"">
<local name=""d"" il_index=""18"" il_start=""0xc1"" il_end=""0xce"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""Test+<>c"" name=""<Main>b__0_0"" parameterNames=""score"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""58"" startColumn=""20"" endLine=""58"" endColumn=""25"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""Test+<>c"" name=""<Main>b__0_1"" parameterNames=""score"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""61"" startColumn=""20"" endLine=""61"" endColumn=""25"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBVarVariableLocal()
{
string source = @"
using System;
class Test
{
public static void Main(string[] args)
{
dynamic d = ""1"";
var v = d;
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""d"" />
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""v"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
<slot kind=""0"" offset=""29"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""3"" document=""0"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""19"" document=""0"" />
<entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""13"" document=""0"" />
<entry offset=""0x9"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xa"">
<namespace name=""System"" />
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
<local name=""v"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[Fact]
public void EmitPDBGenericDynamicNonLocal()
{
string source = @"
using System;
class dynamic<T>
{
public T field;
}
class Test
{
public static void Main(string[] args)
{
dynamic<dynamic> obj = new dynamic<dynamic>();
obj.field = ""1"";
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<dynamicLocals>
<bucket flagCount=""2"" flags=""01"" slotId=""0"" localName=""obj"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""22"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""0"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""49"" document=""0"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""19"" document=""0"" />
<entry offset=""0x12"" startLine=""13"" startColumn=""2"" endLine=""13"" endColumn=""3"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x13"">
<namespace name=""System"" />
<local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x13"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_1() //With 2 normal dynamic locals
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
dynamic yyy;
dynamic zzz;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""yyy"" />
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""zzz"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""41"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_2() //With 1 normal dynamic local and 1 containing dynamic local
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
dynamic yyy;
Foo<dynamic> zzz;
}
}
class Foo<T>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""yyy"" />
<bucket flagCount=""2"" flags=""01"" slotId=""1"" localName=""zzz"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""46"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_3() //With 1 normal dynamic local and 1 containing(more than one) dynamic local
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
dynamic yyy;
Foo<dynamic, Foo<dynamic,dynamic>> zzz;
}
}
class Foo<T,V>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""yyy"" />
<bucket flagCount=""5"" flags=""01011"" slotId=""1"" localName=""zzz"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""68"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_4() //With 1 normal dynamic local, 1 containing dynamic local with a normal local variable
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
dynamic yyy;
int dummy = 0;
Foo<dynamic, Foo<dynamic,dynamic>> zzz;
}
}
class Foo<T,V>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""yyy"" />
<bucket flagCount=""5"" flags=""01011"" slotId=""2"" localName=""zzz"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""37"" />
<slot kind=""0"" offset=""92"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""23"" document=""0"" />
<entry offset=""0x3"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x4"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
<local name=""dummy"" il_index=""1"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
<local name=""zzz"" il_index=""2"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_5_Just_Long() //Dynamic local with dynamic attribute of length 63 above which the flag is emitted empty
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz;
}
}
class F<T,V>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""63"" flags=""010101010101010101010101010101010101010101010101010101010101011"" slotId=""0"" localName=""zzz"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""361"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_6_Too_Long() //The limitation of the previous testcase with dynamic attribute length 64 and not emitted
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz;
}
}
class F<T,V>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""0"" flags="""" slotId=""0"" localName=""zzz"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""372"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_7() //Cornercase dynamic locals with normal locals
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z1;
int dummy1 = 0;
F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z2;
F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3;
int dummy2 = 0;
}
}
class F<T,V>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""0"" flags="""" slotId=""0"" localName=""z1"" />
<bucket flagCount=""0"" flags="""" slotId=""2"" localName=""z2"" />
<bucket flagCount=""0"" flags="""" slotId=""3"" localName=""z3"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""372"" />
<slot kind=""0"" offset=""389"" />
<slot kind=""0"" offset=""771"" />
<slot kind=""0"" offset=""1145"" />
<slot kind=""0"" offset=""1162"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""0"" />
<entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""0"" />
<entry offset=""0x6"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x7"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""z1"" il_index=""0"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" />
<local name=""dummy1"" il_index=""1"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" />
<local name=""z2"" il_index=""2"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" />
<local name=""z3"" il_index=""3"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" />
<local name=""dummy2"" il_index=""4"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_8_Mixed_Corner_Cases() //Mixed case with one more limitation. If identifier length is greater than 63 then the info is not emitted
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3;
dynamic www;
dynamic length63length63length63length63length63length63length63length6;
dynamic length64length64length64length64length64length64length64length64;
}
}
class F<T,V>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""0"" flags="""" slotId=""0"" localName=""z3"" />
<bucket flagCount=""1"" flags=""1"" slotId=""1"" localName=""www"" />
<bucket flagCount=""1"" flags=""1"" slotId=""2"" localName=""length63length63length63length63length63length63length63length6"" />
<bucket flagCount=""0"" flags="""" slotId=""0"" localName="""" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""372"" />
<slot kind=""0"" offset=""393"" />
<slot kind=""0"" offset=""415"" />
<slot kind=""0"" offset=""497"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""z3"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""www"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""length63length63length63length63length63length63length63length6"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""length64length64length64length64length64length64length64length64"" il_index=""3"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_9() //Check corner case with only corner cases
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> yes;
F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> no;
dynamic www;
}
}
class F<T>
{
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""64"" flags=""0000000000000000000000000000000000000000000000000000000000000001"" slotId=""0"" localName=""yes"" />
<bucket flagCount=""0"" flags="""" slotId=""1"" localName=""no"" />
<bucket flagCount=""1"" flags=""1"" slotId=""2"" localName=""www"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""208"" />
<slot kind=""0"" offset=""422"" />
<slot kind=""0"" offset=""443"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""yes"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""no"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
<local name=""www"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>");
}
[WorkItem(17390, "DevDiv_Projects/Roslyn")]
[Fact]
public void EmitPDBForDynamicLocals_TwoScope()
{
string source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
dynamic simple;
for(int x =0 ; x < 10 ; ++x)
{ dynamic inner; }
}
static void nothing(dynamic localArg)
{
dynamic localInner;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Program"" name=""Main"" parameterNames=""args"">
<customDebugInfo>
<using>
<namespace usingCount=""2"" />
</using>
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""simple"" />
<bucket flagCount=""1"" flags=""1"" slotId=""2"" localName=""inner"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
<slot kind=""0"" offset=""44"" />
<slot kind=""0"" offset=""84"" />
<slot kind=""temp"" />
<slot kind=""1"" offset=""36"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""21"" document=""0"" />
<entry offset=""0x3"" hidden=""true"" document=""0"" />
<entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""0"" />
<entry offset=""0x6"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x7"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""0"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""24"" endLine=""9"" endColumn=""30"" document=""0"" />
<entry offset=""0x14"" hidden=""true"" document=""0"" />
<entry offset=""0x18"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x19"">
<namespace name=""System"" />
<namespace name=""System.Collections.Generic"" />
<local name=""simple"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" />
<scope startOffset=""0x1"" endOffset=""0x18"">
<local name=""x"" il_index=""1"" il_start=""0x1"" il_end=""0x18"" attributes=""0"" />
<scope startOffset=""0x5"" endOffset=""0x7"">
<local name=""inner"" il_index=""2"" il_start=""0x5"" il_end=""0x7"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
<method containingType=""Program"" name=""nothing"" parameterNames=""localArg"">
<customDebugInfo>
<forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" />
<dynamicLocals>
<bucket flagCount=""1"" flags=""1"" slotId=""0"" localName=""localInner"" />
</dynamicLocals>
<encLocalSlotMap>
<slot kind=""0"" offset=""19"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x2"">
<local name=""localInner"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" />
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(637465, "DevDiv")]
[Fact]
public void DynamicLocalOptimizedAway()
{
string source = @"
class C
{
public static void Main()
{
dynamic d = GetDynamic();
}
static dynamic GetDynamic()
{
throw null;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.ReleaseDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""34"" document=""0"" />
<entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""GetDynamic"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""20"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>
");
}
}
}
| apache-2.0 |
tommyip/zulip | analytics/migrations/0010_clear_messages_sent_values.py | 1161 | # -*- coding: utf-8 -*-
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def clear_message_sent_by_message_type_values(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserCount = apps.get_model('analytics', 'UserCount')
StreamCount = apps.get_model('analytics', 'StreamCount')
RealmCount = apps.get_model('analytics', 'RealmCount')
InstallationCount = apps.get_model('analytics', 'InstallationCount')
FillState = apps.get_model('analytics', 'FillState')
property = 'messages_sent:message_type:day'
UserCount.objects.filter(property=property).delete()
StreamCount.objects.filter(property=property).delete()
RealmCount.objects.filter(property=property).delete()
InstallationCount.objects.filter(property=property).delete()
FillState.objects.filter(property=property).delete()
class Migration(migrations.Migration):
dependencies = [('analytics', '0009_remove_messages_to_stream_stat')]
operations = [
migrations.RunPython(clear_message_sent_by_message_type_values),
]
| apache-2.0 |
Jiri-Kremser/util | util-core/src/main/scala/com/twitter/concurrent/ConcurrentBijection.scala | 1831 | // Copyright 2010 Twitter, Inc.
package com.twitter.concurrent
import java.util.concurrent.ConcurrentHashMap
import scala.collection.JavaConversions._
import scala.collection.mutable.{Map => MMap}
// A bijection that may be modified and accessed simultaneously. Note
// that we can allow only one modification at a time. Updates need to
// be serialized to ensure that the bijective property is maintained.
class ConcurrentBijection[A, B] extends MMap[A, B] {
val forward = new ConcurrentHashMap[A, B]
val reverse = new ConcurrentHashMap[B, A]
def toOpt[T](x: T) = if (x == null) None else Some(x)
def -=(key: A) = {
synchronized {
val value = forward.remove(key)
if (value != null)
reverse.remove(value)
}
this
}
def +=(elem: (A, B)) = {
elem match {
case (key, value) => update(key, value)
}
this
}
override def update(key: A, value: B) = synchronized {
// We need to update:
//
// a -> b
// b -> a
//
// There may be existing mappings:
//
// a -> b'
// b' -> a
//
// or
//
// a' -> b
// b -> a'
//
// So we need to ensure these are killed.
val oldValue = forward.put(key, value)
if (oldValue != value) {
if (oldValue != null) {
// Remove the old reverse mapping.
val keyForOldValue = reverse.remove(oldValue)
if (key != keyForOldValue)
forward.remove(keyForOldValue)
}
val oldKeyForValue = reverse.put(value, key)
if (oldKeyForValue != null)
forward.remove(oldKeyForValue)
}
}
override def size = forward.size
def get(key: A) = toOpt(forward.get(key))
def getReverse(value: B) = toOpt(reverse.get(value))
def iterator = forward.entrySet.iterator.map(e => (e.getKey, e.getValue))
}
| apache-2.0 |
zaragoza-sedeelectronica/hackathon-co.sa | node_modules/cordova/node_modules/cordova-lib/node_modules/cordova-js/tasks/lib/test-jsdom.js | 2340 | /*
*
* 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.
*
*/
var path = require('path');
var fs = require('fs');
var collect = require('./collect');
var jas = require('jasmine-node');
var testLibName = path.join(__dirname, '..', '..', 'pkg', 'cordova.test.js')
var testLib = fs.readFileSync(testLibName, 'utf8')
var jsdom = require("jsdom-nogyp").jsdom;
var document = jsdom(null, null, { url: 'file:///jsdomtest.info/a?b#c' });
var window = document.createWindow();
module.exports = function(callback) {
console.log('starting node-based tests');
// put jasmine in scope
Object.keys(jas).forEach(function (key) {
this[key] = window[key] = global[key] = jas[key];
});
// Hack to fix jsdom with node v0.11.13+
delete String.prototype.normalize;
try {
eval(testLib);
}
catch (e) {
console.log("error eval()ing " + testLibName + ": " + e);
console.log(e.stack);
throw e;
}
// hijack require
require = window.cordova.require;
define = window.cordova.define;
// load in our tests
var tests = [];
collect(path.join(__dirname, '..', '..', 'test'), tests);
for (var x in tests) {
eval(fs.readFileSync(tests[x], "utf-8"));
}
var env = jasmine.getEnv();
env.addReporter(new jas.TerminalReporter({
color: true,
onComplete: function(runner) { callback(runner.results().passed()); }
}));
console.log("------------");
console.log("Unit Tests:");
env.execute();
};
| apache-2.0 |
Philippe2201/vraptor4 | vraptor-core/src/main/java/br/com/caelum/vraptor/serialization/IgnoringSerializer.java | 1386 | /***
* Copyright (c) 2009 Caelum - www.caelum.com.br/opensource 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 br.com.caelum.vraptor.serialization;
import javax.enterprise.inject.Vetoed;
/**
* Doesn't serialize anything
* @author Lucas Cavalcanti
* @author Jose Donizetti
* @since 3.0.3
*/
@Vetoed
public class IgnoringSerializer implements SerializerBuilder {
@Override
public Serializer exclude(String... names) {
return this;
}
@Override
public <T> Serializer from(T object) {
return this;
}
@Override
public Serializer include(String... names) {
return this;
}
@Override
public Serializer recursive() {
return this;
}
@Override
public void serialize() {
}
@Override
public <T> Serializer from(T object, String alias) {
return this;
}
@Override
public Serializer excludeAll() {
return this;
}
}
| apache-2.0 |
agoncharuk/ignite | modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridCachePartitionedPreloadEventsSelfTest.java | 4590 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed.dht;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.affinity.AffinityFunction;
import org.apache.ignite.cache.affinity.AffinityFunctionContext;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.events.Event;
import org.apache.ignite.internal.processors.cache.distributed.GridCachePreloadEventsAbstractSelfTest;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtForceKeysFuture;
import org.apache.ignite.internal.util.typedef.F;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.events.EventType.EVT_CACHE_REBALANCE_OBJECT_LOADED;
/**
*
*/
public class GridCachePartitionedPreloadEventsSelfTest extends GridCachePreloadEventsAbstractSelfTest {
/** */
private boolean replicatedAffinity = true;
/** */
private long rebalanceDelay;
/** {@inheritDoc} */
@Override protected CacheConfiguration cacheConfiguration() {
CacheConfiguration cacheCfg = super.cacheConfiguration();
if (replicatedAffinity)
// replicate entries to all nodes
cacheCfg.setAffinity(notSerializableProxy(new AffinityFunction() {
/** {@inheritDoc} */
@Override public void reset() {
}
/** {@inheritDoc} */
@Override public int partitions() {
return 1;
}
/** {@inheritDoc} */
@Override public int partition(Object key) {
return 0;
}
/** {@inheritDoc} */
@Override public List<List<ClusterNode>> assignPartitions(AffinityFunctionContext affCtx) {
List<ClusterNode> nodes = new ArrayList<>(affCtx.currentTopologySnapshot());
return Collections.singletonList(nodes);
}
/** {@inheritDoc} */
@Override public void removeNode(UUID nodeId) {
}
}, AffinityFunction.class));
cacheCfg.setRebalanceDelay(rebalanceDelay);
return cacheCfg;
}
/** {@inheritDoc} */
@Override protected CacheMode getCacheMode() {
return PARTITIONED;
}
/**
* Test events fired from
* {@link GridDhtForceKeysFuture}
*
* @throws Exception if failed.
*/
public void testForcePreload() throws Exception {
replicatedAffinity = false;
rebalanceDelay = -1;
Ignite g1 = startGrid("g1");
Collection<Integer> keys = new HashSet<>();
IgniteCache<Integer, String> cache = g1.cache(null);
for (int i = 0; i < 100; i++) {
keys.add(i);
cache.put(i, "val");
}
Ignite g2 = startGrid("g2");
Map<ClusterNode, Collection<Object>> keysMap = g1.affinity(null).mapKeysToNodes(keys);
Collection<Object> g2Keys = keysMap.get(g2.cluster().localNode());
assertNotNull(g2Keys);
assertFalse("There are no keys assigned to g2", g2Keys.isEmpty());
for (Object key : g2Keys)
// Need to force keys loading.
assertEquals("val", g2.cache(null).getAndPut(key, "changed val"));
Collection<Event> evts = g2.events().localQuery(F.<Event>alwaysTrue(), EVT_CACHE_REBALANCE_OBJECT_LOADED);
checkPreloadEvents(evts, g2, g2Keys);
}
} | apache-2.0 |
yummy222/cgeo | main/src/cgeo/geocaching/ui/WeakReferenceHandler.java | 800 | package cgeo.geocaching.ui;
import android.app.Activity;
import android.os.Handler;
import java.lang.ref.WeakReference;
/**
* Standard handler implementation which uses a weak reference to its activity. This avoids that activities stay in
* memory due to references from the handler to the activity (see Android Lint warning "HandlerLeak")
*
* Create static private subclasses of this handler class in your activity.
*
*/
public abstract class WeakReferenceHandler<ActivityType extends Activity> extends Handler {
private final WeakReference<ActivityType> activityRef;
protected WeakReferenceHandler(final ActivityType activity) {
this.activityRef = new WeakReference<>(activity);
}
protected ActivityType getActivity() {
return activityRef.get();
}
}
| apache-2.0 |
MattDevo/edk2 | AppPkg/Applications/Python/Python-2.7.2/Lib/test/time_hashlib.py | 2943 | # It's intended that this script be run by hand. It runs speed tests on
# hashlib functions; it does not test for correctness.
import sys, time
import hashlib
def creatorFunc():
raise RuntimeError, "eek, creatorFunc not overridden"
def test_scaled_msg(scale, name):
iterations = 106201/scale * 20
longStr = 'Z'*scale
localCF = creatorFunc
start = time.time()
for f in xrange(iterations):
x = localCF(longStr).digest()
end = time.time()
print ('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name
def test_create():
start = time.time()
for f in xrange(20000):
d = creatorFunc()
end = time.time()
print ('%2.2f' % (end-start)), "seconds", '[20000 creations]'
def test_zero():
start = time.time()
for f in xrange(20000):
x = creatorFunc().digest()
end = time.time()
print ('%2.2f' % (end-start)), "seconds", '[20000 "" digests]'
hName = sys.argv[1]
#
# setup our creatorFunc to test the requested hash
#
if hName in ('_md5', '_sha'):
exec 'import '+hName
exec 'creatorFunc = '+hName+'.new'
print "testing speed of old", hName, "legacy interface"
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec 'creatorFunc = _hashlib.%s' % sys.argv[2]
print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec 'creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2]
print "testing speed of _hashlib.new(%r)" % sys.argv[2]
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
creatorFunc = getattr(hashlib, hName)
print "testing speed of hashlib."+hName, getattr(hashlib, hName)
else:
exec "creatorFunc = lambda x=hashlib.new : x(%r)" % hName
print "testing speed of hashlib.new(%r)" % hName
try:
test_create()
except ValueError:
print
print "pass argument(s) naming the hash to run a speed test on:"
print " '_md5' and '_sha' test the legacy builtin md5 and sha"
print " '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib"
print " '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)"
print " 'hName' tests the hashlib.hName() implementation if it exists"
print " otherwise it uses hashlib.new(hName)."
print
raise
test_zero()
test_scaled_msg(scale=106201, name='[huge data]')
test_scaled_msg(scale=10620, name='[large data]')
test_scaled_msg(scale=1062, name='[medium data]')
test_scaled_msg(scale=424, name='[4*small data]')
test_scaled_msg(scale=336, name='[3*small data]')
test_scaled_msg(scale=212, name='[2*small data]')
test_scaled_msg(scale=106, name='[small data]')
test_scaled_msg(scale=creatorFunc().digest_size, name='[digest_size data]')
test_scaled_msg(scale=10, name='[tiny data]')
| bsd-2-clause |
joone/chromium-crosswalk | ui/views/controls/prefix_selector.cc | 5311 | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/controls/prefix_selector.h"
#include "base/i18n/case_conversion.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/gfx/range/range.h"
#include "ui/views/controls/prefix_delegate.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
const int64_t kTimeBeforeClearingMS = 1000;
void ConvertRectToScreen(const views::View* src, gfx::Rect* r) {
DCHECK(src);
gfx::Point new_origin = r->origin();
views::View::ConvertPointToScreen(src, &new_origin);
r->set_origin(new_origin);
}
} // namespace
PrefixSelector::PrefixSelector(PrefixDelegate* delegate)
: prefix_delegate_(delegate) {
}
PrefixSelector::~PrefixSelector() {
}
void PrefixSelector::OnViewBlur() {
ClearText();
}
void PrefixSelector::SetCompositionText(
const ui::CompositionText& composition) {
}
void PrefixSelector::ConfirmCompositionText() {
}
void PrefixSelector::ClearCompositionText() {
}
void PrefixSelector::InsertText(const base::string16& text) {
OnTextInput(text);
}
void PrefixSelector::InsertChar(const ui::KeyEvent& event) {
OnTextInput(base::string16(1, event.GetCharacter()));
}
ui::TextInputType PrefixSelector::GetTextInputType() const {
return ui::TEXT_INPUT_TYPE_TEXT;
}
ui::TextInputMode PrefixSelector::GetTextInputMode() const {
return ui::TEXT_INPUT_MODE_DEFAULT;
}
int PrefixSelector::GetTextInputFlags() const {
return 0;
}
bool PrefixSelector::CanComposeInline() const {
return false;
}
gfx::Rect PrefixSelector::GetCaretBounds() const {
gfx::Rect rect(prefix_delegate_->GetVisibleBounds().origin(), gfx::Size());
// TextInputClient::GetCaretBounds is expected to return a value in screen
// coordinates.
ConvertRectToScreen(prefix_delegate_, &rect);
return rect;
}
bool PrefixSelector::GetCompositionCharacterBounds(uint32_t index,
gfx::Rect* rect) const {
// TextInputClient::GetCompositionCharacterBounds is expected to fill |rect|
// in screen coordinates and GetCaretBounds returns screen coordinates.
*rect = GetCaretBounds();
return false;
}
bool PrefixSelector::HasCompositionText() const {
return false;
}
bool PrefixSelector::GetTextRange(gfx::Range* range) const {
*range = gfx::Range();
return false;
}
bool PrefixSelector::GetCompositionTextRange(gfx::Range* range) const {
*range = gfx::Range();
return false;
}
bool PrefixSelector::GetSelectionRange(gfx::Range* range) const {
*range = gfx::Range();
return false;
}
bool PrefixSelector::SetSelectionRange(const gfx::Range& range) {
return false;
}
bool PrefixSelector::DeleteRange(const gfx::Range& range) {
return false;
}
bool PrefixSelector::GetTextFromRange(const gfx::Range& range,
base::string16* text) const {
return false;
}
void PrefixSelector::OnInputMethodChanged() {
ClearText();
}
bool PrefixSelector::ChangeTextDirectionAndLayoutAlignment(
base::i18n::TextDirection direction) {
return true;
}
void PrefixSelector::ExtendSelectionAndDelete(size_t before, size_t after) {
}
void PrefixSelector::EnsureCaretInRect(const gfx::Rect& rect) {
}
bool PrefixSelector::IsEditCommandEnabled(int command_id) {
return false;
}
void PrefixSelector::SetEditCommandForNextKeyEvent(int command_id) {
}
void PrefixSelector::OnTextInput(const base::string16& text) {
// Small hack to filter out 'tab' and 'enter' input, as the expectation is
// that they are control characters and will not affect the currently-active
// prefix.
if (text.length() == 1 &&
(text[0] == L'\t' || text[0] == L'\r' || text[0] == L'\n'))
return;
const int row_count = prefix_delegate_->GetRowCount();
if (row_count == 0)
return;
// Search for |text| if it has been a while since the user typed, otherwise
// append |text| to |current_text_| and search for that. If it has been a
// while search after the current row, otherwise search starting from the
// current row.
int row = std::max(0, prefix_delegate_->GetSelectedRow());
const base::TimeTicks now(base::TimeTicks::Now());
if ((now - time_of_last_key_).InMilliseconds() < kTimeBeforeClearingMS) {
current_text_ += text;
} else {
current_text_ = text;
if (prefix_delegate_->GetSelectedRow() >= 0)
row = (row + 1) % row_count;
}
time_of_last_key_ = now;
const int start_row = row;
const base::string16 lower_text(base::i18n::ToLower(current_text_));
do {
if (TextAtRowMatchesText(row, lower_text)) {
prefix_delegate_->SetSelectedRow(row);
return;
}
row = (row + 1) % row_count;
} while (row != start_row);
}
bool PrefixSelector::TextAtRowMatchesText(int row,
const base::string16& lower_text) {
const base::string16 model_text(
base::i18n::ToLower(prefix_delegate_->GetTextForRow(row)));
return (model_text.size() >= lower_text.size()) &&
(model_text.compare(0, lower_text.size(), lower_text) == 0);
}
void PrefixSelector::ClearText() {
current_text_.clear();
time_of_last_key_ = base::TimeTicks();
}
} // namespace views
| bsd-3-clause |
bozazec/learnzf2 | module/User/src/User/Service/Factory/User.php | 768 | <?php
namespace User\Service\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class User implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$config = $serviceLocator->get('config');
$auth = $serviceLocator->get('auth');
if($auth->hasIdentity()) {
$user = $auth->getIdentity();
if(!$user->getRole()) {
$user->setRole($config['acl']['defaults']['member_role']);
}
} else {
$user = $serviceLocator->get('user-entity');
$user->setId(null);
$user->setRole($config['acl']['defaults']['guest_role']);
}
return $user;
}
}
| bsd-3-clause |
LuxusDarkangel/Bungeecord-KFix | protocol/src/main/java/net/md_5/bungee/protocol/packet/ScoreboardScore.java | 1967 | package net.md_5.bungee.protocol.packet;
import net.md_5.bungee.protocol.DefinedPacket;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import net.md_5.bungee.protocol.AbstractPacketHandler;
import net.md_5.bungee.protocol.ProtocolConstants;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class ScoreboardScore extends DefinedPacket
{
private String itemName;
/**
* 0 = create / update, 1 = remove.
*/
private byte action;
private String scoreName;
private int value;
@Override
public void read(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion)
{
itemName = readString( buf );
action = buf.readByte();
if ( protocolVersion >= ProtocolConstants.MINECRAFT_1_8 )
{
scoreName = readString( buf );
if ( action != 1 )
{
value = readVarInt( buf );
}
} else
{
if ( action != 1 )
{
scoreName = readString( buf );
value = buf.readInt();
}
}
}
@Override
public void write(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion)
{
writeString( itemName, buf );
buf.writeByte( action );
if ( protocolVersion >= ProtocolConstants.MINECRAFT_1_8 )
{
writeString( scoreName, buf );
if ( action != 1 )
{
writeVarInt( value, buf );
}
} else
{
if ( action != 1 )
{
writeString( scoreName, buf );
buf.writeInt( value );
}
}
}
@Override
public void handle(AbstractPacketHandler handler) throws Exception
{
handler.handle( this );
}
}
| bsd-3-clause |
alex/sentry | sentry/migrations/0006_auto.py | 3819 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
pass
def backwards(self, orm):
pass
models = {
'sentry.filtervalue': {
'Meta': {'unique_together': "(('key', 'value'),)", 'object_name': 'FilterValue'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'sentry.groupedmessage': {
'Meta': {'unique_together': "(('logger', 'view', 'checksum'),)", 'object_name': 'GroupedMessage'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'class_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '128', 'null': 'True', 'blank': 'True'}),
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'db_index': 'True'}),
'times_seen': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'traceback': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'view': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'sentry.message': {
'Meta': {'object_name': 'Message'},
'checksum': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'class_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '128', 'null': 'True', 'blank': 'True'}),
'data': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'datetime': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'message_set'", 'null': 'True', 'to': "orm['sentry.GroupedMessage']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'default': '40', 'db_index': 'True', 'blank': 'True'}),
'logger': ('django.db.models.fields.CharField', [], {'default': "'root'", 'max_length': '64', 'db_index': 'True', 'blank': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'server_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'db_index': 'True'}),
'traceback': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'view': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
}
}
complete_apps = ['sentry']
| bsd-3-clause |
shoma/mycli | mycli/key_bindings.py | 2409 | import logging
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.filters import Condition
_logger = logging.getLogger(__name__)
def mycli_bindings(get_key_bindings, set_key_bindings):
"""
Custom key bindings for mycli.
"""
assert callable(get_key_bindings)
assert callable(set_key_bindings)
key_binding_manager = KeyBindingManager(
enable_open_in_editor=True,
enable_system_bindings=True,
enable_vi_mode=Condition(lambda cli: get_key_bindings() == 'vi'))
@key_binding_manager.registry.add_binding(Keys.F2)
def _(event):
"""
Enable/Disable SmartCompletion Mode.
"""
_logger.debug('Detected F2 key.')
buf = event.cli.current_buffer
buf.completer.smart_completion = not buf.completer.smart_completion
@key_binding_manager.registry.add_binding(Keys.F3)
def _(event):
"""
Enable/Disable Multiline Mode.
"""
_logger.debug('Detected F3 key.')
buf = event.cli.current_buffer
buf.always_multiline = not buf.always_multiline
@key_binding_manager.registry.add_binding(Keys.F4)
def _(event):
"""
Toggle between Vi and Emacs mode.
"""
_logger.debug('Detected F4 key.')
if get_key_bindings() == 'vi':
set_key_bindings('emacs')
else:
set_key_bindings('vi')
@key_binding_manager.registry.add_binding(Keys.Tab)
def _(event):
"""
Force autocompletion at cursor.
"""
_logger.debug('Detected <Tab> key.')
b = event.cli.current_buffer
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(select_first=True)
@key_binding_manager.registry.add_binding(Keys.ControlSpace)
def _(event):
"""
Initialize autocompletion at cursor.
If the autocompletion menu is not showing, display it with the
appropriate completions for the context.
If the menu is showing, select the next completion.
"""
_logger.debug('Detected <C-Space> key.')
b = event.cli.current_buffer
if b.complete_state:
b.complete_next()
else:
event.cli.start_completion(select_first=False)
return key_binding_manager
| bsd-3-clause |
VProdanov/sdl_core | tools/InterfaceGenerator/generator/parsers/JSONRPC.py | 2763 | """JSON RPC parser.
Contains parser for JSON RPC XML format.
"""
from generator.parsers import RPCBase
class Parser(RPCBase.Parser):
"""JSON RPC parser."""
def __init__(self):
"""Constructor."""
super(Parser, self).__init__()
self._interface_name = None
def _parse_root(self, root):
"""Parse root XML element.
This implementation parses root as interfaces element with multiple
interfaces in it.
Keyword arguments:
root -- root element.
"""
self._params = root.attrib
self._interface_name = None
for element in root:
if element.tag != "interface":
raise RPCBase.ParseError("Subelement '" + element.tag +
"' is unexpected in interfaces")
if "name" not in element.attrib:
raise RPCBase.ParseError(
"Name is not specified for interface")
self._interface_name = element.attrib["name"]
self._parse_interface(element, self._interface_name + "_")
def _provide_enum_element_for_function(self, enum_name, element_name):
"""Provide enum element for functions.
This implementation replaces the underscore separating interface and
function name with dot and sets it as name of enum element leaving
the name with underscore as internal_name. For enums other than
FunctionID the base implementation is called.
Returns EnumElement.
"""
name = element_name
internal_name = None
if "FunctionID" == enum_name:
prefix_length = len(self._interface_name) + 1
if element_name[:prefix_length] != self._interface_name + '_':
raise RPCBase.ParseError(
"Unexpected prefix for function id '" +
element_name + "'")
name = self._interface_name + "." + element_name[prefix_length:]
internal_name = element_name
element = super(Parser, self)._provide_enum_element_for_function(
enum_name,
name)
if internal_name is not None:
element.internal_name = internal_name
return element
def _check_function_param_name(self, function_param_name):
"""Check function param name.
This method is called to check whether the newly parsed function
parameter name conflicts with some predefined name.
"""
if function_param_name in ['method', 'code']:
raise RPCBase.ParseError(
"'" + function_param_name +
"' is a predefined name and can't be used" +
" as a function parameter name")
| bsd-3-clause |
ogrisel/scikit-learn | sklearn/mixture/tests/test_bayesian_mixture.py | 20587 | # Author: Wei Xue <xuewei4d@gmail.com>
# Thierry Guillemot <thierry.guillemot.work@gmail.com>
# License: BSD 3 clause
import copy
import numpy as np
from scipy.special import gammaln
import pytest
from sklearn.utils._testing import assert_raise_message
from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import assert_array_equal
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.mixture._bayesian_mixture import _log_dirichlet_norm
from sklearn.mixture._bayesian_mixture import _log_wishart_norm
from sklearn.mixture import BayesianGaussianMixture
from sklearn.mixture.tests.test_gaussian_mixture import RandomData
from sklearn.exceptions import ConvergenceWarning, NotFittedError
from sklearn.utils._testing import ignore_warnings
COVARIANCE_TYPE = ['full', 'tied', 'diag', 'spherical']
PRIOR_TYPE = ['dirichlet_process', 'dirichlet_distribution']
def test_log_dirichlet_norm():
rng = np.random.RandomState(0)
weight_concentration = rng.rand(2)
expected_norm = (gammaln(np.sum(weight_concentration)) -
np.sum(gammaln(weight_concentration)))
predected_norm = _log_dirichlet_norm(weight_concentration)
assert_almost_equal(expected_norm, predected_norm)
def test_log_wishart_norm():
rng = np.random.RandomState(0)
n_components, n_features = 5, 2
degrees_of_freedom = np.abs(rng.rand(n_components)) + 1.
log_det_precisions_chol = n_features * np.log(range(2, 2 + n_components))
expected_norm = np.empty(5)
for k, (degrees_of_freedom_k, log_det_k) in enumerate(
zip(degrees_of_freedom, log_det_precisions_chol)):
expected_norm[k] = -(
degrees_of_freedom_k * (log_det_k + .5 * n_features * np.log(2.)) +
np.sum(gammaln(.5 * (degrees_of_freedom_k -
np.arange(0, n_features)[:, np.newaxis])), 0))
predected_norm = _log_wishart_norm(degrees_of_freedom,
log_det_precisions_chol, n_features)
assert_almost_equal(expected_norm, predected_norm)
def test_bayesian_mixture_covariance_type():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
covariance_type = 'bad_covariance_type'
bgmm = BayesianGaussianMixture(covariance_type=covariance_type,
random_state=rng)
assert_raise_message(ValueError,
"Invalid value for 'covariance_type': %s "
"'covariance_type' should be in "
"['spherical', 'tied', 'diag', 'full']"
% covariance_type, bgmm.fit, X)
def test_bayesian_mixture_weight_concentration_prior_type():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
bad_prior_type = 'bad_prior_type'
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=bad_prior_type, random_state=rng)
assert_raise_message(ValueError,
"Invalid value for 'weight_concentration_prior_type':"
" %s 'weight_concentration_prior_type' should be in "
"['dirichlet_process', 'dirichlet_distribution']"
% bad_prior_type, bgmm.fit, X)
def test_bayesian_mixture_weights_prior_initialisation():
rng = np.random.RandomState(0)
n_samples, n_components, n_features = 10, 5, 2
X = rng.rand(n_samples, n_features)
# Check raise message for a bad value of weight_concentration_prior
bad_weight_concentration_prior_ = 0.
bgmm = BayesianGaussianMixture(
weight_concentration_prior=bad_weight_concentration_prior_,
random_state=0)
assert_raise_message(ValueError,
"The parameter 'weight_concentration_prior' "
"should be greater than 0., but got %.3f."
% bad_weight_concentration_prior_,
bgmm.fit, X)
# Check correct init for a given value of weight_concentration_prior
weight_concentration_prior = rng.rand()
bgmm = BayesianGaussianMixture(
weight_concentration_prior=weight_concentration_prior,
random_state=rng).fit(X)
assert_almost_equal(weight_concentration_prior,
bgmm.weight_concentration_prior_)
# Check correct init for the default value of weight_concentration_prior
bgmm = BayesianGaussianMixture(n_components=n_components,
random_state=rng).fit(X)
assert_almost_equal(1. / n_components, bgmm.weight_concentration_prior_)
def test_bayesian_mixture_mean_prior_initialisation():
rng = np.random.RandomState(0)
n_samples, n_components, n_features = 10, 3, 2
X = rng.rand(n_samples, n_features)
# Check raise message for a bad value of mean_precision_prior
bad_mean_precision_prior_ = 0.
bgmm = BayesianGaussianMixture(
mean_precision_prior=bad_mean_precision_prior_,
random_state=rng)
assert_raise_message(ValueError,
"The parameter 'mean_precision_prior' should be "
"greater than 0., but got %.3f."
% bad_mean_precision_prior_,
bgmm.fit, X)
# Check correct init for a given value of mean_precision_prior
mean_precision_prior = rng.rand()
bgmm = BayesianGaussianMixture(
mean_precision_prior=mean_precision_prior,
random_state=rng).fit(X)
assert_almost_equal(mean_precision_prior, bgmm.mean_precision_prior_)
# Check correct init for the default value of mean_precision_prior
bgmm = BayesianGaussianMixture(random_state=rng).fit(X)
assert_almost_equal(1., bgmm.mean_precision_prior_)
# Check raise message for a bad shape of mean_prior
mean_prior = rng.rand(n_features + 1)
bgmm = BayesianGaussianMixture(n_components=n_components,
mean_prior=mean_prior,
random_state=rng)
assert_raise_message(ValueError,
"The parameter 'means' should have the shape of ",
bgmm.fit, X)
# Check correct init for a given value of mean_prior
mean_prior = rng.rand(n_features)
bgmm = BayesianGaussianMixture(n_components=n_components,
mean_prior=mean_prior,
random_state=rng).fit(X)
assert_almost_equal(mean_prior, bgmm.mean_prior_)
# Check correct init for the default value of bemean_priorta
bgmm = BayesianGaussianMixture(n_components=n_components,
random_state=rng).fit(X)
assert_almost_equal(X.mean(axis=0), bgmm.mean_prior_)
def test_bayesian_mixture_precisions_prior_initialisation():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
# Check raise message for a bad value of degrees_of_freedom_prior
bad_degrees_of_freedom_prior_ = n_features - 1.
bgmm = BayesianGaussianMixture(
degrees_of_freedom_prior=bad_degrees_of_freedom_prior_,
random_state=rng)
assert_raise_message(ValueError,
"The parameter 'degrees_of_freedom_prior' should be "
"greater than %d, but got %.3f."
% (n_features - 1, bad_degrees_of_freedom_prior_),
bgmm.fit, X)
# Check correct init for a given value of degrees_of_freedom_prior
degrees_of_freedom_prior = rng.rand() + n_features - 1.
bgmm = BayesianGaussianMixture(
degrees_of_freedom_prior=degrees_of_freedom_prior,
random_state=rng).fit(X)
assert_almost_equal(degrees_of_freedom_prior,
bgmm.degrees_of_freedom_prior_)
# Check correct init for the default value of degrees_of_freedom_prior
degrees_of_freedom_prior_default = n_features
bgmm = BayesianGaussianMixture(
degrees_of_freedom_prior=degrees_of_freedom_prior_default,
random_state=rng).fit(X)
assert_almost_equal(degrees_of_freedom_prior_default,
bgmm.degrees_of_freedom_prior_)
# Check correct init for a given value of covariance_prior
covariance_prior = {
'full': np.cov(X.T, bias=1) + 10,
'tied': np.cov(X.T, bias=1) + 5,
'diag': np.diag(np.atleast_2d(np.cov(X.T, bias=1))) + 3,
'spherical': rng.rand()}
bgmm = BayesianGaussianMixture(random_state=rng)
for cov_type in ['full', 'tied', 'diag', 'spherical']:
bgmm.covariance_type = cov_type
bgmm.covariance_prior = covariance_prior[cov_type]
bgmm.fit(X)
assert_almost_equal(covariance_prior[cov_type],
bgmm.covariance_prior_)
# Check raise message for a bad spherical value of covariance_prior
bad_covariance_prior_ = -1.
bgmm = BayesianGaussianMixture(covariance_type='spherical',
covariance_prior=bad_covariance_prior_,
random_state=rng)
assert_raise_message(ValueError,
"The parameter 'spherical covariance_prior' "
"should be greater than 0., but got %.3f."
% bad_covariance_prior_,
bgmm.fit, X)
# Check correct init for the default value of covariance_prior
covariance_prior_default = {
'full': np.atleast_2d(np.cov(X.T)),
'tied': np.atleast_2d(np.cov(X.T)),
'diag': np.var(X, axis=0, ddof=1),
'spherical': np.var(X, axis=0, ddof=1).mean()}
bgmm = BayesianGaussianMixture(random_state=0)
for cov_type in ['full', 'tied', 'diag', 'spherical']:
bgmm.covariance_type = cov_type
bgmm.fit(X)
assert_almost_equal(covariance_prior_default[cov_type],
bgmm.covariance_prior_)
def test_bayesian_mixture_check_is_fitted():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
# Check raise message
bgmm = BayesianGaussianMixture(random_state=rng)
X = rng.rand(n_samples, n_features)
assert_raise_message(ValueError,
'This BayesianGaussianMixture instance is not '
'fitted yet.', bgmm.score, X)
def test_bayesian_mixture_weights():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
# Case Dirichlet distribution for the weight concentration prior type
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type="dirichlet_distribution",
n_components=3, random_state=rng).fit(X)
expected_weights = (bgmm.weight_concentration_ /
np.sum(bgmm.weight_concentration_))
assert_almost_equal(expected_weights, bgmm.weights_)
assert_almost_equal(np.sum(bgmm.weights_), 1.0)
# Case Dirichlet process for the weight concentration prior type
dpgmm = BayesianGaussianMixture(
weight_concentration_prior_type="dirichlet_process",
n_components=3, random_state=rng).fit(X)
weight_dirichlet_sum = (dpgmm.weight_concentration_[0] +
dpgmm.weight_concentration_[1])
tmp = dpgmm.weight_concentration_[1] / weight_dirichlet_sum
expected_weights = (dpgmm.weight_concentration_[0] / weight_dirichlet_sum *
np.hstack((1, np.cumprod(tmp[:-1]))))
expected_weights /= np.sum(expected_weights)
assert_almost_equal(expected_weights, dpgmm.weights_)
assert_almost_equal(np.sum(dpgmm.weights_), 1.0)
@ignore_warnings(category=ConvergenceWarning)
def test_monotonic_likelihood():
# We check that each step of the each step of variational inference without
# regularization improve monotonically the training set of the bound
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=20)
n_components = rand_data.n_components
for prior_type in PRIOR_TYPE:
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type=covar_type,
warm_start=True, max_iter=1, random_state=rng, tol=1e-3)
current_lower_bound = -np.infty
# Do one training iteration at a time so we can make sure that the
# training log likelihood increases after each iteration.
for _ in range(600):
prev_lower_bound = current_lower_bound
current_lower_bound = bgmm.fit(X).lower_bound_
assert current_lower_bound >= prev_lower_bound
if bgmm.converged_:
break
assert(bgmm.converged_)
def test_compare_covar_type():
# We can compare the 'full' precision with the other cov_type if we apply
# 1 iter of the M-step (done during _initialize_parameters).
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=7)
X = rand_data.X['full']
n_components = rand_data.n_components
for prior_type in PRIOR_TYPE:
# Computation of the full_covariance
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='full',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
full_covariances = (
bgmm.covariances_ *
bgmm.degrees_of_freedom_[:, np.newaxis, np.newaxis])
# Check tied_covariance = mean(full_covariances, 0)
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='tied',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
tied_covariance = bgmm.covariances_ * bgmm.degrees_of_freedom_
assert_almost_equal(tied_covariance, np.mean(full_covariances, 0))
# Check diag_covariance = diag(full_covariances)
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='diag',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
diag_covariances = (bgmm.covariances_ *
bgmm.degrees_of_freedom_[:, np.newaxis])
assert_almost_equal(diag_covariances,
np.array([np.diag(cov)
for cov in full_covariances]))
# Check spherical_covariance = np.mean(diag_covariances, 0)
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='spherical',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
spherical_covariances = bgmm.covariances_ * bgmm.degrees_of_freedom_
assert_almost_equal(
spherical_covariances, np.mean(diag_covariances, 1))
@ignore_warnings(category=ConvergenceWarning)
def test_check_covariance_precision():
# We check that the dot product of the covariance and the precision
# matrices is identity.
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=7)
n_components, n_features = 2 * rand_data.n_components, 2
# Computation of the full_covariance
bgmm = BayesianGaussianMixture(n_components=n_components,
max_iter=100, random_state=rng, tol=1e-3,
reg_covar=0)
for covar_type in COVARIANCE_TYPE:
bgmm.covariance_type = covar_type
bgmm.fit(rand_data.X[covar_type])
if covar_type == 'full':
for covar, precision in zip(bgmm.covariances_, bgmm.precisions_):
assert_almost_equal(np.dot(covar, precision),
np.eye(n_features))
elif covar_type == 'tied':
assert_almost_equal(np.dot(bgmm.covariances_, bgmm.precisions_),
np.eye(n_features))
elif covar_type == 'diag':
assert_almost_equal(bgmm.covariances_ * bgmm.precisions_,
np.ones((n_components, n_features)))
else:
assert_almost_equal(bgmm.covariances_ * bgmm.precisions_,
np.ones(n_components))
@ignore_warnings(category=ConvergenceWarning)
def test_invariant_translation():
# We check here that adding a constant in the data change correctly the
# parameters of the mixture
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=100)
n_components = 2 * rand_data.n_components
for prior_type in PRIOR_TYPE:
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
bgmm1 = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=n_components, max_iter=100, random_state=0,
tol=1e-3, reg_covar=0).fit(X)
bgmm2 = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=n_components, max_iter=100, random_state=0,
tol=1e-3, reg_covar=0).fit(X + 100)
assert_almost_equal(bgmm1.means_, bgmm2.means_ - 100)
assert_almost_equal(bgmm1.weights_, bgmm2.weights_)
assert_almost_equal(bgmm1.covariances_, bgmm2.covariances_)
@pytest.mark.filterwarnings("ignore:.*did not converge.*")
@pytest.mark.parametrize('seed, max_iter, tol', [
(0, 2, 1e-7), # strict non-convergence
(1, 2, 1e-1), # loose non-convergence
(3, 300, 1e-7), # strict convergence
(4, 300, 1e-1), # loose convergence
])
def test_bayesian_mixture_fit_predict(seed, max_iter, tol):
rng = np.random.RandomState(seed)
rand_data = RandomData(rng, n_samples=50, scale=7)
n_components = 2 * rand_data.n_components
for covar_type in COVARIANCE_TYPE:
bgmm1 = BayesianGaussianMixture(n_components=n_components,
max_iter=max_iter, random_state=rng,
tol=tol, reg_covar=0)
bgmm1.covariance_type = covar_type
bgmm2 = copy.deepcopy(bgmm1)
X = rand_data.X[covar_type]
Y_pred1 = bgmm1.fit(X).predict(X)
Y_pred2 = bgmm2.fit_predict(X)
assert_array_equal(Y_pred1, Y_pred2)
def test_bayesian_mixture_fit_predict_n_init():
# Check that fit_predict is equivalent to fit.predict, when n_init > 1
X = np.random.RandomState(0).randn(50, 5)
gm = BayesianGaussianMixture(n_components=5, n_init=10, random_state=0)
y_pred1 = gm.fit_predict(X)
y_pred2 = gm.predict(X)
assert_array_equal(y_pred1, y_pred2)
def test_bayesian_mixture_predict_predict_proba():
# this is the same test as test_gaussian_mixture_predict_predict_proba()
rng = np.random.RandomState(0)
rand_data = RandomData(rng)
for prior_type in PRIOR_TYPE:
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
Y = rand_data.Y
bgmm = BayesianGaussianMixture(
n_components=rand_data.n_components,
random_state=rng,
weight_concentration_prior_type=prior_type,
covariance_type=covar_type)
# Check a warning message arrive if we don't do fit
assert_raise_message(NotFittedError,
"This BayesianGaussianMixture instance"
" is not fitted yet. Call 'fit' with "
"appropriate arguments before using "
"this estimator.", bgmm.predict, X)
bgmm.fit(X)
Y_pred = bgmm.predict(X)
Y_pred_proba = bgmm.predict_proba(X).argmax(axis=1)
assert_array_equal(Y_pred, Y_pred_proba)
assert adjusted_rand_score(Y, Y_pred) >= .95
| bsd-3-clause |
ACOKing/ArcherSys | piwik/plugins/VisitTime/Segment.php | 364 | <?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik\Plugins\VisitTime;
/**
* VisitTime segment base class.
*
*/
class Segment extends \Piwik\Plugin\Segment
{
protected function init()
{
$this->setCategory('Visit');
}
}
| mit |
parjong/corefx | src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Symbols/AssemblyQualifiedNamespaceSymbol.cs | 779 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// ----------------------------------------------------------------------------
//
// AssemblyQualifiedNamespaceSymbol
//
// Parented by an NamespaceSymbol. Represents an NamespaceSymbol within an aid (assembly/alias id).
// The name is a form of the aid.
// ----------------------------------------------------------------------------
internal sealed class AssemblyQualifiedNamespaceSymbol : ParentSymbol
{
public NamespaceSymbol GetNS() => parent as NamespaceSymbol;
}
}
| mit |
marcisme/capybara-webkit | spec/capybara_webkit_builder_spec.rb | 707 | require 'spec_helper'
require 'capybara_webkit_builder'
describe CapybaraWebkitBuilder do
let(:builder) { CapybaraWebkitBuilder }
it "will use the env variable for #make_bin" do
with_env_vars("MAKE" => "fake_make") do
builder.make_bin.should == "fake_make"
end
end
it "will use the env variable for #qmake_bin" do
with_env_vars("QMAKE" => "fake_qmake") do
builder.qmake_bin.should == "fake_qmake"
end
end
it "defaults the #make_bin" do
with_env_vars("MAKE_BIN" => nil) do
builder.make_bin.should == 'make'
end
end
it "defaults the #qmake_bin" do
with_env_vars("QMAKE" => nil) do
builder.qmake_bin.should == 'qmake'
end
end
end
| mit |
popham/flow | src/parser/test/flow/async_await/migrated_0017.js | 40 | async function foo() { var await = 4; }
| mit |
constantcontact/open-performance-platform | opp-ui/ui/ext/packages/charts/test/specs-classic/chart/series/Area.js | 5775 | describe('Ext.chart.series.Area', function () {
describe('renderer', function () {
it('should work on markers with style.step = false', function () {
var chart,
red = '#ff0000',
green = '#ff0000',
redrawCount = 0;
run(function () {
chart = new Ext.chart.CartesianChart({
renderTo: Ext.getBody(),
width: 300,
height: 300,
store: {
data: [{
month: 'JAN',
data1: 12
}, {
month: 'FEB',
data1: 14
}, {
month: 'MAR',
data1: 10
}, {
month: 'APR',
data1: 18
}, {
month: 'MAY',
data1: 17
}]
},
axes: [{
type: 'numeric',
position: 'left'
}, {
type: 'category',
position: 'bottom'
}],
series: [{
type: 'area',
renderer: function (sprite, config, rendererData, index) {
return {
fillStyle: index % 2 ? red : green
};
},
xField: 'month',
yField: 'data1',
marker: true
}],
listeners: {
redraw: function () {
redrawCount++;
}
}
})
});
waitFor(function () {
// Chart normally renders twice:
// 1) to measure things
// 2) to adjust layout
return redrawCount == 2;
});
run(function () {
var seriesSprite = chart.getSeries()[0].getSprites()[0],
markerCategory = seriesSprite.getId(),
markers = seriesSprite.getMarker('markers');
expect(markers.getMarkerFor(markerCategory, 0).fillStyle).toBe(green);
expect(markers.getMarkerFor(markerCategory, 1).fillStyle).toBe(red);
expect(markers.getMarkerFor(markerCategory, 2).fillStyle).toBe(green);
expect(markers.getMarkerFor(markerCategory, 3).fillStyle).toBe(red);
Ext.destroy(chart);
});
});
it('should work on markers with style.step = true', function () {
var chart,
red = '#ff0000',
green = '#ff0000',
redrawCount = 0;
run(function () {
chart = new Ext.chart.CartesianChart({
renderTo: Ext.getBody(),
width: 300,
height: 300,
store: {
data: [{
month: 'JAN',
data1: 12
}, {
month: 'FEB',
data1: 14
}, {
month: 'MAR',
data1: 10
}, {
month: 'APR',
data1: 18
}, {
month: 'MAY',
data1: 17
}]
},
axes: [{
type: 'numeric',
position: 'left'
}, {
type: 'category',
position: 'bottom'
}],
series: [{
type: 'area',
style: {
step: true
},
renderer: function (sprite, config, rendererData, index) {
return {
fillStyle: index % 2 ? red : green
};
},
xField: 'month',
yField: 'data1',
marker: true
}],
listeners: {
redraw: function () {
redrawCount++;
}
}
})
});
waitFor(function () {
// Chart normally renders twice:
// 1) to measure things
// 2) to adjust layout
return redrawCount == 2;
});
run(function () {
var seriesSprite = chart.getSeries()[0].getSprites()[0],
markerCategory = seriesSprite.getId(),
markers = seriesSprite.getMarker('markers');
expect(markers.getMarkerFor(markerCategory, 0).fillStyle).toBe(green);
expect(markers.getMarkerFor(markerCategory, 1).fillStyle).toBe(red);
expect(markers.getMarkerFor(markerCategory, 2).fillStyle).toBe(green);
expect(markers.getMarkerFor(markerCategory, 3).fillStyle).toBe(red);
Ext.destroy(chart);
});
});
});
}); | mit |
xsmart/opencvr | 3rdparty/poco/Foundation/testsuite/src/TaskTestSuite.cpp | 528 | //
// TaskTestSuite.cpp
//
// $Id: //poco/1.4/Foundation/testsuite/src/TaskTestSuite.cpp#1 $
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "TaskTestSuite.h"
#include "TaskTest.h"
#include "TaskManagerTest.h"
CppUnit::Test* TaskTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("TaskTestSuite");
pSuite->addTest(TaskTest::suite());
pSuite->addTest(TaskManagerTest::suite());
return pSuite;
}
| mit |
yaoshanliang/phphub | app/views/pages/home.blade.php | 739 | @extends('layouts.default')
@section('content')
<div class="box text-center">
{{ lang('site_intro') }}
</div>
<div class="panel panel-default list-panel">
<div class="panel-heading">
<h3 class="panel-title text-center">
{{ lang('Excellent Topics') }}
<a href="{{ route('feed') }}" style="color: #E5974E; font-size: 14px;" target="_blank">
<i class="fa fa-rss"></i>
</a>
</h3>
</div>
<div class="panel-body">
@include('topics.partials.topics', ['column' => true])
</div>
<div class="panel-footer text-right">
<a href="topics?filter=excellent">
{{ lang('More Excellent Topics') }}...
</a>
</div>
</div>
<!-- Nodes Listing -->
@include('nodes.partials.list')
@stop
| mit |
markogresak/DefinitelyTyped | types/nginstack__engine/lib/dataset/fieldValueIsEqual.d.ts | 95 | declare function _exports(ds: any, fieldName: string, value: any): boolean;
export = _exports;
| mit |
abidghozi/CapstoneProject_BdoCommunity | exp/phpfreechat/lib/csstidy-1.2/class.csstidy_print.php | 10313 | <?php
/**
* CSSTidy - CSS Parser and Optimiser
*
* CSS Printing class
* This class prints CSS data generated by csstidy.
*
* This file is part of CSSTidy.
*
* CSSTidy 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.
*
* CSSTidy is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CSSTidy; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @package csstidy
* @author Florian Schmitz (floele at gmail dot com) 2005-2006
*/
/**
* CSS Printing class
*
* This class prints CSS data generated by csstidy.
*
* @package csstidy
* @author Florian Schmitz (floele at gmail dot com) 2005-2006
* @version 1.0
*/
class csstidy_print
{
/**
* Saves the input CSS string
* @var string
* @access private
*/
var $input_css = '';
/**
* Saves the formatted CSS string
* @var string
* @access public
*/
var $output_css = '';
/**
* Saves the formatted CSS string (plain text)
* @var string
* @access public
*/
var $output_css_plain = '';
/**
* Constructor
* @param array $css contains the class csstidy
* @access private
* @version 1.0
*/
function csstidy_print(&$css)
{
$this->parser =& $css;
$this->css =& $css->css;
$this->template =& $css->template;
$this->tokens =& $css->tokens;
$this->charset =& $css->charset;
$this->import =& $css->import;
$this->namespace =& $css->namespace;
}
/**
* Resets output_css and output_css_plain (new css code)
* @access private
* @version 1.0
*/
function _reset()
{
$this->output_css = '';
$this->output_css_plain = '';
}
/**
* Returns the CSS code as plain text
* @return string
* @access public
* @version 1.0
*/
function plain()
{
$this->_print(true);
return $this->output_css_plain;
}
/**
* Returns the formatted CSS code
* @return string
* @access public
* @version 1.0
*/
function formatted()
{
$this->_print(false);
return $this->output_css;
}
/**
* Returns the formatted CSS Code and saves it into $this->output_css and $this->output_css_plain
* @param bool $plain plain text or not
* @access private
* @version 2.0
*/
function _print($plain = false)
{
if ($this->output_css && $this->output_css_plain) {
return;
}
$output = '';
if (!$this->parser->get_cfg('preserve_css')) {
$this->_convert_raw_css();
}
$template =& $this->template;
if ($plain) {
$template = array_map('strip_tags', $template);
}
if ($this->parser->get_cfg('timestamp')) {
array_unshift($this->tokens, array(COMMENT, ' CSSTidy ' . $this->parser->version . ': ' . date('r') . ' '));
}
if (!empty($this->charset)) {
$output .= $template[0].'@charset '.$template[5].$this->charset.$template[6];
}
if (!empty($this->import)) {
for ($i = 0, $size = count($this->import); $i < $size; $i ++) {
$output .= $template[0].'@import '.$template[5].$this->import[$i].$template[6];
}
}
if (!empty($this->namespace)) {
$output .= $template[0].'@namespace '.$template[5].$this->namespace.$template[6];
}
$output .= $template[13];
$in_at_out = '';
$out =& $output;
foreach ($this->tokens as $key => $token)
{
switch ($token[0])
{
case AT_START:
$out .= $template[0].$this->_htmlsp($token[1], $plain).$template[1];
$out =& $in_at_out;
break;
case SEL_START:
if($this->parser->get_cfg('lowercase_s')) $token[1] = strtolower($token[1]);
$out .= ($token[1]{0} !== '@') ? $template[2].$this->_htmlsp($token[1], $plain) : $template[0].$this->_htmlsp($token[1], $plain);
$out .= $template[3];
break;
case PROPERTY:
if($this->parser->get_cfg('case_properties') == 2) $token[1] = strtoupper($token[1]);
if($this->parser->get_cfg('case_properties') == 1) $token[1] = strtolower($token[1]);
$out .= $template[4] . $this->_htmlsp($token[1], $plain) . ':' . $template[5];
break;
case VALUE:
$out .= $this->_htmlsp($token[1], $plain);
if($this->_seeknocomment($key, 1) == SEL_END && $this->parser->get_cfg('remove_last_;')) {
$out .= str_replace(';', '', $template[6]);
} else {
$out .= $template[6];
}
break;
case SEL_END:
$out .= $template[7];
if($this->_seeknocomment($key, 1) != AT_END) $out .= $template[8];
break;
case AT_END:
$out =& $output;
$out .= $template[10] . str_replace("\n", "\n" . $template[10], $in_at_out);
$in_at_out = '';
$out .= $template[9];
break;
case COMMENT:
$out .= $template[11] . '/*' . $this->_htmlsp($token[1], $plain) . '*/' . $template[12];
break;
}
}
$output = trim($output);
if (!$plain) {
$this->output_css = $output;
$this->_print(true);
} else {
$this->output_css_plain = $output;
}
}
/**
* Gets the next token type which is $move away from $key, excluding comments
* @param integer $key current position
* @param integer $move move this far
* @return mixed a token type
* @access private
* @version 1.0
*/
function _seeknocomment($key, $move) {
$go = ($move > 0) ? 1 : -1;
for ($i = $key + 1; abs($key-$i)-1 < abs($move); $i += $go) {
if (!isset($this->tokens[$i])) {
return;
}
if ($this->tokens[$i][0] == COMMENT) {
$move += 1;
continue;
}
return $this->tokens[$i][0];
}
}
/**
* Converts $this->css array to a raw array ($this->tokens)
* @access private
* @version 1.0
*/
function _convert_raw_css()
{
$this->tokens = array();
ksort($this->css);
foreach ($this->css as $medium => $val)
{
if ($this->parser->get_cfg('sort_selectors')) ksort($val);
if ($medium != DEFAULT_AT) {
$this->parser->_add_token(AT_START, $medium, true);
}
foreach ($val as $selector => $vali)
{
if ($this->parser->get_cfg('sort_properties')) ksort($vali);
$this->parser->_add_token(SEL_START, $selector, true);
foreach ($vali as $property => $valj)
{
$this->parser->_add_token(PROPERTY, $property, true);
$this->parser->_add_token(VALUE, $valj, true);
}
$this->parser->_add_token(SEL_END, $selector, true);
}
if ($medium != DEFAULT_AT) {
$this->parser->_add_token(AT_END, $medium, true);
}
}
}
/**
* Same as htmlspecialchars, only that chars are not replaced if $plain !== true. This makes print_code() cleaner.
* @param string $string
* @param bool $plain
* @return string
* @see csstidy_print::_print()
* @access private
* @version 1.0
*/
function _htmlsp($string, $plain)
{
if (!$plain) {
return htmlspecialchars($string);
}
return $string;
}
/**
* Get compression ratio
* @access public
* @return float
* @version 1.2
*/
function get_ratio()
{
if (!$this->output_css_plain) {
$this->formatted();
}
return round((strlen($this->input_css) - strlen($this->output_css_plain)) / strlen($this->input_css), 3) * 100;
}
/**
* Get difference between the old and new code in bytes and prints the code if necessary.
* @access public
* @return string
* @version 1.1
*/
function get_diff()
{
if (!$this->output_css_plain) {
$this->formatted();
}
$diff = strlen($this->output_css_plain) - strlen($this->input_css);
if ($diff > 0) {
return '+' . $diff;
} elseif ($diff == 0) {
return '+-' . $diff;
}
return $diff;
}
/**
* Get the size of either input or output CSS in KB
* @param string $loc default is "output"
* @access public
* @return integer
* @version 1.0
*/
function size($loc = 'output')
{
if ($loc == 'output' && !$this->output_css) {
$this->formatted();
}
if ($loc == 'input') {
return (strlen($this->input_css) / 1000);
} else {
return (strlen($this->output_css_plain) / 1000);
}
}
}
?> | mit |
markogresak/DefinitelyTyped | types/node-redmine/index.d.ts | 3190 | // Type definitions for node-redmine 0.2
// Project: https://github.com/zanran/node-redmine#readme
// Definitions by: Roberto Rossetti <https://github.com/grptx>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
export interface IssueRecord {
id: number;
project: IssueRecordField;
tracker: IssueRecordField;
status: IssueRecordField;
priority: IssueRecordField;
author: IssueRecordField;
assigned_to: IssueRecordField;
parent?: IssueRecordField | undefined;
subject: string;
description: string;
start_date: string | null;
due_date: string | null;
done_ratio: number;
is_private: boolean;
total_estimated_hours: number | null;
created_at: string;
updated_at: string | null;
closed_on: string | null;
}
export interface IssueRecordField {
id: number;
name?: string | undefined;
}
export interface IssueParams {
project_id?: number | undefined;
tracker_id?: number | undefined;
priority_id?: number | undefined;
category_id?: number | undefined;
status_id?: number | undefined;
assigned_to_id?: number | undefined;
subject?: string | undefined;
description?: string | undefined;
parent_issue_id?: number | undefined;
notes?: string | undefined;
uploads?: UploadRecord[] | undefined;
}
export interface UploadResult {
upload: UploadRecord;
}
export interface UploadRecord {
token: string;
content_type?: string | undefined;
filename: string;
}
export interface IssueData {
issue: IssueParams;
}
export interface Issue {
issue: IssueRecord;
}
export interface Issues {
issues: IssueRecord[];
}
export class Redmine {
constructor(host: string, config: any, port: number);
/////////////////////////////////////// REST API for issues(Stable) ///////////////////////////////////////
issues(params: any, callback: (err: any, data: any) => void): Issues;
get_issue_by_id(id: number, params: any, callback: (err: any, data: any) => void): Issue;
create_issue(issue: IssueData, callback: (err: any, data: any) => void): Issue;
update_issue(id: number, issue: IssueData, callback: (err: any, data: any) => void): Issue;
delete_issue(id: number, callback: (err: any, data: any) => void): void;
add_watcher(id: number, params: any, callback: (err: any, data: any) => void): void;
remove_watcher(id: number, params: any, callback: (err: any, data: any) => void): void;
/////////////////////////////////////// REST API for Issue Relations(Alpha) ///////////////////////////////////////
issue_relation_by_issue_id(id: number, callback: (err: any, data: any) => void): void;
create_issue_relation(id: number, params: any, callback: (err: any, data: any) => void): void;
issue_relation_by_id(id: number, callback: (err: any, data: any) => void): void;
delete_issue_relation(id: number, callback: (err: any, data: any) => void): void;
/////////////////////////////////////// REST API for Common(Alpha) ///////////////////////////////////////
upload(content: any, callback: (err: any, data: any) => void): UploadResult;
}
| mit |